mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-01 22:19:58 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
99f845c691 | ||
|
|
e9b0b27da0 | ||
|
|
4a980c33dd | ||
|
|
58ea1ae240 | ||
|
|
930e1694b2 | ||
|
|
28efbec23d | ||
|
|
7cc73ab189 | ||
|
|
e37df901ef | ||
|
|
0ce1a83c14 | ||
|
|
fc51f46c83 |
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1408294296,
|
||||
"producer_workflow_id": 429734568,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "main",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
|
||||
"producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "main",
|
||||
"signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
@@ -88,9 +88,7 @@
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [
|
||||
"github-actions[bot]"
|
||||
],
|
||||
"automatic_signer_actors": [],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
@@ -102,15 +100,7 @@
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
},
|
||||
"package_formats": [
|
||||
"appimage",
|
||||
"arch",
|
||||
"deb",
|
||||
"flatpak",
|
||||
"oci",
|
||||
"rpm"
|
||||
]
|
||||
}
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
|
||||
@@ -11,7 +11,6 @@ workflows:
|
||||
'.github/workflows/lockfile.yml':
|
||||
- 'actions/[email protected]'
|
||||
- 'step-security/[email protected]'
|
||||
'.github/workflows/nightly-dispatch.yml': []
|
||||
'.github/workflows/nightly-macos.yml':
|
||||
- 'actions/[email protected]'
|
||||
- 'step-security/[email protected]'
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
name: Dispatch release-ref nightly
|
||||
|
||||
# Transport only, never authorization. No checkout, payload parsing or release environment.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [DeckCraft unsigned nightly]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
# Actual context guards only; no checkout, release environment or platform secrets.
|
||||
if: >-
|
||||
github.repository == 'storytold/deckcraft' &&
|
||||
github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Dispatch only the exact completed producer run and attempt
|
||||
shell: python
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise RuntimeError(message)
|
||||
|
||||
# These filters reduce noise; the protected signer-branch validator repeats admission
|
||||
# against authenticated API metadata and required attestation/quality evidence.
|
||||
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/deckcraft', 'wrong repository')
|
||||
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
|
||||
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
|
||||
event = json.load(stream)
|
||||
require(event.get('action') == 'completed', 'producer is not complete')
|
||||
require(event.get('repository', {}).get('full_name') == 'storytold/deckcraft', 'wrong event repository')
|
||||
producer = event.get('workflow_run', {})
|
||||
require(producer.get('head_repository', {}).get('full_name') == 'storytold/deckcraft', 'foreign producer')
|
||||
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
|
||||
require(producer.get('head_branch') == 'main', 'wrong producer branch')
|
||||
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
|
||||
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
|
||||
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
|
||||
run_id, attempt = producer.get('id'), producer.get('run_attempt')
|
||||
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
|
||||
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
|
||||
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
|
||||
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
|
||||
}}).encode('utf-8')
|
||||
request = urllib.request.Request(
|
||||
'https://api.github.com/repos/storytold/deckcraft/actions/workflows/nightly-sign.yml/dispatches',
|
||||
data=body, method='POST', headers={
|
||||
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'User-Agent': 'deckcraft-nightly-dispatch'
|
||||
})
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise RuntimeError('dispatch redirects are forbidden')
|
||||
# One bounded request, no retry: duplicate transport is not publication authority.
|
||||
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
|
||||
require(response.status == 204, 'dispatch was not accepted')
|
||||
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
|
||||
@@ -34,9 +34,9 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
with:
|
||||
tooling-revision: main
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
app-name: deckcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
name: DeckCraft unsigned nightly
|
||||
|
||||
# Runs on the reviewed nightly schedule (01:00 UTC) and for supervised manual runs
|
||||
# by the reviewed manual actors. Completed scheduled runs are forwarded by nightly-dispatch.yml.
|
||||
# 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:
|
||||
schedule:
|
||||
- cron: '0 1 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -24,9 +22,9 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
with:
|
||||
tooling-revision: main
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
app-name: deckcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
|
||||
@@ -34,4 +32,3 @@ jobs:
|
||||
# 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"]'
|
||||
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
|
||||
|
||||
@@ -10,7 +10,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
# A push to main is the run that publishes coverage; superseded runs there would never finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
|
||||
@@ -20,7 +20,6 @@ artwork. The ribbon and menu icons stay original drawings.
|
||||
| `docs/brand/artcraft-mark-black.svg`, `docs/brand/artcraft-mark-black.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Mark for light backgrounds |
|
||||
| `docs/brand/LICENSE-brand.txt` | ArtCraft Team | ArtCraft brand kit | — (licence text) | Terms for the ArtCraft marks |
|
||||
| `assets/app-icon/deckcraft-1024.png`, `assets/app-icon/hicolor/*/apps/ai.storyteller.deckcraft.png` | DeckCraft contributors | rendered by DeckCraft from `assets/app-icon/icon-source.deckcraft` (shapes only) | MIT OR Apache-2.0 | Placeholder app icon (presentation board) until the mascot icon is drawn |
|
||||
| `assets/app-icon/deckcraft-mark.svg` | DeckCraft contributors | Original drawing of the app icon’s card and play triangle | MIT OR Apache-2.0 | About and the Backstage mark |
|
||||
| `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 |
|
||||
|
||||
Generated
+144
-1845
File diff suppressed because it is too large
Load Diff
+40
-45
@@ -12,21 +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 = "82ae5969349f2f70175011e01983eea32e4ae905", version = "0.1.0" }
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
# Compound File Binary directory reads (password-protected deck detection).
|
||||
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "0.1.0" }
|
||||
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
# Bounded XML reader and writer primitives.
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", 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 = "82ae5969349f2f70175011e01983eea32e4ae905", version = "0.1.0" }
|
||||
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
# PresentationML PPTX/POTX/PPSX reader and writer (craft-libs#778).
|
||||
craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "0.1.0" }
|
||||
# The craft facade: UI framework, platform, settings, window and the suite crates DeckCraft's UI uses.
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "0.1.0" }
|
||||
craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", 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 = "82ae5969349f2f70175011e01983eea32e4ae905", version = "0.1.0" }
|
||||
# Nightly profile isolation, launch protocol, and security fence.
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
# internal
|
||||
deckcraft-geom = { path = "crates/geom" }
|
||||
deckcraft-color = { path = "crates/color" }
|
||||
@@ -66,21 +62,27 @@ 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 = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", 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 = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0" }
|
||||
craft-media = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0", default-features = false }
|
||||
craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0", default-features = false, features = ["opus-decode"] }
|
||||
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"] }
|
||||
# H.264, HEVC, VP9 and AV1 decoders.
|
||||
craft-video = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", 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 = "8fa4db64a9bb943520259ea95331a303ba788f21", 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 = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0", default-features = false, features = ["write", "write-simple-text"] }
|
||||
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-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 = "82ae5969349f2f70175011e01983eea32e4ae905", features = ["ui"] }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0" }
|
||||
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" }
|
||||
i_overlay = "9"
|
||||
quick-xml = "0.41"
|
||||
zip = { version = "3", default-features = false, features = ["deflate"] }
|
||||
@@ -88,10 +90,12 @@ miniz_oxide = { version = "0.9", default-features = false, features = ["with-all
|
||||
|
||||
# ui
|
||||
egui = { version = "0.37", default-features = false }
|
||||
egui_extras = { version = "0.37", default-features = false }
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
egui_kittest = "0.37"
|
||||
web-time = "1.1"
|
||||
rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
@@ -125,28 +129,19 @@ codegen-units = 16
|
||||
debug = 0
|
||||
|
||||
[patch.crates-io]
|
||||
# BEGIN port-kit framework overrides
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.8.2" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
|
||||
# END port-kit framework overrides
|
||||
|
||||
[workspace.metadata.cl]
|
||||
selection = ["deckcraft", "deckcraft-anim", "deckcraft-cli", "deckcraft-color", "deckcraft-engine", "deckcraft-format", "deckcraft-geom", "deckcraft-mcp", "deckcraft-model", "deckcraft-pdf", "deckcraft-ppt", "deckcraft-pptx", "deckcraft-render", "deckcraft-text", "deckcraft-ui-egui", "deckcraft-web"]
|
||||
tracked = ["egui", "eframe", "craft-ui", "craft-pptx", "craft-drawingml"]
|
||||
unset_env = ["DECKCRAFT_BUILD_CHANNEL", "DECKCRAFT_VERSION", "DECKCRAFT_REQUIRE_WINRES", "CRAFT_FONTS_REQUIRED"]
|
||||
|
||||
# BEGIN port-kit framework patch
|
||||
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" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
@@ -160,7 +160,7 @@ same verbs:
|
||||
deckcraft-cli commands format. # list commands
|
||||
deckcraft-cli run --sample --cmd 'slide.new={"layout":"titleOnly","title":"Hello"}' --save hello.deckcraft
|
||||
deckcraft-cli mcp # MCP server over stdio (headless)
|
||||
deckcraft-cli mcp --connect 7990 --control-token-file PATH # drive the running app with its token file
|
||||
deckcraft-cli mcp --connect 7990 # drive the running app (deckcraft --control 7990)
|
||||
deckcraft-cli mcp --automation-read-root DIR --automation-write-root DIR # confine the headless agent to folders
|
||||
```
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ name = "deckcraft-cli"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
craft = { workspace = true, features = ["automation", "font-catalog"] }
|
||||
deckcraft-engine = { workspace = true }
|
||||
deckcraft-mcp = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -125,34 +125,23 @@ calls it.
|
||||
},
|
||||
Subcommand {
|
||||
name: "app",
|
||||
usage: "app [--port PORT] [--control-token TOKEN | --control-token-file PATH] (COMMAND [PARAMS] | --method METHOD [PARAMS])",
|
||||
usage: "app [--port PORT] COMMAND [PARAMS] | --method METHOD [PARAMS]",
|
||||
summary: "run a command in the DeckCraft app started with --control",
|
||||
details: "Sends one request to the DeckCraft app started with `deckcraft --control PORT` (port 7979 by default)
|
||||
and prints its answer as JSON. COMMAND [PARAMS] runs a command, as run --cmd does; --method METHOD
|
||||
[PARAMS] calls a control-channel method such as ui.screenshot. PARAMS is a JSON object.
|
||||
|
||||
Authenticate with the app's per-launch token: --control-token-file PATH reads its token file;
|
||||
--control-token TOKEN supplies the token directly. DECKCRAFT_CONTROL_TOKEN and
|
||||
DECKCRAFT_CONTROL_TOKEN_FILE supply fallbacks when their corresponding flags are absent.
|
||||
Start the app with --control-token-file PATH to have it create or read that file.
|
||||
|
||||
deckcraft-cli app --control-token-file PATH shape.insert '{\"preset\":\"star5\",\"rect\":[100,100,200,200]}'
|
||||
deckcraft-cli app --control-token-file PATH --method ui.screenshot '{\"path\":\"/tmp/shot.png\"}'",
|
||||
deckcraft-cli app shape.insert '{\"preset\":\"star5\",\"rect\":[100,100,200,200]}'
|
||||
deckcraft-cli app --method ui.screenshot '{\"path\":\"/tmp/shot.png\"}'",
|
||||
},
|
||||
Subcommand {
|
||||
name: "mcp",
|
||||
usage: "mcp [--connect PORT [--control-token TOKEN | --control-token-file PATH]] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...",
|
||||
usage: "mcp [--connect PORT] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...",
|
||||
summary: "serve the commands to an agent over MCP on stdio",
|
||||
details: "Runs a Model Context Protocol server on stdin and stdout. It works on its own presentation without a
|
||||
window, or with --connect PORT (or host:port) on the DeckCraft app started with --control PORT.
|
||||
--sample opens the sample presentation.
|
||||
|
||||
Connected mode requires the app's per-launch token: --control-token-file PATH reads its token file,
|
||||
or --control-token TOKEN supplies it directly. DECKCRAFT_CONTROL_TOKEN and
|
||||
DECKCRAFT_CONTROL_TOKEN_FILE supply fallbacks when their corresponding flags are absent.
|
||||
Start the app with --control-token-file PATH to have it create or read that file.
|
||||
Headless mode does not resolve these credentials.
|
||||
|
||||
--automation-read-root DIR and --automation-write-root DIR confine every file the agent's commands read
|
||||
(open, pictures, audio, video) and write (save, export, PDF) to those folders, links followed. Repeat either
|
||||
flag to grant access to more folders; a root left out grants none of its access. They run the in-process
|
||||
|
||||
@@ -9,8 +9,6 @@ mod help;
|
||||
use std::process::ExitCode;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use craft::automation::args::{ControlOptions, EnvNames, FlagNames};
|
||||
use deckcraft_engine::Session;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -59,10 +57,6 @@ fn main() -> ExitCode {
|
||||
outln!("{page}");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
craft::font_catalog::app::configure(craft::font_catalog::app::AppFonts {
|
||||
dirs: craft::font_catalog::office_font_dirs(&craft::font_catalog::FontEnv::from_process()),
|
||||
..Default::default()
|
||||
});
|
||||
match args.first().map(String::as_str) {
|
||||
Some("help" | "--help" | "-h") => match rest.first() {
|
||||
None => {
|
||||
@@ -672,35 +666,16 @@ fn remark(args: &str) -> &str {
|
||||
after.strip_prefix('(').and_then(|n| n.strip_suffix(')')).unwrap_or(after)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn control_token(flags: ControlOptions) -> Result<String, String> {
|
||||
let names = EnvNames::for_app("DECKCRAFT");
|
||||
let options = ControlOptions::resolve_tokens(flags, &names).map_err(|error| error.to_string())?;
|
||||
craft::automation::security::client_token(options.token.as_deref(), options.token_file.as_deref(), &FlagNames::default(), &names)
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn app(_args: &[String]) -> Result<(), String> {
|
||||
Err("app: connecting to a desktop app requires a native build of deckcraft-cli".into())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn app(args: &[String]) -> Result<(), String> {
|
||||
use deckcraft_mcp::{Backend, Remote, control_addr};
|
||||
let mut port = deckcraft_mcp::DEFAULT_PORT.to_string();
|
||||
let mut method: Option<String> = None;
|
||||
let mut rest = vec![];
|
||||
let mut tokens = ControlOptions::default();
|
||||
let mut it = args.iter().cloned();
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
// PLAN: assumed ControlOptions::take_flag(&mut self, arg: &str, rest: &mut dyn Iterator<Item = String>) -> Result<bool, OptionsError> (platform-w1)
|
||||
if tokens.take_flag(&a, &mut it).map_err(|error| error.to_string())? {
|
||||
continue;
|
||||
}
|
||||
match a.as_str() {
|
||||
"--port" => port = it.next().ok_or("--port needs a value")?,
|
||||
"--method" => method = Some(it.next().ok_or("--method needs a name")?),
|
||||
"--port" => port = it.next().cloned().ok_or("--port needs a value")?,
|
||||
"--method" => method = Some(it.next().cloned().ok_or("--method needs a name")?),
|
||||
"--help" | "-h" => {
|
||||
outln!("{}", help_page("app"));
|
||||
return Ok(());
|
||||
@@ -708,14 +683,8 @@ fn app(args: &[String]) -> Result<(), String> {
|
||||
other => rest.push(other.to_string()),
|
||||
}
|
||||
}
|
||||
let token = control_token(tokens)?;
|
||||
let mut r = Remote::connect(&control_addr(&port), &token).map_err(|e| {
|
||||
if e.kind() == std::io::ErrorKind::PermissionDenied {
|
||||
format!("DeckCraft app on port {port} refused the control token: {e}")
|
||||
} else {
|
||||
format!("no DeckCraft app on port {port} ({e}); start it with `deckcraft --control {port}` and pass its token with --control-token-file PATH or --control-token TOKEN")
|
||||
}
|
||||
})?;
|
||||
let mut r = Remote::connect(&control_addr(&port))
|
||||
.map_err(|e| format!("no DeckCraft app on port {port} ({e}); start it with `deckcraft --control {port}`"))?;
|
||||
let parse = |s: Option<&String>| -> Result<Value, String> {
|
||||
s.map(|j| serde_json::from_str(j).map_err(|e| format!("bad JSON: {e}"))).transpose().map(|v| v.unwrap_or(json!({})))
|
||||
};
|
||||
@@ -732,24 +701,15 @@ fn app(args: &[String]) -> Result<(), String> {
|
||||
|
||||
fn mcp(args: &[String]) -> Result<(), String> {
|
||||
use deckcraft_engine::file_access::{self, AutomationRoots};
|
||||
use deckcraft_mcp::{Backend, Headless, Server};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use deckcraft_mcp::{Remote, control_addr};
|
||||
use deckcraft_mcp::{Backend, Headless, Remote, Server, control_addr};
|
||||
let mut connect: Option<String> = None;
|
||||
let mut sample = false;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let mut tokens = ControlOptions::default();
|
||||
let mut roots_args = automation_args::AutomationArgs::new(None, None);
|
||||
let mut it = args.iter().cloned();
|
||||
while let Some(a) = it.next() {
|
||||
if roots_args.consume(&a, &mut it)? {
|
||||
continue;
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
// PLAN: assumed ControlOptions::take_flag(&mut self, arg: &str, rest: &mut dyn Iterator<Item = String>) -> Result<bool, OptionsError> (platform-w1)
|
||||
if tokens.take_flag(&a, &mut it).map_err(|error| error.to_string())? {
|
||||
continue;
|
||||
}
|
||||
match a.as_str() {
|
||||
"--connect" => connect = Some(it.next().ok_or("--connect needs a port or host:port")?),
|
||||
"--sample" => sample = true,
|
||||
@@ -767,15 +727,7 @@ so drop --connect (or use --connect without the roots)"
|
||||
.into());
|
||||
}
|
||||
let backend: Box<dyn Backend> = match connect {
|
||||
Some(c) => {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
return Err(format!("can't connect to the app at {c}: connected MCP requires a native build of deckcraft-cli"));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let token = control_token(tokens)?;
|
||||
Box::new(Remote::connect(&control_addr(&c), &token).map_err(|e| format!("can't reach the app at {c}: {e}"))?)
|
||||
}
|
||||
}
|
||||
Some(c) => Box::new(Remote::connect(&control_addr(&c)).map_err(|e| format!("can't reach the app at {c}: {e}"))?),
|
||||
None => {
|
||||
let mut h = Headless::new();
|
||||
// `--sample` is the operator's own choice, made before the roots come into force.
|
||||
|
||||
@@ -14,18 +14,21 @@ name = "deckcraft-web"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
craft = { workspace = true, features = ["ui", "automation", "window", "settings", "font-catalog"] }
|
||||
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" }
|
||||
# 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" }
|
||||
egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
craft = { workspace = true, features = ["web-api", "web-host", "platform-browser"] }
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
|
||||
rfd = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "UrlSearchParams"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "MessageEvent", "Event", "EventTarget", "UrlSearchParams"] }
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
//! `window.deckcraft`: the page command API (`craft::web_api`) over the
|
||||
//! `window.deckcraft`: the page command API (`craft-web-api`, storytold/craft-libs#413) over the
|
||||
//! app's own control channel, the one the desktop control server drives (`docs/control-protocol.md`).
|
||||
//!
|
||||
//! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`,
|
||||
//! `screenshot`, as promises with a timeout). This module is DeckCraft's part: a page request that
|
||||
//! queues a [`ControlRequest`](craft::automation::control::ControlRequest) for the app, which answers it on its next frame, and waits for the
|
||||
//! `screenshot`, as promises with a timeout). This module is DeckCraft's part: a [`Request`] that
|
||||
//! queues a [`ControlRequest`] for the app, which answers it on its next frame, and waits for the
|
||||
//! reply. A call the page gave up on is released ([`Pending`]), so the app skips it if it has not started it, instead of
|
||||
//! applying a command the page was told had failed.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicU8;
|
||||
use std::sync::mpsc::{Receiver, TryRecvError};
|
||||
|
||||
use craft::automation::control::Dispatch;
|
||||
use deckcraft_ui_egui::ControlRequest;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// How often a waiting call looks for the app's reply, in milliseconds (about a frame).
|
||||
@@ -20,7 +22,7 @@ const POLL_MS: i32 = 16;
|
||||
/// timeout fired, or the call was abandoned) releases the request: the app skips it if it has not started it (one it has taken still finishes).
|
||||
struct Pending {
|
||||
reply: Receiver<Value>,
|
||||
dispatch: Dispatch,
|
||||
state: Arc<AtomicU8>,
|
||||
answered: bool,
|
||||
}
|
||||
|
||||
@@ -44,7 +46,7 @@ impl Pending {
|
||||
impl Drop for Pending {
|
||||
fn drop(&mut self) {
|
||||
if !self.answered {
|
||||
self.dispatch.give_up();
|
||||
ControlRequest::abandon(&self.state);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,11 +57,11 @@ pub use web::install;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod web {
|
||||
use std::rc::Rc;
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
use std::sync::mpsc::channel;
|
||||
|
||||
use craft::automation::control::ControlRequest;
|
||||
use craft::web_api::methods::Methods;
|
||||
use craft::web_api::page::{PageApi, Request};
|
||||
use craft_web_api::methods::Methods;
|
||||
use craft_web_api::page::{PageApi, Request};
|
||||
use deckcraft_ui_egui::{ControlRequest, SlideApp};
|
||||
use serde_json::json;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
@@ -68,13 +70,14 @@ mod web {
|
||||
/// The app id in `window.<app>`.
|
||||
const APP: &str = "deckcraft";
|
||||
|
||||
/// Return the app's control queue and put `window.deckcraft` on the page. An existing
|
||||
/// Give the app its control queue and put `window.deckcraft` on the page. An existing
|
||||
/// `window.deckcraft` keeps the functions it already has.
|
||||
pub fn install(ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
pub fn install(app: &mut SlideApp, ctx: egui::Context) {
|
||||
let (queue, requests) = channel::<ControlRequest>();
|
||||
app.control_rx = Some(requests);
|
||||
let request: Request = Rc::new(move |method, params| {
|
||||
let (control, reply) = ControlRequest::new(method, params);
|
||||
let mut pending = Pending { reply, dispatch: control.dispatch.clone(), answered: false };
|
||||
let mut pending = Pending { reply, state: control.state.clone(), answered: false };
|
||||
if queue.send(control).is_err() {
|
||||
pending.answered = true;
|
||||
return Box::pin(async { json!({"ok": false, "error": "the app is not running"}) });
|
||||
@@ -92,7 +95,6 @@ mod web {
|
||||
if let Err(e) = Rc::new(PageApi::new(APP, Methods::default(), request)).install() {
|
||||
log::warn!("couldn't install window.{APP}: {e:?}");
|
||||
}
|
||||
requests
|
||||
}
|
||||
|
||||
async fn sleep(ms: i32) {
|
||||
@@ -107,16 +109,43 @@ mod web {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use craft::automation::control::ControlRequest;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// `ControlRequest`'s `state` values (`deckcraft_ui_egui::control`): the app has started it, or its
|
||||
/// sender gave up.
|
||||
const TAKEN: u8 = 1;
|
||||
const ABANDONED: u8 = 2;
|
||||
|
||||
fn pending() -> (Pending, ControlRequest) {
|
||||
let (control, reply) = ControlRequest::new("document.inspect", json!({}));
|
||||
(Pending { reply, state: control.state.clone(), answered: false }, control)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_the_page_gave_up_on_is_released_so_the_app_skips_it() {
|
||||
let (control, reply) = ControlRequest::new("document.inspect", json!({}));
|
||||
let mut waiting = Pending { reply, dispatch: control.dispatch.clone(), answered: false };
|
||||
assert!(waiting.poll().is_none());
|
||||
let (waiting, control) = pending();
|
||||
drop(waiting);
|
||||
assert!(!control.dispatch.start(), "the app must not run a request the page was told had failed");
|
||||
assert_eq!(control.state.load(Ordering::SeqCst), ABANDONED);
|
||||
assert!(!control.take(), "the app must not run a request the page was told had failed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answered_call_is_not_released() {
|
||||
let (mut waiting, control) = pending();
|
||||
assert!(control.take());
|
||||
control.reply.send(json!({"ok": true, "result": 1})).unwrap_or_default();
|
||||
assert_eq!(waiting.poll(), Some(json!({"ok": true, "result": 1})));
|
||||
drop(waiting);
|
||||
assert_eq!(control.state.load(Ordering::SeqCst), TAKEN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_the_app_never_runs_waits_until_it_is_dropped() {
|
||||
let (mut waiting, control) = pending();
|
||||
assert_eq!(waiting.poll(), None);
|
||||
drop(control);
|
||||
assert_eq!(waiting.poll().and_then(|r| r["ok"].as_bool()), Some(false), "the app went away");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The host bridge, for pages that embed DeckCraft and keep its files (a Nextcloud app, a personal
|
||||
//! file server). The messages and the two transports are `craft::web_host`'s
|
||||
//! file server). The messages and the two transports are `craft-web-host`'s
|
||||
//! (storytold/craft-libs), the same contract as the other Craft apps' bridges, with the
|
||||
//! `deckcraft:` prefix. This module is DeckCraft's part of it.
|
||||
//!
|
||||
@@ -15,7 +15,7 @@
|
||||
//! as its file, so Save goes back to it; an outline (.txt, .md, .rtf), a file without a name and
|
||||
//! a damaged file open untitled.
|
||||
//! - `deckcraft:save` (to the host): `{ name, saveAs, bytes }` (with the bytes as a transferred `ArrayBuffer` over `postMessage`) for
|
||||
//! every file delivered through `Files::save` or `Files::write`. The host stores it and reports failures
|
||||
//! every file DeckCraft would otherwise download. The host stores it and reports failures
|
||||
//! itself. `saveAs` says whether the file becomes the presentation's file:
|
||||
//! - Save: `false`. It writes the opened file under its own name and format (a .pptx stays a
|
||||
//! .pptx), as the desktop app does. A name the parent never sent (an untitled presentation, an
|
||||
@@ -36,12 +36,16 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft::web_host::web::{FileData, Host, Message};
|
||||
use deckcraft_ui_egui::SlideApp;
|
||||
use craft_web_host::web::{FileData, Host, Message};
|
||||
use deckcraft_ui_egui::{Services, SlideApp};
|
||||
|
||||
/// The app id in the host messages (`deckcraft:ready`).
|
||||
const APP: &str = "deckcraft";
|
||||
|
||||
/// The name `craft-web-host` gives an open request that carries none (it cleans a host's name and
|
||||
/// falls back to this): no name is no file, so the presentation opens untitled.
|
||||
const NAMELESS: &str = "document";
|
||||
|
||||
/// The largest file a host may send. File › Open on the desktop refuses anything over 2 GiB.
|
||||
/// On wasm32 a `Vec` cannot hold 2 GiB (`isize::MAX` is one byte less), so a file of exactly
|
||||
/// 2 GiB is refused too, before its bytes are copied.
|
||||
@@ -50,7 +54,6 @@ const MAX_OPEN_BYTES: f64 = 2_147_483_648.0;
|
||||
/// The longest user name taken from `?author=` (the preferences' own limit).
|
||||
const MAX_AUTHOR_CHARS: usize = 256;
|
||||
|
||||
/// The embedding page's connection and files waiting for the app to open them.
|
||||
#[derive(Clone)]
|
||||
pub struct Bridge {
|
||||
host: Rc<Host>,
|
||||
@@ -63,7 +66,27 @@ impl Bridge {
|
||||
/// `data-host="page"` on the canvas, an unframed `?host=parent` page (it stays the normal app
|
||||
/// with downloads), or a parent on another origin.
|
||||
pub fn detect(canvas: &web_sys::HtmlCanvasElement) -> Option<Self> {
|
||||
Host::connect(APP, canvas).map(|host| Self { host: Rc::new(host), opened: Rc::default() })
|
||||
let host = Host::connect(APP, canvas)?;
|
||||
// An opaque origin (a file:// page in some browsers) can't be a postMessage target.
|
||||
if host.mode() == craft_web_host::Mode::Parent && web_sys::window()?.location().origin().ok()? == "null" {
|
||||
return None;
|
||||
}
|
||||
Some(Self { host: Rc::new(host), opened: Rc::default() })
|
||||
}
|
||||
|
||||
/// Hand saved and exported files to the host instead of downloading them, and hear the files
|
||||
/// it sends.
|
||||
pub fn connect(&self, services: &mut Services, ctx: egui::Context) {
|
||||
self.listen(ctx);
|
||||
let bridge = self.clone();
|
||||
services.host_save = Some(Box::new(move |name: &str, bytes: &[u8], save_as: bool| bridge.post_save(name, bytes, save_as)));
|
||||
// Exports and Print are copies.
|
||||
let bridge = self.clone();
|
||||
services.download = Some(Box::new(move |name: &str, bytes: &[u8]| {
|
||||
if let Err(e) = bridge.post_save(name, bytes, false) {
|
||||
log::error!("couldn't hand {name} to the page: {e}");
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
/// `?author=`: the host's name for the user signs new comments.
|
||||
@@ -74,7 +97,6 @@ impl Bridge {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tell the embedding page it can send files after the runner has started.
|
||||
pub fn post_ready(&self) {
|
||||
let _ = self.host.post_ready(env!("CARGO_PKG_VERSION"), false);
|
||||
}
|
||||
@@ -84,7 +106,7 @@ impl Bridge {
|
||||
let _ = self.host.post_failed(error, None);
|
||||
}
|
||||
|
||||
/// Opens the files the page sent since the last call.
|
||||
/// Before each frame: open the files the host sent.
|
||||
pub fn open_files(&self, app: &mut SlideApp) {
|
||||
let opened = std::mem::take(&mut *self.opened.borrow_mut());
|
||||
for (name, bytes) in opened {
|
||||
@@ -98,22 +120,28 @@ impl Bridge {
|
||||
self.host.post_dirty(app.session.documents().iter().any(|d| d.is_dirty()));
|
||||
}
|
||||
|
||||
fn post_save(&self, path: &str, bytes: &[u8], save_as: bool) -> Result<(), String> {
|
||||
let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());
|
||||
self.host.post_save(&name, bytes, None, save_as)
|
||||
}
|
||||
|
||||
/// Hear `deckcraft:open` and queue the file for the next frame.
|
||||
pub fn listen(&self, ctx: egui::Context) {
|
||||
fn listen(&self, ctx: egui::Context) {
|
||||
let opened = self.opened.clone();
|
||||
let host = self.host.clone();
|
||||
self.host.listen(move |message| {
|
||||
let Message::Open { name, data } = message else { return };
|
||||
if data.size() >= MAX_OPEN_BYTES {
|
||||
let label = name.as_deref().unwrap_or("a file");
|
||||
log::warn!("host file {label} is 2 GiB or larger; not opened");
|
||||
let _ = host.post_failed(&format!("{label} is 2 GiB or larger, which DeckCraft's web build cannot open"), None);
|
||||
log::warn!("host file {name} is 2 GiB or larger; not opened");
|
||||
let _ = host.post_failed(&format!("{name} is 2 GiB or larger, which DeckCraft's web build cannot open"), None);
|
||||
return;
|
||||
}
|
||||
let FileData::Bytes(array) = data else {
|
||||
log::warn!("host file {} came as a File; DeckCraft reads bytes only; not opened", name.as_deref().unwrap_or("a file"));
|
||||
log::warn!("host file {name} came as a File; DeckCraft reads bytes only; not opened");
|
||||
return;
|
||||
};
|
||||
// No name is no file: the presentation opens untitled, never under an invented name.
|
||||
let name = (name != NAMELESS).then_some(name);
|
||||
opened.borrow_mut().push((name, array.to_vec()));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
|
||||
@@ -6,8 +6,11 @@
|
||||
//!
|
||||
//! Differences from the desktop app:
|
||||
//! - no TCP control channel (browsers can't listen on sockets);
|
||||
//! - pickers, saves and drops use the framework's browser services, which read files asynchronously;
|
||||
//! - Save and Export reach the framing page through `Files` when hosted, or use browser saves;
|
||||
//! - File → Open and Insert → Pictures/Audio/Video use the browser file picker; bytes arrive
|
||||
//! asynchronously through `Services::inbox`, applied to the document, slide and operation
|
||||
//! that started the pick (a dismissed picker or a closed document drops the file);
|
||||
//! - Save and Export trigger a browser download (or go to the framing page with `?host=parent`);
|
||||
//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox;
|
||||
//! - preferences are not persisted.
|
||||
//!
|
||||
//! URL query flags: `?webgl` forces the WebGL2 backend instead of WebGPU; `?blank` starts with an
|
||||
|
||||
+284
-169
@@ -1,191 +1,306 @@
|
||||
//! Browser presenter peer; the audience owns playback and this page emits requests.
|
||||
//! Same-origin popup transport. Each window starts its own eframe/WASM runner.
|
||||
use deckcraft_ui_egui::presenter::{Command, DeltaCache, Host, Snapshot, View};
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::VecDeque,
|
||||
rc::{Rc, Weak},
|
||||
};
|
||||
use wasm_bindgen::{JsCast, closure::Closure};
|
||||
|
||||
use craft::i18n::Word;
|
||||
use craft::ui::contract::{Politeness, Props as _, Show as _};
|
||||
use craft::ui::fonts::{I18nScripts, UiFonts};
|
||||
use craft::ui::notices::{Notice, NoticeLayout};
|
||||
use craft::ui::primitives::{CachedTexture, Revision, TextureStore, TextureStoreOptions};
|
||||
use craft::ui::runtime::env::WindowKey;
|
||||
use craft::ui::runtime::frame::FrameInput;
|
||||
use craft::ui::shell::{AppShell, embed};
|
||||
use craft::web_host::link::{LinkLimits, LinkState, WindowLink};
|
||||
use craft::web_host::popup::{PopupOpener, PopupPeer};
|
||||
use deckcraft_ui_egui::presenter::{Command, Preview, Snapshot, SnapshotDelta, merge};
|
||||
// PLAN: assumed pub const SHOW_SCOPE: craft::ui::runtime::commands::CommandScope in presenter_view (show-w7)
|
||||
use deckcraft_ui_egui::presenter_view::{NextPic, PresenterModel, PreviewPic, SHOW_SCOPE, presenter_body};
|
||||
use deckcraft_ui_egui::show::{Blank, GridSource};
|
||||
|
||||
const MAX_SNAPSHOT: usize = 16 * 1024 * 1024;
|
||||
const MAX_COMMAND: usize = 8192;
|
||||
|
||||
fn limits(max_in: usize, max_out: usize) -> LinkLimits {
|
||||
let mut limits = LinkLimits::default();
|
||||
limits.max_in = max_in;
|
||||
limits.max_out = max_out;
|
||||
limits.max_queued = 64;
|
||||
limits
|
||||
const MAX_MESSAGE: usize = 16 * 1024 * 1024;
|
||||
const MAX_COMMANDS: usize = 64;
|
||||
const PREFIX: &str = "#deckcraft-presenter=";
|
||||
fn error(e: wasm_bindgen::JsValue) -> String {
|
||||
format!("{e:?}")
|
||||
}
|
||||
|
||||
/// Creates the audience's presenter link; opening it remains a user action.
|
||||
pub fn opener(ctx: &egui::Context) -> Option<Box<dyn WindowLink>> {
|
||||
let ctx = ctx.clone();
|
||||
PopupOpener::new("deckcraft", "popup,width=1100,height=700", limits(MAX_COMMAND, MAX_SNAPSHOT), move || ctx.request_repaint())
|
||||
.ok()
|
||||
.map(|link| Box::new(link) as Box<dyn WindowLink>)
|
||||
fn origin() -> Result<String, String> {
|
||||
web_sys::window().ok_or("No browser window")?.location().origin().map_err(error)
|
||||
}
|
||||
|
||||
// Separate variants keep slide zero distinct from either large preview.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
enum Picture {
|
||||
Current,
|
||||
Next,
|
||||
Slide(usize),
|
||||
pub fn token() -> Option<String> {
|
||||
let hash = web_sys::window()?.location().hash().ok()?;
|
||||
let token = hash.strip_prefix(PREFIX)?;
|
||||
(!token.is_empty() && token.len() < 128).then(|| token.to_owned())
|
||||
}
|
||||
|
||||
/// A presenter page with its own show command scope and no playback state.
|
||||
pub struct PopupApp {
|
||||
peer: PopupPeer,
|
||||
snapshot: Option<Snapshot>,
|
||||
/// The number of the last delta received.
|
||||
seq: Option<u64>,
|
||||
textures: TextureStore<Picture>,
|
||||
current_revision: u64,
|
||||
next_revision: u64,
|
||||
slides_revision: u64,
|
||||
fn same_source(event: &web_sys::MessageEvent, window: &web_sys::Window, expected_origin: &str) -> bool {
|
||||
event.origin() == expected_origin && event.source().is_some_and(|source| js_sys::Object::is(source.as_ref(), window.as_ref()))
|
||||
}
|
||||
|
||||
impl PopupApp {
|
||||
/// Installs the page runtime and connects to its same-origin audience window.
|
||||
pub fn new(ctx: &egui::Context, install: craft::ui::runtime::InstallSpec) -> Result<Self, String> {
|
||||
embed::install(ctx, install, &UiFonts::new(&I18nScripts)).map_err(|error| error.to_string())?;
|
||||
let wake = ctx.clone();
|
||||
let peer = PopupPeer::connect("deckcraft", limits(MAX_SNAPSHOT, MAX_COMMAND), move || wake.request_repaint())
|
||||
.ok_or_else(|| "The audience window is unavailable".to_owned())?;
|
||||
if let Some(document) = web_sys::window().and_then(|window| window.document()) {
|
||||
document.set_title("Presenter View — DeckCraft");
|
||||
}
|
||||
Ok(Self {
|
||||
peer,
|
||||
snapshot: None,
|
||||
seq: None,
|
||||
textures: TextureStore::in_context(ctx, "deckcraft.popup", TextureStoreOptions::frames()),
|
||||
current_revision: 0,
|
||||
next_revision: 0,
|
||||
slides_revision: 0,
|
||||
})
|
||||
fn send(window: &web_sys::Window, origin: &str, value: serde_json::Value) -> Result<(), String> {
|
||||
let text = serde_json::to_string(&value).map_err(|e| e.to_string())?;
|
||||
if text.len() > MAX_MESSAGE {
|
||||
return Err("Presenter message is too large".into());
|
||||
}
|
||||
|
||||
fn receive(&mut self, ctx: &egui::Context) {
|
||||
// take drains only this pass's arrivals; a second pass sees no replay of earlier deltas.
|
||||
for payload in self.peer.take() {
|
||||
let Some(delta) = SnapshotDelta::from_payload(&payload) else { continue };
|
||||
if self.seq.is_some_and(|seq| delta.seq != seq.wrapping_add(1)) {
|
||||
// A full inbox dropped a delta, which may have carried an image: ask for every image again.
|
||||
let _ = self.peer.post(&Command::Resync.to_payload());
|
||||
window.post_message(&wasm_bindgen::JsValue::from_str(&text), origin).map_err(error)
|
||||
}
|
||||
struct State {
|
||||
popup: Option<web_sys::Window>,
|
||||
token: String,
|
||||
commands: VecDeque<Command>,
|
||||
ready: bool,
|
||||
refresh_images: bool,
|
||||
}
|
||||
pub struct BrowserHost {
|
||||
state: Rc<RefCell<State>>,
|
||||
origin: String,
|
||||
listener: Closure<dyn FnMut(web_sys::MessageEvent)>,
|
||||
button: Option<(web_sys::HtmlElement, Closure<dyn FnMut(web_sys::Event)>)>,
|
||||
images: DeltaCache,
|
||||
}
|
||||
impl BrowserHost {
|
||||
pub fn new(ctx: egui::Context) -> Result<Self, String> {
|
||||
let window = web_sys::window().ok_or("No browser window")?;
|
||||
let origin = origin()?;
|
||||
let state = Rc::new(RefCell::new(State { popup: None, token: String::new(), commands: VecDeque::new(), ready: false, refresh_images: true }));
|
||||
let weak = Rc::downgrade(&state);
|
||||
let expected = origin.clone();
|
||||
let listener = Closure::new(move |event: web_sys::MessageEvent| {
|
||||
let Some(state) = weak.upgrade() else { return };
|
||||
let Ok(mut state) = state.try_borrow_mut() else { return };
|
||||
let Some(popup) = state.popup.as_ref() else { return };
|
||||
if !same_source(&event, popup, &expected) {
|
||||
return;
|
||||
}
|
||||
self.seq = Some(delta.seq);
|
||||
if delta.current_changed {
|
||||
self.current_revision = self.current_revision.wrapping_add(1);
|
||||
self.textures.forget(ctx, &Picture::Current);
|
||||
let Some(text) = event.data().as_string().filter(|s| s.len() <= 8192) else { return };
|
||||
let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else { return };
|
||||
if value.get("token").and_then(|v| v.as_str()) != Some(state.token.as_str()) {
|
||||
return;
|
||||
}
|
||||
if delta.next_changed {
|
||||
self.next_revision = self.next_revision.wrapping_add(1);
|
||||
self.textures.forget(ctx, &Picture::Next);
|
||||
match value.get("kind").and_then(|v| v.as_str()) {
|
||||
Some("ready") => {
|
||||
state.ready = true;
|
||||
state.refresh_images = true;
|
||||
}
|
||||
Some("command") if state.commands.len() < MAX_COMMANDS => {
|
||||
if let Some(command) = value.get("command").and_then(|v| serde_json::from_value(v.clone()).ok()) {
|
||||
state.commands.push_back(command);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if delta.snapshot.slides.is_some() {
|
||||
self.slides_revision = self.slides_revision.wrapping_add(1);
|
||||
self.textures.retain(ctx, |key| !matches!(key, Picture::Slide(_)));
|
||||
}
|
||||
self.snapshot = Some(merge(self.snapshot.as_ref(), delta));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
window.add_event_listener_with_callback("message", listener.as_ref().unchecked_ref()).map_err(error)?;
|
||||
Ok(Self { state, origin, listener, button: None, images: DeltaCache::default() })
|
||||
}
|
||||
fn remove_button(&mut self) {
|
||||
if let Some((button, callback)) = self.button.take() {
|
||||
let _ = button.remove_event_listener_with_callback("click", callback.as_ref().unchecked_ref());
|
||||
button.remove();
|
||||
}
|
||||
}
|
||||
|
||||
fn picture(&self, ctx: &egui::Context, key: Picture, revision: u64, preview: Option<&Preview>) -> Option<CachedTexture> {
|
||||
let preview = preview?;
|
||||
let revision = Revision::new(revision);
|
||||
self.textures.state(ctx, &key, revision).shown().or_else(|| Some(self.textures.put(ctx, key, revision, preview.image()?)))
|
||||
}
|
||||
|
||||
fn page(&mut self, ui: &mut egui::Ui, cx: &mut craft::ui::contract::BodyCx<'_>) {
|
||||
let notice = if self.peer.state() == LinkState::Closed {
|
||||
Some(("The audience window has closed.", ""))
|
||||
} else if js_sys::Date::now() - self.peer.last_heard() > 10_000.0 {
|
||||
Some(("The audience window is not responding.", "Return to the audience window to resume the connection."))
|
||||
} else if self.snapshot.is_none() {
|
||||
Some(("Waiting for the audience window…", ""))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some((title, detail)) = notice {
|
||||
Notice::new(craft::theme::variant::Tone::Info, Word::plain(detail))
|
||||
.id_salt("audience-link-state")
|
||||
.title(Word::plain(title))
|
||||
.layout(NoticeLayout::Centred)
|
||||
.announce(Politeness::Polite)
|
||||
.show(ui);
|
||||
fn recovery_button(&mut self) {
|
||||
if self.button.is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(snapshot) = &self.snapshot else { return };
|
||||
let current = self.picture(ui.ctx(), Picture::Current, self.current_revision, snapshot.current.as_ref());
|
||||
let next = self.picture(ui.ctx(), Picture::Next, self.next_revision, snapshot.next.as_ref());
|
||||
// Slide(0), Slide(1), Slide(2) remain tiles 1, 2, 3; a malformed image must not shift later picks.
|
||||
let slides: Vec<_> = snapshot
|
||||
.slides
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, preview)| self.picture(ui.ctx(), Picture::Slide(index), self.slides_revision, Some(preview)))
|
||||
.collect::<Option<_>>()
|
||||
.unwrap_or_default();
|
||||
let model = PresenterModel {
|
||||
aspect: snapshot.aspect,
|
||||
slide: snapshot.slide,
|
||||
total: snapshot.total,
|
||||
ended: snapshot.ended,
|
||||
elapsed: snapshot.elapsed,
|
||||
paused: snapshot.paused,
|
||||
notes: &snapshot.notes,
|
||||
notes_px: snapshot.notes_px,
|
||||
blank: match snapshot.blank.as_deref() {
|
||||
Some("black") => Some(Blank::Black),
|
||||
Some("white") => Some(Blank::White),
|
||||
_ => None,
|
||||
},
|
||||
grid: snapshot.grid,
|
||||
zoom_armed: snapshot.zoom_armed,
|
||||
zoomed: snapshot.zoomed,
|
||||
zoom_frame: None,
|
||||
current: current.as_ref().map_or(PreviewPic::Pending, PreviewPic::Shown),
|
||||
next: if let Some(next) = &next {
|
||||
NextPic::Shown(next)
|
||||
} else if snapshot.slide.saturating_add(1) >= snapshot.total {
|
||||
NextPic::End
|
||||
} else {
|
||||
NextPic::Pending
|
||||
},
|
||||
slides: GridSource::Pictures(&slides),
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
presenter_body(ui, cx, &model, &mut out);
|
||||
for command in out {
|
||||
let _ = self.peer.post(&command.to_payload());
|
||||
let Some(document) = web_sys::window().and_then(|w| w.document()) else { return };
|
||||
let Some(body) = document.body() else { return };
|
||||
let Ok(element) = document.create_element("button") else { return };
|
||||
let Ok(button) = element.dyn_into::<web_sys::HtmlElement>() else { return };
|
||||
button.set_text_content(Some("Open presenter window"));
|
||||
let _ = button.set_attribute("style", "position:fixed;top:12px;right:12px;z-index:9999;padding:12px;color:white;background:#333;border:1px solid #aaa;border-radius:4px;cursor:pointer");
|
||||
let weak: Weak<RefCell<State>> = Rc::downgrade(&self.state);
|
||||
let button_copy = button.clone();
|
||||
let callback = Closure::new(move |_event: web_sys::Event| {
|
||||
if let Some(state) = weak.upgrade() {
|
||||
match open_popup(&state) {
|
||||
Ok(()) => {
|
||||
button_copy.set_text_content(Some("Opening presenter window…"));
|
||||
}
|
||||
Err(_) => {
|
||||
button_copy.set_text_content(Some("Popup blocked. Allow popups, then click to retry."));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if button.add_event_listener_with_callback("click", callback.as_ref().unchecked_ref()).is_ok() && body.append_child(&button).is_ok() {
|
||||
self.button = Some((button, callback));
|
||||
} else {
|
||||
let _ = button.remove_event_listener_with_callback("click", callback.as_ref().unchecked_ref());
|
||||
button.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
fn open_popup(state: &Rc<RefCell<State>>) -> Result<(), String> {
|
||||
let window = web_sys::window().ok_or("No browser window")?;
|
||||
let mut state = state.try_borrow_mut().map_err(|_| "Presenter is busy")?;
|
||||
if let Some(popup) = &state.popup
|
||||
&& !popup.closed().unwrap_or(true)
|
||||
{
|
||||
let _ = popup.focus();
|
||||
return Ok(());
|
||||
}
|
||||
let token = format!("{}-{}", js_sys::Date::now(), js_sys::Math::random());
|
||||
let url = web_sys::Url::new(&window.location().href().map_err(error)?).map_err(error)?;
|
||||
url.set_hash(&format!("{PREFIX}{token}"));
|
||||
let popup = window
|
||||
.open_with_url_and_target_and_features(&url.href(), "_blank", "popup,width=1100,height=700")
|
||||
.map_err(error)?
|
||||
.ok_or("Presenter popup was blocked. Use Open presenter window to retry.")?;
|
||||
if popup.closed().unwrap_or(true) {
|
||||
return Err("Browser isolation prevented connecting the presenter window".into());
|
||||
}
|
||||
state.popup = Some(popup);
|
||||
state.token = token;
|
||||
state.commands.clear();
|
||||
state.ready = false;
|
||||
Ok(())
|
||||
}
|
||||
impl Host for BrowserHost {
|
||||
fn open(&mut self) -> Result<(), String> {
|
||||
self.close();
|
||||
let result = open_popup(&self.state);
|
||||
if result.is_err() {
|
||||
self.recovery_button();
|
||||
}
|
||||
result
|
||||
}
|
||||
fn is_open(&self) -> bool {
|
||||
self.state.borrow().popup.as_ref().is_some_and(|w| !w.closed().unwrap_or(true))
|
||||
}
|
||||
fn commands(&mut self) -> Vec<Command> {
|
||||
self.state.borrow_mut().commands.drain(..).collect()
|
||||
}
|
||||
fn update(&mut self, snapshot: Snapshot) {
|
||||
if !self.is_open() {
|
||||
self.recovery_button();
|
||||
return;
|
||||
}
|
||||
self.remove_button();
|
||||
let mut state = self.state.borrow_mut();
|
||||
if !state.ready {
|
||||
return;
|
||||
}
|
||||
if let Some(popup) = state.popup.clone() {
|
||||
let token = state.token.clone();
|
||||
let sent = self.images.send(snapshot, &token, state.refresh_images, |delta, current_changed, next_changed| {
|
||||
send(
|
||||
&popup,
|
||||
&self.origin,
|
||||
serde_json::json!({"kind":"snapshot", "token":token, "snapshot":delta,
|
||||
"currentChanged":current_changed, "nextChanged":next_changed}),
|
||||
)
|
||||
});
|
||||
if sent.is_ok() {
|
||||
state.refresh_images = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
fn close(&mut self) {
|
||||
self.remove_button();
|
||||
let mut state = self.state.borrow_mut();
|
||||
if let Some(window) = state.popup.take() {
|
||||
let _ = window.close();
|
||||
}
|
||||
state.commands.clear();
|
||||
state.ready = false;
|
||||
state.token.clear();
|
||||
}
|
||||
}
|
||||
impl Drop for BrowserHost {
|
||||
fn drop(&mut self) {
|
||||
self.close();
|
||||
if let Some(window) = web_sys::window() {
|
||||
let _ = window.remove_event_listener_with_callback("message", self.listener.as_ref().unchecked_ref());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl eframe::App for PopupApp {
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, _input: &mut egui::RawInput) {
|
||||
embed::before_input(ctx, |_| FrameInput::new(deckcraft_ui_egui::theme::root_env()));
|
||||
pub struct Popup {
|
||||
token: String,
|
||||
origin: String,
|
||||
opener: web_sys::Window,
|
||||
snapshot: Rc<RefCell<Option<Snapshot>>>,
|
||||
last_received: Rc<RefCell<f64>>,
|
||||
listener: Closure<dyn FnMut(web_sys::MessageEvent)>,
|
||||
view: View,
|
||||
}
|
||||
impl Popup {
|
||||
pub fn new(token: String, ctx: egui::Context) -> Result<Self, String> {
|
||||
let window = web_sys::window().ok_or("No browser window")?;
|
||||
// `opener` is a WindowProxy from another realm; instanceof Window can fail across
|
||||
// realms. The browser API supplies a WindowProxy or null, and messages still verify
|
||||
// exact source identity and origin before any data is accepted.
|
||||
let opener = window.opener().map_err(error)?;
|
||||
if opener.is_null() || opener.is_undefined() {
|
||||
return Err("The audience window is unavailable".into());
|
||||
}
|
||||
let opener: web_sys::Window = opener.unchecked_into();
|
||||
let origin = origin()?;
|
||||
let snapshot: Rc<RefCell<Option<Snapshot>>> = Rc::new(RefCell::new(None));
|
||||
let last_received = Rc::new(RefCell::new(js_sys::Date::now()));
|
||||
let received = last_received.clone();
|
||||
let target = snapshot.clone();
|
||||
let expected_origin = origin.clone();
|
||||
let expected_opener = opener.clone();
|
||||
let expected_token = token.clone();
|
||||
let listener = Closure::new(move |event: web_sys::MessageEvent| {
|
||||
if !same_source(&event, &expected_opener, &expected_origin) {
|
||||
return;
|
||||
}
|
||||
let Some(text) = event.data().as_string().filter(|s| s.len() <= MAX_MESSAGE) else { return };
|
||||
let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else { return };
|
||||
if value.get("token").and_then(|v| v.as_str()) != Some(expected_token.as_str())
|
||||
|| value.get("kind").and_then(|v| v.as_str()) != Some("snapshot")
|
||||
{
|
||||
return;
|
||||
}
|
||||
if let Some(mut data) = value.get("snapshot").and_then(|v| serde_json::from_value::<Snapshot>(v.clone()).ok()) {
|
||||
if let Some(previous) = target.borrow().as_ref() {
|
||||
if value.get("currentChanged").and_then(|v| v.as_bool()) == Some(false) {
|
||||
data.current = previous.current.clone();
|
||||
}
|
||||
if value.get("nextChanged").and_then(|v| v.as_bool()) == Some(false) {
|
||||
data.next = previous.next.clone();
|
||||
}
|
||||
if data.slides.is_none() {
|
||||
data.slides = previous.slides.clone();
|
||||
}
|
||||
}
|
||||
*target.borrow_mut() = Some(data);
|
||||
*received.borrow_mut() = js_sys::Date::now();
|
||||
ctx.request_repaint();
|
||||
}
|
||||
});
|
||||
window.add_event_listener_with_callback("message", listener.as_ref().unchecked_ref()).map_err(error)?;
|
||||
if let Some(document) = window.document() {
|
||||
document.set_title("Presenter View — DeckCraft");
|
||||
}
|
||||
let popup = Self { token, origin, opener, snapshot, last_received, listener, view: View::default() };
|
||||
send(&popup.opener, &popup.origin, serde_json::json!({"kind":"ready","token":popup.token}))?;
|
||||
Ok(popup)
|
||||
}
|
||||
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
embed::logic(ctx, || embed::CloseDecision::Close);
|
||||
}
|
||||
|
||||
}
|
||||
impl eframe::App for Popup {
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
self.receive(ui.ctx());
|
||||
let snapshot = self.snapshot.borrow();
|
||||
let notes = snapshot.as_ref().map_or("", |snapshot| snapshot.notes.as_str());
|
||||
if !self.view.prepare(ui.ctx(), notes) {
|
||||
return;
|
||||
}
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_millis(500));
|
||||
AppShell::new(WindowKey::main()).page(true, SHOW_SCOPE, |_| None, |ui, cx, app: &mut Self| app.page(ui, cx)).show(ui, self);
|
||||
if self.opener.closed().unwrap_or(true) {
|
||||
ui.heading("The audience window has closed.");
|
||||
return;
|
||||
}
|
||||
if js_sys::Date::now() - *self.last_received.borrow() > 10_000.0 {
|
||||
ui.heading("The audience window is not responding.");
|
||||
ui.label("Return to the audience window to resume the connection.");
|
||||
return;
|
||||
}
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
if let Some(snapshot) = snapshot.as_ref() {
|
||||
for command in self.view.ui(ui, snapshot) {
|
||||
let _ = send(&self.opener, &self.origin, serde_json::json!({"kind":"command","token":self.token,"command":command}));
|
||||
}
|
||||
} else {
|
||||
ui.label("Waiting for the audience window…");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
impl Drop for Popup {
|
||||
fn drop(&mut self) {
|
||||
if let Some(window) = web_sys::window() {
|
||||
let _ = window.remove_event_listener_with_callback("message", self.listener.as_ref().unchecked_ref());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+133
-82
@@ -1,21 +1,13 @@
|
||||
//! The browser shell: platform services, the embedding page, and the eframe web runner.
|
||||
//! The browser shell: web `Services`, drag-and-drop, and the eframe web runner.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::automation::control::ControlChannel;
|
||||
use craft::host::target::ShellInfo;
|
||||
use craft::host::{AppInfo, Host, Wake};
|
||||
use craft::platform::browser_files::BrowserFiles;
|
||||
use craft::platform::open::{DroppedFile, FileIntake, IntakeSender};
|
||||
use craft::settings::Location;
|
||||
use craft::ui::runtime::InstallSpec;
|
||||
use craft::ui::runtime::env::SystemReader;
|
||||
use craft::web_host::link::role_token;
|
||||
use craft::window::policy::Frame;
|
||||
use craft::window::system::SystemWindows;
|
||||
use deckcraft_ui_egui::{Platform, SlideApp};
|
||||
use deckcraft_engine::Session;
|
||||
use deckcraft_ui_egui::{Inbox, InboxEvent, InboxFile, Services, SlideApp};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
|
||||
const PRESENTATION_EXTS: &[&str] = &["deckcraft", "pptx", "potx", "ppsx", "ppt", "pot", "pps", "txt", "md"];
|
||||
const PICTURE_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "tif", "tiff"];
|
||||
const AUDIO_EXTS: &[&str] = &["wav", "mp3", "m4a", "aac", "flac", "ogg", "opus", "aif", "aiff"];
|
||||
const VIDEO_EXTS: &[&str] = &["mp4", "m4v", "mov", "webm"];
|
||||
const CANVAS_ID: &str = "deckcraft_canvas";
|
||||
const LOADING_ID: &str = "deckcraft_loading";
|
||||
|
||||
@@ -23,7 +15,6 @@ const LOADING_ID: &str = "deckcraft_loading";
|
||||
/// build the sample or blank deck, and replace the loading element when launch finishes.
|
||||
pub fn start() {
|
||||
eframe::WebLogger::init(log::LevelFilter::Info).ok();
|
||||
craft::font_catalog::app::start(craft::font_catalog::app::AppFonts { store_poll: None, ..Default::default() });
|
||||
wasm_bindgen_futures::spawn_local(async {
|
||||
let Some(document) = web_sys::window().and_then(|w| w.document()) else {
|
||||
log::error!("no document");
|
||||
@@ -37,8 +28,7 @@ pub fn start() {
|
||||
// opens presentations in it and stores what it saves (`host`); `data-host="page"` on the
|
||||
// canvas opts a page in that runs DeckCraft in its own document. The presenter popup is
|
||||
// never the framed page.
|
||||
let hash = web_sys::window().and_then(|window| window.location().hash().ok()).unwrap_or_default();
|
||||
let hosted = role_token(&hash).is_none();
|
||||
let hosted = crate::presenter::token().is_none();
|
||||
let bridge = if hosted { crate::host::Bridge::detect(&canvas) } else { None };
|
||||
if hosted && bridge.is_none() && query_param("host").as_deref() == Some("parent") {
|
||||
log::warn!("?host=parent needs a framing page on the same origin; saves download instead");
|
||||
@@ -58,38 +48,20 @@ pub fn start() {
|
||||
if let Some(rs) = &cc.wgpu_render_state {
|
||||
log::info!("deckcraft-web {}: wgpu backend {:?}", env!("CARGO_PKG_VERSION"), rs.adapter.get_info().backend);
|
||||
}
|
||||
let shell_info = ShellInfo::default();
|
||||
let repaint = cc.egui_ctx.clone();
|
||||
let install = InstallSpec::new(shell_info, Arc::new(SystemWindows))
|
||||
.system(SystemReader::start(move || repaint.request_repaint()))
|
||||
.app_id(deckcraft_ui_egui::os_window::app_id());
|
||||
if role_token(&hash).is_some() {
|
||||
let presenter = crate::presenter::PopupApp::new(&cc.egui_ctx, install).map_err(std::io::Error::other)?;
|
||||
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>);
|
||||
}
|
||||
let wake = cc.egui_ctx.clone();
|
||||
let files = BrowserFiles::new(move || wake.request_repaint());
|
||||
let files = if app_bridge.is_some() { files.page_saves(craft::web_host::files::page_save) } else { files };
|
||||
let host = Host::builder(AppInfo { id: "deckcraft", name: "DeckCraft", version: env!("CARGO_PKG_VERSION") })
|
||||
.files(Arc::new(files))
|
||||
.build();
|
||||
let wake = cc.egui_ctx.clone();
|
||||
let (intake, drops) = FileIntake::new(Wake::new(move || wake.request_repaint()));
|
||||
let platform = Platform {
|
||||
install,
|
||||
host,
|
||||
settings: Location::Memory,
|
||||
intake: Some(intake),
|
||||
audio_out: None,
|
||||
control: Some(ControlChannel::new(crate::api::install(cc.egui_ctx.clone()))),
|
||||
frame: Frame::Native,
|
||||
at_exit: None,
|
||||
};
|
||||
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 {
|
||||
bridge.listen(cc.egui_ctx.clone());
|
||||
bridge.connect(&mut services, cc.egui_ctx.clone());
|
||||
}
|
||||
let mut app = SlideApp::new(&cc.egui_ctx, platform).map_err(|error| std::io::Error::other(error.to_string()))?;
|
||||
app.services.presenter = crate::presenter::opener(&cc.egui_ctx);
|
||||
let mut app = SlideApp::new(Session::new(), services);
|
||||
// In host mode the parent sends the presentation to edit; no sample meanwhile.
|
||||
if app_bridge.is_some() {
|
||||
if let Err(e) = app.start_for_host() {
|
||||
@@ -110,7 +82,8 @@ pub fn start() {
|
||||
{
|
||||
crate::host::Bridge::set_author(&mut app, &author);
|
||||
}
|
||||
Ok(Box::new(WebShell { app, bridge: app_bridge, drops }))
|
||||
crate::api::install(&mut app, cc.egui_ctx.clone());
|
||||
Ok(Box::new(WebShell { app, inbox, bridge: app_bridge }))
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
@@ -124,20 +97,7 @@ pub fn start() {
|
||||
if let Some(el) = document.get_element_by_id(LOADING_ID) {
|
||||
match result {
|
||||
Ok(()) => el.remove(),
|
||||
Err(e) => {
|
||||
el.set_text_content(None);
|
||||
for text in [format!("DeckCraft failed to start: {e:?}"), "A browser with WebGPU or WebGL2 is required.".to_owned()] {
|
||||
match document.create_element("p") {
|
||||
Ok(paragraph) => {
|
||||
paragraph.set_text_content(Some(&text));
|
||||
if let Err(error) = el.append_child(¶graph) {
|
||||
log::error!("couldn't display startup failure: {error:?}");
|
||||
}
|
||||
}
|
||||
Err(error) => log::error!("couldn't display startup failure: {error:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => el.set_inner_html(&format!("<p>DeckCraft failed to start: {e:?}</p><p>A browser with WebGPU or WebGL2 is required.</p>")),
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -157,13 +117,13 @@ fn query_has(key: &str) -> bool {
|
||||
web_sys::UrlSearchParams::new_with_str(&query()).is_ok_and(|q| q.has(key))
|
||||
}
|
||||
|
||||
/// Opens the embedding page's files before app logic and reports dirtiness afterwards.
|
||||
/// Wraps the app to read dropped files asynchronously (browsers can't read them synchronously)
|
||||
/// and feed them through the inbox.
|
||||
struct WebShell {
|
||||
app: SlideApp,
|
||||
inbox: Inbox,
|
||||
/// The parent page that keeps the files (`?host=parent`).
|
||||
bridge: Option<crate::host::Bridge>,
|
||||
/// Feeds the files dropped on the canvas into the app's intake once the browser has read them.
|
||||
drops: IntakeSender,
|
||||
}
|
||||
|
||||
impl eframe::App for WebShell {
|
||||
@@ -174,6 +134,7 @@ 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);
|
||||
}
|
||||
@@ -184,33 +145,123 @@ impl eframe::App for WebShell {
|
||||
}
|
||||
}
|
||||
|
||||
/// Delegate only this pass's input to the app's framework hooks. Browsers read dropped files
|
||||
/// only asynchronously: this pass's drops are taken here and reach the app's intake, in drop
|
||||
/// order, once read. A file that cannot be read arrives without bytes, which the app reports.
|
||||
/// Consume browser drops with fresh input, capture the identity before the asynchronous read,
|
||||
/// and deliver the id, name, and bytes through the inbox.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
let dropped = std::mem::take(&mut raw.dropped_files);
|
||||
if !dropped.is_empty() {
|
||||
let drops = self.drops.clone();
|
||||
// Browsers cannot read dropped files synchronously. Consume this pass's drops here, with
|
||||
// fresh input, and capture the document/slide before the asynchronous read finishes.
|
||||
for f in std::mem::take(&mut raw.dropped_files) {
|
||||
let id = self.app.begin_external_file("drop");
|
||||
let inbox = self.inbox.clone();
|
||||
let ctx = ctx.clone();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let mut files = Vec::with_capacity(dropped.len());
|
||||
for file in dropped {
|
||||
let name = file.path().file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let bytes = match file.bytes_async().await {
|
||||
Ok(bytes) => Some(bytes.into()),
|
||||
Err(error) => {
|
||||
log::error!("couldn't read dropped file {name}: {error}");
|
||||
None
|
||||
}
|
||||
};
|
||||
files.push(DroppedFile { path: None, name, bytes });
|
||||
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
|
||||
match f.bytes_async().await {
|
||||
Ok(bytes) => {
|
||||
push_inbox(&inbox, InboxEvent::File(InboxFile { id, name, bytes }));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("couldn't read dropped file {name}: {e}");
|
||||
push_inbox(&inbox, InboxEvent::Cancelled { id });
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
drops.dropped(files);
|
||||
});
|
||||
}
|
||||
self.app.raw_input_hook(ctx, raw);
|
||||
self.app.before_input(ctx);
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
self.app.ui(ui);
|
||||
}
|
||||
}
|
||||
|
||||
/// Web services: no file paths, so `pick_open`/`pick_save`/`read` stay `None` and the UI falls
|
||||
/// back to `open_async` (browser picker → inbox) and `download`.
|
||||
fn services(inbox: Inbox, ctx: egui::Context) -> Services {
|
||||
let open_inbox = inbox.clone();
|
||||
let presenter = match crate::presenter::BrowserHost::new(ctx.clone()) {
|
||||
Ok(host) => Some(Box::new(host) as Box<dyn deckcraft_ui_egui::presenter::Host>),
|
||||
Err(error) => {
|
||||
log::error!("Presenter window: {error}");
|
||||
None
|
||||
}
|
||||
};
|
||||
Services {
|
||||
presenter,
|
||||
open_async: Some(Box::new(move |purpose: &str, request: u64| {
|
||||
let inbox = open_inbox.clone();
|
||||
let ctx = ctx.clone();
|
||||
let dialog = match purpose {
|
||||
"picture" => rfd::AsyncFileDialog::new().add_filter("Pictures", PICTURE_EXTS),
|
||||
"audio" => rfd::AsyncFileDialog::new().add_filter("Audio", AUDIO_EXTS),
|
||||
"video" => rfd::AsyncFileDialog::new().add_filter("Video", VIDEO_EXTS),
|
||||
_ => rfd::AsyncFileDialog::new().add_filter("Presentations", PRESENTATION_EXTS),
|
||||
};
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let Some(file) = dialog.pick_file().await else {
|
||||
push_inbox(&inbox, InboxEvent::Cancelled { id: request });
|
||||
ctx.request_repaint();
|
||||
return;
|
||||
};
|
||||
let bytes = file.read().await;
|
||||
push_inbox(&inbox, InboxEvent::File(InboxFile { id: request, name: file.file_name(), bytes }));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
})),
|
||||
write: Some(Box::new(|name: &str, bytes: &[u8]| download(name, bytes))),
|
||||
download: Some(Box::new(|name: &str, bytes: &[u8]| {
|
||||
if let Err(e) = download(name, bytes) {
|
||||
log::error!("download of {name} failed: {e}");
|
||||
}
|
||||
})),
|
||||
inbox: Some(inbox),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn push_inbox(inbox: &Inbox, event: InboxEvent) {
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push(event);
|
||||
}
|
||||
|
||||
/// Trigger a browser download of `bytes` named after the last component of `path`.
|
||||
fn download(path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "deckcraft".into());
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let document = window.document().ok_or("no document")?;
|
||||
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
|
||||
let opts = web_sys::BlobPropertyBag::new();
|
||||
opts.set_type(mime_for(&name));
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
|
||||
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
|
||||
let a: web_sys::HtmlAnchorElement = document.create_element("a").map_err(js)?.dyn_into().map_err(|_| "not an anchor")?;
|
||||
a.set_href(&url);
|
||||
a.set_download(&name);
|
||||
a.style().set_property("display", "none").map_err(js)?;
|
||||
let body = document.body().ok_or("no body")?;
|
||||
body.append_child(&a).map_err(js)?;
|
||||
a.click();
|
||||
a.remove();
|
||||
// Revoke after the click has been dispatched; the download keeps its own reference.
|
||||
let revoke = wasm_bindgen::closure::Closure::once_into_js(move || {
|
||||
web_sys::Url::revoke_object_url(&url).ok();
|
||||
});
|
||||
window.set_timeout_with_callback_and_timeout_and_arguments_0(revoke.unchecked_ref(), 10_000).map_err(js)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mime_for(name: &str) -> &'static str {
|
||||
match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("png") => "image/png",
|
||||
Some("jpg" | "jpeg") => "image/jpeg",
|
||||
Some("pdf") => "application/pdf",
|
||||
Some("gif") => "image/gif",
|
||||
Some("txt") => "text/plain",
|
||||
Some("pptx") => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
Some("deckcraft") => "application/zip",
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,11 +11,9 @@ default-run = "deckcraft"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-nightly = { workspace = true }
|
||||
deckcraft-engine = { workspace = true }
|
||||
deckcraft-ui-egui = { workspace = true }
|
||||
deckcraft-media = { workspace = true }
|
||||
craft = { workspace = true, features = ["ui-app", "window", "gpu-startup", "quit", "dialogs", "platform", "platform-clipboard-system", "automation", "settings", "font-catalog"] }
|
||||
# `clipboard` is the OS clipboard (Ctrl+C/X/V with other apps). Without it egui simulates one inside
|
||||
# the app; the egui 0.37 migration (#1350) dropped it from this list.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "links", "wayland", "x11"] }
|
||||
@@ -32,6 +30,7 @@ winresource = "0.1"
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
arboard = { workspace = true, features = ["image-data"] }
|
||||
image = { workspace = true }
|
||||
cpal = "0.16"
|
||||
|
||||
@@ -40,7 +39,11 @@ cpal = "0.16"
|
||||
winsafe = { version = "0.0.29", features = ["user", "shell"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
craft = { workspace = true, features = ["platform-apple-events"] }
|
||||
# Finder double-click, Open With, Dock drops and `open -a DeckCraft deck.pptx` arrive as a
|
||||
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle. This audited crate (also used by
|
||||
# GridCraft, PdfCraft and PhotoCraft) registers the handler (Objective-C interop needs unsafe, which
|
||||
# our workspace forbids) behind a safe API. Pinned exactly: review the diff before bumping.
|
||||
fmv-macos-events = "=0.1.0"
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
|
||||
@@ -8,19 +8,29 @@
|
||||
//! `%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 `craft-nightly` fence
|
||||
//! ([`crate::profile_root`]) still refuses a `portable.txt` marker beside a nightly executable.
|
||||
//! 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::PathBuf;
|
||||
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 isolated Nightly profile root (from `--launch-profile nightly-v1` or direct self-isolation).
|
||||
/// The profile root chosen by the Launcher (`--launch-profile nightly-v1`).
|
||||
Override,
|
||||
/// The platform convention (stable).
|
||||
Platform,
|
||||
@@ -85,6 +95,26 @@ 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::*;
|
||||
@@ -128,4 +158,32 @@ mod tests {
|
||||
assert!(std::ptr::eq(resolved, current()));
|
||||
assert_eq!(resolved.dir, config_dir());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permanent_probe_does_not_replace_an_existing_entry() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-writable-{}-{}", std::process::id(), line!()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let probe = |attempt: u32| dir.join(format!(".deckcraft-write-probe-{}-{attempt}", std::process::id()));
|
||||
// An entry already at the probe's name must never be truncated: the probe takes the next
|
||||
// free name, and it removes only the file it created.
|
||||
std::fs::write(probe(0), b"someone else's file").unwrap();
|
||||
ensure_writable(&dir).unwrap();
|
||||
assert_eq!(std::fs::read(probe(0)).unwrap(), b"someone else's file");
|
||||
assert!(!probe(1).exists());
|
||||
// Every name taken is an error, not a truncation of any of them.
|
||||
for attempt in 0..8 {
|
||||
std::fs::write(probe(attempt), b"someone else's file").unwrap();
|
||||
}
|
||||
assert!(ensure_writable(&dir).is_err(), "no free probe name is reported, not truncated");
|
||||
for attempt in 0..8 {
|
||||
assert_eq!(std::fs::read(probe(attempt)).unwrap(), b"someone else's file", "{attempt}");
|
||||
}
|
||||
for attempt in 0..8 {
|
||||
std::fs::remove_file(probe(attempt)).unwrap();
|
||||
}
|
||||
// A folder whose stale probes were cleared is writable, and the probe leaves nothing behind.
|
||||
ensure_writable(&dir).unwrap();
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
//! macOS open-documents and quit Apple events.
|
||||
//!
|
||||
//! Finder double-clicks, Open With, drops on the Dock icon and `open -a DeckCraft deck.pptx` don't
|
||||
//! pass paths on the command line: LaunchServices sends the running (or just-launched) app a
|
||||
//! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the
|
||||
//! `NSApplicationDelegate`. Handling it ourselves needs Objective-C class declarations, i.e.
|
||||
//! `unsafe`, which this workspace forbids. The audited `fmv-macos-events` crate (also used by
|
||||
//! GridCraft, PdfCraft and PhotoCraft) wraps exactly that, an `NSAppleEventManager` handler
|
||||
//! registered before Finder's launch event that leaves winit's delegate alone, behind a safe
|
||||
//! main-thread API.
|
||||
|
||||
use deckcraft_ui_egui::SlideApp;
|
||||
use fmv_macos_events::{Event, Inbox, Registration};
|
||||
|
||||
/// Keeps the Apple-event handlers registered; hold it until the event loop returns.
|
||||
pub struct AppleEvents {
|
||||
_registration: Registration,
|
||||
inbox: Inbox,
|
||||
}
|
||||
|
||||
impl AppleEvents {
|
||||
/// Register the handlers. Call on the main thread before the event loop starts, so the event
|
||||
/// that launched the app (a Finder double-click) is caught too.
|
||||
pub fn install() -> Self {
|
||||
let (registration, inbox) = Registration::install();
|
||||
Self { _registration: registration, inbox }
|
||||
}
|
||||
|
||||
/// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`.
|
||||
pub fn connect(&self, ctx: &egui::Context) -> Inbox {
|
||||
let ctx = ctx.clone();
|
||||
self.inbox.set_wake(move || ctx.request_repaint());
|
||||
self.inbox.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the documents and act on the quit requests that arrived since the last frame.
|
||||
pub fn poll(inbox: &Inbox, app: &mut SlideApp, ctx: &egui::Context) {
|
||||
for e in inbox.drain() {
|
||||
match e {
|
||||
Event::Open(paths) => {
|
||||
for p in paths.iter().filter_map(|p| p.to_str()) {
|
||||
if let Err(e) = app.open_path(p) {
|
||||
let safe_p = p.replace(['\r', '\n'], " ");
|
||||
log::error!("{safe_p}: {e}");
|
||||
app.set_status(format!("Couldn't open {safe_p}: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Event::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,4 +120,18 @@ mod tests {
|
||||
keep_stream_error(&slot, &"a later error");
|
||||
assert_eq!(take_stream_error(&slot).as_deref(), Some("a later error"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_poisoned_slot_still_reports() {
|
||||
let slot = ErrorSlot::default();
|
||||
keep_stream_error(&slot, &"lost");
|
||||
let s = slot.clone();
|
||||
let _ = std::thread::spawn(move || {
|
||||
let _g = s.lock();
|
||||
panic!("poison the slot");
|
||||
})
|
||||
.join();
|
||||
assert!(slot.is_poisoned());
|
||||
assert_eq!(take_stream_error(&slot).as_deref(), Some("lost"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,31 @@
|
||||
//! 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;
|
||||
|
||||
pub use craft_nightly::BuildFlavor;
|
||||
#[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(),
|
||||
@@ -17,10 +35,7 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::ffi::OsString;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
@@ -30,51 +45,28 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_direct_launch_self_isolates_into_canonical_profile_root() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let expected_root = craft_nightly::canonical_profile_root(crate::profile_root::APP_ID).unwrap();
|
||||
let launch = craft_nightly::parse_startup(
|
||||
BuildFlavor::NightlyV1,
|
||||
&spec,
|
||||
[OsString::from("--sample"), OsString::from("deck.pptx")],
|
||||
&crate::launch_profile::startup_options(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(launch.profile, craft_nightly::Profile::NightlyV1(expected_root));
|
||||
assert_eq!(launch.passthrough_args, [OsString::from("--sample"), OsString::from("deck.pptx")]);
|
||||
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_flavor_rejects_nightly_launch_flags() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let root = if cfg!(windows) { r"C:\NightlyData\profiles\deckcraft" } else { "/nightly-data/profiles/deckcraft" };
|
||||
let result = craft_nightly::parse_startup(
|
||||
BuildFlavor::Stable,
|
||||
&spec,
|
||||
[
|
||||
OsString::from(craft_nightly::LAUNCH_PROFILE_FLAG),
|
||||
OsString::from(craft_nightly::NIGHTLY_V1_CONTRACT),
|
||||
OsString::from(craft_nightly::PROFILE_ROOT_FLAG),
|
||||
OsString::from(root),
|
||||
],
|
||||
&crate::launch_profile::startup_options(),
|
||||
);
|
||||
assert!(matches!(result, Err(craft_nightly::ProfileError::NightlyFlagsInStableBuild)));
|
||||
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() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let opts = crate::launch_profile::startup_options();
|
||||
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!(craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, [OsString::from("--version")], &opts).unwrap().is_version_query());
|
||||
assert!(craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, [OsString::from("-V")], &opts).unwrap().is_version_query());
|
||||
assert!(
|
||||
!craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, [OsString::from("--"), OsString::from("--version")], &opts)
|
||||
.unwrap()
|
||||
.is_version_query()
|
||||
);
|
||||
assert!(!craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, Vec::<OsString>::new(), &opts).unwrap().is_version_query());
|
||||
assert!(version_query(&["--version".into()]));
|
||||
assert!(version_query(&["-V".into()]));
|
||||
assert!(!version_query(&["--".into(), "--version".into()]));
|
||||
assert!(!version_query(&[]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
//! Loopback JSON-lines control server: one request per line, one reply per line.
|
||||
//! This is the transport the MCP server (`deckcraft-cli mcp --connect`) wraps.
|
||||
//!
|
||||
//! The server only reads requests: a line that is not a JSON object with a string `method` (an
|
||||
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
|
||||
//! closed, so nothing sent after it runs. Every resource a client can hold is bounded
|
||||
//! ([`Limits`]): simultaneous connections, request line length, queued requests, and how long a
|
||||
//! socket may sit idle or blocked on a write.
|
||||
|
||||
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
|
||||
use std::net::{Shutdown, TcpListener, TcpStream};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{Receiver, SyncSender, TrySendError, sync_channel};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use deckcraft_ui_egui::ControlRequest;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Resource bounds for the control server.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Limits {
|
||||
/// Connections served at once; more are told `busy` and closed.
|
||||
pub max_clients: usize,
|
||||
/// Longest request line in bytes (newline excluded); a longer one closes the connection.
|
||||
pub max_line: usize,
|
||||
/// Requests waiting for the UI at once; more are answered `busy`.
|
||||
pub queue: usize,
|
||||
/// How long a connection may go without sending a byte before it is closed.
|
||||
pub idle_timeout: Duration,
|
||||
/// How long a reply write may block before the connection is closed.
|
||||
pub write_timeout: Duration,
|
||||
/// How long a request waits for the UI's answer.
|
||||
pub reply_timeout: Duration,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_clients: 16,
|
||||
// Picture and media inserts carry base64 payloads: room for files of about 190 MB.
|
||||
max_line: 256 * 1024 * 1024,
|
||||
queue: 64,
|
||||
idle_timeout: Duration::from_secs(600),
|
||||
write_timeout: Duration::from_secs(30),
|
||||
reply_timeout: Duration::from_secs(60),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
match TcpListener::bind(("127.0.0.1", port)) {
|
||||
Ok(l) => {
|
||||
log::info!("control server listening on 127.0.0.1:{port}");
|
||||
serve_listener(l, Limits::default(), ctx)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("control server failed to bind 127.0.0.1:{port}: {e}");
|
||||
sync_channel::<ControlRequest>(0).1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How long the accepting thread waits after a failed accept. Accepting can keep failing, for
|
||||
/// example while the process has no file descriptors left, and retrying at once would keep a
|
||||
/// core busy until it recovers.
|
||||
const ACCEPT_RETRY: Duration = Duration::from_millis(100);
|
||||
|
||||
/// The longest a connection refused as busy is drained before it is closed.
|
||||
const REFUSED_GRACE: Duration = Duration::from_millis(250);
|
||||
|
||||
/// Refused connections drained at once, each on a thread of its own. Past this many, a refused
|
||||
/// connection gets the busy reply and is closed without a drain.
|
||||
const MAX_REFUSING: usize = 16;
|
||||
|
||||
/// The connections `incoming` accepts, calling `wait` after each failed accept.
|
||||
fn accepted<T>(incoming: impl Iterator<Item = std::io::Result<T>>, mut wait: impl FnMut()) -> impl Iterator<Item = T> {
|
||||
incoming.filter_map(move |stream| stream.map_err(|_| wait()).ok())
|
||||
}
|
||||
|
||||
/// Accept connections on `listener` under `limits`; requests arrive on the returned receiver.
|
||||
fn serve_listener(listener: TcpListener, limits: Limits, ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
let (tx, rx) = sync_channel::<ControlRequest>(limits.queue.max(1));
|
||||
let active = Arc::new(AtomicUsize::new(0));
|
||||
let refusing = Arc::new(AtomicUsize::new(0));
|
||||
std::thread::spawn(move || {
|
||||
for mut stream in accepted(listener.incoming(), || std::thread::sleep(ACCEPT_RETRY)) {
|
||||
let _ = stream.set_write_timeout(Some(limits.write_timeout));
|
||||
if active.fetch_add(1, Ordering::SeqCst) >= limits.max_clients {
|
||||
active.fetch_sub(1, Ordering::SeqCst);
|
||||
let _ = writeln!(stream, "{}", json!({"ok": false, "error": "busy: too many control connections"}));
|
||||
refuse(stream, &refusing, limits.write_timeout.min(REFUSED_GRACE));
|
||||
continue;
|
||||
}
|
||||
let slot = Slot(Arc::clone(&active));
|
||||
let tx = tx.clone();
|
||||
let ctx = ctx.clone();
|
||||
let spawned = std::thread::Builder::new().name("control-client".into()).spawn(move || {
|
||||
let _slot = slot;
|
||||
serve(stream, &tx, &ctx, limits);
|
||||
});
|
||||
if spawned.is_err() {
|
||||
log::warn!("control server could not start a client thread");
|
||||
}
|
||||
}
|
||||
});
|
||||
rx
|
||||
}
|
||||
|
||||
/// Close a connection that was told it is refused. A peer that wrote a line before it read the
|
||||
/// reply would see only a reset, so the connection is drained for up to `grace` first, on a
|
||||
/// thread of its own: the accepting thread goes straight back to accepting. Past
|
||||
/// [`MAX_REFUSING`] drains at once, the connection is closed without one.
|
||||
fn refuse(stream: TcpStream, refusing: &Arc<AtomicUsize>, grace: Duration) {
|
||||
if refusing.fetch_add(1, Ordering::SeqCst) >= MAX_REFUSING {
|
||||
refusing.fetch_sub(1, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
let slot = Slot(Arc::clone(refusing));
|
||||
let spawned = std::thread::Builder::new().name("control-refused".into()).spawn(move || {
|
||||
let _slot = slot;
|
||||
if let Ok(read) = stream.try_clone() {
|
||||
close_politely(&stream, &mut BufReader::new(read), grace);
|
||||
}
|
||||
});
|
||||
if spawned.is_err() {
|
||||
log::warn!("control server could not start a thread to close a refused connection");
|
||||
}
|
||||
}
|
||||
|
||||
/// Holds one connection slot; gives it back when the client thread ends, however it ends.
|
||||
struct Slot(Arc<AtomicUsize>);
|
||||
|
||||
impl Drop for Slot {
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
enum Line {
|
||||
Text(Vec<u8>),
|
||||
TooLong,
|
||||
Closed,
|
||||
}
|
||||
|
||||
/// Read one `\n`-terminated line of at most `max` bytes without buffering more than `max + 1`.
|
||||
fn read_line(r: &mut impl BufRead, max: usize) -> Line {
|
||||
let mut buf = Vec::new();
|
||||
let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
|
||||
match r.by_ref().take(limit).read_until(b'\n', &mut buf) {
|
||||
Ok(0) | Err(_) => Line::Closed,
|
||||
Ok(_) => {
|
||||
if buf.last() == Some(&b'\n') {
|
||||
buf.pop();
|
||||
Line::Text(buf)
|
||||
} else if buf.len() > max {
|
||||
Line::TooLong
|
||||
} else {
|
||||
// EOF inside a line: serve what arrived, the next read reports Closed.
|
||||
Line::Text(buf)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One request line, parsed.
|
||||
enum Parsed {
|
||||
Request {
|
||||
id: Value,
|
||||
method: String,
|
||||
params: Value,
|
||||
},
|
||||
Blank,
|
||||
/// Not a request: reply with this error and close the connection.
|
||||
Reject(String),
|
||||
}
|
||||
|
||||
fn parse(bytes: &[u8]) -> Parsed {
|
||||
let Ok(text) = std::str::from_utf8(bytes) else {
|
||||
return Parsed::Reject("not a control request (invalid UTF-8); closing the connection".into());
|
||||
};
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Parsed::Blank;
|
||||
}
|
||||
if is_http_request_line(text) {
|
||||
return Parsed::Reject("HTTP is not served here: this port takes JSON lines; closing the connection".into());
|
||||
}
|
||||
let msg = match serde_json::from_str::<Value>(text) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return Parsed::Reject(format!("bad JSON ({e}); expected one JSON request object per line; closing the connection")),
|
||||
};
|
||||
let Some(obj) = msg.as_object() else {
|
||||
return Parsed::Reject("not a control request (expected a JSON object); closing the connection".into());
|
||||
};
|
||||
let Some(method) = obj.get("method").and_then(Value::as_str) else {
|
||||
return Parsed::Reject("not a control request (missing string `method`); closing the connection".into());
|
||||
};
|
||||
Parsed::Request {
|
||||
id: obj.get("id").cloned().unwrap_or(Value::Null),
|
||||
method: method.to_string(),
|
||||
params: obj.get("params").cloned().unwrap_or(json!({})),
|
||||
}
|
||||
}
|
||||
|
||||
/// An HTTP/1 request line (`POST / HTTP/1.1`) or the HTTP/2 preface (`PRI * HTTP/2.0`).
|
||||
fn is_http_request_line(text: &str) -> bool {
|
||||
const METHODS: [&str; 10] = ["GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"];
|
||||
text.split_once(' ').is_some_and(|(method, _)| METHODS.contains(&method))
|
||||
|| text.rsplit_once(' ').is_some_and(|(_, version)| version.starts_with("HTTP/"))
|
||||
}
|
||||
|
||||
/// Close after the last reply so the peer can still read it. A peer that had sent another line
|
||||
/// before the reply arrived -- two lines in one write, which any script does -- leaves input
|
||||
/// unread in the socket, and closing a socket with unread input resets the connection: the reply
|
||||
/// already queued for the peer is discarded and it sees only the reset. Sending the FIN first and
|
||||
/// then draining, briefly and boundedly, makes the close orderly and the reason survive.
|
||||
fn close_politely(out: &TcpStream, reader: &mut BufReader<TcpStream>, grace: Duration) {
|
||||
if out.shutdown(Shutdown::Write).is_err() {
|
||||
return;
|
||||
}
|
||||
// Enough for a pipelined line or two; a peer that keeps talking is dropped at the deadline.
|
||||
// The timeout is what is left of the grace before each read, not the whole of it: a peer that
|
||||
// sends a byte just before each one expires would otherwise hold this thread, and its slot,
|
||||
// for close to twice as long as the deadline says. The timeout is set on the handle that
|
||||
// reads: on Windows, a read timeout set on one handle of a `try_clone` pair can fail to apply
|
||||
// to reads through the other.
|
||||
const MAX_DRAIN: usize = 64 << 10;
|
||||
let until = Instant::now() + grace;
|
||||
let mut sink = [0u8; 4 << 10];
|
||||
let mut drained = 0;
|
||||
while drained < MAX_DRAIN {
|
||||
let left = until.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() || reader.get_ref().set_read_timeout(Some(left)).is_err() {
|
||||
break;
|
||||
}
|
||||
match reader.read(&mut sink) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => drained += n,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context, limits: Limits) {
|
||||
if stream.set_read_timeout(Some(limits.idle_timeout)).is_err() || stream.set_write_timeout(Some(limits.write_timeout)).is_err() {
|
||||
return;
|
||||
}
|
||||
let Ok(read) = stream.try_clone() else { return };
|
||||
let mut out = stream;
|
||||
let mut reader = BufReader::new(read);
|
||||
loop {
|
||||
let line = match read_line(&mut reader, limits.max_line) {
|
||||
Line::Text(t) => t,
|
||||
Line::TooLong => {
|
||||
let _ = writeln!(out, "{}", json!({"ok": false, "error": format!("request line longer than {} bytes", limits.max_line)}));
|
||||
close_politely(&out, &mut reader, limits.write_timeout);
|
||||
break;
|
||||
}
|
||||
Line::Closed => break,
|
||||
};
|
||||
let reply = match parse(&line) {
|
||||
Parsed::Blank => continue,
|
||||
Parsed::Reject(e) => {
|
||||
// The connection closes either way, but the peer is told why first: see
|
||||
// `close_politely`, without which a peer that had pipelined another line had this
|
||||
// reply reset away and saw nothing.
|
||||
let _ = writeln!(out, "{}", json!({"ok": false, "error": e}));
|
||||
close_politely(&out, &mut reader, limits.write_timeout);
|
||||
break;
|
||||
}
|
||||
Parsed::Request { id, method, params } => {
|
||||
let (req, rrx) = ControlRequest::new(method, params);
|
||||
let state = Arc::clone(&req.state);
|
||||
let mut r = match tx.try_send(req) {
|
||||
Ok(()) => {
|
||||
ctx.request_repaint();
|
||||
match rrx.recv_timeout(limits.reply_timeout) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
// Give up on the request. While it was still queued this makes
|
||||
// sure it never runs late (#719); if the app had already taken
|
||||
// it, its outcome is unknown rather than a definite failure.
|
||||
if ControlRequest::abandon(&state) {
|
||||
json!({"ok": false, "error": "timeout"})
|
||||
} else {
|
||||
json!({"ok": false, "error": "timeout: the app had already started the request, so it may still run; its outcome is unknown"})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(TrySendError::Full(_)) => json!({"ok": false, "error": "busy: too many queued requests"}),
|
||||
Err(TrySendError::Disconnected(_)) => break,
|
||||
};
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("id".into(), id);
|
||||
}
|
||||
r
|
||||
}
|
||||
};
|
||||
if let Err(e) = writeln!(out, "{reply}") {
|
||||
if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) {
|
||||
log::debug!("control client stopped reading replies; closing");
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,299 @@
|
||||
use super::*;
|
||||
|
||||
/// A failed accept is followed by a wait before the next one, so a listener that keeps
|
||||
/// failing does not spin, and the connections around the failures still come through.
|
||||
#[test]
|
||||
fn a_failed_accept_waits_before_the_next() {
|
||||
let failed = || Err(std::io::Error::other("no file descriptors left"));
|
||||
let incoming = vec![failed(), Ok(1), failed(), failed(), Ok(2)];
|
||||
let mut waits = 0;
|
||||
let connections: Vec<i32> = super::accepted(incoming.into_iter(), || waits += 1).collect();
|
||||
assert_eq!(connections, [1, 2]);
|
||||
assert_eq!(waits, 3, "one wait per failed accept");
|
||||
}
|
||||
use std::net::SocketAddr;
|
||||
use std::time::Instant;
|
||||
|
||||
fn small() -> Limits {
|
||||
Limits {
|
||||
max_clients: 2,
|
||||
max_line: 64,
|
||||
queue: 1,
|
||||
idle_timeout: Duration::from_millis(300),
|
||||
write_timeout: Duration::from_millis(300),
|
||||
reply_timeout: Duration::from_millis(300),
|
||||
}
|
||||
}
|
||||
|
||||
fn server(limits: Limits) -> (SocketAddr, Receiver<ControlRequest>) {
|
||||
let l = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = l.local_addr().unwrap();
|
||||
(addr, serve_listener(l, limits, egui::Context::default()))
|
||||
}
|
||||
|
||||
fn client(addr: SocketAddr) -> (BufReader<TcpStream>, TcpStream) {
|
||||
let s = TcpStream::connect(addr).unwrap();
|
||||
s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
(BufReader::new(s.try_clone().unwrap()), s)
|
||||
}
|
||||
|
||||
fn reply(r: &mut BufReader<TcpStream>) -> Option<Value> {
|
||||
let mut s = String::new();
|
||||
match r.read_line(&mut s) {
|
||||
Ok(0) | Err(_) => None,
|
||||
Ok(_) => serde_json::from_str(&s).ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer every request with its method name until the server goes away.
|
||||
fn ui(rx: Receiver<ControlRequest>) {
|
||||
std::thread::spawn(move || {
|
||||
for req in rx {
|
||||
let _ = req.reply.send(json!({"ok": true, "result": req.method}));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_round_trip() {
|
||||
let (addr, rx) = server(small());
|
||||
ui(rx);
|
||||
let (mut r, mut w) = client(addr);
|
||||
writeln!(w, r#"{{"id":7,"method":"ui.inspect"}}"#).unwrap();
|
||||
let v = reply(&mut r).unwrap();
|
||||
assert_eq!(v["id"], 7);
|
||||
assert_eq!(v["result"], "ui.inspect");
|
||||
}
|
||||
|
||||
/// Every reply line until the server closes the connection.
|
||||
fn replies_until_closed(r: &mut BufReader<TcpStream>) -> Vec<Value> {
|
||||
std::iter::from_fn(|| reply(r)).collect()
|
||||
}
|
||||
|
||||
/// A browser can POST to the port: its request line closes the connection before the JSON
|
||||
/// line in its body is read, so nothing is dispatched.
|
||||
#[test]
|
||||
fn an_http_request_closes_the_connection_before_its_body_is_dispatched() {
|
||||
let (addr, rx) = server(Limits { max_line: 512, ..small() });
|
||||
let (mut r, mut w) = client(addr);
|
||||
w.write_all(
|
||||
b"POST / HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: text/plain\r\n\r\n\
|
||||
{\"id\":1,\"method\":\"engine.execute\",\"params\":{\"command\":\"slide.new\"}}\n",
|
||||
)
|
||||
.unwrap();
|
||||
let replies = replies_until_closed(&mut r);
|
||||
assert_eq!(replies.len(), 1, "{replies:?}");
|
||||
assert!(replies[0]["error"].as_str().unwrap().contains("closing the connection"), "{replies:?}");
|
||||
assert!(rx.try_recv().is_err(), "the body was dispatched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_that_is_not_a_request_closes_the_connection() {
|
||||
let (addr, rx) = server(small());
|
||||
ui(rx);
|
||||
for junk in [&b"hello\n"[..], b"[1,2]\n", b"{\"id\":1}\n", b"{\"method\":5}\n", b"\xff\xfe\n", b"GET /x HTTP/1.1\n"] {
|
||||
let (mut r, mut w) = client(addr);
|
||||
w.write_all(junk).unwrap();
|
||||
w.write_all(b"{\"id\":2,\"method\":\"m\"}\n").unwrap();
|
||||
let replies = replies_until_closed(&mut r);
|
||||
assert_eq!(replies.len(), 1, "{replies:?}");
|
||||
assert_eq!(replies[0]["ok"], false);
|
||||
}
|
||||
assert!(is_http_request_line("OPTIONS * HTTP/1.1"));
|
||||
assert!(is_http_request_line("PRI * HTTP/2.0"));
|
||||
assert!(!is_http_request_line("{\"method\":\"GET /\"}"));
|
||||
}
|
||||
|
||||
/// A peer that pipelines -- two lines in one write, as a script does -- still reads why its
|
||||
/// line was rejected. Closing with its second line unread resets the connection and discards
|
||||
/// the reply already on its way, so the peer saw nothing at all; repeated here because it
|
||||
/// depended on the timing of the two.
|
||||
#[test]
|
||||
fn a_pipelined_peer_still_reads_why_its_line_was_rejected() {
|
||||
// A slot comes back only when the thread serving a peer ends, which can be after the next
|
||||
// peer connects, so every peer has a slot of its own.
|
||||
const PEERS: usize = 12;
|
||||
let (addr, rx) = server(Limits { max_clients: PEERS, ..small() });
|
||||
for _ in 0..PEERS {
|
||||
let (mut r, mut w) = client(addr);
|
||||
w.write_all(b"hello\n").unwrap();
|
||||
// A second line, written after the first as a script writes it: it races the close.
|
||||
let _ = w.write_all(b"{\"id\":2,\"method\":\"m\"}\n");
|
||||
let replies = replies_until_closed(&mut r);
|
||||
assert_eq!(replies.len(), 1, "{replies:?}");
|
||||
assert_eq!(replies[0]["ok"], false);
|
||||
assert!(replies[0]["error"].as_str().unwrap_or_default().contains("closing the connection"), "{replies:?}");
|
||||
}
|
||||
// The line after the rejected one is never dispatched, pipelined or not.
|
||||
assert!(rx.try_recv().is_err(), "a line after the rejection was dispatched");
|
||||
}
|
||||
|
||||
/// A peer refused because every connection is taken still reads why when it had already
|
||||
/// written a line: closing with that line unread resets the connection and discards the
|
||||
/// reply. Repeated because it depends on the timing of the two.
|
||||
#[test]
|
||||
fn a_pipelined_peer_refused_as_busy_still_reads_why() {
|
||||
let (addr, rx) = server(Limits { max_clients: 1, idle_timeout: Duration::from_secs(30), ..small() });
|
||||
ui(rx);
|
||||
// Take the only slot, and make sure it is being served.
|
||||
let (mut hr, mut hw) = client(addr);
|
||||
writeln!(hw, r#"{{"id":1,"method":"m"}}"#).unwrap();
|
||||
assert!(reply(&mut hr).is_some());
|
||||
for _ in 0..50 {
|
||||
let (mut r, mut w) = client(addr);
|
||||
let _ = w.write_all(b"{\"id\":2,\"method\":\"m\"}\n");
|
||||
let replies = replies_until_closed(&mut r);
|
||||
assert_eq!(replies.len(), 1, "{replies:?}");
|
||||
assert!(replies[0]["error"].as_str().unwrap_or_default().starts_with("busy"), "{replies:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Peers refused as busy that stay connected without sending anything do not hold up the
|
||||
/// connections after them: each one's drain runs to its deadline on a thread of its own, and
|
||||
/// past `MAX_REFUSING` drains at once a refused connection is closed without one.
|
||||
#[test]
|
||||
fn silent_refused_peers_do_not_delay_the_next_refusal() {
|
||||
let (addr, rx) = server(Limits { max_clients: 1, idle_timeout: Duration::from_secs(30), ..small() });
|
||||
ui(rx);
|
||||
let (mut hr, mut hw) = client(addr);
|
||||
writeln!(hw, r#"{{"id":1,"method":"m"}}"#).unwrap();
|
||||
assert!(reply(&mut hr).is_some());
|
||||
// Twenty drains of 250 ms each, one after another, would take five seconds.
|
||||
let silent: Vec<_> = (0..MAX_REFUSING + 4).map(|_| client(addr)).collect();
|
||||
let start = Instant::now();
|
||||
let (mut r, _w) = client(addr);
|
||||
let refused = reply(&mut r).unwrap();
|
||||
assert!(refused["error"].as_str().unwrap_or_default().starts_with("busy"), "{refused}");
|
||||
assert!(start.elapsed() < Duration::from_secs(1), "refused after {:?}", start.elapsed());
|
||||
drop(silent);
|
||||
}
|
||||
|
||||
/// A peer that keeps its connection open after its line was rejected gives its slot back at
|
||||
/// the drain deadline (the write timeout), not at the idle timeout.
|
||||
#[test]
|
||||
fn a_rejected_peer_that_stays_connected_frees_its_slot_at_the_deadline() {
|
||||
let (addr, rx) = server(Limits { max_clients: 1, idle_timeout: Duration::from_secs(30), ..small() });
|
||||
ui(rx);
|
||||
let (mut r, mut w) = client(addr);
|
||||
w.write_all(b"hello\n").unwrap();
|
||||
assert_eq!(reply(&mut r).unwrap()["ok"], false);
|
||||
// `w` stays open, sending nothing.
|
||||
let deadline = Instant::now() + Duration::from_secs(4);
|
||||
loop {
|
||||
let (mut dr, mut dw) = client(addr);
|
||||
writeln!(dw, r#"{{"id":2,"method":"m"}}"#).unwrap();
|
||||
if reply(&mut dr).is_some_and(|v| v["ok"] == true) {
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "slot never freed");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
drop(w);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_line_closes_connection() {
|
||||
let (addr, rx) = server(small());
|
||||
ui(rx);
|
||||
let (mut r, mut w) = client(addr);
|
||||
w.write_all(&[b'x'; 200]).unwrap();
|
||||
let v = reply(&mut r).unwrap();
|
||||
assert!(v["error"].as_str().unwrap().contains("longer than 64"));
|
||||
assert!(reply(&mut r).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_connection_is_closed() {
|
||||
let (addr, rx) = server(small());
|
||||
ui(rx);
|
||||
let (mut r, mut w) = client(addr);
|
||||
w.write_all(b"{\"id\":1,").unwrap(); // unterminated, then silence
|
||||
let t = Instant::now();
|
||||
assert!(reply(&mut r).is_none());
|
||||
assert!(t.elapsed() < Duration::from_secs(4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connection_limit_refuses_then_frees_slot() {
|
||||
// `a` sends nothing. Under a 300 ms idle timeout, a slow run could close it before the
|
||||
// third peer connected, and that peer then took its slot instead of reading `busy`.
|
||||
let (addr, rx) = server(Limits { idle_timeout: Duration::from_secs(30), ..small() });
|
||||
ui(rx);
|
||||
let a = client(addr);
|
||||
let (mut br, mut bw) = client(addr);
|
||||
// Make sure both are being served before the third arrives.
|
||||
writeln!(bw, r#"{{"id":1,"method":"m"}}"#).unwrap();
|
||||
assert!(reply(&mut br).is_some());
|
||||
let (mut cr, _cw) = client(addr);
|
||||
let v = reply(&mut cr).unwrap();
|
||||
assert!(v["error"].as_str().unwrap().starts_with("busy"));
|
||||
drop(a);
|
||||
// The freed slot is reusable once the server notices the disconnect.
|
||||
let deadline = Instant::now() + Duration::from_secs(4);
|
||||
loop {
|
||||
let (mut dr, mut dw) = client(addr);
|
||||
writeln!(dw, r#"{{"id":2,"method":"m"}}"#).unwrap();
|
||||
if reply(&mut dr).is_some_and(|v| v["ok"] == true) {
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "slot never freed");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_ui_times_out_and_full_queue_is_busy() {
|
||||
let (addr, rx) = server(small());
|
||||
// No UI: the request that reaches the one-slot queue first fills it and times out; the
|
||||
// other finds it full. Each connection has its own thread, so either request can be first.
|
||||
let (mut ar, mut aw) = client(addr);
|
||||
let (mut br, mut bw) = client(addr);
|
||||
writeln!(aw, r#"{{"id":1,"method":"m"}}"#).unwrap();
|
||||
writeln!(bw, r#"{{"id":2,"method":"m"}}"#).unwrap();
|
||||
let a = reply(&mut ar).unwrap();
|
||||
let b = reply(&mut br).unwrap();
|
||||
assert_eq!((&a["id"], &b["id"]), (&json!(1), &json!(2)));
|
||||
let mut errors = [a["error"].as_str().unwrap_or_default(), b["error"].as_str().unwrap_or_default()];
|
||||
errors.sort_unstable();
|
||||
assert_eq!(errors, ["busy: too many queued requests", "timeout"], "{a} {b}");
|
||||
drop(rx);
|
||||
}
|
||||
|
||||
/// A request that timed out while it was still queued must not run when the window resumes (#719).
|
||||
#[test]
|
||||
fn timed_out_request_does_not_run_when_the_window_resumes() {
|
||||
let (addr, rx) = server(Limits { max_line: 512, ..small() });
|
||||
let (mut r, mut w) = client(addr);
|
||||
writeln!(w, r#"{{"id":1,"method":"engine.execute","params":{{"command":"slide.new"}}}}"#).unwrap();
|
||||
let t = reply(&mut r).unwrap();
|
||||
assert_eq!(t["error"], "timeout");
|
||||
// The window resumes and drains the queue, exactly as `SlideApp::drain_control` does.
|
||||
let mut app = deckcraft_ui_egui::SlideApp::new(deckcraft_engine::Session::with_new(), deckcraft_ui_egui::Services::default());
|
||||
let ctx = egui::Context::default();
|
||||
let before = app.session.active().unwrap().doc.slides.len();
|
||||
let req = rx.try_recv().expect("the timed-out request is still queued");
|
||||
if req.take() {
|
||||
let _ = deckcraft_ui_egui::control::handle(&mut app, &ctx, &req);
|
||||
}
|
||||
assert_eq!(app.session.active().unwrap().doc.slides.len(), before, "a request that timed out must not run when the window resumes");
|
||||
drop(rx);
|
||||
}
|
||||
|
||||
/// A request the app had already started when the reply timed out reports an unknown outcome,
|
||||
/// not a definite failure (#719).
|
||||
#[test]
|
||||
fn a_request_already_started_when_the_reply_times_out_reports_an_unknown_outcome() {
|
||||
let (addr, rx) = server(small());
|
||||
let ui = std::thread::spawn(move || {
|
||||
let req = rx.recv().expect("the request is queued");
|
||||
assert!(req.take(), "the app claims the request");
|
||||
// Still running it when the sender's wait expires.
|
||||
std::thread::sleep(Duration::from_millis(450));
|
||||
let _ = req.reply.send(json!({"ok": true, "result": "ran"}));
|
||||
});
|
||||
let (mut r, mut w) = client(addr);
|
||||
writeln!(w, r#"{{"id":1,"method":"m"}}"#).unwrap();
|
||||
let v = reply(&mut r).unwrap();
|
||||
assert!(v["error"].as_str().unwrap().contains("outcome is unknown"), "{v}");
|
||||
ui.join().unwrap();
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
//! Windows graphics instance configuration, applied before wgpu can initialize any driver.
|
||||
|
||||
use eframe::{
|
||||
NativeOptions,
|
||||
egui_wgpu::WgpuSetup,
|
||||
wgpu::{Backends, Dx12Compiler},
|
||||
};
|
||||
|
||||
/// Default to DirectX 12 with FXC before creating the wgpu instance. Explicit
|
||||
/// `WGPU_BACKEND` and `WGPU_DX12_COMPILER` choices, read by the caller, take precedence.
|
||||
pub fn configure(options: &mut NativeOptions, backend_override: Option<Backends>, compiler_override: Option<Dx12Compiler>) {
|
||||
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
// eframe's default includes GL. Creating that backend can crash inside AMD's
|
||||
// atio6axx.dll before adapter selection or any Rust error handling runs, so the
|
||||
// window never appears. Choosing an adapter afterwards is too late: only leaving GL
|
||||
// out of the instance avoids it. This matches the verified WGPU_BACKEND=dx12
|
||||
// workaround without mutating process environment variables.
|
||||
create.instance_descriptor.backends = backend_override.unwrap_or(Backends::DX12);
|
||||
// Auto loads whichever dxcompiler.dll the DLL search path finds; DeckCraft ships
|
||||
// none, and without a matching dxil.dll the unsigned-DXIL warning fails wgpu's
|
||||
// indirect-validation pipeline and loses the device before the first frame
|
||||
// (issue #153). FXC uses the compiler that is part of Windows.
|
||||
create.instance_descriptor.backend_options.dx12.shader_compiler = compiler_override.unwrap_or(Dx12Compiler::Fxc);
|
||||
log::info!(
|
||||
"Windows graphics: backends={:?}, DX12 compiler={:?}",
|
||||
create.instance_descriptor.backends,
|
||||
create.instance_descriptor.backend_options.dx12.shader_compiler
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn configured_backends(backend_override: Option<Backends>) -> Backends {
|
||||
let mut options = NativeOptions::default();
|
||||
configure(&mut options, backend_override, None);
|
||||
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
create.instance_descriptor.backends
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_default_initializes_only_dx12() {
|
||||
// eframe's own default (PRIMARY | GL) would initialize OpenGL as well.
|
||||
let WgpuSetup::CreateNew(eframe_default) = NativeOptions::default().wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
assert!(eframe_default.instance_descriptor.backends.contains(Backends::GL));
|
||||
assert_eq!(configured_backends(None), Backends::DX12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_default_uses_fxc_instead_of_searching_for_dxc() {
|
||||
let mut options = NativeOptions::default();
|
||||
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
// Auto can find an unrelated DXC without its matching DXIL runtime (issue #153).
|
||||
create.instance_descriptor.backend_options.dx12.shader_compiler = Dx12Compiler::Auto;
|
||||
}
|
||||
configure(&mut options, None, None);
|
||||
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
assert!(matches!(create.instance_descriptor.backend_options.dx12.shader_compiler, Dx12Compiler::Fxc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_compiler_override_is_preserved() {
|
||||
for compiler in [Dx12Compiler::Fxc, Dx12Compiler::Auto, Dx12Compiler::DynamicDxc { dxc_path: "custom/dxcompiler.dll".into() }] {
|
||||
let mut options = NativeOptions::default();
|
||||
configure(&mut options, None, Some(compiler.clone()));
|
||||
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
match (compiler, create.instance_descriptor.backend_options.dx12.shader_compiler) {
|
||||
(Dx12Compiler::Fxc, Dx12Compiler::Fxc) | (Dx12Compiler::Auto, Dx12Compiler::Auto) => {}
|
||||
(Dx12Compiler::DynamicDxc { dxc_path: expected }, Dx12Compiler::DynamicDxc { dxc_path: actual }) => {
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
(expected, actual) => panic!("compiler override changed from {expected:?} to {actual:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_backend_override_is_preserved() {
|
||||
for backends in [Backends::VULKAN, Backends::GL, Backends::DX12, Backends::VULKAN | Backends::DX12, Backends::empty()] {
|
||||
assert_eq!(configured_backends(Some(backends)), backends);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,105 +1,221 @@
|
||||
//! Nightly-v1 bootstrap powered by `craft-nightly`. Selected before logging, updates, fonts or
|
||||
//! saved state. Stable launches retain their original arguments and directory policy; direct
|
||||
//! nightly launches self-isolate into [`craft_nightly::canonical_profile_root`].
|
||||
//! 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;
|
||||
|
||||
use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions};
|
||||
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 {
|
||||
craft_nightly::current().unwrap_or(&Profile::Stable)
|
||||
PROFILE.get().unwrap_or(&Profile::Stable)
|
||||
}
|
||||
|
||||
pub fn startup_options() -> StartupOptions {
|
||||
StartupOptions::new()
|
||||
pub fn install(profile: Profile) -> Result<(), String> {
|
||||
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
|
||||
}
|
||||
|
||||
/// Parses startup arguments for `flavor`, validates and prepares the isolated profile root when
|
||||
/// running as [`BuildFlavor::NightlyV1`], and installs the resolved profile process-wide.
|
||||
pub fn prepare(flavor: BuildFlavor, args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
|
||||
let spec = crate::profile_root::spec();
|
||||
craft_nightly::prepare_launch(flavor, &spec, args, &startup_options())
|
||||
/// 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 std::path::PathBuf;
|
||||
|
||||
use craft_nightly::{LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, canonical_profile_root, parse_startup};
|
||||
|
||||
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_profile_are_unchanged() {
|
||||
let spec = crate::profile_root::spec();
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
for argv in [args(&[]), args(&["--sample", "a.pptx"]), args(&["--", "--launch-profile", "file.pptx"])] {
|
||||
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &startup_options()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::Stable);
|
||||
assert_eq!(launch.passthrough_args, argv);
|
||||
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 explicit_launcher_arguments_are_parsed_without_reinterpreting_file_names() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let argv = args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--", "--profile-root", "talk with spaces.pptx"]);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &startup_options()).unwrap();
|
||||
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.passthrough_args, args(&["--profile-root", "talk with spaces.pptx"]));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "talk with spaces.pptx"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_nightly_launch_self_isolates_and_preserves_user_args() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let expected_root = canonical_profile_root(crate::profile_root::APP_ID).unwrap();
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, args(&["--show", "deck.ppsx"]), &startup_options()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
|
||||
assert_eq!(launch.passthrough_args, args(&["--show", "deck.ppsx"]));
|
||||
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 launcher_and_plain_version_queries_are_recognized() {
|
||||
let spec = crate::profile_root::spec();
|
||||
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(&["-V"]),
|
||||
args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--version"]),
|
||||
args(&[PROFILE_ROOT_FLAG, absolute(), LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, "-V"]),
|
||||
args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--", "--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"]),
|
||||
] {
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &startup_options()).unwrap();
|
||||
assert!(launch.is_version_query(), "{argv:?}");
|
||||
}
|
||||
for argv in [
|
||||
args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--version", "--version"]),
|
||||
args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--help"]),
|
||||
] {
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &startup_options()).unwrap();
|
||||
assert!(!launch.is_version_query(), "{argv:?}");
|
||||
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 missing_duplicate_unknown_and_misplaced_profile_arguments_are_refused() {
|
||||
let spec = crate::profile_root::spec();
|
||||
for argv in [
|
||||
args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT]),
|
||||
args(&[PROFILE_ROOT_FLAG, absolute()]),
|
||||
args(&[LAUNCH_PROFILE_FLAG, "future-v2", PROFILE_ROOT_FLAG, absolute(), "--"]),
|
||||
args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--"]),
|
||||
args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), PROFILE_ROOT_FLAG, absolute(), "--"]),
|
||||
args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, "", "--"]),
|
||||
args(&["--sample", LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute()]),
|
||||
] {
|
||||
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &startup_options()).is_err(), "{argv:?}");
|
||||
}
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,601 @@
|
||||
//! The desktop app's logger: `log::` records go to standard error and to a log file.
|
||||
//!
|
||||
//! Without a logger every `log::warn!`/`log::error!` in the workspace (the crash guard's panic
|
||||
//! report, a failed crash-recovery save, PowerPoint parts that were skipped on import, audio output
|
||||
//! problems) vanished. A launch from a desktop menu has no terminal, so the file is what a bug report
|
||||
//! can attach: `<settings dir>/logs/deckcraft.log`, beside `ui.json` and `prefs.json`. Each start
|
||||
//! moves the previous log to `deckcraft.1.log` (and that one to `.2`), so the log of a run that
|
||||
//! crashed survives the next launch.
|
||||
//!
|
||||
//! Levels: `info` for DeckCraft's own crates, `warn` for everything else (wgpu and naga are
|
||||
//! chatty). `RUST_LOG` replaces that with env_logger-style directives: `debug`,
|
||||
//! `warn,deckcraft_pptx=trace`, `wgpu_core=info`. A directive ending in `*` matches every target
|
||||
//! that starts with it (`deckcraft*=debug`).
|
||||
//!
|
||||
//! Records logged before the settings directory is known are kept (up to [`MAX_PENDING`]) and
|
||||
//! written once the file is attached. Writing never panics: a file that can't be created or written
|
||||
//! leaves standard error as the only sink.
|
||||
//!
|
||||
//! Realtime audio: the cpal callbacks (`audio.rs`) do not log; a stream error is kept and logged
|
||||
//! from the UI thread when the stream stops. A record takes the sink lock only for one `write_all`
|
||||
//! of an already formatted line (standard error is written outside the lock).
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, OnceLock, PoisonError};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use log::LevelFilter;
|
||||
|
||||
/// The current log file's name inside the log directory.
|
||||
pub const LOG_FILE: &str = "deckcraft.log";
|
||||
/// The log directory inside the settings directory.
|
||||
pub const LOG_DIR: &str = "logs";
|
||||
/// How many previous logs are kept (`deckcraft.1.log` … `deckcraft.<KEEP>.log`).
|
||||
pub const KEEP: usize = 2;
|
||||
/// The log file stops growing past this size (a runaway warning can't fill the disk).
|
||||
pub const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
|
||||
/// Records kept in memory until the log file is attached.
|
||||
pub const MAX_PENDING: usize = 512;
|
||||
/// The built-in filter when `RUST_LOG` is unset or empty.
|
||||
pub const DEFAULT_FILTER: &str = "warn,deckcraft*=info";
|
||||
|
||||
/// Per-target level filter parsed from env_logger-style directives.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Filter {
|
||||
default: LevelFilter,
|
||||
directives: Vec<(String, LevelFilter)>,
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
/// Parse `spec`; unknown levels and empty parts are skipped. Without a bare level, targets no
|
||||
/// directive names log errors only.
|
||||
pub fn parse(spec: &str) -> Filter {
|
||||
let mut f = Filter { default: LevelFilter::Error, directives: Vec::new() };
|
||||
for part in spec.split(',').map(str::trim).filter(|p| !p.is_empty()) {
|
||||
match part.split_once('=') {
|
||||
Some((name, level)) => {
|
||||
let name = name.trim();
|
||||
if let (false, Some(level)) = (name.is_empty(), parse_level(level)) {
|
||||
f.directives.push((name.to_owned(), level));
|
||||
}
|
||||
}
|
||||
None => match parse_level(part) {
|
||||
Some(level) => f.default = level,
|
||||
// A bare target name: everything from it (env_logger does the same).
|
||||
None => f.directives.push((part.to_owned(), LevelFilter::Trace)),
|
||||
},
|
||||
}
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
/// The level that applies to `target` (the most specific matching directive wins).
|
||||
pub fn level_for(&self, target: &str) -> LevelFilter {
|
||||
self.directives.iter().filter(|(name, _)| matches(name, target)).max_by_key(|(name, _)| name.len()).map_or(self.default, |(_, level)| *level)
|
||||
}
|
||||
|
||||
/// The most verbose level any target can reach (for `log::set_max_level`).
|
||||
pub fn max(&self) -> LevelFilter {
|
||||
self.directives.iter().map(|(_, level)| *level).fold(self.default, Ord::max)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_level(s: &str) -> Option<LevelFilter> {
|
||||
s.trim().parse().ok()
|
||||
}
|
||||
|
||||
/// `name` matches `target` itself and its submodules (`a` matches `a` and `a::b`, not `ab`);
|
||||
/// `name*` matches every target starting with `name`.
|
||||
fn matches(name: &str, target: &str) -> bool {
|
||||
match name.strip_suffix('*') {
|
||||
Some(prefix) => target.starts_with(prefix),
|
||||
None => target.strip_prefix(name).is_some_and(|rest| rest.is_empty() || rest.starts_with("::")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `2026-10-08T07:59:17.728Z` (UTC, milliseconds). A clock before 1970 reads as the epoch; a clock
|
||||
/// set absurdly far ahead keeps its real year (years far outside chrono's own range are preserved)
|
||||
/// instead of panicking.
|
||||
pub fn timestamp(t: SystemTime) -> String {
|
||||
let since = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
|
||||
let (y, dt) = utc_parts(since.as_secs(), since.subsec_nanos());
|
||||
// `{:04}` rather than `%Y`, which writes a `+` before years past 9999.
|
||||
format!("{y:04}-{}", dt.format("%m-%dT%H:%M:%S%.3fZ"))
|
||||
}
|
||||
|
||||
/// Unix seconds (+ nanos) → (proleptic Gregorian year, the same wall-clock instant moved into
|
||||
/// chrono's range by whole 400-year cycles). The Gregorian calendar repeats every 400 years
|
||||
/// (146_097 days), so month, day and time of day come from chrono and only the year is carried,
|
||||
/// which keeps every input exact instead of collapsing out-of-range years to the epoch. `secs` is
|
||||
/// `u64` (the clock is clamped at the epoch before 1970), so `days` always fits an `i64`.
|
||||
fn utc_parts(secs: u64, nanos: u32) -> (i64, chrono::NaiveDateTime) {
|
||||
use chrono::Datelike;
|
||||
let (days, sod) = ((secs / 86_400) as i64, (secs % 86_400) as i64);
|
||||
let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097));
|
||||
// `rest + 719_163` (1970-01-01 is CE day 719_163) is always a valid CE day, and `sod` < 86_400.
|
||||
let date = i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt);
|
||||
let time = u32::try_from(sod).ok().and_then(|s| chrono::NaiveTime::from_num_seconds_from_midnight_opt(s, nanos.min(999_999_999)));
|
||||
match (date, time) {
|
||||
(Some(d), Some(t)) => {
|
||||
let y = i128::from(d.year()) + i128::from(cycles) * 400;
|
||||
(i64::try_from(y).unwrap_or(i64::MAX), d.and_time(t))
|
||||
}
|
||||
_ => (1970, chrono::NaiveDateTime::default()), // unreachable
|
||||
}
|
||||
}
|
||||
|
||||
fn numbered(dir: &Path, n: usize) -> PathBuf {
|
||||
if n == 0 { dir.join(LOG_FILE) } else { dir.join(format!("deckcraft.{n}.log")) }
|
||||
}
|
||||
|
||||
/// Shift the previous logs up one (`.log` → `.1.log` → … → `.<KEEP>.log`, the oldest dropped)
|
||||
/// and create a fresh, empty log file in `dir` (created if missing).
|
||||
pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
for n in (1..=KEEP).rev() {
|
||||
match std::fs::rename(numbered(dir, n - 1), numbered(dir, n)) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let path = numbered(dir, 0);
|
||||
let file = File::create(&path)?;
|
||||
Ok((path, file))
|
||||
}
|
||||
|
||||
/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`.
|
||||
pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String {
|
||||
let message = message.strip_suffix('\n').unwrap_or(message);
|
||||
// Messages can embed document-controlled text (a part name, a relationship id): control
|
||||
// characters other than tab are escaped and each continuation line is marked, so such text
|
||||
// cannot start a line that looks like a record of its own.
|
||||
let mut text = String::with_capacity(message.len());
|
||||
for c in message.chars() {
|
||||
match c {
|
||||
'\n' => text.push_str("\n | "),
|
||||
'\t' => text.push(c),
|
||||
c if c.is_control() => text.extend(c.escape_default()),
|
||||
c => text.push(c),
|
||||
}
|
||||
}
|
||||
format!("{ts} {level:<5} [{thread}] {target}: {text}\n")
|
||||
}
|
||||
|
||||
/// Where formatted lines go besides standard error: kept in memory until a file is attached,
|
||||
/// then appended to it until it reaches its size cap.
|
||||
pub struct Sink {
|
||||
file: Option<File>,
|
||||
pending: Vec<String>,
|
||||
dropped: usize,
|
||||
written: u64,
|
||||
max_bytes: u64,
|
||||
capped: bool,
|
||||
}
|
||||
|
||||
impl Sink {
|
||||
pub fn new(max_bytes: u64) -> Sink {
|
||||
Sink { file: None, pending: Vec::new(), dropped: 0, written: 0, max_bytes, capped: false }
|
||||
}
|
||||
|
||||
/// Append `line` to the file, or keep it until [`Sink::attach`].
|
||||
pub fn write(&mut self, line: &str) {
|
||||
if self.file.is_none() {
|
||||
if self.capped {
|
||||
return;
|
||||
}
|
||||
if self.pending.len() < MAX_PENDING {
|
||||
self.pending.push(line.to_owned());
|
||||
} else {
|
||||
self.dropped = self.dropped.saturating_add(1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.append(line);
|
||||
}
|
||||
|
||||
/// Start writing to `file`, first the lines kept so far.
|
||||
pub fn attach(&mut self, file: File) {
|
||||
self.file = Some(file);
|
||||
for line in std::mem::take(&mut self.pending) {
|
||||
self.append(&line);
|
||||
}
|
||||
if self.dropped > 0 {
|
||||
let note = format!("{} earlier log lines were dropped before the log file was opened\n", self.dropped);
|
||||
self.dropped = 0;
|
||||
self.append(¬e);
|
||||
}
|
||||
}
|
||||
|
||||
/// No file will come: drop the kept lines and keep none from now on.
|
||||
pub fn close(&mut self) {
|
||||
self.file = None;
|
||||
self.pending = Vec::new();
|
||||
self.capped = true;
|
||||
}
|
||||
|
||||
fn append(&mut self, line: &str) {
|
||||
if self.capped {
|
||||
return;
|
||||
}
|
||||
let Some(file) = self.file.as_mut() else { return };
|
||||
let len = u64::try_from(line.len()).unwrap_or(u64::MAX);
|
||||
let text = if self.written.saturating_add(len) > self.max_bytes {
|
||||
self.capped = true;
|
||||
format!("log file reached {} bytes; later records go to standard error only\n", self.max_bytes)
|
||||
} else {
|
||||
self.written = self.written.saturating_add(len);
|
||||
line.to_owned()
|
||||
};
|
||||
// A full disk or a vanished file must not take the app down: drop the file sink (and
|
||||
// stop buffering, since no file will come).
|
||||
if file.write_all(text.as_bytes()).is_err() {
|
||||
self.file = None;
|
||||
self.capped = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The installed logger: a [`Filter`], standard error and a [`Sink`].
|
||||
pub struct AppLogger {
|
||||
filter: Filter,
|
||||
stderr: bool,
|
||||
sink: Mutex<Sink>,
|
||||
}
|
||||
|
||||
impl AppLogger {
|
||||
pub fn new(filter: Filter, stderr: bool) -> AppLogger {
|
||||
AppLogger { filter, stderr, sink: Mutex::new(Sink::new(MAX_FILE_BYTES)) }
|
||||
}
|
||||
|
||||
/// Rotate the logs in `dir` and send records to the fresh file; returns its path.
|
||||
/// An unusable directory leaves standard error as the only sink ([`AppLogger::stderr_only`]).
|
||||
pub fn attach_dir(&self, dir: &Path) -> Result<PathBuf, String> {
|
||||
match rotate(dir) {
|
||||
Ok((path, file)) => {
|
||||
self.sink.lock().unwrap_or_else(PoisonError::into_inner).attach(file);
|
||||
Ok(path)
|
||||
}
|
||||
Err(e) => {
|
||||
self.stderr_only();
|
||||
Err(format!("{}: {e}", dir.display()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// No log file this run (no settings directory, or it can't be used): stop keeping records for one.
|
||||
pub fn stderr_only(&self) {
|
||||
self.sink.lock().unwrap_or_else(PoisonError::into_inner).close();
|
||||
}
|
||||
}
|
||||
|
||||
impl log::Log for AppLogger {
|
||||
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
|
||||
metadata.level() <= self.filter.level_for(metadata.target())
|
||||
}
|
||||
|
||||
fn log(&self, record: &log::Record<'_>) {
|
||||
if !self.enabled(record.metadata()) {
|
||||
return;
|
||||
}
|
||||
// Format before taking the lock, so the lock covers one write only.
|
||||
let thread = std::thread::current();
|
||||
let line =
|
||||
format_line(×tamp(SystemTime::now()), record.level(), thread.name().unwrap_or("?"), record.target(), &record.args().to_string());
|
||||
if self.stderr {
|
||||
let _ = std::io::stderr().write_all(line.as_bytes());
|
||||
}
|
||||
self.sink.lock().unwrap_or_else(PoisonError::into_inner).write(&line);
|
||||
}
|
||||
|
||||
fn flush(&self) {}
|
||||
}
|
||||
|
||||
/// Install the logger (filter from `RUST_LOG`, else [`DEFAULT_FILTER`]); `None` when another
|
||||
/// logger was installed first. Call [`AppLogger::attach_dir`] once the settings directory is known.
|
||||
pub fn install() -> Option<&'static AppLogger> {
|
||||
static LOGGER: OnceLock<AppLogger> = OnceLock::new();
|
||||
let spec = std::env::var("RUST_LOG").ok().filter(|s| !s.trim().is_empty());
|
||||
let filter = Filter::parse(spec.as_deref().unwrap_or(DEFAULT_FILTER));
|
||||
let max = filter.max();
|
||||
let logger = LOGGER.get_or_init(|| AppLogger::new(filter, true));
|
||||
log::set_logger(logger).ok()?;
|
||||
log::set_max_level(max);
|
||||
Some(logger)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use log::Log;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
let d = std::env::temp_dir().join(format!("deckcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
d
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> String {
|
||||
std::fs::read_to_string(path).expect("read log")
|
||||
}
|
||||
|
||||
fn record(logger: &AppLogger, level: log::Level, target: &'static str, msg: &'static str) {
|
||||
logger.log(&log::Record::builder().level(level).target(target).args(format_args!("{msg}")).build());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_filter_shows_deckcraft_info_and_other_crates_warnings() {
|
||||
let f = Filter::parse(DEFAULT_FILTER);
|
||||
assert_eq!(f.level_for("deckcraft"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("deckcraft::audio"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("deckcraft_engine::guard"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("deckcraft_pptx::read"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("wgpu_core::device"), LevelFilter::Warn);
|
||||
assert_eq!(f.level_for("naga"), LevelFilter::Warn);
|
||||
assert_eq!(f.max(), LevelFilter::Info);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directives_follow_env_logger_and_the_most_specific_one_wins() {
|
||||
let f = Filter::parse("info,wgpu_core=error,deckcraft_pptx=trace,deckcraft_pptx::opc=off");
|
||||
assert_eq!(f.level_for("eframe"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("wgpu_core::instance"), LevelFilter::Error);
|
||||
assert_eq!(f.level_for("deckcraft_pptx::read"), LevelFilter::Trace);
|
||||
assert_eq!(f.level_for("deckcraft_pptx::opc"), LevelFilter::Off);
|
||||
assert_eq!(f.max(), LevelFilter::Trace);
|
||||
// A module name is matched at `::` boundaries, not as a bare prefix.
|
||||
assert_eq!(f.level_for("wgpu_core_extra"), LevelFilter::Info);
|
||||
// A trailing `*` is a prefix.
|
||||
assert_eq!(Filter::parse("warn,deckcraft_ui*=debug").level_for("deckcraft_ui_egui::canvas"), LevelFilter::Debug);
|
||||
assert_eq!(Filter::parse("warn,deckcraft_ui*=debug").level_for("deckcraft_engine"), LevelFilter::Warn);
|
||||
// A bare target name sets that target to the most verbose level, as env_logger does.
|
||||
assert_eq!(Filter::parse("naga").level_for("naga::front"), LevelFilter::Trace);
|
||||
assert_eq!(Filter::parse("naga").level_for("eframe"), LevelFilter::Error);
|
||||
// Levels are case-insensitive; the last bare level wins.
|
||||
assert_eq!(Filter::parse("debug,WARN").level_for("x"), LevelFilter::Warn);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_specs_never_panic_and_fall_back_sensibly() {
|
||||
let long = "a".repeat(100_000);
|
||||
let specs = [
|
||||
"",
|
||||
",,,",
|
||||
"=",
|
||||
"==",
|
||||
"=debug",
|
||||
"deckcraft=",
|
||||
"nonsense=loud",
|
||||
"🦀=info",
|
||||
"*",
|
||||
"*=debug",
|
||||
"a=b=c",
|
||||
"warn,,deckcraft=DEBUG",
|
||||
" \t ",
|
||||
"\u{0}",
|
||||
"é*=trace",
|
||||
&long,
|
||||
];
|
||||
for spec in specs {
|
||||
let f = Filter::parse(spec);
|
||||
for target in ["deckcraft", "", "🦀", "é", "a::b"] {
|
||||
let _ = f.level_for(target);
|
||||
}
|
||||
let _ = f.max();
|
||||
}
|
||||
assert_eq!(Filter::parse("warn,,deckcraft=DEBUG").level_for("deckcraft"), LevelFilter::Debug);
|
||||
assert_eq!(Filter::parse("nonsense=loud").level_for("nonsense"), LevelFilter::Error);
|
||||
assert_eq!(Filter::parse("=debug").max(), LevelFilter::Error, "a directive without a name is skipped");
|
||||
assert_eq!(Filter::parse("*=debug").level_for("anything"), LevelFilter::Debug, "a lone `*` matches every target");
|
||||
assert_eq!(Filter::parse("é*=trace").level_for("éa"), LevelFilter::Trace);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timestamps_are_utc_with_milliseconds() {
|
||||
assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_millis(1_791_446_357_728)), "2026-10-08T07:59:17.728Z");
|
||||
// Leap day, and the day after it.
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), "2024-02-29T00:00:00.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_199)), "2024-02-29T23:59:59.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_200)), "2024-03-01T00:00:00.000Z");
|
||||
// 2000 is a leap year (divisible by 400), 2100 is not.
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00:00:00.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z");
|
||||
// Before the epoch (a clock set wrong) clamps instead of panicking.
|
||||
assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z");
|
||||
// A clock set absurdly far ahead (past chrono's own range) keeps its real year rather than
|
||||
// collapsing to the epoch. Windows' SystemTime can't hold such an instant, so it is built
|
||||
// with a checked add and only asserted where it exists.
|
||||
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) {
|
||||
assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z");
|
||||
}
|
||||
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) {
|
||||
assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z");
|
||||
}
|
||||
// Years past 9999 keep the plain zero-padded year (no `+`).
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() {
|
||||
let dir = temp_dir("rotate");
|
||||
for run in 1..=4 {
|
||||
let (path, _file) = rotate(&dir).expect("rotate");
|
||||
assert_eq!(path, dir.join(LOG_FILE));
|
||||
assert_eq!(read(&path), "");
|
||||
std::fs::write(&path, format!("run {run}")).expect("write");
|
||||
}
|
||||
assert_eq!(read(&dir.join(LOG_FILE)), "run 4");
|
||||
assert_eq!(read(&dir.join("deckcraft.1.log")), "run 3");
|
||||
assert_eq!(read(&dir.join("deckcraft.2.log")), "run 2");
|
||||
assert!(!dir.join("deckcraft.3.log").exists(), "only {KEEP} old logs are kept");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_into_an_unusable_directory_is_an_error_not_a_panic() {
|
||||
let dir = temp_dir("blocked");
|
||||
std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp");
|
||||
std::fs::write(&dir, "a file where the directory should be").expect("block");
|
||||
assert!(rotate(&dir).is_err());
|
||||
assert!(rotate(&dir.join("below")).is_err());
|
||||
let _ = std::fs::remove_file(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_carries_time_level_thread_target_and_message() {
|
||||
assert_eq!(
|
||||
format_line(
|
||||
"2026-10-08T07:59:17.728Z",
|
||||
log::Level::Warn,
|
||||
"main",
|
||||
"deckcraft_pptx::opc",
|
||||
"pptx: skipping oversized part ppt/media/image1.png"
|
||||
),
|
||||
"2026-10-08T07:59:17.728Z WARN [main] deckcraft_pptx::opc: pptx: skipping oversized part ppt/media/image1.png\n"
|
||||
);
|
||||
// A multi-line message keeps its lines, each continuation marked; the record still ends in
|
||||
// exactly one newline.
|
||||
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\n | b\n"));
|
||||
// Injected line breaks and escape sequences cannot forge a record.
|
||||
let line = format_line("t", log::Level::Warn, "w", "x", "part a\r\n2026 ERROR [m] y: forged\x1b[2J");
|
||||
assert_eq!(line.matches('\n').count(), 2);
|
||||
assert!(!line.contains('\r') && !line.contains('\x1b'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_logged_before_the_file_exists_are_written_when_it_is_attached() {
|
||||
let dir = temp_dir("pending");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
sink.write("early 1\n");
|
||||
sink.write("early 2\n");
|
||||
sink.attach(file);
|
||||
sink.write("late\n");
|
||||
assert_eq!(read(&path), "early 1\nearly 2\nlate\n");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() {
|
||||
let dir = temp_dir("bounded");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
for i in 0..MAX_PENDING + 5 {
|
||||
sink.write(&format!("line {i}\n"));
|
||||
}
|
||||
sink.attach(file);
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), MAX_PENDING);
|
||||
assert_eq!(text.matches("5 earlier log lines were dropped").count(), 1, "{text}");
|
||||
assert!(text.contains("line 0\n") && !text.contains(&format!("line {MAX_PENDING}\n")));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exactly_max_pending_lines_drop_nothing() {
|
||||
let dir = temp_dir("exact");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
for i in 0..MAX_PENDING {
|
||||
sink.write(&format!("line {i}\n"));
|
||||
}
|
||||
sink.attach(file);
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().count(), MAX_PENDING);
|
||||
assert!(!text.contains("dropped"), "{text}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_stops_at_its_size_cap_with_one_note() {
|
||||
let dir = temp_dir("cap");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(100);
|
||||
sink.attach(file);
|
||||
for i in 0..50 {
|
||||
sink.write(&format!("line {i:02} with some padding\n"));
|
||||
}
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), 3, "{text}");
|
||||
assert_eq!(text.matches("log file reached 100 bytes").count(), 1, "{text}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_logger_filters_records_and_writes_them_to_the_attached_file() {
|
||||
let dir = temp_dir("logger");
|
||||
let logger = AppLogger::new(Filter::parse(DEFAULT_FILTER), false);
|
||||
record(&logger, log::Level::Info, "deckcraft", "DeckCraft starting");
|
||||
record(&logger, log::Level::Info, "wgpu_core::device", "too chatty");
|
||||
let path = logger.attach_dir(&dir).expect("attach");
|
||||
assert_eq!(path, dir.join(LOG_FILE));
|
||||
record(&logger, log::Level::Warn, "wgpu_hal::vulkan", "a real warning");
|
||||
record(&logger, log::Level::Debug, "deckcraft", "below info");
|
||||
let text = read(&path);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines.len(), 2, "{text}");
|
||||
assert!(lines.first().is_some_and(|l| l.contains(" INFO [") && l.ends_with("deckcraft: DeckCraft starting")), "{text}");
|
||||
assert!(lines.get(1).is_some_and(|l| l.ends_with("wgpu_hal::vulkan: a real warning")), "{text}");
|
||||
assert!(logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("deckcraft_engine::recovery").build()));
|
||||
assert!(!logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("naga").build()));
|
||||
// A second launch rotates: the first log becomes `.1`.
|
||||
let second = AppLogger::new(Filter::parse(DEFAULT_FILTER), false);
|
||||
assert_eq!(second.attach_dir(&dir).expect("attach again"), dir.join(LOG_FILE));
|
||||
assert_eq!(read(&dir.join("deckcraft.1.log")), text);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn records_from_many_threads_are_whole_lines() {
|
||||
let dir = temp_dir("threads");
|
||||
let logger = AppLogger::new(Filter::parse("info"), false);
|
||||
let path = logger.attach_dir(&dir).expect("attach");
|
||||
std::thread::scope(|s| {
|
||||
for _ in 0..4 {
|
||||
s.spawn(|| {
|
||||
for _ in 0..100 {
|
||||
record(&logger, log::Level::Info, "deckcraft", "from a worker");
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().count(), 400);
|
||||
assert!(text.lines().all(|l| l.ends_with("deckcraft: from a worker")), "{text}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attaching_to_an_unusable_directory_reports_an_error_and_keeps_logging() {
|
||||
let dir = temp_dir("unusable");
|
||||
std::fs::write(&dir, "not a directory").expect("block");
|
||||
let logger = AppLogger::new(Filter::parse("info"), false);
|
||||
let e = logger.attach_dir(&dir).expect_err("a file is not a log directory");
|
||||
assert!(e.contains(&dir.display().to_string()), "{e}");
|
||||
record(&logger, log::Level::Error, "x", "still fine");
|
||||
let sink = logger.sink.lock().expect("sink");
|
||||
assert!(sink.file.is_none() && sink.pending.is_empty(), "nothing is kept for a file that will not come");
|
||||
drop(sink);
|
||||
let _ = std::fs::remove_file(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_poisoned_lock_does_not_stop_logging() {
|
||||
let dir = temp_dir("poison");
|
||||
let logger = AppLogger::new(Filter::parse("info"), false);
|
||||
let path = logger.attach_dir(&dir).expect("attach");
|
||||
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
let _guard = logger.sink.lock();
|
||||
panic!("poison the sink");
|
||||
}));
|
||||
assert!(logger.sink.is_poisoned());
|
||||
record(&logger, log::Level::Info, "deckcraft", "after the panic");
|
||||
assert!(read(&path).contains("after the panic"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
+298
-242
@@ -1,119 +1,170 @@
|
||||
//! DeckCraft desktop app.
|
||||
//!
|
||||
//! Usage: `deckcraft [--control <port>] [--control-token <token> | --control-token-file <path>] [--sample] [--show] [files…]`
|
||||
//! Usage: `deckcraft [--control <port>] [--sample] [--show] [files…]`
|
||||
//! A PowerPoint Show (`.ppsx`) given last starts its slide show, as a double-click does in PowerPoint.
|
||||
//! `deckcraft --help` prints the flags and exits. `deckcraft --version` prints the version and exits.
|
||||
//!
|
||||
//! `--control <port>` (or `DECKCRAFT_CONTROL_PORT`) starts an authenticated localhost JSON-lines server.
|
||||
//! Supply `--control-token` or `--control-token-file`, or use the per-launch token printed to stderr.
|
||||
//! After authentication, a request and reply look like:
|
||||
//! `--control <port>` (or `DECKCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server:
|
||||
//! `{"id":1,"method":"ui.inspect","params":{}}` → `{"id":1,"ok":true,"result":…}`.
|
||||
//! See `deckcraft_ui_egui::control` for the methods.
|
||||
//!
|
||||
//! `log` records go to standard error and `<settings dir>/logs/deckcraft.log` (`RUST_LOG` sets the
|
||||
//! levels); see [`craft::platform::logs`].
|
||||
//! levels); see [`logging`].
|
||||
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
|
||||
#![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 std::sync::{Arc, OnceLock};
|
||||
use deckcraft_engine::Session;
|
||||
use deckcraft_ui_egui::{Services, SlideApp};
|
||||
|
||||
use craft::automation::args::{ControlOptions, EnvNames, FlagNames, OptionsError, Source, USAGE_EXIT_CODE, control_port};
|
||||
use craft::automation::control::ControlChannel;
|
||||
use craft::automation::server::{Listening, ServerLimits, listen_with};
|
||||
use craft::behavior::placement::Defaults;
|
||||
use craft::dialogs::service::{FilePanels, FileService};
|
||||
use craft::host::target::{Backend, ShellInfo};
|
||||
use craft::host::{AppInfo, Host, Wake};
|
||||
use craft::platform::clipboard::{Clipboard, ClipboardImage, SystemClipboard};
|
||||
use craft::platform::logs::{self, LogNames};
|
||||
use craft::platform::open::FileIntake;
|
||||
use craft::settings::Location;
|
||||
use craft::ui::runtime::InstallSpec;
|
||||
use craft::ui::runtime::env::SystemReader;
|
||||
use craft::ui::runtime::windows::WindowHost;
|
||||
use craft::ui::shell::app::{AppSpec, native_options};
|
||||
use craft::ui::shell::embed;
|
||||
use craft::window::Prefix;
|
||||
use craft::window::policy::{Frame, TitleBarPref, decide_for};
|
||||
use deckcraft_ui_egui::{Platform, SlideApp};
|
||||
|
||||
const NAMES: LogNames = LogNames::new("deckcraft");
|
||||
const PREFIX: Prefix = Prefix::new("DECKCRAFT");
|
||||
const ICON_128: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.deckcraft.png");
|
||||
|
||||
struct App {
|
||||
app: SlideApp,
|
||||
panels: FilePanels,
|
||||
_control: Option<Listening>,
|
||||
}
|
||||
struct App(
|
||||
SlideApp,
|
||||
/// Files opened from Finder and quit requests (see `apple_events`).
|
||||
#[cfg(target_os = "macos")]
|
||||
fmv_macos_events::Inbox,
|
||||
);
|
||||
|
||||
impl eframe::App for App {
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
self.app.logic(ctx);
|
||||
#[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.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
// egui-winit's WindowEvent::Focused arm emits WindowFocused. Only this pass's events
|
||||
// trigger a refresh; a second pass with no input cannot repeat the activation.
|
||||
if raw.events.iter().any(|event| matches!(event, egui::Event::WindowFocused(true))) {
|
||||
craft::font_catalog::app::on_activated();
|
||||
}
|
||||
self.app.raw_input_hook(ctx, raw);
|
||||
self.0.raw_input_hook(ctx, raw);
|
||||
self.0.before_input(ctx);
|
||||
}
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
embed::before_ui(ui.ctx(), frame);
|
||||
self.app.ui(ui);
|
||||
self.panels.pump(Some(frame));
|
||||
deckcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
|
||||
self.0.ui(ui);
|
||||
}
|
||||
fn on_exit(&mut self) {
|
||||
self.app.leave();
|
||||
// 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.
|
||||
self.0.start_pending_update();
|
||||
// macOS (#279): end the process here, before eframe tears the window down. AccessKit's
|
||||
// macOS adapter subclasses the window's content view and restores its class on teardown;
|
||||
// AppKit's Touch Bar support observes that view (KVO), so in the next display cycle
|
||||
// `-[_NSTouchBarFinderObservation invalidate]` throws "not registered" and the quit ends
|
||||
// in a crash report. eframe calls `on_exit` on every way of quitting (⌘Q, the close
|
||||
// button, `app.quit`), once the unsaved-changes prompt has let the window close, and
|
||||
// nothing after it is needed: the preferences are saved and the log file is unbuffered.
|
||||
// `on_exit` only runs once the app exists, never on a failed start. Same as GridCraft #117.
|
||||
#[cfg(target_os = "macos")]
|
||||
self.0.cleanup_print_previews();
|
||||
#[cfg(target_os = "macos")]
|
||||
std::process::exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
fn desktop_platform(install: InstallSpec, settings: Location, wake: Wake, at_exit: Option<Box<dyn FnOnce()>>) -> (Platform, FilePanels) {
|
||||
let (service, panels) = FileService::new(wake);
|
||||
let host = Host::builder(AppInfo {
|
||||
id: "deckcraft",
|
||||
name: deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::identity()),
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
})
|
||||
.icon_png(ICON_128)
|
||||
.files(Arc::new(service))
|
||||
.build();
|
||||
let frame = install.frame.as_ref().map_or(Frame::Native, |decision| decision.frame.clone());
|
||||
(Platform { install, host, settings, intake: None, audio_out: None, control: None, frame, at_exit }, panels)
|
||||
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 (ui, prefs) = deckcraft_ui_egui::settings::load(&dir);
|
||||
if let Some(ui) = ui {
|
||||
app.ui = ui;
|
||||
}
|
||||
if let Some(prefs) = prefs {
|
||||
app.session.prefs = prefs;
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_png(bytes: &[u8]) -> Option<ClipboardImage> {
|
||||
let rgba = image::load_from_memory_with_format(bytes, image::ImageFormat::Png).ok()?.into_rgba8();
|
||||
Some(ClipboardImage { width: rgba.width(), height: rgba.height(), rgba: rgba.into_raw() })
|
||||
fn save_prefs(app: &SlideApp) {
|
||||
if std::env::var_os("DECKCRAFT_NO_PREFS").is_some() {
|
||||
return;
|
||||
}
|
||||
if let Some(dir) = app_dirs::config_dir() {
|
||||
deckcraft_ui_egui::settings::save(&dir, &app.ui, &app.session.prefs);
|
||||
}
|
||||
}
|
||||
|
||||
/// The desktop services. `native_wayland`: the window is a Wayland client (not Xwayland).
|
||||
fn services(native_wayland: bool) -> Services {
|
||||
// On native Wayland, egui-winit owns the clipboard through winit's data device, which carries
|
||||
// text and PNG but no HTML. `pasteboard` (arboard, built for X11 only) would put a copy on the
|
||||
// Xwayland selection instead and skip egui's Wayland claim, so Ctrl+V would read something
|
||||
// else. There, text goes through egui and pictures arrive as `PasteImage` events.
|
||||
let pasteboard = !native_wayland;
|
||||
Services {
|
||||
pick_open: Some(Box::new(|purpose: &str| {
|
||||
let d = rfd::FileDialog::new();
|
||||
let d = match purpose {
|
||||
"picture" => d.add_filter("Pictures", &["png", "jpg", "jpeg", "gif", "webp", "bmp", "tif", "tiff"]),
|
||||
"audio" => d.add_filter(
|
||||
"Audio",
|
||||
&["wav", "mp3", "m4a", "m4b", "aac", "flac", "ogg", "oga", "opus", "aif", "aiff", "aifc", "caf", "wma", "weba", "mka"],
|
||||
),
|
||||
"video" => d.add_filter("Video", &["mp4", "m4v", "mov", "webm", "mkv", "wmv"]),
|
||||
"theme" => d.add_filter("Themes and presentations", &["thmx", "pptx", "potx", "ppsx"]).add_filter("Office Theme", &["thmx"]),
|
||||
_ => d
|
||||
.add_filter("Presentations", &["deckcraft", "pptx", "potx", "ppsx", "ppt", "pot", "pps"])
|
||||
.add_filter("DeckCraft", &["deckcraft"])
|
||||
.add_filter("PowerPoint", &["pptx", "potx", "ppsx"])
|
||||
.add_filter("PowerPoint 97-2003", &["ppt", "pot", "pps"])
|
||||
.add_filter("Outline", &["txt", "md"]),
|
||||
};
|
||||
d.pick_file().map(|p| p.to_string_lossy().to_string())
|
||||
})),
|
||||
pick_save: Some(Box::new(|name: &str| rfd::FileDialog::new().set_file_name(name).save_file().map(|p| p.to_string_lossy().to_string()))),
|
||||
read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),
|
||||
write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))),
|
||||
clipboard_image: pasteboard.then(|| Box::new(pasteboard::image_png) as Box<dyn FnMut() -> Option<Vec<u8>>>),
|
||||
clipboard_html: pasteboard.then(|| Box::new(pasteboard::html) as Box<dyn FnMut() -> Option<String>>),
|
||||
clipboard_set_html: pasteboard.then(|| Box::new(pasteboard::set_html) as Box<dyn FnMut(&str, &str) -> bool>),
|
||||
// Media is mixed and clocked by the output device; `DECKCRAFT_NO_AUDIO` plays silently.
|
||||
audio_out: std::env::var_os("DECKCRAFT_NO_AUDIO")
|
||||
.is_none()
|
||||
.then(|| Box::new(audio::CpalOut::default()) as Box<dyn deckcraft_media::AudioOut>),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Displays winit lists for `window`, counting an output Wayland lists twice once. `None` when it
|
||||
/// lists none: Presenter View then stays as it was.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn display_count(window: &winit::window::Window) -> Option<usize> {
|
||||
let n = window.available_monitors().collect::<std::collections::BTreeSet<_>>().len();
|
||||
(n > 0).then_some(n)
|
||||
}
|
||||
|
||||
const USAGE: &str = "\
|
||||
Usage: deckcraft [--control PORT] [--control-token TOKEN | --control-token-file PATH] [--sample] [--show] [FILE...]
|
||||
Usage: deckcraft [--control PORT] [--sample] [--show] [FILE...]
|
||||
|
||||
--control PORT JSON control server on 127.0.0.1:PORT
|
||||
--control-token TOKEN authenticate with a 64-character hexadecimal token
|
||||
--control-token-file PATH read the control token from a file
|
||||
--sample open the sample presentation
|
||||
--show start the slide show
|
||||
--help, -h print this help and exit
|
||||
--version, -V print the version and exit
|
||||
--control PORT JSON control server on 127.0.0.1:PORT
|
||||
--sample open the sample presentation
|
||||
--show start the slide show
|
||||
--help, -h print this help and exit
|
||||
--version, -V print the version and exit
|
||||
|
||||
A PowerPoint Show (.ppsx) given last starts its slide show.
|
||||
";
|
||||
@@ -121,12 +172,11 @@ A PowerPoint Show (.ppsx) given last starts its slide show.
|
||||
enum Startup {
|
||||
Help,
|
||||
Version,
|
||||
Run { control: ControlOptions, files: Vec<String>, sample: bool, show: bool },
|
||||
Run { control_port: Option<u16>, files: Vec<String>, sample: bool, show: bool },
|
||||
}
|
||||
|
||||
/// `--help` and `--version` leave before the window and the log file.
|
||||
fn startup(nightly: bool, args: impl IntoIterator<Item = String>) -> Result<Startup, String> {
|
||||
let mut flags = ControlOptions::default();
|
||||
fn startup(mut control_port: Option<u16>, args: impl IntoIterator<Item = String>) -> Startup {
|
||||
let mut files = Vec::new();
|
||||
let mut sample = false;
|
||||
let mut show = false;
|
||||
@@ -138,42 +188,17 @@ fn startup(nightly: bool, args: impl IntoIterator<Item = String>) -> Result<Star
|
||||
files.extend(args.by_ref());
|
||||
break;
|
||||
}
|
||||
"--control" | "--control-token" | "--control-token-file" => {
|
||||
let value = args.next().ok_or_else(|| format!("a value is required for '{a}'"))?;
|
||||
match a.as_str() {
|
||||
"--control" => {
|
||||
let port =
|
||||
control_port(&value).map_err(|_| OptionsError::NotAPort { value, shown: "--control <PORT>".into() }.to_string())?;
|
||||
flags.port = Some(port);
|
||||
flags.sources.port = Some(Source::Flag);
|
||||
}
|
||||
"--control-token" => {
|
||||
flags.token = Some(value);
|
||||
flags.sources.token = Some(Source::Flag);
|
||||
}
|
||||
_ => {
|
||||
flags.token_file = Some(value.into());
|
||||
flags.sources.token_file = Some(Source::Flag);
|
||||
}
|
||||
}
|
||||
}
|
||||
"--control" => control_port = args.next().and_then(|p| p.parse().ok()),
|
||||
"--sample" => sample = true,
|
||||
"--show" => show = true,
|
||||
"--version" | "-V" => return Ok(Startup::Version),
|
||||
"--help" | "-h" => return Ok(Startup::Help),
|
||||
"--version" | "-V" => return Startup::Version,
|
||||
"--help" | "-h" => return Startup::Help,
|
||||
// The process serial number older macOS adds when Finder launches the app.
|
||||
a if a.starts_with("-psn_") => {}
|
||||
_ => files.push(a),
|
||||
}
|
||||
}
|
||||
let names = EnvNames::for_app("DECKCRAFT");
|
||||
let control = if nightly {
|
||||
ControlOptions::merged(flags, ControlOptions::default())
|
||||
} else {
|
||||
ControlOptions::resolve(flags, &names).map_err(|e| e.to_string())?
|
||||
};
|
||||
control.check(&FlagNames::default(), &names).map_err(|e| e.to_string())?;
|
||||
Ok(Startup::Run { control, files, sample, show })
|
||||
Startup::Run { control_port, files, sample, show }
|
||||
}
|
||||
|
||||
fn app_icon() -> Option<egui::IconData> {
|
||||
@@ -187,44 +212,42 @@ fn app_icon() -> Option<egui::IconData> {
|
||||
|
||||
/// Select the immutable launch profile before any startup service or side effect.
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
// The trusted Launcher protocol (or direct nightly self-isolation) is decided before
|
||||
// logger/crash/update/font/prefs access.
|
||||
// The trusted Launcher protocol is decided before logger/crash/update/font/prefs access.
|
||||
let argv: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
// Preserve standalone version probes in environments without a resolvable profile directory.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1
|
||||
&& argv.len() == 1
|
||||
&& argv.first().is_some_and(|arg| arg == "--version" || arg == "-V")
|
||||
// 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::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2)
|
||||
});
|
||||
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// [--] --version`: answered before process identity, IPC or any window.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() {
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(std::io::stdout(), "DeckCraft {}", build_flavor::version(build_flavor::COMPILED, deckcraft_ui_egui::flavor::version()));
|
||||
return None;
|
||||
}
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2);
|
||||
}
|
||||
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) = deckcraft_ui_egui::os_window::select_identity(identity) {
|
||||
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.passthrough_args)
|
||||
Some(early.args)
|
||||
}
|
||||
|
||||
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
|
||||
@@ -264,9 +287,6 @@ fn report_launch_profile_error(error: &str) {
|
||||
|
||||
/// Install logging, parse startup arguments and environment, launch the native app, and
|
||||
/// propagate an eframe startup failure.
|
||||
/// The log folder's name in the profile (and the config folder), which the profile check expects.
|
||||
pub(crate) const LOG_DIR: &str = "logs";
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
let Some(arguments) = prepare_launch() else { return Ok(()) };
|
||||
let nightly = launch_profile::current().is_nightly();
|
||||
@@ -285,9 +305,9 @@ fn main() -> eframe::Result {
|
||||
let notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let exit_session = session.clone();
|
||||
let exit_notice = notice_shown.clone();
|
||||
// The engine's first Session chains its panic hook to the platform crash hook.
|
||||
let logger = logs::install(NAMES);
|
||||
logs::crash::install("DeckCraft", env!("CARGO_PKG_VERSION"), None);
|
||||
// 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<_>>())
|
||||
@@ -298,11 +318,10 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let launch = startup(nightly, arguments.into_iter().map(|a| a.to_string_lossy().into_owned())).unwrap_or_else(|error| {
|
||||
eprintln!("error: {error}\nFor more information, try '--help'.");
|
||||
std::process::exit(USAGE_EXIT_CODE);
|
||||
});
|
||||
let (control, files, sample, show) = match launch {
|
||||
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(());
|
||||
@@ -311,15 +330,14 @@ fn main() -> eframe::Result {
|
||||
println!("deckcraft {}", env!("CARGO_PKG_VERSION"));
|
||||
return Ok(());
|
||||
}
|
||||
Startup::Run { control, files, sample, show } => (control, files, sample, show),
|
||||
Startup::Run { control_port, files, sample, show } => (control_port, files, sample, show),
|
||||
};
|
||||
log::info!("DeckCraft {} ({} {})", deckcraft_ui_egui::flavor::version(), std::env::consts::OS, std::env::consts::ARCH);
|
||||
|
||||
// The log file lives under the settings directory; opened after the arguments, so `--help` and
|
||||
// `--version` leave no file behind. Records logged until now are written to it first.
|
||||
let log_dir = app_dirs::config_dir().map(|dir| dir.join(LOG_DIR));
|
||||
if let Some(logger) = logger {
|
||||
match log_dir.as_deref().map(|dir| logger.attach_dir(dir)) {
|
||||
match app_dirs::config_dir().map(|d| logger.attach_dir(&d.join(logging::LOG_DIR))) {
|
||||
Some(Ok(path)) => log::info!("log file {}", path.display()),
|
||||
Some(Err(e)) => log::warn!("no log file: {e}"),
|
||||
None => {
|
||||
@@ -328,111 +346,74 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
}
|
||||
}
|
||||
logs::crash::install("DeckCraft", env!("CARGO_PKG_VERSION"), log_dir);
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let backend = match display::choose_from_env() {
|
||||
display::Choice::X11 => Backend::X11,
|
||||
display::Choice::Default => Backend::from_env(),
|
||||
display::Choice::None => {
|
||||
// winit's own error says little to someone who started DeckCraft from a console.
|
||||
log::error!("no display: DISPLAY and WAYLAND_DISPLAY are not set");
|
||||
eprintln!("DeckCraft needs a graphical session: neither DISPLAY nor WAYLAND_DISPLAY is set.");
|
||||
Backend::from_env()
|
||||
}
|
||||
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_inner_size([1440.0, 900.0])
|
||||
.with_min_inner_size([900.0, 560.0])
|
||||
.with_drag_and_drop(true)
|
||||
.with_fullsize_content_view(true)
|
||||
.with_titlebar_shown(false)
|
||||
.with_title_shown(false),
|
||||
..Default::default()
|
||||
};
|
||||
#[cfg(not(all(unix, not(target_os = "macos"))))]
|
||||
let backend = Backend::from_env();
|
||||
let decision = decide_for(PREFIX, backend, if cfg!(target_os = "macos") { TitleBarPref::Integrated } else { TitleBarPref::System });
|
||||
let spec = AppSpec::new(
|
||||
deckcraft_ui_egui::os_window::app_id(),
|
||||
deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::identity()),
|
||||
Defaults::new([1440.0, 900.0], [900.0, 560.0]),
|
||||
)
|
||||
.shell_info(ShellInfo::default().backend(backend))
|
||||
.frame(decision.clone());
|
||||
let mut options = native_options(&spec);
|
||||
options.viewport = options.viewport.with_drag_and_drop(true);
|
||||
options.viewport = options.viewport.with_app_id(deckcraft_ui_egui::os_window::app_id());
|
||||
if let Some(icon) = app_icon() {
|
||||
options.viewport = options.viewport.with_icon(icon);
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if backend == Backend::X11 {
|
||||
let x11 = match display::choose_from_env() {
|
||||
display::Choice::X11 => true,
|
||||
display::Choice::Default => false,
|
||||
display::Choice::None => {
|
||||
// winit's own error says little to someone who started DeckCraft from a console.
|
||||
log::error!("no display: DISPLAY and WAYLAND_DISPLAY are not set");
|
||||
eprintln!("DeckCraft needs a graphical session: neither DISPLAY nor WAYLAND_DISPLAY is set.");
|
||||
false
|
||||
}
|
||||
};
|
||||
// `Default` lets winit choose, and winit takes Wayland whenever `WAYLAND_DISPLAY` is set.
|
||||
#[cfg(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"))))]
|
||||
let native_wayland = false;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if x11 {
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
use winit::platform::x11::EventLoopBuilderExtX11;
|
||||
b.with_x11();
|
||||
}));
|
||||
}
|
||||
// eframe supplies the display handle when the event loop exists.
|
||||
let mut setup = eframe::egui_wgpu::WgpuSetupCreateNew::without_display_handle();
|
||||
craft::gpu::configure(&mut setup);
|
||||
options.wgpu_options.wgpu_setup = eframe::egui_wgpu::WgpuSetup::CreateNew(setup);
|
||||
let context = Arc::new(OnceLock::<egui::Context>::new());
|
||||
let wake_context = context.clone();
|
||||
let wake = Wake::new(move || {
|
||||
if let Some(ctx) = wake_context.get() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
});
|
||||
let font_wake = wake.clone();
|
||||
craft::font_catalog::app::start(craft::font_catalog::app::AppFonts {
|
||||
dirs: craft::font_catalog::office_font_dirs(&craft::font_catalog::FontEnv::from_process()),
|
||||
on_change: Some(Arc::new(move |_| font_wake.wake())),
|
||||
..Default::default()
|
||||
});
|
||||
// Installation precedes the event loop so Finder's launch event reaches the same intake.
|
||||
let (intake, _sender) = FileIntake::new(wake.clone());
|
||||
// Before eframe creates the wgpu instance: default Windows to DirectX 12 with FXC (see graphics.rs).
|
||||
#[cfg(target_os = "windows")]
|
||||
graphics::configure(&mut options, eframe::wgpu::Backends::from_env(), eframe::wgpu::Dx12Compiler::from_env());
|
||||
// Registered before the event loop starts, so it catches the Finder event that launched us as
|
||||
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
|
||||
#[cfg(target_os = "macos")]
|
||||
let _apple = craft::platform::open::apple_events::install(_sender.clone());
|
||||
let apple_events = apple_events::AppleEvents::install();
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = &apple_events;
|
||||
let creator_notice = notice_shown.clone();
|
||||
let at_exit: Option<Box<dyn FnOnce()>> = Some(Box::new(move || {
|
||||
let mut services = services(native_wayland);
|
||||
// The Nightly session record is finished exactly once, on the clean exit path macOS has.
|
||||
services.at_exit = Some(Box::new(move || {
|
||||
nightly_session::finish_once(&exit_session, exit_notice.load(std::sync::atomic::Ordering::Relaxed));
|
||||
}));
|
||||
let result = eframe::run_native(
|
||||
deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::identity()),
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
let ctx = &cc.egui_ctx;
|
||||
let _ = context.set(ctx.clone());
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly"))]
|
||||
let window_system = embed::listed_monitors(cc);
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly")))]
|
||||
// PLAN: plan error: SystemWindows is craft::window::system::SystemWindows, supplied by AppSpec, not craft::ui::runtime::SystemWindows.
|
||||
let window_system = spec.window_system;
|
||||
let appearance_wake = wake.clone();
|
||||
let install = InstallSpec::new(spec.shell_info, window_system)
|
||||
.placement(spec.placement)
|
||||
.system(SystemReader::start(move || appearance_wake.wake()))
|
||||
.app_id(spec.app_id)
|
||||
.frame(decision)
|
||||
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)));
|
||||
let settings = if std::env::var_os("DECKCRAFT_NO_PREFS").is_some() {
|
||||
Location::Memory
|
||||
} else {
|
||||
app_dirs::config_dir().map_or(Location::Memory, Location::Dir)
|
||||
};
|
||||
let (mut platform, panels) = desktop_platform(install, settings, wake, at_exit);
|
||||
platform.intake = Some(intake);
|
||||
// The output device clocks media; disabling audio leaves playback silent.
|
||||
platform.audio_out =
|
||||
std::env::var_os("DECKCRAFT_NO_AUDIO").is_none().then(|| Box::new(audio::CpalOut::default()) as Box<dyn deckcraft_media::AudioOut>);
|
||||
let mut listening = None;
|
||||
if let Some(port) = control.port {
|
||||
let token = control.server_token().unwrap_or_else(|error| {
|
||||
eprintln!("error: {error}\nFor more information, try '--help'.");
|
||||
std::process::exit(USAGE_EXIT_CODE);
|
||||
});
|
||||
eprintln!("deckcraft: {}", control.token_notice(&token));
|
||||
let limits = ServerLimits::default().max_request(256 << 20).max_response(256 << 20);
|
||||
match listen_with(port, token, WindowHost::of(ctx), limits) {
|
||||
Ok((rx, server)) => {
|
||||
log::info!("control server listening on {}", server.addr);
|
||||
platform.control = Some(ControlChannel::new(rx));
|
||||
listening = Some(server);
|
||||
}
|
||||
Err(error) => log::error!("control server: {error}"),
|
||||
}
|
||||
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);
|
||||
// Presenter View asks winit how many displays there are when a show starts.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if let Some(window) = cc.winit_window().cloned() {
|
||||
app.services.displays = Some(Box::new(move || display_count(&window)));
|
||||
}
|
||||
let mut app = SlideApp::new(ctx, platform)?;
|
||||
load_prefs(&mut app);
|
||||
if !nightly {
|
||||
// Nightly is managed by ArtCraft Launcher: no self-update prompt or stable feed.
|
||||
app.enable_update_checks();
|
||||
@@ -455,6 +436,11 @@ fn main() -> eframe::Result {
|
||||
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());
|
||||
app = app.with_control(rx);
|
||||
}
|
||||
if sample && let Err(e) = deckcraft_engine::sample::open_sample(&mut app.session) {
|
||||
log::error!("sample: {e}");
|
||||
}
|
||||
@@ -465,7 +451,11 @@ fn main() -> eframe::Result {
|
||||
if show {
|
||||
app.start_show(0, false);
|
||||
}
|
||||
Ok(Box::new(App { app, panels, _control: listening }))
|
||||
Ok(Box::new(App(
|
||||
app,
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events.connect(&cc.egui_ctx),
|
||||
)))
|
||||
}),
|
||||
);
|
||||
// The exit hook normally finished it already; this covers a start that never created a window.
|
||||
@@ -477,6 +467,33 @@ fn main() -> eframe::Result {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// #279: on macOS the process ends inside `on_exit`, before eframe would tear the window down.
|
||||
/// The check runs in a child (this test binary again), since on macOS it ends the process.
|
||||
#[test]
|
||||
fn on_exit_ends_the_process_on_macos() {
|
||||
if std::env::var_os("DECKCRAFT_TEST_ON_EXIT").is_some() {
|
||||
let mut app = App(
|
||||
SlideApp::new(Session::new(), Services::default()),
|
||||
#[cfg(target_os = "macos")]
|
||||
fmv_macos_events::Inbox::default(),
|
||||
);
|
||||
println!("calling on_exit");
|
||||
eframe::App::on_exit(&mut app);
|
||||
println!("on_exit returned");
|
||||
return;
|
||||
}
|
||||
let out = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "tests::on_exit_ends_the_process_on_macos", "--nocapture"])
|
||||
.env("DECKCRAFT_TEST_ON_EXIT", "1")
|
||||
.env("DECKCRAFT_NO_PREFS", "1")
|
||||
.output()
|
||||
.unwrap();
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(out.status.success(), "{stdout}");
|
||||
assert!(stdout.contains("calling on_exit"), "the child didn't run the test: {stdout}");
|
||||
assert_eq!(stdout.contains("on_exit returned"), !cfg!(target_os = "macos"), "{stdout}");
|
||||
}
|
||||
|
||||
/// The egui 0.37 migration (#1350) left `clipboard` out of eframe's features. egui then
|
||||
/// simulated a clipboard inside the app: nothing pasted from other apps, and Ctrl+C/Ctrl+V
|
||||
/// lost text that went out as HTML. Keep the OS clipboard on.
|
||||
@@ -487,11 +504,37 @@ mod tests {
|
||||
assert!(eframe.contains("\"clipboard\""), "eframe must enable the OS clipboard: {eframe}");
|
||||
}
|
||||
|
||||
/// On native Wayland, the X11-only pasteboard would bypass egui's Wayland clipboard; elsewhere
|
||||
/// it carries HTML and pictures beside egui's text.
|
||||
#[test]
|
||||
fn the_pasteboard_stays_off_native_wayland() {
|
||||
let s = services(true);
|
||||
assert!(s.clipboard_html.is_none() && s.clipboard_set_html.is_none() && s.clipboard_image.is_none());
|
||||
let s = services(false);
|
||||
assert!(s.clipboard_html.is_some() && s.clipboard_set_html.is_some() && s.clipboard_image.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_exits_instead_of_opening_a_file() {
|
||||
assert!(matches!(startup(None, ["--help".to_string()]), Startup::Help));
|
||||
assert!(matches!(startup(None, ["-h".to_string()]), Startup::Help));
|
||||
assert!(matches!(startup(None, ["talk.pptx".to_string(), "--help".to_string()]), Startup::Help));
|
||||
assert!(matches!(startup(None, ["--version".to_string()]), Startup::Version));
|
||||
let launch = startup(Some(9), ["--sample".to_string(), "--control".to_string(), "4242".to_string(), "talk.pptx".to_string()]);
|
||||
assert!(matches!(launch, Startup::Run { .. }));
|
||||
if let Startup::Run { control_port, files, sample, show } = launch {
|
||||
assert_eq!(control_port, Some(4242));
|
||||
assert_eq!(files, ["talk.pptx".to_string()]);
|
||||
assert!(sample);
|
||||
assert!(!show);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(true, ["--", "--control", "deck.pptx"].map(str::to_string)).unwrap();
|
||||
assert!(matches!(&launch, Startup::Run { control, .. } if control.port.is_none()));
|
||||
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()]);
|
||||
}
|
||||
@@ -504,26 +547,39 @@ mod tests {
|
||||
assert_eq!(deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::LaunchIdentity::NightlyV1), "DeckCraft Nightly");
|
||||
}
|
||||
|
||||
/// Repeated exit paths must not finish a successor's Nightly record or start an update twice.
|
||||
/// 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() {
|
||||
let ctx = egui::Context::default();
|
||||
let runs = std::rc::Rc::new(std::cell::Cell::new(0));
|
||||
let counted = runs.clone();
|
||||
let install = InstallSpec::new(ShellInfo::default(), Arc::new(craft::window::system::SystemWindows));
|
||||
let (platform, panels) = desktop_platform(install, Location::Memory, Wake::none(), Some(Box::new(move || counted.set(counted.get() + 1))));
|
||||
let mut app = App { app: SlideApp::new(&ctx, platform).unwrap(), panels, _control: None };
|
||||
assert_eq!(runs.get(), 0);
|
||||
app.app.leave();
|
||||
assert_eq!(runs.get(), 1);
|
||||
app.app.leave();
|
||||
eframe::App::on_exit(&mut app);
|
||||
assert_eq!(runs.get(), 1, "repeating the exit path must not repeat its hook");
|
||||
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(true, ["-psn_0_1234567".to_string(), "talk.pptx".to_string()]).unwrap();
|
||||
let launch = startup(None, ["-psn_0_1234567".to_string(), "talk.pptx".to_string()]);
|
||||
assert!(matches!(launch, Startup::Run { .. }));
|
||||
if let Startup::Run { files, .. } = launch {
|
||||
assert_eq!(files, ["talk.pptx".to_string()]);
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
//! System pasteboard: HTML rich text, and a picture (TIFF on macOS, via arboard).
|
||||
//!
|
||||
//! Pages keeps bold, italic and underline when the pasteboard carries HTML plus the same plain
|
||||
//! words. A shape with no text is copied as an image by the UI; this module only reads a picture
|
||||
//! back (Keynote's TIFF) as PNG bytes.
|
||||
|
||||
/// HTML currently on the pasteboard, when there is some.
|
||||
pub fn html() -> Option<String> {
|
||||
let mut cb = arboard::Clipboard::new().ok()?;
|
||||
let html = cb.get().html().ok()?;
|
||||
let html = html.trim();
|
||||
if html.is_empty() { None } else { Some(html.to_string()) }
|
||||
}
|
||||
|
||||
/// Write `html` and the plain alternative `text`. `false` when the pasteboard refuses it.
|
||||
pub fn set_html(html: &str, text: &str) -> bool {
|
||||
let Ok(mut cb) = arboard::Clipboard::new() else { return false };
|
||||
cb.set_html(html, Some(text)).is_ok()
|
||||
}
|
||||
|
||||
/// The pasteboard picture as PNG bytes (TIFF on macOS is decoded by arboard).
|
||||
pub fn image_png() -> Option<Vec<u8>> {
|
||||
let mut cb = arboard::Clipboard::new().ok()?;
|
||||
let img = cb.get_image().ok()?;
|
||||
let width = u32::try_from(img.width).ok()?;
|
||||
let height = u32::try_from(img.height).ok()?;
|
||||
let rgba = image::RgbaImage::from_raw(width, height, img.bytes.into_owned())?;
|
||||
let mut out = Vec::new();
|
||||
rgba.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?;
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// Puts HTML and a 1×1 picture on the macOS pasteboard and reads them back.
|
||||
/// Restores whatever plain text was there. Other platforms return immediately.
|
||||
#[test]
|
||||
fn html_and_a_picture_round_trip_on_macos() {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return;
|
||||
}
|
||||
let previous = arboard::Clipboard::new().ok().and_then(|mut cb| cb.get_text().ok());
|
||||
let _restore = Restore(previous);
|
||||
assert!(super::set_html("<b>DeckCraft</b>", "DeckCraft"), "set html");
|
||||
let html = super::html().unwrap_or_default();
|
||||
assert!(html.contains("<b>") || html.contains("<B>"), "{html}");
|
||||
let text = arboard::Clipboard::new().ok().and_then(|mut cb| cb.get_text().ok()).unwrap_or_default();
|
||||
assert_eq!(text, "DeckCraft");
|
||||
let mut cb = arboard::Clipboard::new().expect("pasteboard");
|
||||
let img = arboard::ImageData { width: 1, height: 1, bytes: Cow::Owned(vec![255, 0, 0, 255]) };
|
||||
cb.set_image(img).expect("set image");
|
||||
drop(cb);
|
||||
let png = super::image_png().expect("png");
|
||||
let decoded = image::load_from_memory(&png).expect("decode").to_rgba8();
|
||||
let p = decoded.get_pixel(0, 0);
|
||||
assert!(p[0] > 200 && p[1] < 40 && p[3] > 200, "{p:?}");
|
||||
}
|
||||
|
||||
/// Puts the previous plain text back, including when the test fails halfway.
|
||||
struct Restore(Option<String>);
|
||||
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
let Ok(mut cb) = arboard::Clipboard::new() else { return };
|
||||
match self.0.take() {
|
||||
Some(t) => {
|
||||
let _ = cb.set_text(t);
|
||||
}
|
||||
None => {
|
||||
let _ = cb.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,3 +39,32 @@ pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
+652
-193
@@ -1,238 +1,697 @@
|
||||
//! DeckCraft's nightly profile specification and extra forbidden-root fence for `craft-nightly`.
|
||||
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use craft_nightly::AppProfileSpec;
|
||||
use crate::app_dirs::{PORTABLE_DATA_DIR, portable_marker};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
/// Canonical application identifier for DeckCraft nightly profile isolation.
|
||||
pub const APP_ID: &str = "deckcraft";
|
||||
/// 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";
|
||||
|
||||
const STABLE_DIR_NAMES: &[&str] = &["DeckCraft", "deckcraft"];
|
||||
const FOLDER_ONLY_ENTRIES: &[&str] = &["Recovery", "Dictionaries", crate::LOG_DIR];
|
||||
|
||||
/// Builds DeckCraft's [`AppProfileSpec`] for `craft-nightly`, preserving DeckCraft's exact
|
||||
/// stable directory names, portable markers, folder-only entries, and OS-specific extra
|
||||
/// forbidden roots.
|
||||
pub fn spec() -> AppProfileSpec {
|
||||
spec_with(|k| std::env::var_os(k))
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
}
|
||||
|
||||
fn spec_with(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
|
||||
AppProfileSpec {
|
||||
app_id: APP_ID,
|
||||
display_name: "DeckCraft",
|
||||
stable_dir_names: STABLE_DIR_NAMES,
|
||||
stable_package_id: "ai.storyteller.deckcraft",
|
||||
nightly_package_id: "ai.storyteller.deckcraft.nightly",
|
||||
profile_root_env: None,
|
||||
forbidden_env_vars: &[],
|
||||
portable_markers: &crate::app_dirs::PORTABLE_MARKERS,
|
||||
folder_only_entries: FOLDER_ONLY_ENTRIES,
|
||||
extra_forbidden_roots: extra_forbidden_roots(env),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(unix, target_os = "windows"))]
|
||||
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
|
||||
let value = env(key)?;
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = PathBuf::from(value);
|
||||
path.is_absolute().then_some(path)
|
||||
}
|
||||
|
||||
fn extra_forbidden_roots(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let mut roots = Vec::new();
|
||||
// The MSI's default per-user and per-machine folders (install-policy.wxi).
|
||||
if let Some(local) = non_empty_abs(&env, "LOCALAPPDATA") {
|
||||
roots.push(local.join("Programs").join("ArtCraft").join("DeckCraft"));
|
||||
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()),
|
||||
}
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = non_empty_abs(&env, key) {
|
||||
roots.push(base.join("ArtCraft").join("DeckCraft"));
|
||||
}
|
||||
|
||||
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}")),
|
||||
}
|
||||
roots
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let mut roots = vec![PathBuf::from("/Applications/DeckCraft.app")];
|
||||
if let Some(home) = non_empty_abs(&env, "HOME") {
|
||||
let library = home.join("Library");
|
||||
roots.push(library.join("Preferences/ai.storyteller.deckcraft.plist"));
|
||||
roots.push(library.join("Saved Application State/ai.storyteller.deckcraft.savedState"));
|
||||
roots.push(home.join("Applications/DeckCraft.app"));
|
||||
}
|
||||
roots
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let mut roots = vec![PathBuf::from("/usr/bin/deckcraft"), PathBuf::from("/usr/local/bin/deckcraft"), PathBuf::from("/opt/deckcraft")];
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
if let Some(home) = non_empty_abs(&env, "HOME") {
|
||||
roots.push(home.join(".var/app/ai.storyteller.deckcraft"));
|
||||
}
|
||||
roots
|
||||
}
|
||||
#[cfg(not(any(unix, target_os = "windows")))]
|
||||
{
|
||||
let _ = env;
|
||||
Vec::new()
|
||||
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}"))?;
|
||||
let path = entry.path();
|
||||
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
// Settings and session state are ordinary files, not directories. Keep the existing
|
||||
// directory-boundary check for folders (including the known folder-only entries).
|
||||
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
|
||||
if metadata.is_file() {
|
||||
if folder_only {
|
||||
return Err(format!("the nightly {} must be a directory", entry.file_name().to_string_lossy()));
|
||||
}
|
||||
private_regular_file(&path, &metadata)?;
|
||||
} else {
|
||||
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(())
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use winsafe::{HFILE, co};
|
||||
let (file, _) = HFILE::CreateFile(
|
||||
path.to_str().ok_or("the nightly profile file path is not textual")?,
|
||||
co::GENERIC::default(),
|
||||
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
|
||||
None,
|
||||
co::DISPOSITION::OPEN_EXISTING,
|
||||
co::FILE_ATTRIBUTE::NORMAL,
|
||||
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
|
||||
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
if info.nNumberOfLinks != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
let _ = (path, metadata);
|
||||
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)
|
||||
}
|
||||
|
||||
const PROFILE_FOLDERS: [&str; 3] = ["Recovery", "Dictionaries", crate::logging::LOG_DIR];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use craft_nightly::{ProfileError, validate_and_prepare_root};
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(label: &str) -> Self {
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate = std::env::temp_dir().join(format!(
|
||||
"deckcraft-profile-spec-{label}-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
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 temp dir: {error}"),
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
};
|
||||
Self(root)
|
||||
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 path(&self) -> &Path {
|
||||
&self.0
|
||||
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 TempDir {
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
// Only the directory successfully created by this fixture is owned for removal.
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spec_preserves_deckcraft_isolation_constants() {
|
||||
let s = spec();
|
||||
assert_eq!(s.app_id, "deckcraft");
|
||||
assert_eq!(s.display_name, "DeckCraft");
|
||||
assert_eq!(s.stable_dir_names, &["DeckCraft", "deckcraft"]);
|
||||
assert_eq!(s.stable_package_id, "ai.storyteller.deckcraft");
|
||||
assert_eq!(s.nightly_package_id, "ai.storyteller.deckcraft.nightly");
|
||||
assert_eq!(s.profile_root_env, None);
|
||||
assert!(s.forbidden_env_vars.is_empty());
|
||||
assert_eq!(s.portable_markers, &["portable.txt"]);
|
||||
assert_eq!(s.folder_only_entries, &["Recovery", "Dictionaries", "logs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_forbidden_roots_cover_platform_install_and_stable_paths() {
|
||||
let mut env = BTreeMap::<String, OsString>::new();
|
||||
if cfg!(target_os = "windows") {
|
||||
env.insert("LOCALAPPDATA".into(), r"C:\Users\me\AppData\Local".into());
|
||||
env.insert("ProgramFiles".into(), r"C:\Program Files".into());
|
||||
} else {
|
||||
env.insert("HOME".into(), "/home/me".into());
|
||||
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 roots = extra_forbidden_roots(|key| env.get(key).cloned());
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
assert!(roots.contains(&PathBuf::from(r"C:\Users\me\AppData\Local\Programs\ArtCraft\DeckCraft")));
|
||||
assert!(roots.contains(&PathBuf::from(r"C:\Program Files\ArtCraft\DeckCraft")));
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
assert!(roots.contains(&PathBuf::from("/Applications/DeckCraft.app")));
|
||||
assert!(roots.contains(&PathBuf::from("/home/me/Applications/DeckCraft.app")));
|
||||
assert!(roots.contains(&PathBuf::from("/home/me/Library/Preferences/ai.storyteller.deckcraft.plist")));
|
||||
assert!(roots.contains(&PathBuf::from("/home/me/Library/Saved Application State/ai.storyteller.deckcraft.savedState")));
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
assert!(roots.contains(&PathBuf::from("/usr/bin/deckcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/usr/local/bin/deckcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/opt/deckcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/home/me/.var/app/ai.storyteller.deckcraft")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_profile_root_reopens_and_enforces_folder_only_entries() {
|
||||
let tmp = TempDir::new("reopen");
|
||||
let profile = tmp.path().join("nightly-profile");
|
||||
let s = spec();
|
||||
|
||||
let prepared = validate_and_prepare_root(&profile, &s).unwrap();
|
||||
assert_eq!(prepared, profile);
|
||||
|
||||
for file_name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(prepared.join(file_name), b"saved profile data").unwrap();
|
||||
}
|
||||
for dir_name in FOLDER_ONLY_ENTRIES {
|
||||
std::fs::create_dir(prepared.join(dir_name)).unwrap();
|
||||
}
|
||||
assert_eq!(validate_and_prepare_root(&profile, &s).unwrap(), prepared);
|
||||
for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
assert_eq!(std::fs::read(prepared.join(name)).unwrap(), b"saved profile data", "{name} changed when reopening");
|
||||
}
|
||||
|
||||
for dir_name in FOLDER_ONLY_ENTRIES {
|
||||
let entry = prepared.join(dir_name);
|
||||
std::fs::remove_dir(&entry).unwrap();
|
||||
std::fs::write(&entry, b"not a directory").unwrap();
|
||||
assert!(matches!(validate_and_prepare_root(&profile, &s), Err(ProfileError::ExpectedDirectoryEntry(_))));
|
||||
std::fs::remove_file(&entry).unwrap();
|
||||
std::fs::create_dir(&entry).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_directory_profile_stops_startup_without_installing_a_profile() {
|
||||
let temp = TempDir::new("invalid-root");
|
||||
let root = temp.path().join("ordinary-file");
|
||||
std::fs::write(&root, b"existing file").unwrap();
|
||||
let argv = craft_nightly::launch_arguments(&root, &[]);
|
||||
assert!(craft_nightly::current().is_none());
|
||||
let result = crate::launch_profile::prepare(craft_nightly::BuildFlavor::NightlyV1, argv);
|
||||
assert!(matches!(result, Err(ProfileError::NotADirectory(_))));
|
||||
assert!(craft_nightly::current().is_none());
|
||||
assert_eq!(std::fs::read(root).unwrap(), b"existing file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_and_traversal_profile_roots_are_refused() {
|
||||
let tmp = TempDir::new("lexical");
|
||||
let s = spec();
|
||||
assert!(matches!(validate_and_prepare_root(Path::new("relative/nightly"), &s), Err(ProfileError::RelativeProfileRoot(_))));
|
||||
assert!(matches!(validate_and_prepare_root(&tmp.path().join("nightly/../escape"), &s), Err(ProfileError::ParentTraversalInProfileRoot(_))));
|
||||
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 symlink_inside_profile_root_is_refused() {
|
||||
let tmp = TempDir::new("symlink");
|
||||
let outside = tmp.path().join("outside");
|
||||
let profile = tmp.path().join("nightly-profile");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::fs::create_dir_all(&profile).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, profile.join("Recovery")).unwrap();
|
||||
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");
|
||||
}
|
||||
|
||||
let s = spec();
|
||||
assert!(matches!(validate_and_prepare_root(&profile, &s), Err(ProfileError::SymlinkEntry(_))));
|
||||
#[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 nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
|
||||
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data");
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<rect x="7.68" y="8.32" width="53.76" height="53.76" rx="8.96" fill="#C24E14"/>
|
||||
<rect x="5.12" y="5.12" width="53.76" height="53.76" rx="8.96" fill="#F26B1D"/>
|
||||
<polygon points="23.7,20.2 43.8,32 23.7,43.8" fill="#FFFFFF"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 297 B |
@@ -297,16 +297,6 @@ pub fn parse_params(doc: &str) -> std::result::Result<Vec<Param<'_>>, String> {
|
||||
/// growing would duplicate ids (#407).
|
||||
pub(crate) const NO_ID_SPACE: &str = "the presentation has used every object id and can hold no more";
|
||||
|
||||
/// A style command whose keys are all optional is refused when it is given none of them, rather
|
||||
/// than answering `changed` for a call that sets nothing.
|
||||
pub(crate) fn require_any(p: &Value, cmd: &str, keys: &[&str]) -> Result<()> {
|
||||
if keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
|
||||
return Ok(());
|
||||
}
|
||||
let (last, rest) = keys.split_last().map_or(("", &[][..]), |(l, r)| (*l, r));
|
||||
Err(bad(cmd, format!("`{cmd}` was given nothing to set: pass {} or {last}", rest.join(", "))))
|
||||
}
|
||||
|
||||
pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
|
||||
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
|
||||
}
|
||||
@@ -387,17 +377,12 @@ pub(crate) fn ok() -> Result<Value> {
|
||||
|
||||
/// Parse a colour param: `"#RRGGBB"`, `"accent1"`…, or `{"scheme":"accent2","lumMod":75000}`.
|
||||
/// A preset or system colour keeps its base: `{"preset":"red"}`,
|
||||
/// `{"system":"windowText","last":"#000000"}`. `"mods"` lists transforms in order:
|
||||
/// `{"preset":"red","mods":[{"op":"inv"},{"op":"inv"}]}`. A list longer than [`MAX_COLOR_MODS`]
|
||||
/// makes the color invalid.
|
||||
/// `{"system":"windowText","last":"#000000"}`.
|
||||
pub(crate) fn color_param(p: &Value, key: &str) -> Option<deckcraft_model::ColorRef> {
|
||||
let v = p.get(key)?;
|
||||
color_value(v)
|
||||
}
|
||||
|
||||
/// Most transforms a color param's `"mods"` list may hold.
|
||||
pub(crate) const MAX_COLOR_MODS: usize = 256;
|
||||
|
||||
pub(crate) fn color_value(v: &Value) -> Option<deckcraft_model::ColorRef> {
|
||||
use deckcraft_model::ColorRef;
|
||||
match v {
|
||||
@@ -428,22 +413,8 @@ pub(crate) fn color_value(v: &Value) -> Option<deckcraft_model::ColorRef> {
|
||||
ColorRef::rgb(deckcraft_color::Rgba::from_hex(o.get("rgb").and_then(Value::as_str)?)?)
|
||||
};
|
||||
for (k, val) in o {
|
||||
let n = val.as_i64().and_then(|x| i32::try_from(x).ok());
|
||||
if let Some(t) = deckcraft_color::ColorTransform::from_xml(k, n) {
|
||||
// A value-bearing transform without a usable integer is skipped, not zeroed.
|
||||
if n.is_some() || t.value().is_none() {
|
||||
c.mods.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
// `mods` lists transforms in order, repeats included: `[{"op":"inv"},{"op":"lumMod","val":50000}]`.
|
||||
if let Some(list) = o.get("mods") {
|
||||
let list = list.as_array()?;
|
||||
if list.len() > MAX_COLOR_MODS {
|
||||
return None;
|
||||
}
|
||||
for m in list {
|
||||
c.mods.push(<deckcraft_color::ColorTransform as serde::Deserialize>::deserialize(m).ok()?);
|
||||
if let Some(t) = deckcraft_color::ColorTransform::from_xml(k, val.as_i64().and_then(|x| i32::try_from(x).ok())) {
|
||||
c.mods.push(t);
|
||||
}
|
||||
}
|
||||
Some(c)
|
||||
@@ -576,10 +547,6 @@ pub(crate) fn current_names(doc: &deckcraft_model::Presentation, sel: &crate::Se
|
||||
/// A name ending in `?` is optional. Text after `→` is the result, not an input.
|
||||
pub fn needs_arguments(params: &str) -> bool {
|
||||
let input = params.split('→').next().unwrap_or(params);
|
||||
// Every key optional, but the command refuses a call that gives none of them.
|
||||
if input.contains("(at least one key)") {
|
||||
return true;
|
||||
}
|
||||
let Some(start) = input.find('{') else { return false };
|
||||
let inside = input.get(start + 1..).unwrap_or("");
|
||||
let inside = inside.split('}').next().unwrap_or(inside);
|
||||
@@ -776,16 +743,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_integer_colour_transform_is_skipped_not_zeroed() {
|
||||
for bad in [serde_json::json!("75000"), serde_json::json!(75000.0), serde_json::json!(0.75), serde_json::json!(3_000_000_000i64)] {
|
||||
let c = color_value(&serde_json::json!({"scheme": "accent1", "lumMod": bad})).unwrap();
|
||||
assert!(c.mods.is_empty(), "{bad}: {:?}", c.mods);
|
||||
}
|
||||
let c = color_value(&serde_json::json!({"scheme": "accent1", "lumMod": 75000})).unwrap();
|
||||
assert_eq!(c.mods, vec![deckcraft_color::ColorTransform::LumMod(75000)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_palette_skips_a_command_that_needs_a_value() {
|
||||
assert!(needs_arguments("{path}"));
|
||||
@@ -795,7 +752,6 @@ mod tests {
|
||||
assert!(needs_arguments("{axis: horizontal|vertical, ids?}"));
|
||||
assert!(needs_arguments("{percent}"));
|
||||
assert!(!needs_arguments("{}"));
|
||||
assert!(needs_arguments("{left?: pt, top?: pt} (at least one key)"));
|
||||
assert!(!needs_arguments("{on?: bool}"));
|
||||
assert!(!needs_arguments("{theme?: name, size?: [w,h] pt, blank?: bool}"));
|
||||
assert!(!needs_arguments("{uid?: one entry, else all}"));
|
||||
@@ -827,40 +783,5 @@ mod tests {
|
||||
assert!(color_value(&json!({"preset": name})).is_some(), "{name}");
|
||||
}
|
||||
assert!(color_value(&json!({"system": "3dDkShadow", "last": "#000000"})).is_some());
|
||||
let listed = color_value(&json!({"preset": "red", "mods": [{"op": "inv"}, {"op": "lumOff", "val": 20_000}, {"op": "inv"}]}));
|
||||
let mods = vec![ColorTransform::Inv, ColorTransform::LumOff(20_000), ColorTransform::Inv];
|
||||
assert_eq!(listed, Some(ColorRef { base: ColorBase::Preset { name: "red".into() }, mods }));
|
||||
assert_eq!(color_value(&json!({"preset": "red", "mods": [{"op": "notATransform"}]})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_mods_lists_follow_keyed_transforms() {
|
||||
use deckcraft_color::{ColorTransform, SchemeSlot};
|
||||
use deckcraft_model::{ColorBase, ColorRef};
|
||||
use serde_json::json;
|
||||
let red = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] };
|
||||
assert_eq!(color_value(&json!({"preset": "red", "mods": []})), Some(red.clone()), "an empty list adds no transforms");
|
||||
let two = color_value(&json!({"preset": "red", "mods": [{"op": "lumMod", "val": 75_000}, {"op": "lumOff", "val": 10_000}]}));
|
||||
assert_eq!(two, Some(red.with(ColorTransform::LumMod(75_000)).with(ColorTransform::LumOff(10_000))));
|
||||
// The keyed `lumMod` comes first, then the list in order.
|
||||
let both =
|
||||
color_value(&json!({"scheme": "accent2", "lumMod": 75_000, "mods": [{"op": "lumOff", "val": 10_000}, {"op": "lumMod", "val": 50_000}]}));
|
||||
let want = ColorRef::scheme(SchemeSlot::Accent2)
|
||||
.with(ColorTransform::LumMod(75_000))
|
||||
.with(ColorTransform::LumOff(10_000))
|
||||
.with(ColorTransform::LumMod(50_000));
|
||||
assert_eq!(both, Some(want));
|
||||
// An unknown op anywhere in the list, or a `mods` value that is not a list, makes the color invalid.
|
||||
assert_eq!(color_value(&json!({"scheme": "accent2", "lumMod": 75_000, "mods": [{"op": "lumOff", "val": 10_000}, {"op": "sparkle"}]})), None);
|
||||
assert_eq!(color_value(&json!({"preset": "red", "mods": {"op": "inv"}})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_mods_lists_longer_than_the_cap_are_invalid() {
|
||||
use deckcraft_color::ColorTransform;
|
||||
use serde_json::json;
|
||||
let at_cap = color_value(&json!({"preset": "red", "mods": vec![json!({"op": "inv"}); MAX_COLOR_MODS]}));
|
||||
assert_eq!(at_cap.map(|c| c.mods), Some(vec![ColorTransform::Inv; MAX_COLOR_MODS]));
|
||||
assert_eq!(color_value(&json!({"preset": "red", "mods": vec![json!({"op": "inv"}); MAX_COLOR_MODS + 1]})), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,8 +56,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Animation Painter",
|
||||
["Animations", "Advanced Animation"],
|
||||
Some("Alt+Shift+C"),
|
||||
"{sticky?: bool, on?: bool, id?}",
|
||||
painter_enabled,
|
||||
"{sticky?: bool, id?}",
|
||||
has_selection,
|
||||
painter_pick
|
||||
),
|
||||
cmd!("animation.painterApply", "Apply Animation", [], Some("Alt+Shift+V"), "{ids?}", has_selection, painter_apply),
|
||||
@@ -470,15 +470,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(serde_json::to_value(&sl.animations).unwrap_or_default())
|
||||
}
|
||||
|
||||
fn painter_enabled(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.anim_painter.is_some() { Ok(()) } else { has_selection(s) }
|
||||
}
|
||||
|
||||
fn painter_pick(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("on").and_then(Value::as_bool) == Some(false) {
|
||||
s.anim_painter = None;
|
||||
return Ok(json!({"armed": false}));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let id = id_param(p, "id", "animation.painter")?
|
||||
.or_else(|| st.selection.shapes.first().copied())
|
||||
@@ -552,30 +544,6 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_armed_animation_painter_can_disarm_without_a_source_but_cannot_rearm() -> crate::Result<()> {
|
||||
let mut s = Session::with_new();
|
||||
let source = s.execute("shape.insert", &json!({"preset": "rect"}))?["id"].clone();
|
||||
s.execute("animation.add", &json!({"effect": "fade"}))?;
|
||||
s.execute("animation.painter", &json!({"sticky": true}))?;
|
||||
s.select(|_, sel| {
|
||||
sel.shapes.clear();
|
||||
sel.text = None;
|
||||
})?;
|
||||
assert!(s.execute("animation.painter", &json!({})).is_err());
|
||||
assert!(s.anim_painter.is_some());
|
||||
s.execute("animation.painter", &json!({"on": false, "id": "invalid"}))?;
|
||||
assert!(s.anim_painter.is_none(), "disarming precedes even explicit source validation");
|
||||
assert!(s.execute("animation.painter", &json!({})).is_err());
|
||||
s.execute("animation.painter", &json!({"id": source}))?;
|
||||
assert!(s.anim_painter.is_some(), "an explicit animated source needs no selection");
|
||||
s.execute("animation.painter", &json!({"on": false}))?;
|
||||
s.execute("animation.clear", &json!({}))?;
|
||||
assert!(s.execute("animation.painter", &json!({"id": source})).is_err());
|
||||
assert!(s.anim_painter.is_none());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_rejects_invalid_index() {
|
||||
let mut s = Session::with_new();
|
||||
|
||||
@@ -23,7 +23,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!("guide.move", "Move Guide", [], None, "{index, pos: pt}", has_doc, guide_move),
|
||||
cmd!("guide.delete", "Delete Guide", [], None, "{index}", has_doc, guide_delete),
|
||||
cmd!("guide.set", "Set Guides", [], None, "{guides: [{vertical: bool, pos: pt}]} replaces all guides in one undo step", has_doc, guide_set),
|
||||
cmd!(query "guide.list", "Guides", [], None, "{} → [{vertical, pos}]", has_doc, guide_list),
|
||||
cmd!("arrange.bringToFront", "Bring to Front", ["Arrange"], Some("Cmd+Shift+]"), "{ids?}", has_selection, |s, p| order(s, p, 2)),
|
||||
cmd!("arrange.bringForward", "Bring Forward", ["Arrange"], Some("Cmd+]"), "{ids?}", has_selection, |s, p| order(s, p, 1)),
|
||||
@@ -579,25 +578,6 @@ fn guide_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
fn guide_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let items = p.get("guides").and_then(Value::as_array).ok_or_else(|| bad("guide.set", "`guides` must be an array"))?;
|
||||
if items.len() > MAX_GUIDES {
|
||||
return Err(bad("guide.set", "too many guides"));
|
||||
}
|
||||
let mut guides: Vec<deckcraft_model::DrawGuide> =
|
||||
serde_json::from_value(Value::Array(items.clone())).map_err(|_| bad("guide.set", "each guide needs `vertical` and a finite `pos`"))?;
|
||||
for guide in &mut guides {
|
||||
if !guide.pos.is_finite() {
|
||||
return Err(bad("guide.set", "`pos` must be finite"));
|
||||
}
|
||||
guide.pos = guide.pos.clamp(0.0, guide_limit(s, guide.vertical)?);
|
||||
}
|
||||
s.edit(|doc, _| {
|
||||
doc.guides = guides;
|
||||
ok()
|
||||
})
|
||||
}
|
||||
|
||||
fn guide_list(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
Ok(serde_json::to_value(&s.doc()?.doc.guides).unwrap_or_default())
|
||||
}
|
||||
|
||||
@@ -28,8 +28,7 @@ use master_view::{
|
||||
};
|
||||
pub use master_view::{handout_placeholder, notes_placeholder};
|
||||
use slide_background::{background, hide_bg_graphics};
|
||||
// PLAN: assumed slide_setup::SLIDE_SIZE_RANGE: RangeInclusive<f64> (dialogs-w8)
|
||||
pub use slide_setup::{SLIDE_SIZE_RANGE, civil, date_field_text, today};
|
||||
pub use slide_setup::{civil, date_field_text, today};
|
||||
use slide_setup::{header_footer, scale_shapes, slide_size};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -86,13 +85,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
header_footer
|
||||
),
|
||||
cmd!(noundo "view.slideMaster", "Slide Master", ["View", "Master Views"], None, "{master?: index, layout?: index, toggle?: bool}", has_doc, master_view),
|
||||
cmd!(noundo "view.slideMaster", "Slide Master", ["View", "Master Views"], None, "{master?: index, layout?: index}", has_doc, master_view),
|
||||
cmd!(
|
||||
"view.handoutMaster",
|
||||
"Handout Master",
|
||||
["View", "Master Views"],
|
||||
None,
|
||||
"{toggle?: bool} (creates the handout master with header, date, footer and page number if the deck has none)",
|
||||
"{} (creates the handout master with header, date, footer and page number if the deck has none)",
|
||||
has_doc,
|
||||
handout_view
|
||||
),
|
||||
@@ -110,7 +109,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Notes Master",
|
||||
["View", "Master Views"],
|
||||
None,
|
||||
"{toggle?: bool} (creates the notes master with header, date, slide image, notes body, footer and page number if the deck has none)",
|
||||
"{} (creates the notes master with header, date, slide image, notes body, footer and page number if the deck has none)",
|
||||
has_doc,
|
||||
notes_view
|
||||
),
|
||||
@@ -309,25 +308,3 @@ mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod browse_theme_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod master_view_tests;
|
||||
|
||||
/// A master view whose shown state is shared by commands and the ribbon.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum MasterView {
|
||||
/// Any master view.
|
||||
Slide,
|
||||
/// The handout master view.
|
||||
Handout,
|
||||
/// The notes master view.
|
||||
Notes,
|
||||
}
|
||||
/// Reports whether the requested master view is shown, or false without a document.
|
||||
pub fn master_view_shown(s: &Session, which: MasterView) -> bool {
|
||||
s.active().is_some_and(|st| match which {
|
||||
MasterView::Slide => st.selection.target != Target::Slides,
|
||||
MasterView::Handout => st.selection.target == Target::Handout,
|
||||
MasterView::Notes => st.selection.target == Target::NotesMaster,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
use super::{
|
||||
Arc, Fill, MasterView, NO_ID_SPACE, PhType, Result, Run, RunKind, Session, Shape, ShapeId, Size, Target, TextBody, Value, bad, bool_param, json,
|
||||
master_index, master_view_shown, ok, opt_usize_param, rect_param, str_param,
|
||||
Arc, Fill, NO_ID_SPACE, PhType, Result, Run, RunKind, Session, Shape, ShapeId, Size, Target, TextBody, Value, bad, bool_param, json,
|
||||
master_index, ok, opt_usize_param, rect_param, str_param,
|
||||
};
|
||||
|
||||
pub(super) fn master_view(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("toggle").and_then(Value::as_bool) == Some(true) && master_view_shown(s, MasterView::Slide) {
|
||||
return close_master(s, p);
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let mi = opt_usize_param(p, "master", "view.slideMaster")?.unwrap_or_else(|| master_index(&st.doc, &st.selection));
|
||||
// A master thumbnail sends `{master}` and means the master itself. `{master, layout}` selects
|
||||
@@ -61,10 +58,7 @@ pub fn handout_placeholder(kind: PhType, size: Size, id: ShapeId) -> Shape {
|
||||
const HANDOUT_KINDS: [(&str, PhType); 4] =
|
||||
[("header", PhType::Header), ("date", PhType::Date), ("footer", PhType::Footer), ("pageNumber", PhType::SlideNum)];
|
||||
|
||||
pub(super) fn handout_view(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("toggle").and_then(Value::as_bool) == Some(true) && master_view_shown(s, MasterView::Handout) {
|
||||
return close_master(s, p);
|
||||
}
|
||||
pub(super) fn handout_view(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let created = s.doc()?.doc.handout_master.is_none();
|
||||
if created {
|
||||
s.edit(|doc, _| {
|
||||
@@ -172,10 +166,7 @@ pub fn notes_placeholder(kind: PhType, size: Size, id: ShapeId) -> Shape {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn notes_view(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("toggle").and_then(Value::as_bool) == Some(true) && master_view_shown(s, MasterView::Notes) {
|
||||
return close_master(s, p);
|
||||
}
|
||||
pub(super) fn notes_view(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let created = s.doc()?.doc.notes_master.as_ref().is_none_or(|m| m.shapes.is_empty());
|
||||
if created {
|
||||
s.edit(|doc, _| {
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{Session, Target};
|
||||
|
||||
#[test]
|
||||
fn a_master_view_command_with_toggle_closes_the_master_it_shows() -> crate::Result<()> {
|
||||
let commands = ["view.slideMaster", "view.handoutMaster", "view.notesMaster"];
|
||||
for initial in [None, Some(commands[0]), Some(commands[1]), Some(commands[2])] {
|
||||
for command in commands {
|
||||
let mut s = Session::with_new();
|
||||
let slides = s.doc()?.selection.target;
|
||||
if let Some(initial) = initial {
|
||||
s.execute(initial, &json!({}))?;
|
||||
}
|
||||
let before = s.doc()?.selection.target;
|
||||
let closes = match command {
|
||||
"view.slideMaster" => before != slides,
|
||||
"view.handoutMaster" => before == Target::Handout,
|
||||
_ => before == Target::NotesMaster,
|
||||
};
|
||||
s.execute(command, &json!({"toggle": true}))?;
|
||||
let after = s.doc()?.selection.target;
|
||||
if closes {
|
||||
assert_eq!(after, slides, "{command} closes from {before:?}");
|
||||
} else {
|
||||
assert_ne!(after, slides, "{command} opens from {before:?}");
|
||||
match command {
|
||||
"view.handoutMaster" => assert_eq!(after, Target::Handout),
|
||||
"view.notesMaster" => assert_eq!(after, Target::NotesMaster),
|
||||
_ => assert!(matches!(after, Target::Master { .. } | Target::Layout { .. })),
|
||||
}
|
||||
}
|
||||
s.execute(command, &json!({}))?;
|
||||
let opened = s.doc()?.selection.target;
|
||||
assert_ne!(opened, slides);
|
||||
s.execute(command, &json!({}))?;
|
||||
assert_eq!(s.doc()?.selection.target, opened, "{command} without toggle keeps its view open");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -21,9 +21,6 @@ pub(super) fn scale_shapes(shapes: &mut [Shape], sx: f64, sy: f64, k: f64, ox: f
|
||||
}
|
||||
}
|
||||
|
||||
/// The supported slide dimensions in points.
|
||||
pub const SLIDE_SIZE_RANGE: std::ops::RangeInclusive<f64> = 72.0..=4032.0;
|
||||
|
||||
pub(super) fn slide_size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let size = if let Some(pre) = str_param(p, "preset") {
|
||||
let k = pre.to_ascii_lowercase();
|
||||
@@ -32,8 +29,8 @@ pub(super) fn slide_size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Size::new(*w, *h)
|
||||
} else {
|
||||
Size::new(
|
||||
f64_param(p, "w").ok_or_else(|| bad("design.slideSize", "missing `w`"))?.clamp(*SLIDE_SIZE_RANGE.start(), *SLIDE_SIZE_RANGE.end()),
|
||||
f64_param(p, "h").ok_or_else(|| bad("design.slideSize", "missing `h`"))?.clamp(*SLIDE_SIZE_RANGE.start(), *SLIDE_SIZE_RANGE.end()),
|
||||
f64_param(p, "w").ok_or_else(|| bad("design.slideSize", "missing `w`"))?.clamp(72.0, 4032.0),
|
||||
f64_param(p, "h").ok_or_else(|| bad("design.slideSize", "missing `h`"))?.clamp(72.0, 4032.0),
|
||||
)
|
||||
};
|
||||
let size = match str_param(p, "orientation") {
|
||||
|
||||
@@ -335,9 +335,8 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
return paste_plain(s, t);
|
||||
}
|
||||
let (editing, notes) = s.doc()?.selection.text.as_ref().map_or((false, false), |t| (true, t.notes));
|
||||
// Copied shapes are pasted as shapes even while a text box is being edited (the caret leaves it), but never into the notes.
|
||||
if editing && (notes || s.clipboard.text.is_some() || s.clipboard.shapes.is_empty()) {
|
||||
let editing = s.doc()?.selection.text.is_some();
|
||||
if editing {
|
||||
if let Some(body) = s.clipboard.text.clone() {
|
||||
return super::text::paste_body(s, &body);
|
||||
}
|
||||
|
||||
@@ -500,9 +500,17 @@ pub fn format_for_path(path: &str) -> &'static str {
|
||||
/// becomes its file. `file.save` calls it after writing; the web host bridge calls it once the
|
||||
/// page has the bytes.
|
||||
pub fn mark_saved(s: &mut Session, path: Option<String>) -> Result<()> {
|
||||
let st = s.doc()?;
|
||||
let (uid, snapshot) = (st.uid, st.doc.clone());
|
||||
mark_saved_snapshot(s, uid, snapshot, path)
|
||||
let st = s.doc_mut()?;
|
||||
st.saved_doc = st.doc.clone();
|
||||
if path.is_some() {
|
||||
st.path = path;
|
||||
}
|
||||
st.revision += 1;
|
||||
let uid = st.uid;
|
||||
if let Some(dir) = &s.recovery_dir {
|
||||
crate::recovery::discard(dir, uid);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
@@ -848,31 +856,3 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads through the common validated transport callbacks and parses the presentation.
|
||||
/// Maps transport failures to the engine error type.
|
||||
pub fn read_presentation_file_with<M, R>(path: &str, metadata: M, read: R) -> crate::Result<LoadedFile>
|
||||
where
|
||||
M: FnOnce(&str) -> std::result::Result<(bool, u64), String>,
|
||||
R: FnOnce(&str) -> std::result::Result<Vec<u8>, String>,
|
||||
{
|
||||
let bytes = crate::io::read_file_with(path, metadata, read).map_err(EngineError::Other)?;
|
||||
loaded_file(path, &bytes)
|
||||
}
|
||||
|
||||
/// Records the serialized snapshot as the saved state of its originating document.
|
||||
/// Leaves later edits dirty and never switches or redirects a closed document.
|
||||
pub fn mark_saved_snapshot(s: &mut Session, uid: u64, snapshot: std::sync::Arc<deckcraft_model::Presentation>, path: Option<String>) -> Result<()> {
|
||||
let st = s.docs.iter_mut().find(|d| d.uid == uid).ok_or_else(|| EngineError::Other("the presentation is closed".into()))?;
|
||||
st.saved_doc = snapshot;
|
||||
if path.is_some() {
|
||||
st.path = path;
|
||||
}
|
||||
st.revision += 1;
|
||||
if !st.is_dirty()
|
||||
&& let Some(dir) = &s.recovery_dir
|
||||
{
|
||||
crate::recovery::discard(dir, uid);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::sync::Arc;
|
||||
use super::text::{format_body, format_para, format_run, format_run_levels};
|
||||
use super::{
|
||||
CommandSpec, always, bad, base64_decode, bool_or, bool_param, cmd, color_param, edit_shapes, f64_or, f64_param, has_doc, has_text,
|
||||
has_text_or_shapes, ids_param, ok, require_any, str_param,
|
||||
has_text_or_shapes, ids_param, ok, str_param,
|
||||
};
|
||||
use crate::{Result, Session};
|
||||
use deckcraft_model::ShapeId;
|
||||
@@ -29,10 +29,7 @@ use font::{
|
||||
};
|
||||
pub use painter::Painted;
|
||||
pub(crate) use painter::apply_painted;
|
||||
use painter::{font_add, font_rescan, painter_apply, painter_enabled, painter_pick, state};
|
||||
// PLAN: assumed paragraph::PARAGRAPH_PT_RANGE: RangeInclusive<f64> (dialogs-w8)
|
||||
// PLAN: assumed paragraph::COLUMN_COUNT_RANGE: RangeInclusive<u32> (dialogs-w8)
|
||||
pub use paragraph::{COLUMN_COUNT_RANGE, PARAGRAPH_PT_RANGE};
|
||||
use painter::{font_add, font_rescan, painter_apply, painter_pick, state};
|
||||
use paragraph::{
|
||||
align, align_to, anchor, autofit, bullets, columns, direction, level, line_spacing, margins, numbering, paragraph, paragraph_dialog, rtl, wrap,
|
||||
};
|
||||
@@ -210,7 +207,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paragraph…",
|
||||
["Format"],
|
||||
None,
|
||||
"{align?, indentLeft?: pt, indentFirst?: pt (negative = hanging), spaceBefore?: pt, spaceAfter?: pt, lineSpacing?: lines, lineSpacingPt?: pt} (at least one key)",
|
||||
"{align?, indentLeft?: pt, indentFirst?: pt (negative = hanging), spaceBefore?: pt, spaceAfter?: pt, lineSpacing?: lines}",
|
||||
has_text_or_shapes,
|
||||
paragraph
|
||||
),
|
||||
@@ -259,11 +256,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Text Box Margins",
|
||||
["Format Shape", "Text Box"],
|
||||
None,
|
||||
"{left?: pt, top?: pt, right?: pt, bottom?: pt} (at least one key)",
|
||||
"{left?: pt, top?: pt, right?: pt, bottom?: pt}",
|
||||
has_text_or_shapes,
|
||||
margins
|
||||
),
|
||||
cmd!(noundo "format.painter", "Format Painter", ["Home", "Clipboard"], Some("Cmd+Shift+C"), "{sticky?: bool, on?: bool}", painter_enabled, painter_pick),
|
||||
cmd!(noundo "format.painter", "Format Painter", ["Home", "Clipboard"], Some("Cmd+Shift+C"), "{sticky?: bool}", has_text_or_shapes, painter_pick),
|
||||
cmd!("format.painterApply", "Paste Formatting", [], Some("Cmd+Shift+V"), "{ids?}", has_text_or_shapes, painter_apply),
|
||||
cmd!(query "format.state", "Formatting State", [], None, "{} → the effective formatting at the selection (font, size, bold, …)", has_doc, state),
|
||||
]
|
||||
@@ -331,24 +328,6 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::{Session, UiRequest};
|
||||
|
||||
#[test]
|
||||
fn an_armed_format_painter_can_disarm_without_a_source_but_cannot_rearm() -> crate::Result<()> {
|
||||
let mut s = Session::with_new();
|
||||
s.execute("shape.insert", &json!({"preset": "rect"}))?;
|
||||
s.execute("format.painter", &json!({"sticky": true}))?;
|
||||
s.select(|_, sel| {
|
||||
sel.shapes.clear();
|
||||
sel.text = None;
|
||||
})?;
|
||||
assert!(s.execute("format.painter", &json!({})).is_err());
|
||||
assert!(s.painter.is_some(), "a refused pick keeps the armed painter available to disarm");
|
||||
s.execute("format.painter", &json!({"on": false}))?;
|
||||
assert!(s.painter.is_none());
|
||||
assert!(s.execute("format.painter", &json!({})).is_err());
|
||||
assert!(s.painter.is_none());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn shape() -> Session {
|
||||
let mut s = Session::with_new();
|
||||
s.execute("shape.insert", &json!({"preset": "rect", "rect": [40.0, 40.0, 240.0, 80.0], "text": "Hello"})).unwrap();
|
||||
@@ -426,87 +405,6 @@ mod tests {
|
||||
assert!(r.size.is_none() && r.fill.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn font_dialog_ok_keeps_the_text_color() {
|
||||
use deckcraft_color::Rgba;
|
||||
let preset = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] }.with(ColorTransform::LumMod(50_000));
|
||||
let system = ColorRef { base: ColorBase::System { name: "windowText".into(), last: Rgba::rgb(0x12, 0x34, 0x56) }, mods: vec![] }
|
||||
.with(ColorTransform::Alpha(60_000));
|
||||
// A transform without a value, and a color that is not opaque.
|
||||
let inverted = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] }.with(ColorTransform::Inv);
|
||||
let translucent = ColorRef { base: ColorBase::System { name: "windowText".into(), last: Rgba::rgba(0x12, 0x34, 0x56, 0x80) }, mods: vec![] };
|
||||
let rgb = ColorRef::rgb(Rgba::rgba(0x12, 0x34, 0x56, 0x80));
|
||||
// A repeated transform, and two transforms in an order that is not alphabetical.
|
||||
let twice = inverted.clone().with(ColorTransform::Inv);
|
||||
let ordered = ColorRef::scheme(SchemeSlot::Accent2).with(ColorTransform::LumOff(20_000)).with(ColorTransform::LumMod(50_000));
|
||||
for color in [preset, system, inverted, translucent, rgb, twice, ordered] {
|
||||
let mut s = shape();
|
||||
let fill = Fill::Solid { color: color.clone() };
|
||||
format_run(&mut s, &|r| r.fill = Some(fill.clone())).unwrap();
|
||||
s.ui_requests.clear();
|
||||
s.execute("format.fontDialog", &json!({})).unwrap();
|
||||
let Some(UiRequest::Dialog { params, .. }) = s.ui_requests.last().cloned() else { panic!("dialog request") };
|
||||
s.execute("format.fontDialog", &json!({"color": params["color"]})).unwrap();
|
||||
assert_eq!(props(&s).fill, Some(Fill::Solid { color }), "{}", params["color"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn font_dialog_ok_without_color_keeps_colors_a_command_cannot_give() {
|
||||
use deckcraft_color::Rgba;
|
||||
let last = Rgba::rgb(0x12, 0x34, 0x56);
|
||||
let preset = ColorRef { base: ColorBase::Preset { name: "notAColor".into() }, mods: vec![] }.with(ColorTransform::LumMod(50_000));
|
||||
let system = ColorRef { base: ColorBase::System { name: "notAColor".into(), last }, mods: vec![] };
|
||||
// More transforms than a command's `mods` list may carry, as an opened file can hold.
|
||||
let many = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![ColorTransform::Inv; crate::cmd::MAX_COLOR_MODS + 1] };
|
||||
for color in [preset, system, many] {
|
||||
let mut s = shape();
|
||||
let fill = Fill::Solid { color: color.clone() };
|
||||
format_run(&mut s, &|r| r.fill = Some(fill.clone())).unwrap();
|
||||
s.ui_requests.clear();
|
||||
s.execute("format.fontDialog", &json!({})).unwrap();
|
||||
let Some(UiRequest::Dialog { mut params, .. }) = s.ui_requests.last().cloned() else { panic!("dialog request") };
|
||||
// OK with the Color field untouched and another field edited, as the dialog sends it.
|
||||
params.as_object_mut().unwrap().remove("color");
|
||||
params["size"] = json!(20.0);
|
||||
params["bold"] = json!(true);
|
||||
s.execute("format.fontDialog", ¶ms).unwrap();
|
||||
let r = props(&s);
|
||||
assert_eq!((r.size, r.bold), (Some(20.0), Some(true)));
|
||||
assert_eq!(r.fill, Some(Fill::Solid { color }));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn font_dialog_color_mods_round_trip_and_unknown_ops_are_errors() {
|
||||
let two = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] }
|
||||
.with(ColorTransform::LumMod(75_000))
|
||||
.with(ColorTransform::LumOff(10_000));
|
||||
let mut s = shape();
|
||||
let fill = Fill::Solid { color: two.clone() };
|
||||
format_run(&mut s, &|r| r.fill = Some(fill.clone())).unwrap();
|
||||
s.ui_requests.clear();
|
||||
s.execute("format.fontDialog", &json!({})).unwrap();
|
||||
let Some(UiRequest::Dialog { params, .. }) = s.ui_requests.last().cloned() else { panic!("dialog request") };
|
||||
assert_eq!(params["color"], json!({"preset": "red", "mods": [{"op": "lumMod", "val": 75_000}, {"op": "lumOff", "val": 10_000}]}));
|
||||
s.execute("format.fontDialog", &json!({"color": params["color"]})).unwrap();
|
||||
assert_eq!(props(&s).fill, Some(Fill::Solid { color: two.clone() }));
|
||||
// An unknown op is an error, and the run keeps its color.
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
let err = s.execute("format.fontDialog", &json!({"color": {"preset": "red", "mods": [{"op": "sparkle"}]}})).unwrap_err();
|
||||
assert!(err.to_string().contains("color"), "{err}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), n);
|
||||
assert_eq!(props(&s).fill, Some(Fill::Solid { color: two }));
|
||||
// An empty list gives the color with no transforms.
|
||||
s.execute("format.fontDialog", &json!({"color": {"preset": "red", "mods": []}})).unwrap();
|
||||
assert_eq!(props(&s).fill, Some(Fill::Solid { color: ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] } }));
|
||||
// A scheme color with a keyed `lumMod` and a list keeps both, the keyed one first.
|
||||
s.execute("format.fontDialog", &json!({"color": {"scheme": "accent2", "lumMod": 75_000, "mods": [{"op": "lumOff", "val": 10_000}]}}))
|
||||
.unwrap();
|
||||
let scheme = ColorRef::scheme(SchemeSlot::Accent2).with(ColorTransform::LumMod(75_000)).with(ColorTransform::LumOff(10_000));
|
||||
assert_eq!(props(&s).fill, Some(Fill::Solid { color: scheme }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn font_dialog_with_no_fields_asks_the_ui_to_open() {
|
||||
let mut s = shape();
|
||||
|
||||
@@ -443,39 +443,23 @@ fn font_edits(p: &Value) -> Result<FontEdits> {
|
||||
fn color_command_value(c: &deckcraft_model::ColorRef) -> Value {
|
||||
use deckcraft_model::ColorBase;
|
||||
let mut o = serde_json::Map::new();
|
||||
// An ordered list, so the order of the transforms and repeated ones such as `[inv, inv]` are kept.
|
||||
if !c.mods.is_empty() {
|
||||
o.insert("mods".into(), json!(c.mods));
|
||||
for m in &c.mods {
|
||||
if let Some(v) = m.value() {
|
||||
o.insert(m.xml_name().to_string(), json!(v));
|
||||
}
|
||||
}
|
||||
// `#RRGGBB`, or `#RRGGBBAA` for a color that is not opaque.
|
||||
let hex = |c: &deckcraft_color::Rgba| if c.a == 255 { format!("#{}", c.hex()) } else { format!("#{}{:02X}", c.hex(), c.a) };
|
||||
// A preset or system name that `color_value` does not know (kept from an opened file) is given as
|
||||
// the color it is drawn with, so a caller that sends this `color` back gets a valid color. The
|
||||
// Font dialog sends no `color` when its Color field is untouched, so the run keeps the stored name.
|
||||
let base = match &c.base {
|
||||
ColorBase::Preset { name } if !deckcraft_color::is_preset_name(name) => ColorBase::Rgb { rgb: deckcraft_color::Rgba::BLACK },
|
||||
ColorBase::System { name, last } if !deckcraft_color::is_system_name(name) => ColorBase::Rgb { rgb: *last },
|
||||
b => b.clone(),
|
||||
};
|
||||
match &base {
|
||||
ColorBase::Rgb { rgb } if o.is_empty() => json!(hex(rgb)),
|
||||
match &c.base {
|
||||
ColorBase::Rgb { rgb } if o.is_empty() => json!(format!("#{}", rgb.hex())),
|
||||
ColorBase::Rgb { rgb } => {
|
||||
o.insert("rgb".into(), json!(hex(rgb)));
|
||||
o.insert("rgb".into(), json!(format!("#{}", rgb.hex())));
|
||||
Value::Object(o)
|
||||
}
|
||||
ColorBase::Scheme { slot } => {
|
||||
o.insert("scheme".into(), json!(slot.xml_name()));
|
||||
Value::Object(o)
|
||||
}
|
||||
ColorBase::Preset { name } => {
|
||||
o.insert("preset".into(), json!(name));
|
||||
Value::Object(o)
|
||||
}
|
||||
ColorBase::System { name, last } => {
|
||||
o.insert("system".into(), json!(name));
|
||||
o.insert("last".into(), json!(hex(last)));
|
||||
Value::Object(o)
|
||||
}
|
||||
ColorBase::Preset { name } => json!(name),
|
||||
ColorBase::System { last, .. } => json!(format!("#{}", last.hex())),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Bullet, Effects, Fill, Line, ParaProps, Result, RunProps, Session, Shape, Strike, Value, bad, base64_decode, bool_or, current_para, current_run,
|
||||
ed, edit_shapes, format_run, has_text_or_shapes, ids_param, json, ok, resolve, str_param,
|
||||
ed, edit_shapes, format_run, ids_param, json, ok, resolve, str_param,
|
||||
};
|
||||
|
||||
/// Formatting picked up by the Format Painter.
|
||||
@@ -14,17 +14,7 @@ pub struct Painted {
|
||||
pub style: Option<deckcraft_model::ShapeStyle>,
|
||||
}
|
||||
|
||||
/// Keeps disarming available when the source selection has gone away.
|
||||
pub(super) fn painter_enabled(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.painter.is_some() { Ok(()) } else { has_text_or_shapes(s) }
|
||||
}
|
||||
|
||||
pub(super) fn painter_pick(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("on").and_then(Value::as_bool) == Some(false) {
|
||||
s.painter = None;
|
||||
return Ok(json!({"armed": false}));
|
||||
}
|
||||
has_text_or_shapes(s).map_err(|why| bad("format.painter", why))?;
|
||||
let st = s.doc()?;
|
||||
let mut painted = Painted::default();
|
||||
if let Some(t) = &st.selection.text {
|
||||
@@ -134,7 +124,7 @@ pub(super) fn state(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
}))
|
||||
}
|
||||
|
||||
/// Registers font bytes through the catalogue adapter shared by rendering and the picker.
|
||||
/// Add a font from its bytes for this session (it then shows in the font menu and draws).
|
||||
pub(super) fn font_add(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let data = str_param(p, "data").and_then(base64_decode).ok_or_else(|| bad("font.add", "missing or invalid base64 `data`"))?;
|
||||
if data.len() > 64 << 20 {
|
||||
@@ -147,9 +137,12 @@ pub(super) fn font_add(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"faces": faces}))
|
||||
}
|
||||
|
||||
/// Refreshes installed fonts through the catalogue adapter shared by rendering and the picker.
|
||||
/// Catalog the installed fonts again, so fonts installed while DeckCraft runs appear.
|
||||
pub(super) fn font_rescan(_s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let db = deckcraft_fonts::FontDb::global();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let faces = db.load_system_fonts();
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let faces = 0usize;
|
||||
Ok(json!({"faces": faces, "families": db.families().len()}))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Align, Anchor, AutoFit, Bullet, Result, Session, Spacing, TextDir, Value, bad, bool_or, color_param, current_para, f64_or, f64_param,
|
||||
format_body, format_para, json, ok, on_param, require_any, resolve, str_param,
|
||||
format_body, format_para, json, ok, on_param, resolve, str_param,
|
||||
};
|
||||
|
||||
pub(super) fn align_to(s: &mut Session, a: Align) -> Result<Value> {
|
||||
@@ -114,31 +114,12 @@ pub(super) fn level(s: &mut Session, d: i32) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn line_spacing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sp = if let Some(pt) = f64_param(p, "pt") { Spacing::Pts(clamp_pt(pt)) } else { Spacing::Pct(f64_or(p, "lines", 1.0).clamp(0.0, 9.99)) };
|
||||
let sp =
|
||||
if let Some(pt) = f64_param(p, "pt") { Spacing::Pts(pt.clamp(0.0, 1584.0)) } else { Spacing::Pct(f64_or(p, "lines", 1.0).clamp(0.0, 9.99)) };
|
||||
format_para(s, &move |para| para.props.line_spacing = Some(sp))
|
||||
}
|
||||
|
||||
pub(super) fn paragraph(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The Paragraph dialog's other fields are format.paragraphDialog's; say so instead of
|
||||
// calling the call empty.
|
||||
if let Some(k) =
|
||||
["special", "specialBy", "indentRight", "spaceBeforeKind", "spaceAfterKind"].into_iter().find(|k| p.get(*k).is_some_and(|v| !v.is_null()))
|
||||
{
|
||||
// The dialog applies a kind or `specialBy` only with the value it qualifies.
|
||||
let with = match k {
|
||||
"spaceBeforeKind" => " together with `spaceBefore`",
|
||||
"spaceAfterKind" => " together with `spaceAfter`",
|
||||
"specialBy" => " together with `special`",
|
||||
_ => "",
|
||||
};
|
||||
return Err(bad(
|
||||
"format.paragraph",
|
||||
format!(
|
||||
"`{k}` is a field of format.paragraphDialog (the whole Paragraph dialog); pass it there{with}. format.paragraph does not read it"
|
||||
),
|
||||
));
|
||||
}
|
||||
require_any(p, "format.paragraph", &["align", "indentLeft", "indentFirst", "spaceBefore", "spaceAfter", "lineSpacing", "lineSpacingPt"])?;
|
||||
let a = str_param(p, "align").map(|a| parse_align("format.paragraph", a)).transpose()?;
|
||||
let ml = f64_param(p, "indentLeft");
|
||||
let ind = f64_param(p, "indentFirst");
|
||||
@@ -188,14 +169,8 @@ pub(super) fn finite_key(p: &Value, cmd: &str, key: &str) -> Result<Option<f64>>
|
||||
}
|
||||
}
|
||||
|
||||
/// The supported paragraph spacing in points.
|
||||
pub const PARAGRAPH_PT_RANGE: std::ops::RangeInclusive<f64> = 0.0..=1584.0;
|
||||
|
||||
/// The supported first-line and hanging indent in points: the paragraph spacing range on both sides of zero.
|
||||
pub const PARAGRAPH_INDENT_RANGE: std::ops::RangeInclusive<f64> = -*PARAGRAPH_PT_RANGE.end()..=*PARAGRAPH_PT_RANGE.end();
|
||||
|
||||
pub(super) fn clamp_pt(v: f64) -> f64 {
|
||||
v.clamp(*PARAGRAPH_PT_RANGE.start(), *PARAGRAPH_PT_RANGE.end())
|
||||
v.clamp(0.0, 1584.0)
|
||||
}
|
||||
|
||||
fn parse_align(cmd: &str, s: &str) -> Result<Align> {
|
||||
@@ -285,7 +260,7 @@ pub(super) fn paragraph_dialog(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let indent_right = finite_key(p, CMD, "indentRight")?.map(clamp_pt);
|
||||
let special_by = finite_key(p, CMD, "specialBy")?.map(|v| clamp_pt(v.max(0.0)));
|
||||
let indent = match p.get("special") {
|
||||
None => finite_key(p, CMD, "indentFirst")?.map(|v| v.clamp(*PARAGRAPH_INDENT_RANGE.start(), *PARAGRAPH_INDENT_RANGE.end())),
|
||||
None => finite_key(p, CMD, "indentFirst")?.map(|v| v.clamp(-1584.0, 1584.0)),
|
||||
Some(Value::String(kind)) => {
|
||||
let by = special_by.unwrap_or(0.0);
|
||||
Some(match kind.as_str() {
|
||||
@@ -383,12 +358,9 @@ fn current_columns(s: &Session) -> (u32, f64) {
|
||||
Some(c) => resolve::body(&c, sh),
|
||||
None => sh.text.as_ref().map(|b| b.body.clone()).unwrap_or_default(),
|
||||
};
|
||||
(body.columns.unwrap_or(1).clamp(*COLUMN_COUNT_RANGE.start(), *COLUMN_COUNT_RANGE.end()), body.col_spacing.unwrap_or(0.0).max(0.0))
|
||||
(body.columns.unwrap_or(1).clamp(1, 16), body.col_spacing.unwrap_or(0.0).max(0.0))
|
||||
}
|
||||
|
||||
/// The supported text column counts.
|
||||
pub const COLUMN_COUNT_RANGE: std::ops::RangeInclusive<u32> = 1..=16;
|
||||
|
||||
pub(super) fn columns(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "format.columns";
|
||||
let count = match p.get("count") {
|
||||
@@ -396,10 +368,8 @@ pub(super) fn columns(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(v) => {
|
||||
let n = v
|
||||
.as_f64()
|
||||
.filter(|n| n.fract() == 0.0 && (f64::from(*COLUMN_COUNT_RANGE.start())..=f64::from(*COLUMN_COUNT_RANGE.end())).contains(n))
|
||||
.ok_or_else(|| {
|
||||
bad(CMD, format!("`count` must be a whole number from {} to {}", COLUMN_COUNT_RANGE.start(), COLUMN_COUNT_RANGE.end()))
|
||||
})?;
|
||||
.filter(|n| n.fract() == 0.0 && (1.0..=16.0).contains(n))
|
||||
.ok_or_else(|| bad(CMD, "`count` must be a whole number from 1 to 16"))?;
|
||||
Some(n as u32)
|
||||
}
|
||||
};
|
||||
@@ -434,7 +404,6 @@ pub(super) fn wrap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn margins(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
require_any(p, "format.margins", &["left", "top", "right", "bottom"])?;
|
||||
let (l, t, r, b) = (f64_param(p, "left"), f64_param(p, "top"), f64_param(p, "right"), f64_param(p, "bottom"));
|
||||
format_body(s, &move |bp| {
|
||||
if l.is_some() {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Drawing guides: commands, shape snapping while visible and the PPTX round trip.
|
||||
//! Drawing guides: commands, dragging a guide with the pointer, snapping shapes to guides, and
|
||||
//! the PPTX round trip.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
@@ -31,8 +32,17 @@ fn drag_a_guide_drop_it_off_the_slide_and_snap_shapes_to_it() {
|
||||
let mut s = Session::with_new();
|
||||
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap();
|
||||
s.execute("guide.move", &json!({"index": 0, "pos": 350})).unwrap();
|
||||
// Hidden guides can't be grabbed: the press starts a marquee instead.
|
||||
ev(&mut s, PointerKind::Down, 300.0, 50.0);
|
||||
ev(&mut s, PointerKind::Up, 300.0, 50.0);
|
||||
assert_eq!(s.doc().unwrap().doc.guides[0].pos, 300.0);
|
||||
s.tool.guides_visible = true;
|
||||
ev(&mut s, PointerKind::Down, 301.0, 50.0);
|
||||
ev(&mut s, PointerKind::Drag, 350.4, 60.0);
|
||||
assert_eq!(s.tool.guide_drag, Some((0, 350.0)), "whole points while dragging");
|
||||
ev(&mut s, PointerKind::Up, 350.4, 60.0);
|
||||
assert_eq!(s.doc().unwrap().doc.guides[0].pos, 350.0);
|
||||
assert_eq!(s.tool.guide_drag, None);
|
||||
|
||||
// A shape dragged near the guide snaps its left edge onto it.
|
||||
let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [100, 200, 80, 60]})).unwrap()["id"].as_u64().unwrap();
|
||||
@@ -42,43 +52,15 @@ fn drag_a_guide_drop_it_off_the_slide_and_snap_shapes_to_it() {
|
||||
ev(&mut s, PointerKind::Drag, 388.0, 231.0);
|
||||
ev(&mut s, PointerKind::Up, 388.0, 231.0);
|
||||
let x = s.doc().unwrap().shapes().iter().find(|sh| sh.id.0 as u64 == id).and_then(|sh| sh.xfrm).unwrap();
|
||||
let guide = s.doc().unwrap().doc.guides[0].pos;
|
||||
assert!((x.x - guide).abs() < 0.01, "{x:?}");
|
||||
assert!((x.x - 350.0).abs() < 0.01, "{x:?}");
|
||||
|
||||
s.execute("shape.setBounds", &json!({"id": id, "x": 100, "y": 200, "w": 80, "h": 60})).unwrap();
|
||||
s.tool.guides_visible = false;
|
||||
ev(&mut s, PointerKind::Down, 140.0, 230.0);
|
||||
ev(&mut s, PointerKind::Drag, 200.0, 230.0);
|
||||
ev(&mut s, PointerKind::Drag, 388.0, 231.0);
|
||||
ev(&mut s, PointerKind::Up, 388.0, 231.0);
|
||||
let hidden = s.doc().unwrap().shapes().iter().find(|sh| sh.id.0 as u64 == id).and_then(|sh| sh.xfrm).unwrap();
|
||||
assert!((hidden.x - guide).abs() > 1.0, "a hidden guide does not snap the shape: {hidden:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_guides_validates_atomically_and_undoes_the_whole_vector() {
|
||||
let mut s = Session::with_new();
|
||||
for (vertical, pos) in [(true, 100.0), (false, 150.0), (true, 200.0)] {
|
||||
s.execute("guide.add", &json!({"vertical": vertical, "pos": pos})).unwrap();
|
||||
}
|
||||
let before = s.doc().unwrap().doc.guides.clone();
|
||||
let replacement = vec![
|
||||
deckcraft_model::DrawGuide { pos: before[2].pos + 25.0, ..before[2] },
|
||||
deckcraft_model::DrawGuide { pos: before[0].pos + 15.0, ..before[0] },
|
||||
];
|
||||
s.execute("guide.set", &json!({"guides": replacement})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.guides, replacement, "one commit preserves the final order, moves and deletion");
|
||||
assert!(s.execute("guide.set", &json!({"guides": [before[0], {"vertical": false, "pos": null}]})).is_err());
|
||||
assert!(s.execute("guide.set", &json!({"guides": vec![before[0]; super::MAX_GUIDES + 1]})).is_err());
|
||||
assert_eq!(s.doc().unwrap().doc.guides, replacement, "a refused vector changes no guide");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.guides, before, "one undo restores every moved and deleted guide");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.guides, replacement);
|
||||
s.execute("guide.set", &json!({"guides": []})).unwrap();
|
||||
// Dropped off the slide: gone, and undo brings it back.
|
||||
ev(&mut s, PointerKind::Down, 350.0, 10.0);
|
||||
ev(&mut s, PointerKind::Drag, -40.0, 10.0);
|
||||
ev(&mut s, PointerKind::Up, -40.0, 10.0);
|
||||
assert!(s.doc().unwrap().doc.guides.is_empty());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.guides, replacement);
|
||||
assert_eq!(s.doc().unwrap().doc.guides.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -20,10 +20,6 @@ mod links;
|
||||
mod picture;
|
||||
mod text_fields;
|
||||
|
||||
pub use album::{
|
||||
ALBUM_MAX_BYTES, ALBUM_MAX_ITEMS, ALBUM_MAX_TEXT, ALBUM_MAX_TOTAL, album_check_item_count, album_check_picture_bytes, album_check_text,
|
||||
album_check_total_bytes,
|
||||
};
|
||||
use album::{photo_album, photo_album_edit};
|
||||
pub use chart::chart_type;
|
||||
use chart::{chart, chart_data, chart_options, chart_type_cmd};
|
||||
|
||||
@@ -1,57 +1,13 @@
|
||||
use super::picture::{content_type, media_bytes};
|
||||
use super::{NO_ID_SPACE, Result, Session, ShapeKind, Value, bad, base64_encode, json};
|
||||
|
||||
/// Maximum number of picture and text items a photo album can carry.
|
||||
pub const ALBUM_MAX_ITEMS: usize = 48;
|
||||
const ALBUM_MAX_ITEMS: usize = 48;
|
||||
|
||||
/// Maximum decoded bytes in one album picture.
|
||||
pub const ALBUM_MAX_BYTES: usize = 32 * 1024 * 1024;
|
||||
const ALBUM_MAX_BYTES: usize = 32 * 1024 * 1024;
|
||||
|
||||
/// Maximum decoded picture bytes in an album.
|
||||
pub const ALBUM_MAX_TOTAL: usize = 64 * 1024 * 1024;
|
||||
const ALBUM_MAX_TOTAL: usize = 64 * 1024 * 1024;
|
||||
|
||||
/// Maximum Unicode characters in an album text box.
|
||||
pub const ALBUM_MAX_TEXT: usize = 400;
|
||||
|
||||
/// Checks the capacity of an album draft, which may still be empty.
|
||||
pub fn album_check_item_count(count: usize) -> std::result::Result<(), String> {
|
||||
if count > ALBUM_MAX_ITEMS {
|
||||
return Err(format!("A photo album holds at most {ALBUM_MAX_ITEMS} pictures or text boxes"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the trimmed text of a valid album text box.
|
||||
pub fn album_check_text(text: &str) -> std::result::Result<&str, String> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Err("A text box needs some text".into());
|
||||
}
|
||||
if text.chars().count() > ALBUM_MAX_TEXT {
|
||||
return Err(format!("Text is longer than {ALBUM_MAX_TEXT} characters"));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// Checks a picture's decoded byte count without decoding its media format.
|
||||
pub fn album_check_picture_bytes(name: &str, bytes: usize) -> std::result::Result<(), String> {
|
||||
if bytes == 0 {
|
||||
return Err("That file is empty".into());
|
||||
}
|
||||
if bytes > ALBUM_MAX_BYTES {
|
||||
return Err(format!("{name} is larger than 32 MB"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds a picture's bytes to an album draft, refusing aggregate overflow.
|
||||
pub fn album_check_total_bytes(total: usize, added: usize) -> std::result::Result<usize, String> {
|
||||
let next = total.saturating_add(added);
|
||||
if next > ALBUM_MAX_TOTAL {
|
||||
return Err("The album is larger than 64 MB".into());
|
||||
}
|
||||
Ok(next)
|
||||
}
|
||||
const ALBUM_MAX_TEXT: usize = 400;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct AlbumLayout {
|
||||
@@ -302,7 +258,9 @@ fn album_items(p: &Value) -> Result<Vec<AlbumItem>> {
|
||||
if arr.is_empty() {
|
||||
return Err(bad("insert.photoAlbum", "add at least one picture or text box"));
|
||||
}
|
||||
album_check_item_count(arr.len()).map_err(|message| bad("insert.photoAlbum", message))?;
|
||||
if arr.len() > ALBUM_MAX_ITEMS {
|
||||
return Err(bad("insert.photoAlbum", "a photo album holds at most 48 pictures or text boxes"));
|
||||
}
|
||||
let mut items = Vec::with_capacity(arr.len());
|
||||
let mut total = 0usize;
|
||||
for item in arr {
|
||||
@@ -314,14 +272,25 @@ fn album_items(p: &Value) -> Result<Vec<AlbumItem>> {
|
||||
let Some(text) = obj.get("text").and_then(Value::as_str) else {
|
||||
return Err(bad("insert.photoAlbum", "each album item needs `path`, `data` or `text`"));
|
||||
};
|
||||
let text = album_check_text(text).map_err(|message| bad("insert.photoAlbum", message))?;
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Err(bad("insert.photoAlbum", "a text box needs some text"));
|
||||
}
|
||||
if text.chars().count() > ALBUM_MAX_TEXT {
|
||||
return Err(bad("insert.photoAlbum", "text is longer than 400 characters"));
|
||||
}
|
||||
items.push(AlbumItem::Text(text.to_string()));
|
||||
continue;
|
||||
}
|
||||
let (name, bytes) = media_bytes(item, "insert.photoAlbum")?;
|
||||
|
||||
album_check_picture_bytes(&name, bytes.len()).map_err(|message| bad("insert.photoAlbum", message))?;
|
||||
total = album_check_total_bytes(total, bytes.len()).map_err(|message| bad("insert.photoAlbum", message))?;
|
||||
if bytes.len() > ALBUM_MAX_BYTES {
|
||||
return Err(bad("insert.photoAlbum", format!("{name} is larger than 32 MB")));
|
||||
}
|
||||
let next = total.saturating_add(bytes.len());
|
||||
if next > ALBUM_MAX_TOTAL {
|
||||
return Err(bad("insert.photoAlbum", "the album is larger than 64 MB"));
|
||||
}
|
||||
total = next;
|
||||
let ct = content_type(&name, &bytes);
|
||||
if !ct.starts_with("image/") {
|
||||
return Err(bad("insert.photoAlbum", format!("{name} is not a picture")));
|
||||
@@ -808,15 +777,6 @@ mod seed_tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn empty_svg_album_input_cannot_edit_the_document() {
|
||||
let mut s = Session::with_new();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
assert!(s.execute("insert.photoAlbum", &json!({"pictures": [{"name": "empty.svg", "data": ""}]})).is_err());
|
||||
assert!(Arc::ptr_eq(&s.active().unwrap().doc, &before));
|
||||
assert!(s.active().unwrap().history.undo.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reopening_an_album_seeds_at_most_the_items_an_album_takes() {
|
||||
// One picture named by 500 shapes: the dialog gets 48 items, not 500 encoded copies.
|
||||
|
||||
@@ -1009,10 +1009,9 @@ pub fn segment_start_of(sh: &Shape, path: usize, index: usize) -> Option<usize>
|
||||
vs.iter().position(|v| Some(*v) == j.checked_sub(1))
|
||||
}
|
||||
|
||||
/// Renumbering invalidates menu picks and any point type remembered for `path`.
|
||||
/// Adding, deleting, opening or closing renumbers the points of `path`: a point type remembered
|
||||
/// for one of them would follow the wrong point.
|
||||
fn forget_kinds(s: &mut Session, path: usize) {
|
||||
s.tool.edit_segment = None;
|
||||
s.tool.edit_vertex = None;
|
||||
if s.tool.vertex_kind.as_ref().is_some_and(|k| k.1 == path) {
|
||||
s.tool.vertex_kind = None;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ use serde_json::{Value, json};
|
||||
|
||||
use super::{
|
||||
CommandSpec, NO_ID_SPACE, bad, bool_or, bool_param, cmd, color_param, color_value, edit_geometry, edit_shapes, f64_param, has_selection,
|
||||
has_slide, id_param, ok, opt_usize_param, require_any, str_param, targets, usize_param, with_param, xfrm_of,
|
||||
has_slide, id_param, ok, opt_usize_param, str_param, targets, usize_param, with_param, xfrm_of,
|
||||
};
|
||||
use crate::{Result, Session};
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Connect Shapes",
|
||||
[],
|
||||
None,
|
||||
"{from: shape id, to: shape id, fromSite?, toSite?: site index (default: with neither given, the sites facing each other along the dominant direction between the shapes, a tie to the lower index; with one given, the closest site of the other shape; a box has 0 top, 1 left, 2 bottom, 3 right; shape.sites lists them), id?: existing line to glue (else a new connector), preset?: straightConnector1|bentConnector3|curvedConnector3} → {id}",
|
||||
"{from: shape id, to: shape id, fromSite?, toSite?: site index (default: the closest pair), id?: existing line to glue (else a new connector), preset?: straightConnector1|bentConnector3|curvedConnector3} → {id}",
|
||||
has_slide,
|
||||
connect
|
||||
),
|
||||
@@ -112,7 +112,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Shape Outline",
|
||||
["Shape Format", "Shape Styles"],
|
||||
None,
|
||||
"{color?, none?, width?: pt, dash?: solid|dot|dash|lgDash|dashDot|sysDot|sysDash, cap?: flat|round|square, join?: round|bevel|miter, compound?: single|double|thickThin|thinThick|triple, head?: none|triangle|stealth|diamond|oval|arrow, tail?, headSize?: sm|med|lg, tailSize?, reset?, ids?} (at least one key); a group also formats its members",
|
||||
"{color?, none?, width?: pt, dash?: solid|dot|dash|lgDash|dashDot|sysDot|sysDash, cap?: flat|round|square, join?: round|bevel|miter, compound?: single|double|thickThin|thinThick|triple, head?: none|triangle|stealth|diamond|oval|arrow, tail?, headSize?: sm|med|lg, tailSize?, reset?, ids?}; a group also formats its members",
|
||||
has_selection,
|
||||
line
|
||||
),
|
||||
@@ -121,7 +121,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Shape Effects",
|
||||
["Shape Format", "Shape Styles"],
|
||||
None,
|
||||
"{shadow?: none|outer|inner|perspective|{color, blur, dist, dir}, glow?: none|{color, radius}, softEdges?: pt, reflection?: none|tight|half|full, bevel?: none|circle|…, threeD?: {camera?: preset, rotX?, rotY?, rotZ?: deg, z?: pt, bevelTop?, bevelBottom?: none|circle|…, bevelTopW?, bevelTopH?, bevelBottomW?, bevelBottomH?, depth?, contour?: pt, material?, lighting?, reset?: true}, shadowProps?: {color?, transparency?: 0..1, size?: 0.01..2 (1 = 100%), blur?: pt, dist?: pt, dir?: deg}, glowProps?: {color?, transparency?, radius?: pt}, reflectionProps?: {transparency?, size?: 0..1, dist?: pt, blur?: pt}, reset?, ids?} (at least one key) (the *Props keys adjust the current effect, adding a default one when there is none)",
|
||||
"{shadow?: none|outer|inner|perspective|{color, blur, dist, dir}, glow?: none|{color, radius}, softEdges?: pt, reflection?: none|tight|half|full, bevel?: none|circle|…, threeD?: {camera?: preset, rotX?, rotY?, rotZ?: deg, z?: pt, bevelTop?, bevelBottom?: none|circle|…, bevelTopW?, bevelTopH?, bevelBottomW?, bevelBottomH?, depth?, contour?: pt, material?, lighting?, reset?: true}, shadowProps?: {color?, transparency?: 0..1, size?: 0.01..2 (1 = 100%), blur?: pt, dist?: pt, dir?: deg}, glowProps?: {color?, transparency?, radius?: pt}, reflectionProps?: {transparency?, size?: 0..1, dist?: pt, blur?: pt}, reset?, ids?} (the *Props keys adjust the current effect, adding a default one when there is none)",
|
||||
has_selection,
|
||||
effects
|
||||
),
|
||||
@@ -135,15 +135,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
quick_style
|
||||
),
|
||||
cmd!("shape.rename", "Rename", ["Selection Pane"], None, "{name, id?}", has_selection, rename),
|
||||
cmd!(
|
||||
"shape.altText",
|
||||
"Alt Text",
|
||||
["Shape Format", "Accessibility"],
|
||||
None,
|
||||
"{text?: string, decorative?: bool, ids?}",
|
||||
has_selection,
|
||||
alt_text
|
||||
),
|
||||
cmd!("shape.altText", "Alt Text", ["Shape Format", "Accessibility"], None, "{text, decorative?: bool, ids?}", has_selection, alt_text),
|
||||
cmd!("shape.visible", "Show/Hide", ["Selection Pane"], None, "{visible?: bool, ids?}", has_selection, visible),
|
||||
cmd!(
|
||||
"shape.lock",
|
||||
@@ -169,7 +161,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Corrections",
|
||||
["Picture Format", "Adjust"],
|
||||
None,
|
||||
"{brightness?: -1..1, contrast?: -1..1, saturation?: 0..4, grayscale?: bool, transparency?: 0..1, reset?: bool, ids?} (at least one key)",
|
||||
"{brightness?: -1..1, contrast?: -1..1, saturation?: 0..4, grayscale?: bool, transparency?: 0..1, reset?: bool, ids?}",
|
||||
has_selection,
|
||||
picture_adjust
|
||||
),
|
||||
@@ -358,12 +350,10 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn alt_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let text = str_param(p, "text");
|
||||
let text = str_param(p, "text").unwrap_or("").to_string();
|
||||
let deco = bool_param(p, "decorative");
|
||||
edit_shapes(s, p, "shape.altText", |sh| {
|
||||
if let Some(text) = text {
|
||||
sh.descr = text.to_owned();
|
||||
}
|
||||
sh.descr = text.clone();
|
||||
if let Some(d) = deco {
|
||||
sh.decorative = d;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{
|
||||
ColorRef, ColorTransform, Dash, Effects, Fill, Geom, Glow, Gradient, GradientShape, GradientStop, Line, LineEnd, PictureFill, PictureMode,
|
||||
Reflection, Result, Rgba, SchemeSlot, Session, Shadow, ShapeStyle, Value, apply_fill, bad, bool_or, color_param, color_value, edit_geometry,
|
||||
edit_shapes, f64_param, inherited_fills, json, opt_usize_param, requested_fill, require_any, str_param, targets,
|
||||
edit_shapes, f64_param, inherited_fills, json, opt_usize_param, requested_fill, str_param, targets,
|
||||
};
|
||||
|
||||
pub(super) fn adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -237,7 +237,6 @@ fn line_end(v: &str) -> Option<LineEnd> {
|
||||
}
|
||||
|
||||
pub(super) fn line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
require_any(p, "shape.line", &["color", "none", "width", "dash", "cap", "join", "compound", "head", "tail", "headSize", "tailSize", "reset"])?;
|
||||
let reset = bool_or(p, "reset", false);
|
||||
let none = bool_or(p, "none", false);
|
||||
let color = color_param(p, "color");
|
||||
@@ -357,15 +356,6 @@ fn shadow_preset(v: &Value) -> Option<Option<Shadow>> {
|
||||
}
|
||||
|
||||
pub(super) fn effects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// `glow: null` and `softEdges: null` clear those effects (No Glow, No Soft Edges), so a null
|
||||
// counts as something to set for them.
|
||||
if !["glow", "softEdges"].iter().any(|k| p.get(*k).is_some()) {
|
||||
require_any(
|
||||
p,
|
||||
"shape.effects",
|
||||
&["shadow", "glow", "softEdges", "reflection", "bevel", "threeD", "shadowProps", "glowProps", "reflectionProps", "reset"],
|
||||
)?;
|
||||
}
|
||||
let reset = bool_or(p, "reset", false);
|
||||
let shadow = p.get("shadow").and_then(shadow_preset);
|
||||
let glow: Option<Option<Glow>> = p.get("glow").map(|g| match g {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{ColorRef, Fill, Geom, Line, NO_ID_SPACE, Result, Session, Value, bad, bool_or, id_param, json, str_param, usize_param, xfrm_of};
|
||||
use super::{ColorRef, Fill, Geom, Line, NO_ID_SPACE, Result, Session, Value, bad, bool_or, id_param, json, str_param, usize_param};
|
||||
|
||||
pub(super) fn sites(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id", "shape.sites")?.ok_or_else(|| bad("shape.sites", "missing `id`"))?;
|
||||
@@ -24,50 +24,20 @@ pub(super) fn connect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad("shape.connect", "both shapes need connection sites (lines and groups have none)"));
|
||||
}
|
||||
let pick = |v: &[deckcraft_geom::Point], key: &str| usize_param(p, key).filter(|i| *i < v.len());
|
||||
// A site left unsaid is the one facing the other shape along the dominant direction between
|
||||
// the two (a box mostly below is left from the bottom), which is where a person glues an
|
||||
// arrow; "the closest pair" chose a side site for a diagonal neighbour and crossed boxes.
|
||||
// The direction runs between the shapes' box centres: the mean of the sites is off-centre
|
||||
// for a shape whose sites are not symmetric (a triangle's lie mostly along its base).
|
||||
// In slide space, as the sites are: a shape inside a group is placed where the group draws it.
|
||||
let centre = |id| {
|
||||
crate::connect::locate(&st.doc, &st.selection, st.shapes(), id)
|
||||
.map(|(sh, to_abs)| to_abs * xfrm_of(&st.doc, &st.selection, sh).center())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let (ca, cb) = (centre(from), centre(to));
|
||||
// A tie goes to the lowest site index: an exact diagonal leaves a box from its bottom (site 2,
|
||||
// before the right side, 3) and enters the other at its top (0, before the left side, 1), and
|
||||
// shapes with one centre, where every direction is as good, both take site 0.
|
||||
let facing = |v: &[deckcraft_geom::Point], c: deckcraft_geom::Point, dx: f64, dy: f64| {
|
||||
let len = dx.hypot(dy).max(1e-9);
|
||||
let cos: Vec<f64> = v
|
||||
.iter()
|
||||
.map(|q| {
|
||||
let (sx, sy) = (q.x - c.x, q.y - c.y);
|
||||
(sx * dx + sy * dy) / (sx.hypot(sy).max(1e-9) * len)
|
||||
})
|
||||
.collect();
|
||||
let best = cos.iter().copied().fold(f64::NEG_INFINITY, f64::max);
|
||||
cos.iter().position(|x| *x >= best - 1e-9).unwrap_or(0)
|
||||
};
|
||||
// With one site given, the other end is the site of the other shape closest to it, as before;
|
||||
// the facing rule is for the case where neither is given.
|
||||
let closest = |v: &[deckcraft_geom::Point], to: deckcraft_geom::Point| {
|
||||
let mut best = (f64::MAX, 0);
|
||||
for (i, q) in v.iter().enumerate() {
|
||||
let d = (*q - to).hypot();
|
||||
if d < best.0 {
|
||||
best = (d, i);
|
||||
}
|
||||
}
|
||||
best.1
|
||||
};
|
||||
let (ia, ib) = match (pick(&a, "fromSite"), pick(&b, "toSite")) {
|
||||
(Some(i), Some(j)) => (i, j),
|
||||
(Some(i), None) => (i, closest(&b, a[i])),
|
||||
(None, Some(j)) => (closest(&a, b[j]), j),
|
||||
(None, None) => (facing(&a, ca, cb.x - ca.x, cb.y - ca.y), facing(&b, cb, ca.x - cb.x, ca.y - cb.y)),
|
||||
(fi, fj) => {
|
||||
let mut best = (f64::MAX, 0, 0);
|
||||
for (i, pa) in a.iter().enumerate().filter(|(i, _)| fi.is_none_or(|f| f == *i)) {
|
||||
for (j, pb) in b.iter().enumerate().filter(|(j, _)| fj.is_none_or(|f| f == *j)) {
|
||||
let d = (*pa - *pb).hypot();
|
||||
if d < best.0 {
|
||||
best = (d, i, j);
|
||||
}
|
||||
}
|
||||
}
|
||||
(best.1, best.2)
|
||||
}
|
||||
};
|
||||
let (p0, p1) = (a[ia], b[ib]);
|
||||
let id = match id_param(p, "id", "shape.connect")? {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{NO_ID_SPACE, Result, Session, Value, bad, bool_or, bool_param, edit_geometry, edit_shapes, f64_param, json, require_any};
|
||||
use super::{NO_ID_SPACE, Result, Session, Value, bad, bool_or, bool_param, edit_geometry, edit_shapes, f64_param, json};
|
||||
|
||||
pub(super) fn crop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = [f64_param(p, "left"), f64_param(p, "top"), f64_param(p, "right"), f64_param(p, "bottom")];
|
||||
@@ -15,7 +15,6 @@ pub(super) fn crop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn picture_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
require_any(p, "picture.adjust", &["brightness", "contrast", "saturation", "grayscale", "transparency", "reset"])?;
|
||||
edit_shapes(s, p, "picture.adjust", |sh| {
|
||||
if let deckcraft_model::ShapeKind::Picture { fill } = &mut sh.kind {
|
||||
let a = &mut fill.adjust;
|
||||
|
||||
@@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!(noundo "slide.first", "First Slide", [], Some("Home"), "{}", has_slide, first),
|
||||
cmd!(noundo "slide.last", "Last Slide", [], Some("End"), "{}", has_slide, last),
|
||||
cmd!(noundo "slide.selectRange", "Select Slide Range", [], None, "{to: index, from?: index (default the current slide), add?: bool (keep the slides already selected)}", has_slide, select_range),
|
||||
cmd!(noundo "slide.selectSlides", "Select Slides", [], None, "{ids?: [slide id], indices?: [index], add?: bool, anchor?: slide id (the range anchor of a grid selection)}", has_slide, select_slides),
|
||||
cmd!(noundo "slide.selectSlides", "Select Slides", [], None, "{ids?: [slide id], indices?: [index], add?: bool}", has_slide, select_slides),
|
||||
cmd!("slide.hide", "Hide Slide", ["Slide Show", "Set Up"], None, "{index?, hidden?: bool}", has_slide, hide),
|
||||
cmd!("slide.layout", "Layout", ["Home", "Slides"], None, "{layout: name or kind, index?}", has_slide, set_layout),
|
||||
cmd!("slide.reset", "Reset", ["Home", "Slides"], None, "{index?}", has_slide, reset),
|
||||
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Notes",
|
||||
["View"],
|
||||
None,
|
||||
"{text | body: formatted notes (as in slide.inspect's notesBody), index?, coalesce?: bool (default false)} (text keeps untouched formatting; coalesce joins consecutive editor changes on one slide)",
|
||||
"{text | body: formatted notes (as in slide.inspect's notesBody), index?} (text as typed: untouched notes keep their formatting)",
|
||||
has_slide,
|
||||
notes
|
||||
),
|
||||
@@ -394,7 +394,6 @@ fn last(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
|
||||
fn select_slides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let add = bool_or(p, "add", false);
|
||||
let anchor = p.get("anchor").and_then(Value::as_u64).and_then(|x| u32::try_from(x).ok()).map(SlideId);
|
||||
let ids: Vec<SlideId> = {
|
||||
let st = s.doc()?;
|
||||
let mut v: Vec<SlideId> = p
|
||||
@@ -423,8 +422,7 @@ fn select_slides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
sel.shapes.clear();
|
||||
sel.text = None;
|
||||
let current = doc.slides.get(sel.slide).map(|x| x.id);
|
||||
sel.range_anchor = anchor.filter(|a| doc.slide_index(*a).is_some()).zip(current);
|
||||
sel.range_anchor = None;
|
||||
})?;
|
||||
Ok(json!({"selected": s.doc()?.selection.slides}))
|
||||
}
|
||||
@@ -595,7 +593,6 @@ fn reset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn notes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = index_of(s, p)?;
|
||||
let coalesce = bool_or(p, "coalesce", false);
|
||||
// Formatted notes as a whole (the notes editors), or text: then only what was retyped
|
||||
// changes, so bold, levels and bullets around it survive.
|
||||
let body = match p.get("body") {
|
||||
@@ -603,26 +600,14 @@ fn notes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => None,
|
||||
};
|
||||
let text = str_param(p, "text").unwrap_or("").to_string();
|
||||
let st = s.doc_mut()?;
|
||||
let slide = st.doc.slides.get(i).ok_or_else(|| bad("slide.notes", "no such slide"))?;
|
||||
let id = slide.id;
|
||||
let mut replacement = body.unwrap_or_else(|| {
|
||||
let mut notes = slide.notes.clone();
|
||||
deckcraft_model::edit::replace_text(&mut notes, &text);
|
||||
notes
|
||||
});
|
||||
if !coalesce || st.notes_run != Some(id) {
|
||||
st.notes_before = None;
|
||||
}
|
||||
st.notes_run = coalesce.then_some(id);
|
||||
if coalesce && slide.notes == replacement {
|
||||
return ok();
|
||||
}
|
||||
s.edit(|doc, _| {
|
||||
if let Some(sl) = doc.slides.get_mut(i) {
|
||||
let sl = Arc::make_mut(sl);
|
||||
let notes = &mut sl.notes;
|
||||
std::mem::swap(notes, &mut replacement);
|
||||
match body {
|
||||
Some(b) => *notes = b,
|
||||
None => deckcraft_model::edit::replace_text(notes, &text),
|
||||
}
|
||||
if !notes.is_empty() {
|
||||
sl.has_notes_slide = true;
|
||||
}
|
||||
@@ -762,63 +747,6 @@ mod tests {
|
||||
|
||||
use crate::Session;
|
||||
|
||||
#[test]
|
||||
fn consecutive_notes_edits_are_one_undo_step() {
|
||||
let (mut s, _) = deck(2);
|
||||
let read = |s: &Session, i: usize| s.doc().expect("doc").doc.slides[i].notes.text();
|
||||
let write = |s: &mut Session, i, text| {
|
||||
s.execute("slide.notes", &json!({"index": i, "text": text, "coalesce": true})).expect("edit notes");
|
||||
};
|
||||
let initial = read(&s, 0);
|
||||
for text in ["one", "one two", "one two three"] {
|
||||
write(&mut s, 0, text);
|
||||
}
|
||||
let first_run = read(&s, 0);
|
||||
s.execute("edit.undo", &json!({})).expect("undo run");
|
||||
assert_eq!(read(&s, 0), initial);
|
||||
s.execute("edit.redo", &json!({})).expect("redo run");
|
||||
assert_eq!(read(&s, 0), first_run);
|
||||
|
||||
write(&mut s, 0, "after redo");
|
||||
let before_command = read(&s, 0);
|
||||
s.execute("slide.rename", &json!({"index": 0, "name": "named"})).expect("intervening edit");
|
||||
write(&mut s, 0, "after command");
|
||||
s.execute("edit.undo", &json!({})).expect("undo later notes");
|
||||
assert_eq!(read(&s, 0), before_command);
|
||||
s.execute("edit.undo", &json!({})).expect("undo rename");
|
||||
assert_eq!(read(&s, 0), before_command);
|
||||
s.execute("edit.undo", &json!({})).expect("undo post-redo run");
|
||||
assert_eq!(read(&s, 0), first_run);
|
||||
|
||||
write(&mut s, 0, "slide zero");
|
||||
let zero = read(&s, 0);
|
||||
let other = read(&s, 1);
|
||||
write(&mut s, 1, "slide one");
|
||||
write(&mut s, 1, "slide one continued");
|
||||
s.execute("edit.undo", &json!({})).expect("undo other slide's run");
|
||||
assert_eq!(read(&s, 1), other);
|
||||
assert_eq!(read(&s, 0), zero);
|
||||
write(&mut s, 0, "after undo");
|
||||
s.execute("edit.undo", &json!({})).expect("undo starts a separate run");
|
||||
assert_eq!(read(&s, 0), zero);
|
||||
assert!(s.doc().expect("doc").history.redo.len() < 2, "typing clears the prior redo branch");
|
||||
|
||||
write(&mut s, 0, "before navigating");
|
||||
let before_navigation = read(&s, 0);
|
||||
s.execute("slide.go", &json!({"index": 0})).expect("select first");
|
||||
s.execute("slide.go", &json!({"index": 1})).expect("leave slide");
|
||||
s.execute("slide.go", &json!({"index": 0})).expect("return to slide");
|
||||
write(&mut s, 0, "after navigating");
|
||||
s.execute("edit.undo", &json!({})).expect("undo post-navigation edit");
|
||||
assert_eq!(read(&s, 0), before_navigation);
|
||||
|
||||
s.execute("slide.notes", &json!({"index": 0, "text": "automation first"})).expect("default separate edit");
|
||||
let automation_first = read(&s, 0);
|
||||
s.execute("slide.notes", &json!({"index": 0, "text": "automation second"})).expect("default separate edit");
|
||||
s.execute("edit.undo", &json!({})).expect("undo one automation edit");
|
||||
assert_eq!(read(&s, 0), automation_first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_index_params_are_rejected_not_defaulted_to_selection() {
|
||||
let mut s = Session::with_new();
|
||||
|
||||
@@ -14,9 +14,7 @@ use deckcraft_model::{
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{
|
||||
CommandSpec, NO_ID_SPACE, NOTHING_SELECTED, bad, bool_or, cmd, current_shapes, has_doc, has_selection, shape_of, str_param, targets, xfrm_of,
|
||||
};
|
||||
use super::{CommandSpec, NO_ID_SPACE, bad, bool_or, cmd, current_shapes, has_selection, shape_of, str_param, targets, xfrm_of};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
mod diagrams;
|
||||
@@ -175,20 +173,6 @@ pub fn is_kind(k: &str) -> bool {
|
||||
LAYOUTS.iter().any(|(id, _)| *id == k)
|
||||
}
|
||||
|
||||
// Session::execute_unguarded defers explicit ids to the handlers only for selection errors.
|
||||
fn selected_diagram(s: &Session) -> std::result::Result<Diagram, String> {
|
||||
has_doc(s)?;
|
||||
s.active().and_then(selected).map(|(_, diagram)| diagram).ok_or_else(|| NOTHING_SELECTED.into())
|
||||
}
|
||||
|
||||
fn has_diagram(s: &Session) -> std::result::Result<(), String> {
|
||||
selected_diagram(s).map(|_| ())
|
||||
}
|
||||
|
||||
fn has_diagram_node(s: &Session) -> std::result::Result<(), String> {
|
||||
selected_diagram(s).and_then(|diagram| if diagram.nodes.is_empty() { Err(NOTHING_SELECTED.into()) } else { Ok(()) })
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -197,7 +181,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Diagram Design", "Create Graphic"],
|
||||
None,
|
||||
"{id?} → {id, kind, nodes: [{text, level}]} (id: the Diagram group or one of its shapes; default the selection)",
|
||||
has_diagram,
|
||||
has_selection,
|
||||
nodes
|
||||
),
|
||||
cmd!(
|
||||
@@ -206,7 +190,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Diagram Design", "Create Graphic"],
|
||||
None,
|
||||
"{id?, nodes?: [{text, level}], lines?: [string] (leading tabs set the level), index?, text?, title?} (index + text edits one node; title: its Name and Title box)",
|
||||
has_diagram,
|
||||
has_selection,
|
||||
set_nodes
|
||||
),
|
||||
cmd!(
|
||||
@@ -215,7 +199,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Diagram Design", "Create Graphic"],
|
||||
None,
|
||||
"{id?, index?, position?: after|before|below|above|assistant, text?} → {index} (default: after the last node)",
|
||||
has_diagram,
|
||||
has_selection,
|
||||
add_node
|
||||
),
|
||||
cmd!(
|
||||
@@ -224,18 +208,18 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Diagram Design", "Create Graphic"],
|
||||
None,
|
||||
"{id?, index} (its sub-points move up one level)",
|
||||
has_diagram,
|
||||
has_selection,
|
||||
remove_node
|
||||
),
|
||||
cmd!("smartArt.promote", "Promote", ["Diagram Design", "Create Graphic"], None, "{id?, index}", has_diagram_node, promote),
|
||||
cmd!("smartArt.demote", "Demote", ["Diagram Design", "Create Graphic"], None, "{id?, index}", has_diagram_node, demote),
|
||||
cmd!("smartArt.promote", "Promote", ["Diagram Design", "Create Graphic"], None, "{id?, index}", has_selection, promote),
|
||||
cmd!("smartArt.demote", "Demote", ["Diagram Design", "Create Graphic"], None, "{id?, index}", has_selection, demote),
|
||||
cmd!(
|
||||
"smartArt.layout",
|
||||
"Change Layout",
|
||||
["Diagram Design", "Layouts"],
|
||||
None,
|
||||
"{id?, kind: list|blockList|hBulletList|process|chevron|verticalProcess|stepUp|cycle|blockCycle|radial|hierarchy|pyramid|invertedPyramid|matrix|titledMatrix|pictureList|pictureCaption|pictureProcess|pictureHList|timeline|venn|target|textCycle|continuousCycle|horizontalHierarchy|gridMatrix|gear|funnel|segmentedCycle|multidirectionalCycle|orgChart|halfCircleOrgChart|cycleMatrix|segmentedPyramid|pie|nameTitleOrgChart|verticalBoxList|trapezoidList|tableList|accentProcess|continuousBlockProcess|bendingProcess|linearVenn|stackedVenn|nestedTarget}",
|
||||
has_diagram,
|
||||
has_selection,
|
||||
change_layout
|
||||
),
|
||||
cmd!(
|
||||
@@ -253,7 +237,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Diagram Design", "Reset"],
|
||||
None,
|
||||
"{id?} → {id} (the graphic becomes a text box of its outline, bulleted by level)",
|
||||
has_diagram,
|
||||
has_selection,
|
||||
to_text
|
||||
),
|
||||
cmd!(
|
||||
@@ -262,7 +246,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Diagram Design", "Reset"],
|
||||
None,
|
||||
"{id?} (the graphic becomes a plain group of its shapes; the outline is dropped)",
|
||||
has_diagram,
|
||||
has_selection,
|
||||
to_shapes
|
||||
),
|
||||
cmd!(
|
||||
@@ -271,7 +255,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Diagram Design", "Create Graphic"],
|
||||
None,
|
||||
"{id?, index, data?: base64 | path?: string | reset?: bool} (the node's picture placeholder in picture layouts)",
|
||||
has_diagram,
|
||||
has_selection,
|
||||
set_picture
|
||||
),
|
||||
cmd!(
|
||||
@@ -280,7 +264,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Diagram Design", "Diagram Styles"],
|
||||
None,
|
||||
"{id?, style: flat|subtle|intense|outline|polished|inset|cartoon|powder|brick}",
|
||||
has_diagram,
|
||||
has_selection,
|
||||
change_style
|
||||
),
|
||||
cmd!(
|
||||
@@ -289,7 +273,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Diagram Design", "Diagram Styles"],
|
||||
None,
|
||||
"{id?, colors: colorful|range23|range34|range45|range56|accent1|…|accent6|accent1Grad|…|accent6Grad}",
|
||||
has_diagram,
|
||||
has_selection,
|
||||
change_colors
|
||||
),
|
||||
]
|
||||
@@ -310,74 +294,6 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_eligibility_follows_the_selected_diagram_and_its_nodes() -> Result<()> {
|
||||
let edits = [
|
||||
"smartArt.nodes",
|
||||
"smartArt.setNodes",
|
||||
"smartArt.addNode",
|
||||
"smartArt.removeNode",
|
||||
"smartArt.layout",
|
||||
"smartArt.toText",
|
||||
"smartArt.toShapes",
|
||||
"smartArt.picture",
|
||||
"smartArt.style",
|
||||
"smartArt.colors",
|
||||
];
|
||||
let node_edits = ["smartArt.promote", "smartArt.demote"];
|
||||
let enabled = |s: &Session, id: &str| crate::find_command(id).is_some_and(|spec| spec.info(s).enabled);
|
||||
let mut s = Session::with_new();
|
||||
s.execute("slide.new", &json!({"layout": "blank"}))?;
|
||||
assert!(edits.iter().chain(&node_edits).all(|id| !enabled(&s, id)));
|
||||
assert!(enabled(&s, "insert.smartArt"));
|
||||
|
||||
s.execute("insert.textBox", &json!({"text": "Plan\nBuild"}))?;
|
||||
assert!(edits.iter().chain(&node_edits).all(|id| !enabled(&s, id)));
|
||||
assert!(enabled(&s, "smartArt.fromText"));
|
||||
let graphic = s.execute("smartArt.fromText", &json!({"kind": "process"}))?["id"].clone();
|
||||
assert!(edits.iter().chain(&node_edits).all(|id| enabled(&s, id)));
|
||||
|
||||
let child = s
|
||||
.doc()?
|
||||
.selected_shapes()
|
||||
.into_iter()
|
||||
.find_map(|shape| match &shape.kind {
|
||||
ShapeKind::Group { children, .. } => children.first().map(|child| child.id.0),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or_else(|| EngineError::Other("diagram has no child".into()))?;
|
||||
s.execute("selection.select", &json!({"id": child}))?;
|
||||
assert!(edits.iter().chain(&node_edits).all(|id| enabled(&s, id)));
|
||||
assert_eq!(s.execute("smartArt.nodes", &json!({}))?["id"], graphic);
|
||||
|
||||
s.execute("smartArt.setNodes", &json!({"nodes": []}))?;
|
||||
assert!(edits.iter().all(|id| enabled(&s, id)));
|
||||
assert!(node_edits.iter().all(|id| !enabled(&s, id)));
|
||||
assert!(s.execute("smartArt.promote", &json!({"index": 0})).is_err());
|
||||
assert!(s.execute("smartArt.demote", &json!({"index": 0})).is_err());
|
||||
s.execute("selection.select", &json!({"id": graphic, "toggle": true}))?;
|
||||
assert!(edits.iter().chain(&node_edits).all(|id| !enabled(&s, id)));
|
||||
assert_eq!(s.execute("smartArt.nodes", &json!({"id": graphic}))?["id"], graphic);
|
||||
assert!(s.execute("smartArt.promote", &json!({"id": graphic, "index": 0})).is_err());
|
||||
assert!(s.execute("smartArt.demote", &json!({"id": graphic, "index": 0})).is_err());
|
||||
s.execute("smartArt.addNode", &json!({"id": graphic, "index": null, "text": "Ship"}))?;
|
||||
assert!(node_edits.iter().all(|id| enabled(&s, id)));
|
||||
|
||||
let text = s.execute("insert.textBox", &json!({"text": "Notes"}))?["id"].clone();
|
||||
assert!(edits.iter().chain(&node_edits).all(|id| !enabled(&s, id)));
|
||||
assert!(s.execute("smartArt.style", &json!({"id": text, "style": "outline"})).is_err());
|
||||
s.execute("smartArt.style", &json!({"id": graphic, "style": "outline"}))?;
|
||||
assert!(selected(s.doc()?).is_some_and(|(_, diagram)| diagram.style == "outline"));
|
||||
assert!(s.execute("smartArt.promote", &json!({"id": graphic, "index": 100})).is_err());
|
||||
s.execute("selection.select", &json!({"id": graphic, "toggle": true}))?;
|
||||
assert!(edits.iter().chain(&node_edits).all(|id| !enabled(&s, id)));
|
||||
s.execute("smartArt.nodes", &json!({"id": graphic}))?;
|
||||
assert!(enabled(&s, "insert.smartArt"));
|
||||
s.execute("insert.smartArt", &json!({"kind": "cycle", "items": ["A", "B"]}))?;
|
||||
assert!(edits.iter().chain(&node_edits).all(|id| enabled(&s, id)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_edits() {
|
||||
let mut n = mk(&[0, 1, 1, 0]);
|
||||
|
||||
+15
-114
@@ -1,7 +1,7 @@
|
||||
//! Table Design and Table Layout tabs.
|
||||
|
||||
use deckcraft_geom::{Affine, Point, Rect};
|
||||
use deckcraft_model::{Cell, Shape, ShapeKind, Table};
|
||||
use deckcraft_model::{Shape, ShapeKind, Table};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{
|
||||
@@ -24,24 +24,18 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"rowBelow",
|
||||
"table.insertRowBelow"
|
||||
)),
|
||||
cmd!(
|
||||
"table.insertColumnLeft",
|
||||
"Insert Left",
|
||||
["Table Layout", "Rows & Columns"],
|
||||
None,
|
||||
"{col?, keepWidth?: bool (default false, as in PowerPoint: the table grows by the new column and the other widths stay; true: the other columns shrink in proportion so the table keeps its width), id?} the new column takes the width and cell formatting (fill, margins, anchor, text properties) of the column it is inserted beside",
|
||||
has_selection,
|
||||
|s, p| rows_cols(s, p, "colLeft", "table.insertColumnLeft")
|
||||
),
|
||||
cmd!(
|
||||
"table.insertColumnRight",
|
||||
"Insert Right",
|
||||
["Table Layout", "Rows & Columns"],
|
||||
None,
|
||||
"{col?, keepWidth?: bool (default false, as in PowerPoint: the table grows by the new column and the other widths stay; true: the other columns shrink in proportion so the table keeps its width), id?} the new column takes the width and cell formatting (fill, margins, anchor, text properties) of the column it is inserted beside",
|
||||
has_selection,
|
||||
|s, p| rows_cols(s, p, "colRight", "table.insertColumnRight")
|
||||
),
|
||||
cmd!("table.insertColumnLeft", "Insert Left", ["Table Layout", "Rows & Columns"], None, "{col?, id?}", has_selection, |s, p| rows_cols(
|
||||
s,
|
||||
p,
|
||||
"colLeft",
|
||||
"table.insertColumnLeft"
|
||||
)),
|
||||
cmd!("table.insertColumnRight", "Insert Right", ["Table Layout", "Rows & Columns"], None, "{col?, id?}", has_selection, |s, p| rows_cols(
|
||||
s,
|
||||
p,
|
||||
"colRight",
|
||||
"table.insertColumnRight"
|
||||
)),
|
||||
cmd!("table.deleteRow", "Delete Rows", ["Table Layout", "Rows & Columns"], None, "{row?, id?}", has_selection, |s, p| rows_cols(
|
||||
s,
|
||||
p,
|
||||
@@ -328,15 +322,6 @@ fn with_table(s: &mut Session, p: &Value, cmd: &str, f: impl Fn(&mut Table) -> R
|
||||
|
||||
fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result<Value> {
|
||||
let (r, c) = at(s, p, name)?;
|
||||
// Absent: the table grows, as in PowerPoint; present, it must be a bool, so a mistyped value is refused
|
||||
// rather than silently taken as the default.
|
||||
let keep_width = match (op, p.get("keepWidth")) {
|
||||
(_, None) | (_, Some(Value::Null)) => false,
|
||||
(_, Some(Value::Bool(b))) => *b,
|
||||
("colLeft", Some(_)) => return Err(bad("table.insertColumnLeft", "`keepWidth` must be true or false")),
|
||||
("colRight", Some(_)) => return Err(bad("table.insertColumnRight", "`keepWidth` must be true or false")),
|
||||
_ => false,
|
||||
};
|
||||
let op = op.to_string();
|
||||
with_table(s, p, name, move |t| {
|
||||
match op.as_str() {
|
||||
@@ -344,8 +329,8 @@ fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result
|
||||
let ok = match op.as_str() {
|
||||
"rowAbove" => t.insert_row(r),
|
||||
"rowBelow" => t.insert_row(r.saturating_add(1)),
|
||||
"colLeft" => insert_col_like(t, c, c, keep_width),
|
||||
_ => insert_col_like(t, c.saturating_add(1), c, keep_width),
|
||||
"colLeft" => t.insert_col(c),
|
||||
_ => t.insert_col(c.saturating_add(1)),
|
||||
};
|
||||
if !ok {
|
||||
return Err(bad(name, format!("the table is at its {}-cell limit", deckcraft_model::table::MAX_CELLS)));
|
||||
@@ -366,90 +351,6 @@ fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result
|
||||
})
|
||||
}
|
||||
|
||||
/// Insert a column before `at` that looks like column `neighbour` (the one it is inserted beside):
|
||||
/// its width, and in every row the neighbour cell's explicit formatting with no text. With
|
||||
/// `keep_width` the columns then shrink in proportion so the table keeps its total width;
|
||||
/// otherwise (PowerPoint's behaviour) the table grows by the new column and the widths stay.
|
||||
/// Returns false, leaving the table as it was, when the column would take it past the cell limit.
|
||||
fn insert_col_like(t: &mut Table, at: usize, neighbour: usize, keep_width: bool) -> bool {
|
||||
let total = t.width();
|
||||
let neighbour = neighbour.min(t.cols.len().saturating_sub(1));
|
||||
let w = t.cols.get(neighbour).copied();
|
||||
// A neighbour covered by a merge (horizontally or vertically) is formatted as its anchor, which is what shows.
|
||||
let covered = |r: usize, c: usize| t.rows.get(r).and_then(|row| row.cells.get(c)).is_some_and(|x| x.h_merge || x.v_merge);
|
||||
let templates: Vec<Option<Cell>> = (0..t.rows.len())
|
||||
.map(|r0| {
|
||||
let (mut r, mut n) = (r0, neighbour);
|
||||
while covered(r, n) {
|
||||
let cell = &t.rows[r].cells[n];
|
||||
if cell.h_merge && n > 0 {
|
||||
n -= 1;
|
||||
} else if cell.v_merge && r > 0 {
|
||||
r -= 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Only the formatting is kept: the anchor's text is not copied once per covered row.
|
||||
t.rows[r].cells.get(n).map(|src| {
|
||||
let mut tpl = Cell::new("");
|
||||
copy_cell_format(&mut tpl, src);
|
||||
tpl
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if !t.insert_col(at) {
|
||||
return false;
|
||||
}
|
||||
let at = at.min(t.cols.len().saturating_sub(1));
|
||||
if let (Some(w), Some(slot)) = (w, t.cols.get_mut(at)) {
|
||||
*slot = w;
|
||||
}
|
||||
for (row, tpl) in t.rows.iter_mut().zip(templates) {
|
||||
if let (Some(cell), Some(tpl)) = (row.cells.get_mut(at), tpl) {
|
||||
copy_cell_format(cell, &tpl);
|
||||
}
|
||||
}
|
||||
let grown = t.width();
|
||||
if keep_width && total > 1e-9 && grown > 1e-9 {
|
||||
let k = total / grown;
|
||||
for cw in &mut t.cols {
|
||||
*cw *= k;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// `dst` takes `src`'s formatting (fill, borders, margins, anchor, text direction and the text
|
||||
/// properties of its first paragraph, kept on the end mark of an empty paragraph) and keeps its
|
||||
/// own spans and merge cover. Hyperlinks are not copied.
|
||||
fn copy_cell_format(dst: &mut Cell, src: &Cell) {
|
||||
dst.fill.clone_from(&src.fill);
|
||||
dst.borders.clone_from(&src.borders);
|
||||
dst.diag_down.clone_from(&src.diag_down);
|
||||
dst.diag_up.clone_from(&src.diag_up);
|
||||
dst.margins = src.margins;
|
||||
dst.anchor = src.anchor;
|
||||
dst.vertical = src.vertical;
|
||||
dst.anchor_ctr = src.anchor_ctr;
|
||||
dst.horz_overflow = src.horz_overflow;
|
||||
let para = src.text.paragraphs.first().map(|p0| {
|
||||
let mut end_props = p0.runs.first().map_or_else(|| p0.end_props.clone(), |r| r.props.clone());
|
||||
end_props.link = None;
|
||||
end_props.hover = None;
|
||||
let mut def_props = p0.def_props.clone();
|
||||
def_props.link = None;
|
||||
def_props.hover = None;
|
||||
deckcraft_model::text::Paragraph { level: p0.level, props: p0.props.clone(), runs: vec![], def_props, end_props }
|
||||
});
|
||||
let mut list_style = src.text.list_style.clone();
|
||||
for l in list_style.levels.iter_mut().flatten() {
|
||||
l.run.link = None;
|
||||
l.run.hover = None;
|
||||
}
|
||||
dst.text = deckcraft_model::text::TextBody { body: src.text.body.clone(), list_style, paragraphs: vec![para.unwrap_or_default()] };
|
||||
}
|
||||
|
||||
fn merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sel = s.doc()?.selection.cells;
|
||||
let from = cell_param(p, "from", "table.merge")?.or(sel.map(|c| c.1)).ok_or_else(|| bad("table.merge", "missing `from`"))?;
|
||||
|
||||
@@ -26,14 +26,15 @@ use autocorrect::autocorrect_options;
|
||||
pub use autocorrect::{AUTOCORRECT, AutoList, correct_word};
|
||||
pub(crate) use caret::{apply_leading_tabs, delete_dir};
|
||||
use caret::{delete, delete_surrounding, get, insert, move_caret, select, select_all, select_para, select_word, set};
|
||||
use editing::{edit, exit};
|
||||
pub(crate) use editing::{insert_field, insert_text, paste_body};
|
||||
pub use formatting::format_range;
|
||||
use formatting::{fonts_used, replace_font};
|
||||
pub(crate) use formatting::{format_body, format_para, format_run, format_run_levels, link_text};
|
||||
pub use ime::{cell_range_underlines, range_underlines};
|
||||
pub use ime::{IME_SURROUNDING_MAX_BYTES, ImeSurrounding, cell_range_underlines, composition_underlines, ime_surrounding, range_underlines};
|
||||
use ime::{commit, compose};
|
||||
pub(crate) use layout::ctx_for;
|
||||
pub use layout::{caret_line, fit_text_box, layout_for, text_frame, text_pos_at};
|
||||
pub use layout::{caret_color, caret_line, fit_text_box, layout_for, text_frame, text_pos_at};
|
||||
|
||||
/// Catalogue text-editing, selection, autocorrect, font, IME, and surrounding-deletion commands
|
||||
/// with their parameter docs and enabled predicates.
|
||||
@@ -94,8 +95,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
// An input method asks for text around the caret to be removed (macOS press-and-hold,
|
||||
// dictation, Wayland text-input). Internal: the keyboard and control protocol keep the
|
||||
// existing text.delete spelling. `bytes` says the counts are UTF-8 bytes (winit's
|
||||
// `Ime::DeleteSurrounding`), otherwise characters, both in the logical coordinates
|
||||
// the editor publishes: a paragraph mark or soft line break is one `\n` byte, so a
|
||||
// `Ime::DeleteSurrounding`), otherwise characters, both in the logical text
|
||||
// `ime_surrounding` publishes: a paragraph mark or soft line break is one `\n` byte, so a
|
||||
// range may cross paragraphs. The selection and pre-edit are kept; byte ranges round
|
||||
// inward to whole scalars. A deletion while composing stays in the composition's single
|
||||
// undo step.
|
||||
@@ -133,128 +134,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Applies one replacement inside the session's guarded, rollback-capable transaction.
|
||||
/// The handler records per-insert history; live preedits retain their original undo snapshot.
|
||||
pub(crate) fn replace_text_range(
|
||||
s: &mut Session,
|
||||
range: std::ops::Range<usize>,
|
||||
text: &str,
|
||||
kind: crate::TextReplaceKind,
|
||||
) -> Result<crate::TextReplaceResult> {
|
||||
use crate::TextReplaceKind;
|
||||
|
||||
let st = s.doc()?;
|
||||
let selection = st.selection.text.clone().ok_or_else(|| bad("text.replaceRange", NO_TEXT_POINT))?;
|
||||
if !selection.notes && st.shape(selection.shape).is_none_or(|shape| shape.locked) {
|
||||
return Err(bad("text.replaceRange", "the text being edited is unavailable or locked"));
|
||||
}
|
||||
let body = body_of(st, &selection).ok_or_else(|| bad("text.replaceRange", "the text being edited is gone"))?;
|
||||
let invalid = || bad("text.replaceRange", "the range is not in the text");
|
||||
if range.start > range.end {
|
||||
return Err(invalid());
|
||||
}
|
||||
let from = flat_pos(body, range.start).ok_or_else(invalid)?;
|
||||
let to = flat_pos(body, range.end).ok_or_else(invalid)?;
|
||||
let old_text = (kind == TextReplaceKind::Typed).then(|| body.text());
|
||||
let composing = st.composition.is_some();
|
||||
if range.is_empty() && text.is_empty() && !composing {
|
||||
return Ok(crate::TextReplaceResult { range, selection });
|
||||
}
|
||||
s.begin_text_edit_session()?;
|
||||
if !matches!(kind, TextReplaceKind::Composing | TextReplaceKind::Committed | TextReplaceKind::Deleted) {
|
||||
s.settle_composition();
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let (before, before_selection) = (st.doc.clone(), st.selection.clone());
|
||||
let vertex_kind = s.tool.vertex_kind.clone();
|
||||
match kind {
|
||||
TextReplaceKind::Composing | TextReplaceKind::Committed => ime::replace_marked(s, from, to, text, kind == TextReplaceKind::Committed)?,
|
||||
TextReplaceKind::Deleted if composing => ime::delete_range(s, range.clone(), text)?,
|
||||
TextReplaceKind::Typed | TextReplaceKind::Pasted | TextReplaceKind::Deleted => {
|
||||
if let Some(t) = s.doc_mut()?.selection.text.as_mut() {
|
||||
// Setting the replacement endpoints is part of this edit, not a selection command
|
||||
// that could settle composition or seal the session's cancellation boundary.
|
||||
t.anchor = from;
|
||||
t.caret = to;
|
||||
t.line_end = None;
|
||||
}
|
||||
if kind == TextReplaceKind::Typed {
|
||||
insert_text(s, text, None)?;
|
||||
} else if from != to || !text.is_empty() {
|
||||
editing::replace_selection(s, text, None)?;
|
||||
}
|
||||
let st = s.doc_mut()?;
|
||||
if !Arc::ptr_eq(&before, &st.doc) {
|
||||
let command = match kind {
|
||||
TextReplaceKind::Pasted => "edit.paste",
|
||||
TextReplaceKind::Deleted => "text.delete",
|
||||
_ => "text.insert",
|
||||
};
|
||||
let label = super::find_command(command).ok_or_else(|| bad("text.replaceRange", "the edit command is not registered"))?.label;
|
||||
push_undo(st, HistoryEntry { label: label.into(), doc: before, selection: before_selection, vertex_kind });
|
||||
}
|
||||
}
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let selection = st.selection.text.clone().ok_or_else(|| bad("text.replaceRange", NO_TEXT_POINT))?;
|
||||
let body = body_of(st, &selection).ok_or_else(|| bad("text.replaceRange", "the text being edited is gone"))?;
|
||||
let caret = flat_offset(body, selection.caret).ok_or_else(invalid)?;
|
||||
let inserted = if kind == TextReplaceKind::Composing && !text.is_empty() {
|
||||
let c = st.composition.as_ref().ok_or_else(|| bad("text.replaceRange", "the composition was refused"))?;
|
||||
let start = flat_offset(body, c.start).ok_or_else(invalid)?;
|
||||
start..start + c.len
|
||||
} else if kind == TextReplaceKind::Deleted {
|
||||
range.start..range.start
|
||||
} else if text.is_empty() {
|
||||
caret..caret
|
||||
} else if let Some(old_text) = old_text {
|
||||
// AutoCorrect can replace text preceding the requested insertion, such as (c) plus Space.
|
||||
let after = body.text();
|
||||
let unchanged = old_text.chars().zip(after.chars()).take_while(|(a, b)| a == b).count();
|
||||
range.start.min(unchanged).min(caret)..caret
|
||||
} else {
|
||||
range.start.min(caret)..caret
|
||||
};
|
||||
Ok(crate::TextReplaceResult { range: inserted, selection })
|
||||
}
|
||||
|
||||
/// Character offsets count each paragraph separator once, including empty paragraphs.
|
||||
fn flat_pos(body: &TextBody, mut offset: usize) -> Option<Pos> {
|
||||
if body.paragraphs.is_empty() {
|
||||
return (offset == 0).then_some((0, 0));
|
||||
}
|
||||
for (pi, para) in body.paragraphs.iter().enumerate() {
|
||||
let len = para.char_len();
|
||||
if offset <= len {
|
||||
return Some((pi, offset));
|
||||
}
|
||||
offset = offset.checked_sub(len.checked_add(1)?)?;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn flat_offset(body: &TextBody, pos: Pos) -> Option<usize> {
|
||||
if body.paragraphs.is_empty() {
|
||||
return (pos == (0, 0)).then_some(0);
|
||||
}
|
||||
let para = body.paragraphs.get(pos.0)?;
|
||||
if pos.1 > para.char_len() {
|
||||
return None;
|
||||
}
|
||||
body.paragraphs.iter().take(pos.0).try_fold(pos.1, |offset, para| offset.checked_add(para.char_len())?.checked_add(1))
|
||||
}
|
||||
|
||||
fn edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let result = editing::edit(s, p)?;
|
||||
s.begin_text_edit_session()?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn exit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.finish_text_edit_session(false)?;
|
||||
editing::exit(s, p)
|
||||
}
|
||||
|
||||
/// The text body a text selection edits.
|
||||
pub fn body_of<'a>(st: &'a DocState, t: &TextSel) -> Option<&'a TextBody> {
|
||||
if t.notes {
|
||||
|
||||
@@ -99,8 +99,8 @@ pub(super) fn delete_surrounding(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let t = st.selection.text.clone().ok_or_else(|| bad("text.deleteSurrounding", "not editing text"))?;
|
||||
let body = body_of(st, &t).ok_or_else(|| bad("text.deleteSurrounding", "the text being edited is gone"))?;
|
||||
let comp = composition_range(body, st.composition.as_ref());
|
||||
// The ranges use the logical coordinates the editor publishes: one byte for a paragraph
|
||||
// separator and for a soft line break. A range may therefore cross paragraphs.
|
||||
// The ranges are in the same logical coordinates `ime_surrounding` publishes: one byte for a
|
||||
// paragraph separator and for a soft line break. A range may therefore cross paragraphs.
|
||||
let ordered = {
|
||||
let a = model_pos(body, t.anchor).ok_or_else(|| bad("text.deleteSurrounding", "the selection is not in the text"))?;
|
||||
let b = model_pos(body, t.caret).ok_or_else(|| bad("text.deleteSurrounding", "the selection is not in the text"))?;
|
||||
|
||||
@@ -73,6 +73,7 @@ fn typed(s: &Session, body: &TextBody, at: Pos, text: &str) -> String {
|
||||
}
|
||||
|
||||
pub(crate) fn insert_text(s: &mut Session, text: &str, props: Option<RunProps>) -> Result<Value> {
|
||||
let inherited = inherited_aligns_for_edit(s);
|
||||
let text = {
|
||||
let st = s.doc()?;
|
||||
match &st.selection.text {
|
||||
@@ -83,21 +84,11 @@ pub(crate) fn insert_text(s: &mut Session, text: &str, props: Option<RunProps>)
|
||||
None => text.to_string(),
|
||||
}
|
||||
};
|
||||
let pos = replace_selection(s, &text, props)?;
|
||||
autocorrect(s, text.chars().count() == 1)?;
|
||||
// AutoCorrect can move the caret: a replaced word, or a list lead it removed.
|
||||
let pos = s.doc()?.selection.text.as_ref().map_or(pos, |t| t.caret);
|
||||
Ok(json!({"caret": [pos.0, pos.1]}))
|
||||
}
|
||||
|
||||
/// Shares insertion styling and paragraph direction rules across typing, pasting and deletion.
|
||||
pub(super) fn replace_selection(s: &mut Session, text: &str, props: Option<RunProps>) -> Result<Pos> {
|
||||
let inherited = inherited_aligns_for_edit(s);
|
||||
edit_text(s, |body, t| {
|
||||
let pos = edit_text(s, |body, t| {
|
||||
let (a, b) = t.ordered();
|
||||
let at = ed::delete(body, a, b);
|
||||
let props = props.clone().or_else(|| if a != b { Some(ed::props_at(body, at)) } else { unlinked_at_link_end(body, at) });
|
||||
let c = ed::insert(body, at, text, props);
|
||||
let c = ed::insert(body, at, &text, props);
|
||||
t.anchor = c;
|
||||
t.caret = c;
|
||||
let last = body.paragraphs.len().saturating_sub(1);
|
||||
@@ -107,7 +98,11 @@ pub(super) fn replace_selection(s: &mut Session, text: &str, props: Option<RunPr
|
||||
}
|
||||
}
|
||||
c
|
||||
})
|
||||
})?;
|
||||
autocorrect(s, text.chars().count() == 1)?;
|
||||
// AutoCorrect can move the caret: a replaced word, or a list lead it removed.
|
||||
let pos = s.doc()?.selection.text.as_ref().map_or(pos, |t| t.caret);
|
||||
Ok(json!({"caret": [pos.0, pos.1]}))
|
||||
}
|
||||
|
||||
/// Per outline level (0..=8), whether shape `id` on the current slide already resolves an
|
||||
|
||||
@@ -1,7 +1,24 @@
|
||||
use super::caret::cell_on_slide;
|
||||
use super::editing::unlinked_at_link_end;
|
||||
use super::layout::{ctx_for, layout_for};
|
||||
use super::{DocState, Paragraph, Result, Session, TextBody, TextSel, Value, bad, body_of, ed, edit_text, json, str_param, xfrm_of};
|
||||
|
||||
/// Maximum number of UTF-8 bytes in an outgoing IME surrounding-text query.
|
||||
///
|
||||
/// This matches `egui::output::MAX_IME_SURROUNDING_TEXT_BYTES`; keeping the bound here lets the
|
||||
/// engine answer without copying a whole body or document.
|
||||
pub const IME_SURROUNDING_MAX_BYTES: usize = 4000;
|
||||
|
||||
/// Bounded committed text around an IME selection, in logical (not visual) order and with UTF-8
|
||||
/// byte offsets. The current input-method composition (pre-edit) is removed from both the text
|
||||
/// and the offsets.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ImeSurrounding {
|
||||
pub text: String,
|
||||
pub cursor: usize,
|
||||
pub anchor: usize,
|
||||
}
|
||||
|
||||
/// How a soft line break reads in the IME view: a newline, like a paragraph break.
|
||||
///
|
||||
/// The model stores it as `\u{b}` ([`RunKind::Break`]); publishing that control character would
|
||||
@@ -149,6 +166,77 @@ pub(super) fn walk_backward(
|
||||
}
|
||||
}
|
||||
|
||||
/// The committed logical text between two model positions (excluding `end`). `None` when it is
|
||||
/// longer than `cap` bytes: every caller only needs a bounded answer.
|
||||
fn logical_between(body: &TextBody, comp: Option<(usize, usize, usize)>, start: (usize, usize), end: (usize, usize), cap: usize) -> Option<String> {
|
||||
let (a, b) = if start <= end { (start, end) } else { (end, start) };
|
||||
let mut out = String::new();
|
||||
for pi in a.0..=b.0 {
|
||||
let Some(para) = body.paragraphs.get(pi) else { return Some(out) };
|
||||
let from = if pi == a.0 { a.1 } else { 0 };
|
||||
let to = if pi == b.0 { b.1 } else { usize::MAX };
|
||||
for (i, ch) in committed_chars(para, comp_in(comp, pi)) {
|
||||
if i < from || i >= to {
|
||||
continue;
|
||||
}
|
||||
out.push(ch);
|
||||
if out.len() > cap {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if pi < b.0 {
|
||||
out.push('\n');
|
||||
if out.len() > cap {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Committed surrounding text for the text being edited.
|
||||
///
|
||||
/// Returns `None` when the body or selection is invalid, or when the selection alone is wider
|
||||
/// than [`IME_SURROUNDING_MAX_BYTES`]. An empty body is `Some` with empty text, which is distinct
|
||||
/// from an unavailable context. `cursor > anchor` is preserved for a reversed selection.
|
||||
///
|
||||
/// Only a bounded window is measured and copied: the query walks at most the budget out from the
|
||||
/// selection on each side and does not copy the rest of the body. Finding the selection's
|
||||
/// character offsets inside one paragraph still scans that paragraph's prefix, so the time is not
|
||||
/// bounded independently of the paragraph length.
|
||||
pub fn ime_surrounding(st: &DocState, t: &TextSel) -> Option<ImeSurrounding> {
|
||||
let body = body_of(st, t)?;
|
||||
let comp = composition_range(body, st.composition.as_ref());
|
||||
let caret = model_pos(body, t.caret)?;
|
||||
let anchor = model_pos(body, t.anchor)?;
|
||||
let (start, end) = if caret <= anchor { (caret, anchor) } else { (anchor, caret) };
|
||||
let selected = logical_between(body, comp, start, end, IME_SURROUNDING_MAX_BYTES)?;
|
||||
let selection_len = selected.len();
|
||||
let budget = IME_SURROUNDING_MAX_BYTES.saturating_sub(selection_len);
|
||||
let (_, _, before_available) = walk_backward(body, comp, start, budget, true);
|
||||
let (_, _, after_available) = walk_forward(body, comp, end, budget, true);
|
||||
let mut before = (budget / 2).min(before_available);
|
||||
let mut after = (budget - before).min(after_available);
|
||||
before = (budget - after).min(before_available);
|
||||
after = (budget - before).min(after_available);
|
||||
let (window_start, _, _) = walk_backward(body, comp, start, before, true);
|
||||
let (window_end, _, _) = walk_forward(body, comp, end, after, true);
|
||||
let before_text = logical_between(body, comp, window_start, start, budget)?;
|
||||
let after_text = logical_between(body, comp, end, window_end, budget)?;
|
||||
let before_len = before_text.len();
|
||||
let mut text = before_text;
|
||||
text.push_str(&selected);
|
||||
text.push_str(&after_text);
|
||||
// The budget arithmetic above already bounds this; refuse rather than publish more.
|
||||
if text.len() > IME_SURROUNDING_MAX_BYTES {
|
||||
return None;
|
||||
}
|
||||
// The caret and anchor are the selection's own endpoints, so their offsets inside the
|
||||
// window are the window's start plus either end of the selected text.
|
||||
let (cursor, anchor) = if caret >= anchor { (before_len + selection_len, before_len) } else { (before_len, before_len + selection_len) };
|
||||
Some(ImeSurrounding { text, cursor, anchor })
|
||||
}
|
||||
|
||||
/// Text an input method sends: no paragraph or line breaks (Enter is a key of its own).
|
||||
fn ime_text(s: &str) -> String {
|
||||
s.chars().filter(|c| !c.is_control()).collect()
|
||||
@@ -185,7 +273,6 @@ pub(super) fn compose(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
match current {
|
||||
None if text.is_empty() => Ok(json!({"composing": false})),
|
||||
None => {
|
||||
s.begin_text_edit_session()?;
|
||||
let st = s.doc()?;
|
||||
let (before, before_selection) = (st.doc.clone(), st.selection.clone());
|
||||
let (start, props) = edit_text(s, |body, t| {
|
||||
@@ -289,52 +376,43 @@ pub fn cell_range_underlines(
|
||||
out
|
||||
}
|
||||
|
||||
/// Replaces the marked text without a selection command that would settle it first.
|
||||
pub(super) fn replace_marked(s: &mut Session, from: super::Pos, to: super::Pos, text: &str, committed: bool) -> Result<()> {
|
||||
let st = s.doc()?;
|
||||
let original_selection = st.selection.clone();
|
||||
let had_composition = st.composition.is_some();
|
||||
if let Some(c) = &st.composition {
|
||||
if from != c.start || to != (c.start.0, c.start.1.saturating_add(c.len)) {
|
||||
return Err(bad("text.replaceRange", "the range does not match the composition"));
|
||||
}
|
||||
} else if let Some(t) = s.doc_mut()?.selection.text.as_mut() {
|
||||
t.anchor = from;
|
||||
t.caret = to;
|
||||
t.line_end = None;
|
||||
/// Underlines under an input method's composition (#101), in slide coordinates: `(from, to,
|
||||
/// thick)` per line, thick under the part being converted. Empty without a composition, or for
|
||||
/// notes (an egui text field draws its own composition).
|
||||
pub fn composition_underlines(st: &DocState) -> Vec<(deckcraft_geom::Point, deckcraft_geom::Point, bool)> {
|
||||
let (Some(c), Some(t)) = (&st.composition, &st.selection.text) else { return vec![] };
|
||||
if t.notes {
|
||||
return vec![];
|
||||
}
|
||||
let params = json!({"text": text});
|
||||
if committed && had_composition {
|
||||
commit(s, ¶ms)?;
|
||||
} else {
|
||||
compose(s, ¶ms)?;
|
||||
if !had_composition && let Some(c) = s.doc_mut()?.composition.as_mut() {
|
||||
c.before_selection = original_selection;
|
||||
}
|
||||
if committed {
|
||||
s.end_composition();
|
||||
}
|
||||
if let Some((row, col)) = t.cell {
|
||||
let Some(placed) = cell_on_slide(st, t.shape, row, col) else { return vec![] };
|
||||
return underline_segments(&placed.layout, placed.to_slide, c);
|
||||
}
|
||||
Ok(())
|
||||
let Some(sh) = st.shape(t.shape) else { return vec![] };
|
||||
let Some(l) = layout_for(st, t) else { return vec![] };
|
||||
let x = xfrm_of(&st.doc, &st.selection, sh);
|
||||
let tr = deckcraft_render::shape_geometry(sh, x.w, x.h).text_rect;
|
||||
let m = deckcraft_render::text_transform(x.affine(), tr, l.rotation);
|
||||
underline_segments(&l, m, c)
|
||||
}
|
||||
|
||||
/// Removes an already normalized character range beside the live composition.
|
||||
pub(super) fn delete_range(s: &mut Session, range: std::ops::Range<usize>, text: &str) -> Result<()> {
|
||||
let st = s.doc()?;
|
||||
let t = st.selection.text.as_ref().ok_or_else(|| bad("text.replaceRange", "not editing text"))?;
|
||||
let body = body_of(st, t).ok_or_else(|| bad("text.replaceRange", "the text being edited is gone"))?;
|
||||
let c = st.composition.as_ref().ok_or_else(|| bad("text.replaceRange", "not composing"))?;
|
||||
let start = super::flat_offset(body, c.start).ok_or_else(|| bad("text.replaceRange", "the composition is not in the text"))?;
|
||||
let end = start.saturating_add(c.len);
|
||||
let (before, after) = if text.is_empty() && range.end == start {
|
||||
(range.len(), 0)
|
||||
} else if text.is_empty() && range.start == end {
|
||||
(0, range.len())
|
||||
} else {
|
||||
return Err(bad("text.replaceRange", "the deletion must be beside the composition"));
|
||||
fn underline_segments(
|
||||
layout: &deckcraft_text::TextLayout,
|
||||
to_slide: deckcraft_geom::Affine,
|
||||
c: &crate::Composition,
|
||||
) -> Vec<(deckcraft_geom::Point, deckcraft_geom::Point, bool)> {
|
||||
let pos = |ch: usize| deckcraft_text::Pos { para: c.start.0, ch: c.start.1 + ch };
|
||||
let mut out = vec![];
|
||||
let mut add = |a: usize, b: usize, thick: bool| {
|
||||
for (x0, x1, y) in layout.composition_underlines(pos(a), pos(b)) {
|
||||
out.push((to_slide * deckcraft_geom::Point::new(x0, y), to_slide * deckcraft_geom::Point::new(x1, y), thick));
|
||||
}
|
||||
};
|
||||
super::caret::delete_surrounding(s, &json!({"before": before, "after": after}))?;
|
||||
Ok(())
|
||||
add(0, c.len, false);
|
||||
if let Some((a, b)) = c.active {
|
||||
add(a, b.min(c.len), true);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -406,14 +484,65 @@ mod ime_surrounding_tests {
|
||||
assert_eq!(text(&s, id), "aéb", "four bytes contain the whole emoji");
|
||||
}
|
||||
|
||||
/// A paragraph mark occupies one logical byte; deleting it merges its paragraphs.
|
||||
/// The committed query is logical text with UTF-8 byte offsets; it keeps a reversed
|
||||
/// selection, removes the model-stored pre-edit, and treats an empty body as available.
|
||||
#[test]
|
||||
fn surrounding_text_is_committed_logical_and_bounded() {
|
||||
use super::{IME_SURROUNDING_MAX_BYTES, ime_surrounding};
|
||||
|
||||
let mut s = Session::with_new();
|
||||
let id = edit(&mut s);
|
||||
let st = s.doc().unwrap();
|
||||
let t = st.selection.text.clone().unwrap();
|
||||
let q = ime_surrounding(st, &t).unwrap();
|
||||
assert_eq!((q.text.as_str(), q.cursor, q.anchor), ("aé😀b", 8, 8));
|
||||
|
||||
s.execute("text.select", &json!({"anchor": [0, 3], "caret": [0, 1]})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let t = st.selection.text.clone().unwrap();
|
||||
let q = ime_surrounding(st, &t).unwrap();
|
||||
assert_eq!((q.cursor, q.anchor), (1, 7), "reversed selection keeps caret before anchor");
|
||||
assert_eq!(q.text, "aé😀b");
|
||||
|
||||
s.execute("text.set", &json!({"id": id, "text": "ab"})).unwrap();
|
||||
s.execute("text.move", &json!({"to": "end"})).unwrap();
|
||||
s.compose_text("日本", None).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let t = st.selection.text.clone().unwrap();
|
||||
let q = ime_surrounding(st, &t).unwrap();
|
||||
assert_eq!((q.text.as_str(), q.cursor, q.anchor), ("ab", 2, 2), "pre-edit is not committed text");
|
||||
|
||||
s.execute("text.set", &json!({"id": id, "text": ""})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let t = st.selection.text.clone().unwrap();
|
||||
let q = ime_surrounding(st, &t).unwrap();
|
||||
assert_eq!((q.text.as_str(), q.cursor, q.anchor), ("", 0, 0), "empty body is available");
|
||||
|
||||
let long = "a".repeat(IME_SURROUNDING_MAX_BYTES + 1500);
|
||||
s.execute("text.set", &json!({"id": id, "text": long})).unwrap();
|
||||
s.execute("text.move", &json!({"to": "end"})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let t = st.selection.text.clone().unwrap();
|
||||
let q = ime_surrounding(st, &t).unwrap();
|
||||
assert!(q.text.len() <= IME_SURROUNDING_MAX_BYTES, "{}", q.text.len());
|
||||
assert_eq!(q.cursor, q.text.len(), "caret stays at the end of the bounded window");
|
||||
}
|
||||
|
||||
/// Paragraph marks are part of the logical text the platform sees (`\n`), so a deletion may
|
||||
/// remove one and merge the paragraphs, exactly as the published offsets say.
|
||||
#[test]
|
||||
fn paragraph_marks_are_deletable_logical_text() {
|
||||
use super::ime_surrounding;
|
||||
|
||||
let mut s = Session::with_new();
|
||||
let id = edit(&mut s);
|
||||
s.execute("text.set", &json!({"id": id, "text": "ab\ncd"})).unwrap();
|
||||
// The caret at the start of the second paragraph: after "ab" and its paragraph mark.
|
||||
s.execute("text.select", &json!({"anchor": [1, 0], "caret": [1, 0]})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let q = ime_surrounding(st, &st.selection.text.clone().unwrap()).unwrap();
|
||||
assert_eq!((q.text.as_str(), q.cursor, q.anchor), ("ab\ncd", 3, 3));
|
||||
|
||||
// One byte before the caret is that paragraph mark.
|
||||
s.delete_surrounding(1, 0, true).unwrap();
|
||||
assert_eq!(text(&s, id), "abcd", "the mark goes and the paragraphs merge");
|
||||
@@ -434,9 +563,12 @@ mod ime_surrounding_tests {
|
||||
assert_eq!(text(&s, id), "abcd");
|
||||
}
|
||||
|
||||
/// A soft line break occupies one logical byte even inside a single paragraph.
|
||||
/// A soft line break (Shift+Enter) is published as a newline, like a paragraph break: the
|
||||
/// platform must never see the model's `\u{b}`, which its own text filter would reject.
|
||||
#[test]
|
||||
fn soft_line_breaks_read_as_newlines() {
|
||||
use super::ime_surrounding;
|
||||
|
||||
let mut s = Session::with_new();
|
||||
let id = edit(&mut s);
|
||||
s.execute("text.autocorrect", &json!({"on": false})).unwrap(); // isolate logical line-break coordinates
|
||||
@@ -445,6 +577,10 @@ mod ime_surrounding_tests {
|
||||
s.execute("text.select", &json!({"anchor": [0, 1], "caret": [0, 1]})).unwrap();
|
||||
s.execute("text.insert", &json!({"text": "\u{b}"})).unwrap();
|
||||
assert_eq!(text(&s, id), "a\u{b}b", "a line break inside one paragraph");
|
||||
let st = s.doc().unwrap();
|
||||
let q = ime_surrounding(st, &st.selection.text.clone().unwrap()).unwrap();
|
||||
assert_eq!((q.text.as_str(), q.cursor, q.anchor), ("a\nb", 2, 2));
|
||||
|
||||
// The break is one logical byte, so removing it removes one character.
|
||||
s.delete_surrounding(1, 0, true).unwrap();
|
||||
assert_eq!(text(&s, id), "ab");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::caret::cell_on_slide;
|
||||
use super::{
|
||||
Affine, Arc, AutoFit, Ctx, DocState, Point, Pos, Presentation, Rect, Result, Selection, Session, Shape, ShapeId, Target, TextBody, TextSel,
|
||||
Value, resolve, xfrm_of,
|
||||
Affine, Arc, AutoFit, Ctx, DocState, Paragraph, Point, Pos, Presentation, Rect, Result, Selection, Session, Shape, ShapeId, Target, TextBody,
|
||||
TextSel, Value, ed, resolve, xfrm_of,
|
||||
};
|
||||
|
||||
/// Refit a shape after its text changed: remember the shrink-on-overflow scale the layout
|
||||
@@ -179,6 +179,22 @@ pub fn caret_line(st: &DocState, t: &TextSel) -> Option<(deckcraft_geom::Point,
|
||||
Some((m * deckcraft_geom::Point::new(cx, top), m * deckcraft_geom::Point::new(cx, bot)))
|
||||
}
|
||||
|
||||
/// The colour of text typed at the caret. The canvas draws the caret in it, so the caret shows
|
||||
/// wherever the text does: light on a dark slide, dark on a light one. `None` when that text
|
||||
/// has no fill to take a colour from.
|
||||
pub fn caret_color(st: &DocState, t: &TextSel) -> Option<deckcraft_color::Rgba> {
|
||||
if t.notes || t.cell.is_some() {
|
||||
return None;
|
||||
}
|
||||
let sh = st.shape(t.shape)?;
|
||||
let body = sh.text.as_ref()?;
|
||||
let ctx = ctx_for(&st.doc, &st.selection)?;
|
||||
let blank = Paragraph::default();
|
||||
let para = body.paragraphs.get(t.caret.0).unwrap_or(&blank);
|
||||
let props = resolve::run(&ctx, sh, para, &ed::props_at(body, t.caret));
|
||||
Some(resolve::text_color(&ctx, &props)).filter(|c| c.a > 0)
|
||||
}
|
||||
|
||||
pub(super) fn pos_param(p: &Value, key: &str) -> Option<Pos> {
|
||||
let a = p.get(key)?.as_array()?;
|
||||
Some((a.first()?.as_u64()? as usize, a.get(1)?.as_u64()? as usize))
|
||||
|
||||
@@ -100,14 +100,10 @@ pub fn endpoints(x: &Xfrm) -> (Point, Point) {
|
||||
/// Move the ends of connectors glued to shapes on the edited slide to the current site positions.
|
||||
/// Connections to shapes that no longer exist are dropped.
|
||||
pub fn reroute(doc: &mut Presentation, sel: &Selection) {
|
||||
// Read first: taking the list mutably would unshare the edited slide even when no connector is glued.
|
||||
if !crate::shapes_of(doc, sel)
|
||||
.iter()
|
||||
.any(|s| matches!(s.kind, ShapeKind::Connector { start: Some(_), .. } | ShapeKind::Connector { end: Some(_), .. }))
|
||||
{
|
||||
let Some(list) = crate::shapes_mut(doc, sel) else { return };
|
||||
if !list.iter().any(|s| matches!(s.kind, ShapeKind::Connector { start: Some(_), .. } | ShapeKind::Connector { end: Some(_), .. })) {
|
||||
return;
|
||||
}
|
||||
let Some(list) = crate::shapes_mut(doc, sel) else { return };
|
||||
let snapshot: Vec<Shape> = list.clone();
|
||||
let view = doc.clone();
|
||||
let site = |id: ShapeId, idx: u32| -> Option<Point> {
|
||||
|
||||
@@ -286,66 +286,6 @@ mod tests {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_backed_reads_preserve_roots_regular_files_and_size_validation() {
|
||||
use std::cell::Cell;
|
||||
|
||||
let (base, roots) = folders("host-read");
|
||||
let inside = s(base.join("in/host.deckcraft"));
|
||||
let outside = s(base.join("outside/host.deckcraft"));
|
||||
let bytes = b"bytes supplied by the host".to_vec();
|
||||
confine(Some(&roots), || {
|
||||
let accepted = crate::io::read_file_with(&inside, |_| Ok((true, bytes.len() as u64)), |_| Ok(bytes.clone())).unwrap();
|
||||
assert_eq!(accepted, bytes);
|
||||
|
||||
let metadata_called = Cell::new(false);
|
||||
let read_called = Cell::new(false);
|
||||
let denied = crate::io::read_file_with(
|
||||
&outside,
|
||||
|_| {
|
||||
metadata_called.set(true);
|
||||
Ok((true, bytes.len() as u64))
|
||||
},
|
||||
|_| {
|
||||
read_called.set(true);
|
||||
Ok(bytes.clone())
|
||||
},
|
||||
);
|
||||
assert!(denied.unwrap_err().contains(&outside));
|
||||
assert!(!metadata_called.get(), "authority is checked before asking the host for metadata");
|
||||
assert!(!read_called.get(), "authority is checked before asking the host for bytes");
|
||||
|
||||
for metadata in [(false, bytes.len() as u64), (true, (2_u64 << 30) + 1)] {
|
||||
let read_called = Cell::new(false);
|
||||
let rejected = crate::io::read_file_with(
|
||||
&inside,
|
||||
|_| Ok(metadata),
|
||||
|_| {
|
||||
read_called.set(true);
|
||||
Ok(bytes.clone())
|
||||
},
|
||||
);
|
||||
assert!(rejected.unwrap_err().contains(&inside));
|
||||
assert!(!read_called.get(), "file kind and size are checked before reading");
|
||||
}
|
||||
|
||||
let metadata_error = crate::io::read_file_with(&inside, |_| Err("metadata unavailable".into()), |_| Ok(bytes.clone()));
|
||||
assert!(metadata_error.unwrap_err().contains(&inside));
|
||||
let read_error = crate::io::read_file_with(&inside, |_| Ok((true, bytes.len() as u64)), |_| Err("read unavailable".into()));
|
||||
assert!(read_error.unwrap_err().contains(&inside));
|
||||
|
||||
let captured = current();
|
||||
let worker_path = outside.clone();
|
||||
let rejected = std::thread::spawn(move || {
|
||||
confine(captured.as_ref(), || crate::io::read_file_with(&worker_path, |_| Ok((true, 0)), |_| Ok(Vec::new())))
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
assert!(rejected.unwrap_err().contains(&outside), "a queued read retains the submitting thread's authority");
|
||||
});
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_inside_the_roots_pass_and_others_dont() {
|
||||
let (base, roots) = folders("inside");
|
||||
|
||||
+10
-28
@@ -7,11 +7,16 @@
|
||||
/// The bytes of the file at `path`, inside the automation read root when there is one.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn read_file(path: &str) -> Result<Vec<u8>, String> {
|
||||
read_file_with(
|
||||
path,
|
||||
|path| std::fs::metadata(path).map(|metadata| (metadata.is_file(), metadata.len())).map_err(|error| error.to_string()),
|
||||
|path| std::fs::read(path).map_err(|error| error.to_string()),
|
||||
)
|
||||
crate::file_access::check_read(path)?;
|
||||
let meta = std::fs::metadata(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
if !meta.is_file() {
|
||||
return Err(format!("{path}: not a regular file"));
|
||||
}
|
||||
const MAX_FILE_SIZE: u64 = 2 << 30; // 2 GiB
|
||||
if meta.len() > MAX_FILE_SIZE {
|
||||
return Err(format!("{path}: file size {} exceeds 2 GiB limit", meta.len()));
|
||||
}
|
||||
std::fs::read(path).map_err(|e| format!("{path}: {e}"))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -82,29 +87,6 @@ pub fn file_len(_path: &str) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Checks read access and regular-file metadata before reading through the callbacks.
|
||||
/// Rejects metadata or returned bytes over 2 GiB, retaining the path in errors.
|
||||
pub fn read_file_with<M, R>(path: &str, metadata: M, read: R) -> Result<Vec<u8>, String>
|
||||
where
|
||||
M: FnOnce(&str) -> Result<(bool, u64), String>,
|
||||
R: FnOnce(&str) -> Result<Vec<u8>, String>,
|
||||
{
|
||||
crate::file_access::check_read(path)?;
|
||||
let (regular, len) = metadata(path).map_err(|error| format!("{path}: {error}"))?;
|
||||
if !regular {
|
||||
return Err(format!("{path}: not a regular file"));
|
||||
}
|
||||
check_read_size(path, len)?;
|
||||
let bytes = read(path).map_err(|error| format!("{path}: {error}"))?;
|
||||
check_read_size(path, bytes.len() as u64)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn check_read_size(path: &str, len: u64) -> Result<(), String> {
|
||||
const MAX_FILE_SIZE: u64 = 2 << 30;
|
||||
if len > MAX_FILE_SIZE { Err(format!("{path}: file size {len} exceeds 2 GiB limit")) } else { Ok(()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
+12
-20
@@ -74,11 +74,18 @@ impl Session {
|
||||
let r = match k {
|
||||
"enter" | "return" => Some(self.execute("text.insert", &json!({"text": if mods.shift { "\u{b}" } else { "\n" }}))),
|
||||
"escape" | "esc" => Some(self.execute("text.exit", &json!({}))),
|
||||
"tab" => match self.text_tab(mods.shift) {
|
||||
Ok(true) => Some(Ok(Value::Null)),
|
||||
Ok(false) => Some(self.execute("text.insert", &json!({"text": "\t"}))),
|
||||
Err(error) => Some(Err(error)),
|
||||
},
|
||||
"tab" => {
|
||||
// Tab at the start of a paragraph changes the list level; elsewhere it types a tab.
|
||||
let at_start = self.active().and_then(|d| d.selection.text.as_ref()).is_some_and(|t| t.ordered().0.1 == 0 || t.is_range());
|
||||
let in_cell = self.active().and_then(|d| d.selection.text.as_ref()).is_some_and(|t| t.cell.is_some());
|
||||
if in_cell {
|
||||
Some(self.next_cell(mods.shift))
|
||||
} else if at_start {
|
||||
Some(self.execute(if mods.shift { "format.outdent" } else { "format.indent" }, &json!({})))
|
||||
} else {
|
||||
Some(self.execute("text.insert", &json!({"text": "\t"})))
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(r) = r {
|
||||
@@ -315,21 +322,6 @@ impl Session {
|
||||
})
|
||||
}
|
||||
|
||||
/// Tab (`back`: Shift+Tab) in edited text where it is not a tab character: in a table cell it goes to the next or
|
||||
/// previous cell, at the start of a paragraph or over a range it changes the list level. `false` elsewhere, where
|
||||
/// Tab types a tab.
|
||||
pub fn text_tab(&mut self, back: bool) -> Result<bool> {
|
||||
let Some(t) = self.active().and_then(|d| d.selection.text.clone()) else { return Ok(false) };
|
||||
if t.cell.is_some() {
|
||||
self.next_cell(back)?;
|
||||
} else if t.ordered().0.1 == 0 || t.is_range() {
|
||||
self.execute(if back { "format.outdent" } else { "format.indent" }, &json!({}))?;
|
||||
} else {
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn next_cell(&mut self, back: bool) -> Result<Value> {
|
||||
let st = self.doc()?;
|
||||
let Some(t) = st.selection.text.clone() else { return Ok(Value::Null) };
|
||||
|
||||
+10
-232
@@ -237,9 +237,6 @@ pub struct DocState {
|
||||
/// The list AutoFormat just started from a typed `* ` or `1. `, so Backspace right after
|
||||
/// can put the typed text back.
|
||||
pub auto_list: Option<cmd::text::AutoList>,
|
||||
/// The slide whose editor's consecutive notes changes share one undo step.
|
||||
pub notes_run: Option<SlideId>,
|
||||
notes_before: Option<Arc<Presentation>>,
|
||||
}
|
||||
|
||||
static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
@@ -269,8 +266,6 @@ impl DocState {
|
||||
compare: None,
|
||||
last_duplicate: None,
|
||||
auto_list: None,
|
||||
notes_run: None,
|
||||
notes_before: None,
|
||||
}
|
||||
}
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
@@ -288,7 +283,14 @@ impl DocState {
|
||||
}
|
||||
/// Shapes of the edited tree (current slide, or the master/layout in Slide Master view).
|
||||
pub fn shapes(&self) -> &[Shape] {
|
||||
shapes_of(&self.doc, &self.selection)
|
||||
match self.selection.target {
|
||||
Target::Slides => self.current_slide().map(|s| s.shapes.as_slice()).unwrap_or(&[]),
|
||||
Target::Master { master } => self.doc.masters.get(master).map(|m| m.shapes.as_slice()).unwrap_or(&[]),
|
||||
Target::Handout | Target::NotesMaster => page_master(&self.doc, self.selection.target).map(|m| m.shapes.as_slice()).unwrap_or(&[]),
|
||||
Target::Layout { master, layout } => {
|
||||
self.doc.masters.get(master).and_then(|m| m.layouts.get(layout)).map(|l| l.shapes.as_slice()).unwrap_or(&[])
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn shape(&self, id: ShapeId) -> Option<&Shape> {
|
||||
deckcraft_model::find_shape(self.shapes(), id)
|
||||
@@ -314,16 +316,6 @@ pub fn master_page(doc: &Presentation, t: Target) -> Option<Presentation> {
|
||||
Some(p)
|
||||
}
|
||||
|
||||
/// The edited shape tree of a presentation, read without unsharing its slide or master.
|
||||
pub fn shapes_of<'a>(doc: &'a Presentation, sel: &Selection) -> &'a [Shape] {
|
||||
match sel.target {
|
||||
Target::Slides => doc.slides.get(sel.slide).map(|s| s.shapes.as_slice()).unwrap_or(&[]),
|
||||
Target::Master { master } => doc.masters.get(master).map(|m| m.shapes.as_slice()).unwrap_or(&[]),
|
||||
Target::Handout | Target::NotesMaster => page_master(doc, sel.target).map(|m| m.shapes.as_slice()).unwrap_or(&[]),
|
||||
Target::Layout { master, layout } => doc.masters.get(master).and_then(|m| m.layouts.get(layout)).map(|l| l.shapes.as_slice()).unwrap_or(&[]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Mutable access to the edited shape tree of a presentation.
|
||||
pub fn shapes_mut<'a>(doc: &'a mut Presentation, sel: &Selection) -> Option<&'a mut Vec<Shape>> {
|
||||
match sel.target {
|
||||
@@ -337,7 +329,7 @@ pub fn shapes_mut<'a>(doc: &'a mut Presentation, sel: &Selection) -> Option<&'a
|
||||
}
|
||||
|
||||
/// Engine preferences (the UI keeps its own).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Prefs {
|
||||
pub snap_to_grid: bool,
|
||||
@@ -490,16 +482,6 @@ pub struct Clipboard {
|
||||
pub pastes: u32,
|
||||
}
|
||||
|
||||
type TextEditTarget = (u64, usize, Target, ShapeId, Option<(usize, usize)>, bool);
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TextEditSession {
|
||||
target: TextEditTarget,
|
||||
before: Arc<DocState>,
|
||||
latest: Arc<Presentation>,
|
||||
journal_start: usize,
|
||||
}
|
||||
|
||||
pub struct Session {
|
||||
docs: Vec<DocState>,
|
||||
active: Option<usize>,
|
||||
@@ -535,8 +517,6 @@ pub struct Session {
|
||||
next_loaded: u64,
|
||||
/// Compositions the application settled itself (see [`Session::composition_settles`]).
|
||||
composition_settles: u64,
|
||||
active_generation: u64,
|
||||
text_edit_session: Option<TextEditSession>,
|
||||
}
|
||||
|
||||
impl Default for Session {
|
||||
@@ -571,8 +551,6 @@ impl Session {
|
||||
loaded: vec![],
|
||||
next_loaded: 0,
|
||||
composition_settles: 0,
|
||||
active_generation: 0,
|
||||
text_edit_session: None,
|
||||
}
|
||||
}
|
||||
/// Hand over a presentation read on another thread ([`cmd::file::read_presentation_file`]);
|
||||
@@ -646,12 +624,6 @@ impl Session {
|
||||
fn forget_vertex_kind_unless(&mut self, was: Option<u64>) {
|
||||
if self.active().map(|d| d.uid) != was {
|
||||
self.tool.vertex_kind = None;
|
||||
self.active_generation = self.active_generation.wrapping_add(1);
|
||||
self.text_edit_session = None;
|
||||
for st in &mut self.docs {
|
||||
st.notes_run = None;
|
||||
st.notes_before = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn next_untitled(&mut self) -> String {
|
||||
@@ -669,32 +641,6 @@ impl Session {
|
||||
/// failed outer command, and committing the resulting undo entry or journal record.
|
||||
fn execute_unguarded(&mut self, id: &str, params: &Value) -> Result<Value> {
|
||||
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
|
||||
if self.depth == 0 {
|
||||
let text_input = matches!(
|
||||
id,
|
||||
"text.edit"
|
||||
| "text.exit"
|
||||
| "text.insert"
|
||||
| "text.delete"
|
||||
| "text.compose"
|
||||
| "text.commit"
|
||||
| "text.deleteSurrounding"
|
||||
| "text.move"
|
||||
| "text.select"
|
||||
| "text.selectAll"
|
||||
| "text.selectWord"
|
||||
| "text.selectParagraph"
|
||||
);
|
||||
if !self.text_boundary_matches() || (!text_input && (spec.undoable || spec.journal)) {
|
||||
self.text_edit_session = None;
|
||||
}
|
||||
if ((spec.undoable && id != "slide.notes") || matches!(id, "edit.undo" | "edit.redo"))
|
||||
&& let Some(st) = self.active_mut()
|
||||
{
|
||||
st.notes_run = None;
|
||||
st.notes_before = None;
|
||||
}
|
||||
}
|
||||
// Any other edit (or a click, a key, undo) settles an input method's composition first.
|
||||
if self.depth == 0 && (spec.journal || spec.undoable) && !matches!(id, "text.compose" | "text.commit") {
|
||||
self.settle_composition();
|
||||
@@ -743,32 +689,14 @@ impl Session {
|
||||
&& spec.undoable
|
||||
&& outer
|
||||
{
|
||||
let joins_notes = id == "slide.notes"
|
||||
&& st.notes_run.is_some()
|
||||
&& st.notes_before.as_ref().is_some_and(|first| st.history.undo.last().is_some_and(|e| Arc::ptr_eq(first, &e.doc)));
|
||||
if joins_notes {
|
||||
st.history.redo.clear();
|
||||
if let Some(first) = &st.notes_before {
|
||||
st.history.costs.insert(Arc::as_ptr(first) as usize, undo_cost(first, &st.doc));
|
||||
}
|
||||
} else {
|
||||
let notes_before = (id == "slide.notes" && st.notes_run.is_some()).then(|| old.clone());
|
||||
push_undo(st, HistoryEntry { label: spec.label.to_string(), doc: old, selection: sel, vertex_kind });
|
||||
st.notes_before = notes_before;
|
||||
}
|
||||
push_undo(st, HistoryEntry { label: spec.label.to_string(), doc: old, selection: sel, vertex_kind });
|
||||
}
|
||||
if spec.journal && outer {
|
||||
self.journal.push((id.to_string(), params.clone()));
|
||||
if self.journal.len() > 10_000 {
|
||||
self.journal.drain(..1000);
|
||||
if let Some(boundary) = &mut self.text_edit_session {
|
||||
boundary.journal_start = boundary.journal_start.saturating_sub(1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
if outer {
|
||||
self.advance_text_boundary();
|
||||
}
|
||||
Ok(if outer { self.with_editing(id, r) } else { r })
|
||||
}
|
||||
|
||||
@@ -856,21 +784,13 @@ impl Session {
|
||||
}
|
||||
let owner = |sel: &Selection| sel.text.as_ref().map(|t| (sel.slide, sel.target, t.shape, t.cell, t.notes));
|
||||
let before = owner(&st.selection);
|
||||
let slide_before = st.selection.slide;
|
||||
f(&doc, &mut st.selection);
|
||||
clamp_selection(st);
|
||||
if st.selection.slide != slide_before {
|
||||
st.notes_run = None;
|
||||
st.notes_before = None;
|
||||
}
|
||||
st.revision += 1;
|
||||
// A composition belongs to the text body it began in: leaving that body settles it.
|
||||
if st.composition.is_some() && owner(&st.selection) != before {
|
||||
self.settle_composition();
|
||||
}
|
||||
if self.text_target() != self.text_edit_session.as_ref().map(|b| b.target) {
|
||||
self.text_edit_session = None;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -995,145 +915,3 @@ mod soak_tests;
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_keys;
|
||||
|
||||
/// The kind of atomic replacement in the current edited text body.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TextReplaceKind {
|
||||
/// Typed input, including typed AutoCorrect.
|
||||
Typed,
|
||||
/// Live composition input.
|
||||
Composing,
|
||||
/// Committed composition input.
|
||||
Committed,
|
||||
/// Pasted text.
|
||||
Pasted,
|
||||
/// Deleted surrounding text, preserving live composition.
|
||||
Deleted,
|
||||
}
|
||||
|
||||
/// The actual flattened inserted range and authoritative selection after replacement.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TextReplaceResult {
|
||||
/// The resulting inserted or marked character range.
|
||||
pub range: std::ops::Range<usize>,
|
||||
/// The complete authoritative text selection.
|
||||
pub selection: TextSel,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Atomically replaces character offsets in the current flattened edited body.
|
||||
/// Restores text, selection, composition and history on error.
|
||||
pub fn replace_text_range(&mut self, range: std::ops::Range<usize>, text: &str, kind: TextReplaceKind) -> Result<TextReplaceResult> {
|
||||
let before = self.doc()?.clone();
|
||||
let boundary = self.text_edit_session.clone();
|
||||
let journal = self.journal.clone();
|
||||
let settles = self.composition_settles;
|
||||
let depth = self.depth;
|
||||
let mut output = None;
|
||||
let result = self.guarded("text.replaceRange", |s| {
|
||||
s.begin_text_edit_session()?;
|
||||
// PLAN: assumed cmd::text::replace_text_range(&mut Session, Range<usize>, &str, TextReplaceKind) -> Result<TextReplaceResult> (shell-w9)
|
||||
output = Some(cmd::text::replace_text_range(s, range, text, kind)?);
|
||||
s.advance_text_boundary();
|
||||
Ok(Value::Null)
|
||||
});
|
||||
if let Err(error) = result {
|
||||
if let Some(st) = self.active_mut()
|
||||
&& st.uid == before.uid
|
||||
{
|
||||
*st = before;
|
||||
}
|
||||
self.depth = depth;
|
||||
self.text_edit_session = boundary;
|
||||
self.journal = journal;
|
||||
self.composition_settles = settles;
|
||||
return Err(error);
|
||||
}
|
||||
output.ok_or_else(|| EngineError::Internal("text.replaceRange".into(), "missing replacement result".into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Opens an idempotent text edit boundary for the current document and target.
|
||||
/// Includes any original composition snapshot without adding an undo entry.
|
||||
pub fn begin_text_edit_session(&mut self) -> Result<()> {
|
||||
let target = self.text_target().ok_or_else(|| cmd::bad("text", cmd::NO_TEXT_POINT))?;
|
||||
if self.text_boundary_matches() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut before = self.doc()?.clone();
|
||||
let latest = before.doc.clone();
|
||||
if let Some(composition) = before.composition.take() {
|
||||
before.doc = composition.before;
|
||||
before.selection = composition.before_selection;
|
||||
}
|
||||
self.text_edit_session = Some(TextEditSession { target, before: Arc::new(before), latest, journal_start: self.journal.len() });
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Finishes the current text edit boundary, optionally restoring only its edits.
|
||||
/// Never crosses a sealed document or target boundary.
|
||||
pub fn finish_text_edit_session(&mut self, cancel: bool) -> Result<()> {
|
||||
let matches = self.text_boundary_matches();
|
||||
let Some(boundary) = self.text_edit_session.take() else { return Ok(()) };
|
||||
if !matches {
|
||||
return Ok(());
|
||||
}
|
||||
if !cancel {
|
||||
self.settle_composition();
|
||||
return Ok(());
|
||||
}
|
||||
if self.active().is_some_and(|st| st.composition.is_some()) {
|
||||
self.composition_settles = self.composition_settles.wrapping_add(1);
|
||||
}
|
||||
let st = self.doc_mut()?;
|
||||
if !Arc::ptr_eq(&st.doc, &boundary.before.doc) {
|
||||
st.doc = boundary.before.doc.clone();
|
||||
st.selection = boundary.before.selection.clone();
|
||||
st.history = boundary.before.history.clone();
|
||||
st.composition = boundary.before.composition.clone();
|
||||
st.auto_list = boundary.before.auto_list.clone();
|
||||
st.notes_run = None;
|
||||
st.notes_before = None;
|
||||
st.revision = st.revision.wrapping_add(1);
|
||||
self.journal.truncate(boundary.journal_start);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Returns the generation of actual active-document transitions.
|
||||
/// Same-active and invalid requests leave the generation unchanged.
|
||||
pub fn active_generation(&self) -> u64 {
|
||||
self.active_generation
|
||||
}
|
||||
|
||||
fn text_target(&self) -> Option<TextEditTarget> {
|
||||
let st = self.active()?;
|
||||
let t = st.selection.text.as_ref()?;
|
||||
Some((st.uid, st.selection.slide, st.selection.target, if t.notes { ShapeId::default() } else { t.shape }, t.cell, t.notes))
|
||||
}
|
||||
|
||||
fn text_boundary_matches(&self) -> bool {
|
||||
self.text_edit_session
|
||||
.as_ref()
|
||||
.is_some_and(|b| self.text_target() == Some(b.target) && self.active().is_some_and(|st| Arc::ptr_eq(&st.doc, &b.latest)))
|
||||
}
|
||||
|
||||
fn advance_text_boundary(&mut self) {
|
||||
let target = self.text_target();
|
||||
let latest = self.active().map(|st| st.doc.clone());
|
||||
if let Some(boundary) = &mut self.text_edit_session {
|
||||
if Some(boundary.target) == target {
|
||||
if let Some(latest) = latest {
|
||||
boundary.latest = latest;
|
||||
}
|
||||
} else {
|
||||
self.text_edit_session = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+23
-176
@@ -22,14 +22,6 @@ enum FlagMode {
|
||||
Num,
|
||||
}
|
||||
|
||||
/// Where a part sits in a compound.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Pos {
|
||||
First,
|
||||
Middle,
|
||||
Last,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Cond {
|
||||
Any,
|
||||
@@ -116,8 +108,6 @@ pub struct Dictionary {
|
||||
compound_begin: Option<Flag>,
|
||||
compound_middle: Option<Flag>,
|
||||
compound_end: Option<Flag>,
|
||||
/// `COMPOUNDPERMITFLAG`: an affix carrying it may sit inside a compound, not only at its ends.
|
||||
compound_permit: Option<Flag>,
|
||||
compound_min: usize,
|
||||
compound_max: usize,
|
||||
}
|
||||
@@ -177,7 +167,6 @@ impl Dictionary {
|
||||
["COMPOUNDBEGIN", f, ..] => d.compound_begin = one_flag(Some(f), mode),
|
||||
["COMPOUNDMIDDLE", f, ..] => d.compound_middle = one_flag(Some(f), mode),
|
||||
["COMPOUNDEND", f, ..] | ["COMPOUNDLAST", f, ..] => d.compound_end = one_flag(Some(f), mode),
|
||||
["COMPOUNDPERMITFLAG", f, ..] => d.compound_permit = one_flag(Some(f), mode),
|
||||
["COMPOUNDMIN", n, ..] => d.compound_min = n.parse::<usize>().unwrap_or(3).max(1),
|
||||
["COMPOUNDWORDMAX", n, ..] => d.compound_max = n.parse().unwrap_or(0),
|
||||
["REP", n] => {
|
||||
@@ -261,26 +250,11 @@ impl Dictionary {
|
||||
self.words.get(word).is_some_and(|hs| hs.iter().any(|f| self.has(f, self.forbidden)))
|
||||
}
|
||||
|
||||
/// An affix that may only be used inside a compound (`ONLYINCOMPOUND` among its continuation
|
||||
/// flags): frami's zero suffixes that turn `Vor` into a compound's first part don't make `Vor`
|
||||
/// a word of its own (#2145).
|
||||
fn only_in_compound_affix(&self, a: &Affix) -> bool {
|
||||
self.only_in_compound.is_some_and(|o| a.cont.contains(&o))
|
||||
}
|
||||
|
||||
/// An affix that needs a further affix (`NEEDAFFIX` among its continuation flags): it can't be
|
||||
/// the last affix of a word or of a compound part.
|
||||
fn needs_another_affix(&self, a: &Affix) -> bool {
|
||||
self.need_affix.is_some_and(|n| a.cont.contains(&n))
|
||||
}
|
||||
|
||||
/// Strip suffixes from `w` (one, or two through continuation flags); `extra` flags must also be
|
||||
/// on the root, `cross` means the suffix must allow a prefix. `completed`: a prefix that needs
|
||||
/// nothing more is already on the word, so a suffix that needs another affix has it
|
||||
/// (`work/US` with `SFX S 0 s/N` makes `unworks`, not `works`).
|
||||
fn suffixed(&self, w: &[char], extra: &[Flag], cross: bool, completed: bool) -> bool {
|
||||
/// on the root, `cross` means the suffix must allow a prefix.
|
||||
fn suffixed(&self, w: &[char], extra: &[Flag], cross: bool) -> bool {
|
||||
for s in &self.sfx {
|
||||
if (cross && !s.cross) || self.only_in_compound_affix(s) || (self.needs_another_affix(s) && !completed) {
|
||||
if cross && !s.cross {
|
||||
continue;
|
||||
}
|
||||
let Some(stem) = strip_end(w, &s.add, &s.strip) else { continue };
|
||||
@@ -295,7 +269,7 @@ impl Dictionary {
|
||||
}
|
||||
// A second suffix whose continuation allows this one (`walk/A` + `ing/B`…).
|
||||
for s2 in &self.sfx {
|
||||
if !s.cont.is_empty() || !s2.cont.contains(&s.flag) || self.only_in_compound_affix(s2) {
|
||||
if !s.cont.is_empty() || !s2.cont.contains(&s.flag) {
|
||||
continue;
|
||||
}
|
||||
let Some(stem2) = strip_end(&stem, &s2.add, &s2.strip) else { continue };
|
||||
@@ -311,47 +285,24 @@ impl Dictionary {
|
||||
false
|
||||
}
|
||||
|
||||
/// A root carrying `flag`, or a root with one affix, as a compound part at `pos`.
|
||||
fn compound_part(&self, part: &[char], flag: Flag, pos: Pos) -> bool {
|
||||
/// A root (or, for the last part, a suffixed root) carrying `flag`, as a compound part.
|
||||
fn compound_part(&self, part: &[char], flag: Flag, last: bool) -> bool {
|
||||
let word: String = part.iter().collect();
|
||||
let ok = self.words.get(&word).is_some_and(|hs| hs.iter().any(|f| !self.has(f, self.forbidden) && f.contains(&flag)));
|
||||
ok || self.affixed_compound_part(part, flag, pos)
|
||||
ok || (last && self.suffixed_compound_end(part, flag))
|
||||
}
|
||||
|
||||
/// A compound part made of a root and one affix, as Hunspell reads them: a suffix ends the last
|
||||
/// part and a prefix starts the first; anywhere else the affix needs `COMPOUNDPERMITFLAG`.
|
||||
/// An affix that carries `NEEDAFFIX` needs a second one and doesn't count. A suffix found
|
||||
/// through the plain compound flag whose continuation flags carry `COMPOUNDEND` may only be on
|
||||
/// the last part. The compound `flag`
|
||||
/// may be on the root or among the affix's continuation flags. German frami gives many first
|
||||
/// parts their flag that way: `Vor/hij` with `SFX j 0 0/xoc` begins `Vorschlag` (#2145).
|
||||
fn affixed_compound_part(&self, w: &[char], flag: Flag, pos: Pos) -> bool {
|
||||
let permit = |a: &Affix| self.compound_permit.is_some_and(|p| a.cont.contains(&p));
|
||||
// An affix that itself needs another (`NEEDAFFIX` among its continuation flags) doesn't
|
||||
// finish a part on its own.
|
||||
let fits = |a: &Affix, stem: &[char], suffix: bool| {
|
||||
!self.needs_another_affix(a)
|
||||
// Only the last part may take a suffix found through the plain compound flag whose
|
||||
// continuation flags carry the compound end flag; the begin, middle and prefix
|
||||
// lookups don't check it, as in Hunspell.
|
||||
&& (pos == Pos::Last || !suffix || Some(flag) != self.compound || !self.compound_end.is_some_and(|e| a.cont.contains(&e)))
|
||||
&& self.words.get(&stem.iter().collect::<String>()).is_some_and(|hs| {
|
||||
hs.iter().any(|f| !self.has(f, self.forbidden) && f.contains(&a.flag) && (f.contains(&flag) || a.cont.contains(&flag)))
|
||||
})
|
||||
};
|
||||
let suffixed = self
|
||||
.sfx
|
||||
.iter()
|
||||
// At the end of a compound, Hunspell refuses a suffix that adds letters and may only be
|
||||
// used inside compounds; a zero-length one is accepted.
|
||||
.filter(|s| if pos == Pos::Last { s.add.is_empty() || !self.only_in_compound_affix(s) } else { permit(s) })
|
||||
.any(|s| strip_end(w, &s.add, &s.strip).is_some_and(|stem| s.cond_ok(&stem, false) && fits(s, &stem, true)));
|
||||
suffixed
|
||||
|| self
|
||||
.pfx
|
||||
.iter()
|
||||
.filter(|p| pos == Pos::First || permit(p))
|
||||
.any(|p| strip_start(w, &p.add, &p.strip).is_some_and(|stem| p.cond_ok(&stem, true) && fits(p, &stem, false)))
|
||||
/// The last part of a compound with a suffix: the root must carry the compound `flag`.
|
||||
fn suffixed_compound_end(&self, w: &[char], flag: Flag) -> bool {
|
||||
self.sfx.iter().any(|s| {
|
||||
strip_end(w, &s.add, &s.strip).is_some_and(|stem| {
|
||||
s.cond_ok(&stem, false)
|
||||
&& self
|
||||
.words
|
||||
.get(&stem.iter().collect::<String>())
|
||||
.is_some_and(|hs| hs.iter().any(|f| !self.has(f, self.forbidden) && f.contains(&flag) && f.contains(&s.flag)))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// `w` made of dictionary parts allowed in compounds (`COMPOUNDFLAG`, or the begin, middle and
|
||||
@@ -372,12 +323,11 @@ impl Dictionary {
|
||||
let role = if index == 0 { self.compound_begin } else { self.compound_middle };
|
||||
for i in min..=w.len() - min {
|
||||
let (head, rest) = w.split_at(i);
|
||||
let pos = if index == 0 { Pos::First } else { Pos::Middle };
|
||||
let head_ok = [self.compound, role].into_iter().flatten().any(|f| self.compound_part(head, f, pos));
|
||||
let head_ok = [self.compound, role].into_iter().flatten().any(|f| self.compound_part(head, f, false));
|
||||
if !head_ok {
|
||||
continue;
|
||||
}
|
||||
if [self.compound, self.compound_end].into_iter().flatten().any(|f| self.compound_part(rest, f, Pos::Last)) {
|
||||
if [self.compound, self.compound_end].into_iter().flatten().any(|f| self.compound_part(rest, f, true)) {
|
||||
return true;
|
||||
}
|
||||
if self.compounded(rest, index + 1, failed) {
|
||||
@@ -396,21 +346,18 @@ impl Dictionary {
|
||||
return true;
|
||||
}
|
||||
let w: Vec<char> = word.chars().collect();
|
||||
if self.suffixed(&w, &[], false, false) {
|
||||
if self.suffixed(&w, &[], false) {
|
||||
return true;
|
||||
}
|
||||
for p in &self.pfx {
|
||||
if self.only_in_compound_affix(p) {
|
||||
continue;
|
||||
}
|
||||
let Some(stem) = strip_start(&w, &p.add, &p.strip) else { continue };
|
||||
if !p.cond_ok(&stem, true) {
|
||||
continue;
|
||||
}
|
||||
if !self.needs_another_affix(p) && self.root(&stem.iter().collect::<String>(), &[p.flag], true) {
|
||||
if self.root(&stem.iter().collect::<String>(), &[p.flag], true) {
|
||||
return true;
|
||||
}
|
||||
if p.cross && self.suffixed(&stem, &[p.flag], true, !self.needs_another_affix(p)) {
|
||||
if p.cross && self.suffixed(&stem, &[p.flag], true) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1085,106 +1032,6 @@ SFX D Y 1\nSFX D 0 ed/S .\n";
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn affixes_give_compound_parts_their_flags() {
|
||||
// #2145, the way German frami builds compounds: the first and middle parts get their flags
|
||||
// from zero affixes' continuation classes, not from the root, and those roots need an affix.
|
||||
let aff = "COMPOUNDBEGIN B\nCOMPOUNDMIDDLE M\nCOMPOUNDEND E\nCOMPOUNDPERMITFLAG P\nONLYINCOMPOUND O\nNEEDAFFIX N\n\
|
||||
COMPOUNDMIN 2\nSFX j Y 1\nSFX j 0 0/BOP .\nSFX m Y 1\nSFX m 0 0/MOP .\nPFX q Y 1\nPFX q 0 0/BO .\n\
|
||||
SFX s Y 1\nSFX s 0 e .\nSFX u Y 1\nSFX u 0 s .\nPFX v Y 1\nPFX v 0 un .\nSFX t Y 1\nSFX t 0 0/BNP .\n";
|
||||
let dic = "8\nvor/Nj\nschlag/OEs\nwerk/Njm\nzeug/OEs\nding/Nq\nhaus/Ev\ntag/Bs\ntor/t\n";
|
||||
let d = Dictionary::parse(aff.as_bytes(), dic.as_bytes());
|
||||
// First part through SFX j, middle part through SFX m (it carries the permit flag), last
|
||||
// part from its root, with or without a suffix there.
|
||||
for w in ["vorschlag", "vorschlage", "werkzeug", "werkzeuge", "vorwerkzeug", "werkhaus", "dinghaus"] {
|
||||
assert!(d.check(w), "{w}");
|
||||
}
|
||||
for w in [
|
||||
// A NEEDAFFIX or ONLYINCOMPOUND root alone, or a part with no compound flag at all.
|
||||
"vor",
|
||||
"werk",
|
||||
"schlag",
|
||||
"hausvor",
|
||||
"schlagzeug",
|
||||
// A suffix on the first part without the permit flag (s), and a prefix on a later part
|
||||
// without it (v).
|
||||
"vorschlageschlag",
|
||||
"werkunhaus",
|
||||
// tag carries B but its suffix s has no permit flag; SFX t gives B but carries NEEDAFFIX.
|
||||
"tageschlag",
|
||||
"torhaus",
|
||||
// Not words.
|
||||
"vorschlagx",
|
||||
"xvorschlag",
|
||||
] {
|
||||
assert!(!d.check(w), "{w}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn affixes_that_need_another_or_only_live_in_compounds_follow_hunspell() {
|
||||
// Each row as Hunspell 1.7.6 reads the same dictionary: `sun/X` and `cat/S`, `SFX S` adding
|
||||
// the compound flag X and NEEDAFFIX (N) or ONLYINCOMPOUND (O).
|
||||
let dict = |sfx: &str| {
|
||||
let aff = format!("COMPOUNDFLAG X\nCOMPOUNDMIN 3\nNEEDAFFIX N\nONLYINCOMPOUND O\nSFX S Y 1\nSFX S {sfx} .\n");
|
||||
Dictionary::parse(aff.as_bytes(), b"2\nsun/X\ncat/S\n".as_slice())
|
||||
};
|
||||
let rows: [(&str, &[&str], &[&str]); 4] = [
|
||||
// An affix that needs another finishes neither a word nor a compound part.
|
||||
("0 s/XN", &["sun", "cat"], &["cats", "suncats", "catssun"]),
|
||||
("0 0/XN", &["sun", "cat"], &["suncat"]),
|
||||
// At the end of a compound a compound-only suffix may be empty, not add letters.
|
||||
("0 s/XO", &["sun", "cat"], &["cats", "suncats"]),
|
||||
("0 0/XO", &["sun", "cat", "suncat"], &["catsun", "suncatsun"]),
|
||||
];
|
||||
for (sfx, good, bad) in rows {
|
||||
let d = dict(sfx);
|
||||
for w in good {
|
||||
assert!(d.check(w), "{sfx}: {w}");
|
||||
}
|
||||
for w in bad {
|
||||
assert!(!d.check(w), "{sfx}: {w}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_completes_a_suffix_that_needs_another_affix() {
|
||||
// As Hunspell 1.7.6 reads it: `work/US`, a suffix needing another affix (N). The prefix
|
||||
// completes it (`unworks`); alone it doesn't (`works`); when both need another, neither
|
||||
// completes the other.
|
||||
for (pfx, good, bad) in
|
||||
[("0 un", &["work", "unwork", "unworks"][..], &["works"][..]), ("0 un/N", &["work"][..], &["works", "unwork", "unworks"][..])]
|
||||
{
|
||||
let aff = format!("NEEDAFFIX N\nPFX U Y 1\nPFX U {pfx} .\nSFX S Y 1\nSFX S 0 s/N .\n");
|
||||
let d = Dictionary::parse(aff.as_bytes(), b"1\nwork/US\n".as_slice());
|
||||
for w in good {
|
||||
assert!(d.check(w), "{pfx}: {w}");
|
||||
}
|
||||
for w in bad {
|
||||
assert!(!d.check(w), "{pfx}: {w}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_affix_carrying_the_compound_end_flag_only_ends_a_compound() {
|
||||
let aff = "COMPOUNDFLAG X\nCOMPOUNDEND E\nCOMPOUNDPERMITFLAG P\nCOMPOUNDMIN 3\nSFX S Y 1\nSFX S 0 s/XEP .\n";
|
||||
let d = Dictionary::parse(aff.as_bytes(), b"2\nsun/X\ncat/S\n".as_slice());
|
||||
assert!(d.check("suncats"));
|
||||
assert!(d.check("cats"));
|
||||
assert!(!d.check("catssun"));
|
||||
// Through the begin flag, the end flag on the suffix doesn't matter: Hunspell 1.7.6
|
||||
// accepts `catssun` here (and `cats`), and rejects `catsun`, `suncats` and `suncat`.
|
||||
let aff = "COMPOUNDBEGIN B\nCOMPOUNDEND E\nCOMPOUNDPERMITFLAG P\nCOMPOUNDMIN 3\nSFX S Y 1\nSFX S 0 s/BEP .\n";
|
||||
let d = Dictionary::parse(aff.as_bytes(), b"2\nsun/E\ncat/S\n".as_slice());
|
||||
assert!(d.check("catssun"));
|
||||
assert!(d.check("cats"));
|
||||
for w in ["catsun", "suncats", "suncat"] {
|
||||
assert!(!d.check(w), "{w}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_compound_roots_with_a_failing_ending_stay_cheap() {
|
||||
// Roots a..aaaaaaaa overlap, so many splits of "aaa…ab" reach the same (tail, part) state; unmemoized that is millions of searches.
|
||||
|
||||
+91
-465
@@ -668,32 +668,6 @@ fn sample_placeholders_paste_with_their_look() {
|
||||
assert!(checked >= 3, "the sample has text placeholders ({checked})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copied_shapes_paste_as_shapes_while_a_text_box_is_being_edited() {
|
||||
let mut s = session();
|
||||
s.execute("shape.insert", &json!({"preset": "ellipse", "rect": [10, 10, 50, 50]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
let r = s.execute("insert.textBox", &json!({"text": "Hello"})).unwrap();
|
||||
let id = r["id"].as_u64().unwrap();
|
||||
s.execute("text.edit", &json!({"id": id})).unwrap();
|
||||
let before = s.doc().unwrap().current_slide().unwrap().shapes.len();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().current_slide().unwrap().shapes.len(), before + 1);
|
||||
assert!(s.doc().unwrap().selection.text.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copied_shapes_are_not_pasted_while_the_notes_are_being_edited() {
|
||||
let mut s = session();
|
||||
s.execute("shape.insert", &json!({"preset": "ellipse", "rect": [10, 10, 50, 50]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("text.edit", &json!({"notes": true})).unwrap();
|
||||
let before = s.doc().unwrap().current_slide().unwrap().shapes.len();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().current_slide().unwrap().shapes.len(), before);
|
||||
assert!(s.doc().unwrap().selection.text.as_ref().is_some_and(|t| t.notes));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasted_shapes_get_the_next_automatic_name() {
|
||||
let mut s = session();
|
||||
@@ -1318,53 +1292,6 @@ fn pointer_draw_move_resize() {
|
||||
assert_eq!(v["box"]["w"], 150.0);
|
||||
}
|
||||
|
||||
/// A cancelled press (Escape over it, a lost capture) abandons its drag: a line being drawn is not inserted and leaves
|
||||
/// no preview, and a resize is put back, neither adding an undo step.
|
||||
#[test]
|
||||
fn a_cancelled_drag_inserts_nothing_and_puts_a_resize_back() {
|
||||
let mut s = session();
|
||||
let ev = |kind, x, y| PointerEvent { kind, x, y, mods: Mods::default(), tol: 3.0, pressure: None };
|
||||
let shapes = |s: &Session| s.doc().unwrap().shapes().len();
|
||||
let (before, undo) = (shapes(&s), s.doc().unwrap().history.undo.len());
|
||||
s.set_tool(ToolKind::Shape { preset: "line".into() });
|
||||
s.pointer(ev(PointerKind::Down, 100.0, 100.0)).unwrap();
|
||||
s.pointer(ev(PointerKind::Drag, 300.0, 200.0)).unwrap();
|
||||
assert!(s.tool.preview.is_some(), "the line shows its preview while drawn");
|
||||
s.cancel_drag();
|
||||
assert!(s.tool.preview.is_none() && !s.tool.dragging(), "the cancelled line leaves no preview");
|
||||
assert_eq!(shapes(&s), before, "the cancelled line is not inserted");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "and adds no undo step");
|
||||
|
||||
let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [100.0, 100.0, 100.0, 80.0]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.set_tool(ToolKind::Select);
|
||||
s.execute("edit.select", &json!({"ids": [id]})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.pointer(ev(PointerKind::Down, 200.0, 180.0)).unwrap();
|
||||
s.pointer(ev(PointerKind::Drag, 250.0, 200.0)).unwrap();
|
||||
let width = |s: &mut Session| s.execute("shape.inspect", &json!({"id": id})).unwrap()["box"]["w"].as_f64().unwrap();
|
||||
let resized = width(&mut s);
|
||||
s.cancel_drag();
|
||||
assert!(width(&mut s) < resized, "the cancelled resize is put back");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "and adds no undo step");
|
||||
}
|
||||
|
||||
/// A cancelled move takes its smart guides with it: none is left on the slide for the next tool's gesture.
|
||||
#[test]
|
||||
fn a_cancelled_move_leaves_no_smart_guide() {
|
||||
let mut s = session();
|
||||
let ev = |kind, x, y| PointerEvent { kind, x, y, mods: Mods::default(), tol: 3.0, pressure: None };
|
||||
s.execute("shape.insert", &json!({"preset": "rect", "rect": [100.0, 100.0, 100.0, 80.0]})).unwrap();
|
||||
let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [400.0, 300.0, 100.0, 80.0]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.set_tool(ToolKind::Select);
|
||||
s.execute("edit.select", &json!({"ids": [id]})).unwrap();
|
||||
s.pointer(ev(PointerKind::Down, 450.0, 340.0)).unwrap();
|
||||
// Level with the first rectangle's top.
|
||||
s.pointer(ev(PointerKind::Drag, 450.0, 142.0)).unwrap();
|
||||
assert!(!s.tool.guides.is_empty(), "the moved shape shows a smart guide");
|
||||
s.cancel_drag();
|
||||
assert!(s.tool.guides.is_empty(), "the cancelled move leaves no guide");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn click_into_placeholder_starts_editing() {
|
||||
let mut s = session();
|
||||
@@ -2578,6 +2505,65 @@ fn ime_on_a_selected_shape_replaces_its_text() {
|
||||
assert_eq!(s.commit_text("x").unwrap()["handled"], false);
|
||||
}
|
||||
|
||||
/// #101: the composition is underlined in place, under the composed characters, with a thicker
|
||||
/// line under the part being converted.
|
||||
#[test]
|
||||
fn ime_composition_underlines_follow_the_text() {
|
||||
let mut s = session();
|
||||
let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0;
|
||||
s.execute("text.edit", &json!({"id": title})).unwrap();
|
||||
assert!(cmd::text::composition_underlines(s.doc().unwrap()).is_empty());
|
||||
s.compose_text("にほんご", Some((2, 4))).unwrap();
|
||||
let u = cmd::text::composition_underlines(s.doc().unwrap());
|
||||
let thin: Vec<_> = u.iter().filter(|x| !x.2).collect();
|
||||
let thick: Vec<_> = u.iter().filter(|x| x.2).collect();
|
||||
assert_eq!((thin.len(), thick.len()), (1, 1), "{u:?}");
|
||||
let sh = s.doc().unwrap().current_slide().unwrap().shapes[0].clone();
|
||||
let x = cmd::xfrm_of(&s.doc().unwrap().doc, &s.doc().unwrap().selection, &sh);
|
||||
for (a, b, _) in &u {
|
||||
assert!(b.x > a.x && (a.y - b.y).abs() < 1e-9, "a horizontal line: {a:?} {b:?}");
|
||||
assert!(a.x >= x.x - 1.0 && b.x <= x.x + x.w + 1.0 && a.y > x.y && a.y < x.y + x.h, "inside the title box");
|
||||
}
|
||||
assert!(thick[0].0.x > thin[0].0.x && (thick[0].1.x - thin[0].1.x).abs() < 1e-6, "the converted part is the end");
|
||||
s.commit_text("日本語").unwrap();
|
||||
assert!(cmd::text::composition_underlines(s.doc().unwrap()).is_empty());
|
||||
}
|
||||
|
||||
/// #101: a composition in a table cell is underlined inside that cell, the same way slide text is.
|
||||
#[test]
|
||||
fn ime_composition_in_a_table_cell_is_underlined() {
|
||||
let mut s = session();
|
||||
let id = s.execute("insert.table", &json!({"rows": 2, "cols": 2, "rect": [80.0, 90.0, 400.0, 120.0]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.edit", &json!({"id": id, "cell": [0, 0]})).unwrap();
|
||||
assert!(cmd::text::composition_underlines(s.doc().unwrap()).is_empty());
|
||||
let ts = s.doc().unwrap().selection.text.clone().unwrap();
|
||||
assert!(cmd::text::caret_line(s.doc().unwrap(), &ts).is_some(), "the caret is in the cell");
|
||||
s.compose_text("にほんご", Some((2, 4))).unwrap();
|
||||
let u = cmd::text::composition_underlines(s.doc().unwrap());
|
||||
let thin: Vec<_> = u.iter().filter(|x| !x.2).collect();
|
||||
let thick: Vec<_> = u.iter().filter(|x| x.2).collect();
|
||||
assert_eq!((thin.len(), thick.len()), (1, 1), "{u:?}");
|
||||
let sh = s.doc().unwrap().shape(deckcraft_model::ShapeId(id as u32)).unwrap().clone();
|
||||
let x = cmd::xfrm_of(&s.doc().unwrap().doc, &s.doc().unwrap().selection, &sh);
|
||||
let deckcraft_model::ShapeKind::Table(tb) = &sh.kind else { panic!("not a table") };
|
||||
let col = tb.cols[0];
|
||||
let row = cmd::table_drawn_heights(&s.doc().unwrap().doc, &s.doc().unwrap().selection, tb)[0];
|
||||
for (a, b, _) in &u {
|
||||
assert!(b.x > a.x && (a.y - b.y).abs() < 1e-6, "a horizontal line: {a:?} {b:?}");
|
||||
assert!(a.x >= x.x - 1.0 && b.x <= x.x + col + 1.0, "inside the first column");
|
||||
assert!(a.y > x.y && a.y < x.y + row + 1.0, "inside the first row");
|
||||
}
|
||||
assert!(thick[0].0.x > thin[0].0.x && (thick[0].1.x - thin[0].1.x).abs() < 1e-6, "the converted part is the end");
|
||||
let ts = s.doc().unwrap().selection.text.clone().unwrap();
|
||||
let (top, bot) = cmd::text::caret_line(s.doc().unwrap(), &ts).unwrap();
|
||||
assert!(top.x >= x.x && top.x <= x.x + col && top.y >= x.y && bot.y <= x.y + row + 1.0, "caret in the cell");
|
||||
s.commit_text("日本語").unwrap();
|
||||
assert!(cmd::text::composition_underlines(s.doc().unwrap()).is_empty());
|
||||
let sh = s.doc().unwrap().shape(deckcraft_model::ShapeId(id as u32)).unwrap().clone();
|
||||
let deckcraft_model::ShapeKind::Table(tb) = &sh.kind else { panic!("not a table") };
|
||||
assert_eq!(tb.cell(0, 0).map(|c| c.text.text()), Some("日本語".into()));
|
||||
}
|
||||
|
||||
/// File › Info (#76): the active presentation's name, location, counts and properties.
|
||||
#[test]
|
||||
fn file_info_reports_the_presentation() {
|
||||
@@ -3227,11 +3213,6 @@ fn shape_effects_props_adjust_shadow_glow_and_reflection() {
|
||||
let g = fx(&s).glow.unwrap();
|
||||
assert_eq!(g.radius, 12.0);
|
||||
assert!((g.color.alpha() - 0.5).abs() < 1e-6);
|
||||
s.execute("shape.effects", &json!({"glowProps": {"radius": 18}})).unwrap();
|
||||
let grown = fx(&s).glow.unwrap();
|
||||
assert_eq!(grown.radius, 18.0);
|
||||
assert_eq!(grown.color, g.color);
|
||||
assert!((grown.color.alpha() - 0.5).abs() < 1e-6);
|
||||
s.execute("shape.effects", &json!({"glowProps": {"radius": 0}})).unwrap();
|
||||
assert!(fx(&s).glow.is_none());
|
||||
// Reflection: transparency, size, distance, blur; hostile values are clamped or ignored.
|
||||
@@ -5591,6 +5572,37 @@ fn language_all_marks_every_text_in_the_deck_with_nothing_selected() {
|
||||
assert!(s.execute("format.languageAll", &json!({"lang": "en US!"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_caret_takes_the_colour_of_the_text() {
|
||||
let caret = |theme: &str| {
|
||||
let mut s = session();
|
||||
s.execute("design.theme", &json!({"name": theme})).unwrap();
|
||||
let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0;
|
||||
s.execute("text.edit", &json!({"id": title})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let empty = cmd::text::caret_color(st, &st.selection.text.clone().unwrap()).unwrap();
|
||||
s.execute("text.insert", &json!({"text": "Typed"})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(cmd::text::caret_color(st, &st.selection.text.clone().unwrap()), Some(empty));
|
||||
empty
|
||||
};
|
||||
// Dark text on the light theme, light text on the dark one: never black on a dark slide.
|
||||
let (light, dark) = (caret("DeckCraft"), caret("Nocturne"));
|
||||
assert!(light.r < 0x60 && light.g < 0x60 && light.b < 0x60, "{light:?}");
|
||||
assert!(dark.r > 0xC0 && dark.g > 0xC0 && dark.b > 0xC0, "{dark:?}");
|
||||
// Text set to red gets a red caret.
|
||||
let mut s = session();
|
||||
let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0;
|
||||
s.execute("text.edit", &json!({"id": title})).unwrap();
|
||||
s.execute("text.insert", &json!({"text": "Red"})).unwrap();
|
||||
s.execute("text.selectAll", &json!({})).unwrap();
|
||||
s.execute("format.color", &json!({"color": "#FF0000"})).unwrap();
|
||||
s.execute("text.move", &json!({"to": "end"})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let red = cmd::text::caret_color(st, &st.selection.text.clone().unwrap()).unwrap();
|
||||
assert_eq!((red.r, red.g, red.b), (0xFF, 0, 0));
|
||||
}
|
||||
|
||||
/// Smooth Corners (#286): a rounded rectangle becomes a squircle outline that survives PPTX.
|
||||
#[test]
|
||||
fn smooth_corners_makes_a_squircle_outline() {
|
||||
@@ -5801,30 +5813,15 @@ fn a_long_ink_stroke_is_extended_in_place_and_capped() {
|
||||
fn double_clicking_a_capped_freeform_keeps_its_vertices() {
|
||||
let mut s = session();
|
||||
let ev = |kind, x: f64, y: f64| tools::PointerEvent { kind, x, y, mods: Default::default(), tol: 3.0, pressure: None };
|
||||
let point_cap = 16;
|
||||
s.set_tool(tools::ToolKind::Shape { preset: "freeform".into() });
|
||||
assert_eq!(s.tool.press_point_cap(), tools::MAX_GESTURE_POINTS);
|
||||
s.tool.freeform_press_point_cap = Some(point_cap);
|
||||
s.pointer(ev(tools::PointerKind::Down, 100.0, 100.0)).unwrap();
|
||||
// Densely clicked vertices, each within the double-click tolerance of the last.
|
||||
// The first press counts toward the cap, so 11 of these presses add no point.
|
||||
for i in 0..point_cap + 10 {
|
||||
for i in 0..tools::MAX_GESTURE_POINTS + 10 {
|
||||
s.pointer(ev(tools::PointerKind::Down, 300.0 + i as f64 * 0.001, 100.0)).unwrap();
|
||||
}
|
||||
s.pointer(ev(tools::PointerKind::DoubleClick, 300.0, 100.0)).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let deckcraft_model::Geom::Custom { paths } = &st.shapes().last().unwrap().geom else { panic!("no freeform") };
|
||||
assert_eq!(paths[0].d.matches(" L ").count(), point_cap - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freeform_command_keeps_points_up_to_the_gesture_cap() {
|
||||
let mut s = session();
|
||||
// Send one point beyond the real cap to check that the command keeps as many as the tool can draw.
|
||||
let points: Vec<_> = (0..=tools::MAX_GESTURE_POINTS).map(|i| [i % 500, i / 500]).collect();
|
||||
let r = s.execute("shape.freeform", &json!({"points": points, "closed": false, "smooth": false})).unwrap();
|
||||
let id = ShapeId(r["id"].as_u64().unwrap() as u32);
|
||||
let deckcraft_model::Geom::Custom { paths } = &s.doc().unwrap().shape(id).unwrap().geom else { panic!("no freeform") };
|
||||
assert_eq!(paths[0].d.matches(" L ").count(), tools::MAX_GESTURE_POINTS - 1);
|
||||
}
|
||||
|
||||
@@ -7230,125 +7227,6 @@ fn invalid_slide_index_never_falls_back_to_the_selection_in_export_commands() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// G6: with no sites given, shape.connect joins the sites that face each other along the
|
||||
/// dominant direction between the two shapes (a box mostly below leaves from the bottom), not
|
||||
/// "the closest pair", which for a diagonal neighbour picked a side site and crossed boxes.
|
||||
#[test]
|
||||
fn connector_default_sites_follow_the_dominant_direction() {
|
||||
let mut s = session();
|
||||
let a = s.execute("shape.insert", &json!({"preset": "rect", "rect": [0, 0, 100, 50]})).unwrap()["id"].as_u64().unwrap();
|
||||
let diag = s.execute("shape.insert", &json!({"preset": "rect", "rect": [150, 200, 100, 50]})).unwrap()["id"].as_u64().unwrap();
|
||||
let r = s.execute("shape.connect", &json!({"from": a, "to": diag})).unwrap();
|
||||
assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(2), Some(0)), "mostly below: bottom → top, not right → left: {r}");
|
||||
let r = s.execute("shape.connect", &json!({"from": diag, "to": a})).unwrap();
|
||||
assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(0), Some(2)), "and back: top → bottom: {r}");
|
||||
// The direction runs between the shapes' centres, not between the means of their sites: a
|
||||
// triangle's sites lie mostly along its base, which pulled the direction sideways and chose
|
||||
// the box's left site for a box that is mostly below.
|
||||
let tri = s.execute("shape.insert", &json!({"preset": "triangle", "rect": [400, 0, 100, 100]})).unwrap()["id"].as_u64().unwrap();
|
||||
let below = s.execute("shape.insert", &json!({"preset": "rect", "rect": [520, 155, 100, 50]})).unwrap()["id"].as_u64().unwrap();
|
||||
let r = s.execute("shape.connect", &json!({"from": tri, "to": below})).unwrap();
|
||||
assert_eq!(r["toSite"].as_u64(), Some(0), "centre to centre is mostly down: the box's top, not its left: {r}");
|
||||
// An exact diagonal ties the bottom with the right side (and the top with the left): the lower
|
||||
// site index wins, so bottom → top, and top → bottom back.
|
||||
let p = s.execute("shape.insert", &json!({"preset": "rect", "rect": [0, 300, 100, 50]})).unwrap()["id"].as_u64().unwrap();
|
||||
let q = s.execute("shape.insert", &json!({"preset": "rect", "rect": [200, 500, 100, 50]})).unwrap()["id"].as_u64().unwrap();
|
||||
let sites = |s: &mut Session, from: u64, to: u64| {
|
||||
let r = s.execute("shape.connect", &json!({"from": from, "to": to})).unwrap();
|
||||
(r["fromSite"].as_u64(), r["toSite"].as_u64())
|
||||
};
|
||||
assert_eq!(sites(&mut s, p, q), (Some(2), Some(0)));
|
||||
assert_eq!(sites(&mut s, q, p), (Some(0), Some(2)));
|
||||
// Shapes with one centre tie every site: site 0 on both.
|
||||
let big = s.execute("shape.insert", &json!({"preset": "rect", "rect": [600, 300, 200, 100]})).unwrap()["id"].as_u64().unwrap();
|
||||
let small = s.execute("shape.insert", &json!({"preset": "rect", "rect": [650, 325, 100, 50]})).unwrap()["id"].as_u64().unwrap();
|
||||
assert_eq!(sites(&mut s, big, small), (Some(0), Some(0)));
|
||||
// One site given: the other end is the other shape's site closest to it, as before the facing
|
||||
// rule (which is for when neither is given). From a's right side (100, 25) the diagonal box's
|
||||
// top (200, 200) is nearest; to its left side (150, 225), a's bottom (50, 50).
|
||||
let r = s.execute("shape.connect", &json!({"from": a, "to": diag, "fromSite": 3})).unwrap();
|
||||
assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(3), Some(0)), "fromSite only: {r}");
|
||||
let r = s.execute("shape.connect", &json!({"from": a, "to": diag, "toSite": 1})).unwrap();
|
||||
assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(2), Some(1)), "toSite only: {r}");
|
||||
let r = s.execute("shape.connect", &json!({"from": a, "to": diag, "fromSite": 2, "toSite": 3})).unwrap();
|
||||
assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(2), Some(3)), "both given: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn style_commands_given_nothing_to_set_are_refused() {
|
||||
let mut s = session();
|
||||
s.execute("insert.textBox", &json!({"text": "Hi", "rect": [50.0, 50.0, 200.0, 100.0]})).unwrap();
|
||||
for cmd in ["shape.line", "shape.effects", "picture.adjust", "format.paragraph", "format.margins"] {
|
||||
let rev = s.doc().unwrap().revision;
|
||||
let e = s.execute(cmd, &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("given nothing to set") && e.contains(cmd), "{cmd}: {e}");
|
||||
assert_eq!(s.doc().unwrap().revision, rev, "{cmd} changed the deck");
|
||||
}
|
||||
let e = s.execute("shape.line", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("pass color, none, width, dash"), "{e}");
|
||||
// A key, even one that changes nothing visible, is something to set.
|
||||
s.execute("shape.line", &json!({"width": 2})).unwrap();
|
||||
s.execute("format.margins", &json!({"left": 5})).unwrap();
|
||||
// A null glow or soft edge clears it (No Glow, No Soft Edges): that is something to set.
|
||||
let fx = |s: &Session| s.doc().unwrap().selected_shapes()[0].effects.clone().unwrap_or_default();
|
||||
s.execute("shape.effects", &json!({"glow": 8, "softEdges": 5})).unwrap();
|
||||
assert!(fx(&s).glow.is_some() && fx(&s).soft_edge.is_some());
|
||||
s.execute("shape.effects", &json!({"glow": null})).unwrap();
|
||||
assert!(fx(&s).glow.is_none() && fx(&s).soft_edge.is_some());
|
||||
s.execute("shape.effects", &json!({"softEdges": null})).unwrap();
|
||||
assert!(fx(&s).soft_edge.is_none());
|
||||
// The Paragraph dialog's own fields are format.paragraphDialog's, and the refusal says so.
|
||||
for (k, v) in [("special", json!("hanging")), ("spaceBeforeKind", json!("pct")), ("indentRight", json!(10))] {
|
||||
let e = s.execute("format.paragraph", &json!({ k: v })).unwrap_err().to_string();
|
||||
assert!(e.contains("format.paragraphDialog") && e.contains(k), "{k}: {e}");
|
||||
}
|
||||
let e = s.execute("format.paragraph", &json!({"spaceBeforeKind": "pct"})).unwrap_err().to_string();
|
||||
assert!(e.contains("together with `spaceBefore`"), "{e}");
|
||||
// The palette lists only commands that run without arguments; these need one key.
|
||||
for cmd in ["shape.line", "shape.effects", "picture.adjust", "format.paragraph", "format.margins"] {
|
||||
let spec = crate::command_specs().iter().find(|c| c.id == cmd).unwrap();
|
||||
assert!(crate::cmd::needs_arguments(spec.params), "{cmd}: {}", spec.params);
|
||||
}
|
||||
s.execute("format.paragraphDialog", &json!({"special": "hanging", "specialBy": 18})).unwrap();
|
||||
}
|
||||
|
||||
/// A call whose keys are all null sets nothing and is refused like an empty one, changing
|
||||
/// nothing; one valid key is enough, nulls beside it ignored.
|
||||
#[test]
|
||||
fn style_commands_refuse_only_nulls_and_take_one_key() {
|
||||
let mut png = vec![];
|
||||
image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(4, 2, image::Rgba([200, 30, 30, 255])))
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let mut s = session();
|
||||
let pic =
|
||||
s.execute("insert.picture", &json!({"data": cmd::base64_encode(&png), "name": "a.png", "rect": [100, 100, 40, 20]})).unwrap()["id"].clone();
|
||||
let text = s.execute("insert.textBox", &json!({"text": "Hi", "rect": [50, 300, 200, 100]})).unwrap()["id"].clone();
|
||||
let nulls = |keys: &[&str]| serde_json::Value::Object(keys.iter().map(|k| ((*k).to_string(), serde_json::Value::Null)).collect());
|
||||
for (cmd, id, keys, one) in [
|
||||
(
|
||||
"picture.adjust",
|
||||
&pic,
|
||||
&["brightness", "contrast", "saturation", "grayscale", "transparency", "reset"][..],
|
||||
json!({"brightness": 0.3, "contrast": null}),
|
||||
),
|
||||
(
|
||||
"format.paragraph",
|
||||
&text,
|
||||
&["align", "indentLeft", "indentFirst", "spaceBefore", "spaceAfter", "lineSpacing", "lineSpacingPt"][..],
|
||||
json!({"align": "center", "spaceBefore": null}),
|
||||
),
|
||||
] {
|
||||
s.execute("edit.select", &json!({"ids": [id]})).unwrap();
|
||||
let rev = s.doc().unwrap().revision;
|
||||
let e = s.execute(cmd, &nulls(keys)).unwrap_err().to_string();
|
||||
assert!(e.contains("given nothing to set") && e.contains(cmd), "{cmd}: {e}");
|
||||
assert_eq!(s.doc().unwrap().revision, rev, "{cmd}: only nulls changed the deck");
|
||||
s.execute(cmd, &one).unwrap_or_else(|e| panic!("{cmd} {one}: {e}"));
|
||||
assert_ne!(s.doc().unwrap().revision, rev, "{cmd}: one key set something");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlight_with_an_invalid_colour_is_rejected_and_keeps_the_highlight() {
|
||||
let mut s = session();
|
||||
@@ -7444,160 +7322,6 @@ fn master_body_placeholder_format_keeps_per_level_formatting() {
|
||||
assert_eq!(shown(&s), vec![Some(28.0), Some(24.0)]);
|
||||
}
|
||||
|
||||
/// A `keepWidth` that is not a bool is refused, naming it, and the table is left alone, not read
|
||||
/// as the default (the table growing by the new column).
|
||||
#[test]
|
||||
fn table_insert_column_refuses_a_keep_width_that_is_not_a_bool() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"]]));
|
||||
for (cmd, bad) in [("table.insertColumnRight", json!("false")), ("table.insertColumnLeft", json!(0))] {
|
||||
let err = s.execute(cmd, &json!({"id": id.0, "col": 1, "keepWidth": bad})).unwrap_err().to_string();
|
||||
assert!(err.contains("keepWidth") && err.contains(cmd), "{err}");
|
||||
let t = table_of(&s, id);
|
||||
assert_eq!(t.n_cols(), 3, "{cmd} changed the table: {:?}", t.cols);
|
||||
assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_insert_column_with_keep_width_keeps_the_table_width_and_copies_the_neighbour_format() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"], ["d", "e", "f"]]));
|
||||
s.execute("table.cellFill", &json!({"id": id.0, "color": "#FF0000", "cells": [[0, 2], [1, 2]]})).unwrap();
|
||||
s.execute("table.cellMargins", &json!({"id": id.0, "left": 20, "right": 20, "top": 5, "bottom": 5, "cells": [[0, 2]]})).unwrap();
|
||||
s.execute("table.cellAlign", &json!({"id": id.0, "anchor": "bottom", "cells": [[0, 2]]})).unwrap();
|
||||
s.execute("edit.select", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("table.selectCells", &json!({"from": [0, 2], "to": [1, 2]})).unwrap();
|
||||
s.execute("format.bold", &json!({"on": true})).unwrap();
|
||||
// Right of the last column: four columns in the same 840 pt, the new one as wide as its
|
||||
// neighbour, the others shrunk to make room.
|
||||
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 2, "keepWidth": true})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
assert_eq!(t.n_cols(), 4);
|
||||
assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width());
|
||||
assert!(t.cols.iter().all(|w| (w - 210.0).abs() < 1e-6), "{:?}", t.cols);
|
||||
let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
|
||||
assert!((x.w - 840.0).abs() < 1e-6, "frame {}", x.w);
|
||||
// The new cells take the neighbour's explicit formatting.
|
||||
let new = t.cell(0, 3).unwrap();
|
||||
assert_eq!(new.fill, Some(deckcraft_model::Fill::solid(deckcraft_model::ColorRef::rgb(deckcraft_color::Rgba::rgb(255, 0, 0)))));
|
||||
assert_eq!(new.margins, Some([20.0, 20.0, 5.0, 5.0]));
|
||||
assert_eq!(new.anchor, Some(deckcraft_model::text::Anchor::Bottom));
|
||||
assert_eq!(new.text.text(), "", "the new cell is empty");
|
||||
let bold = new.text.paragraphs.first().map(|p| p.end_props.bold.or(p.def_props.bold));
|
||||
assert_eq!(bold, Some(Some(true)), "the neighbour's bold carries over: {:?}", new.text);
|
||||
assert_eq!(t.cell(1, 3).unwrap().fill, t.cell(1, 2).unwrap().fill);
|
||||
// Left of the first column: the neighbour is the old first column.
|
||||
s.execute("table.insertColumnLeft", &json!({"id": id.0, "col": 0, "keepWidth": true})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
assert_eq!(t.n_cols(), 5);
|
||||
assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width());
|
||||
assert_eq!(t.cell(0, 1).unwrap().text.text(), "a");
|
||||
assert_eq!(t.cell(0, 0).unwrap().fill, None);
|
||||
// keepWidth: false grows the table by the neighbour's width, as before.
|
||||
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 4, "keepWidth": false})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
assert_eq!(t.n_cols(), 6);
|
||||
assert!((t.width() - 840.0 - 168.0).abs() < 1e-6, "width {}", t.width());
|
||||
// The insertion is journaled as called, and each one is a single undo step back to the table
|
||||
// as it was: the columns, their widths and the frame.
|
||||
let (jid, jp) = s.journal.last().cloned().unwrap();
|
||||
assert_eq!(jid, "table.insertColumnRight");
|
||||
assert_eq!(jp["keepWidth"], json!(false), "{jp}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
assert_eq!(t.n_cols(), 5);
|
||||
assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
assert_eq!(t.n_cols(), 3);
|
||||
assert!(t.cols.iter().all(|w| (w - 280.0).abs() < 1e-6), "{:?}", t.cols);
|
||||
assert_eq!(t.cell(0, 2).unwrap().text.text(), "c");
|
||||
let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
|
||||
assert!((x.w - 840.0).abs() < 1e-6, "frame {}", x.w);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_insert_column_beside_a_merge_copies_the_anchor_format() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"], ["d", "e", "f"]]));
|
||||
s.execute("table.cellFill", &json!({"id": id.0, "color": "#FF0000", "cells": [[0, 0]]})).unwrap();
|
||||
s.execute("table.merge", &json!({"id": id.0, "from": [0, 0], "to": [0, 1]})).unwrap();
|
||||
// Right of the merge: the neighbour column holds the covered cell, but the anchor shows.
|
||||
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 1})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
assert!(t.cell(0, 1).unwrap().h_merge, "the merge stays put");
|
||||
assert_eq!(t.cell(0, 2).unwrap().fill, t.cell(0, 0).unwrap().fill);
|
||||
assert!(t.cell(0, 2).unwrap().fill.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_insert_column_beside_a_two_row_merge_copies_the_anchor_format() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"], ["d", "e", "f"]]));
|
||||
s.execute("table.cellFill", &json!({"id": id.0, "color": "#FF0000", "cells": [[0, 0]]})).unwrap();
|
||||
s.execute("table.merge", &json!({"id": id.0, "from": [0, 0], "to": [1, 1]})).unwrap();
|
||||
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 1})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
assert!(t.cell(1, 1).unwrap().h_merge && t.cell(1, 1).unwrap().v_merge, "the merge stays put");
|
||||
assert!(t.cell(0, 2).unwrap().fill.is_some());
|
||||
assert_eq!(t.cell(1, 2).unwrap().fill, t.cell(0, 0).unwrap().fill);
|
||||
}
|
||||
|
||||
/// A table near the slide's right edge, with no room for another column: by default an inserted
|
||||
/// column widens it past the edge, as PowerPoint's Insert Right does (the frame keeps its left and
|
||||
/// grows), and `keepWidth: true` keeps it on the slide.
|
||||
#[test]
|
||||
fn table_insert_column_near_the_slide_edge_grows_past_it_unless_it_keeps_its_width() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"]]));
|
||||
let slide_w = s.doc().unwrap().doc.slide_size.width;
|
||||
let frame = |s: &Session| s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
|
||||
let before = frame(&s);
|
||||
assert!(before.x + before.w <= slide_w && before.x + before.w + 280.0 > slide_w, "another column won't fit: {before:?}");
|
||||
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 2})).unwrap();
|
||||
assert_eq!(table_of(&s, id).n_cols(), 4);
|
||||
let grown = frame(&s);
|
||||
assert!((grown.x - before.x).abs() < 1e-6 && (grown.w - 1120.0).abs() < 1e-6, "{grown:?}");
|
||||
assert!(grown.x + grown.w > slide_w, "past the edge");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 2, "keepWidth": true})).unwrap();
|
||||
let kept = frame(&s);
|
||||
assert_eq!(table_of(&s, id).n_cols(), 4);
|
||||
assert!((kept.x - before.x).abs() < 1e-6 && (kept.w - before.w).abs() < 1e-6, "{kept:?}");
|
||||
assert!(kept.x + kept.w <= slide_w, "still on the slide");
|
||||
}
|
||||
|
||||
/// PowerPoint inserts a column as wide as its neighbour and widens the table by that amount; the
|
||||
/// other widths stay. Deleting a column narrows the table by its width, the others untouched.
|
||||
#[test]
|
||||
fn table_insert_and_delete_column_leave_other_widths_alone() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[160.0, 234.0, 235.0, 235.0], json!([["a", "b", "c", "d"]]));
|
||||
for (cmd, col, at, wide) in [("table.insertColumnRight", 0, 1, 160.0), ("table.insertColumnLeft", 3, 3, 235.0)] {
|
||||
let before = table_of(&s, id).cols.clone();
|
||||
let w0 = table_of(&s, id).width();
|
||||
s.execute(cmd, &json!({"id": id.0, "col": col})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
let mut want = before.clone();
|
||||
want.insert(at, wide);
|
||||
assert_eq!(t.cols, want, "{cmd}");
|
||||
assert!((t.width() - w0 - wide).abs() < 1e-6, "{cmd} width {}", t.width());
|
||||
let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
|
||||
assert!((x.w - t.width()).abs() < 1e-6, "{cmd} frame {}", x.w);
|
||||
}
|
||||
let before = table_of(&s, id).cols.clone();
|
||||
s.execute("table.deleteColumn", &json!({"id": id.0, "col": 1})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
let mut want = before.clone();
|
||||
let gone = want.remove(1);
|
||||
assert_eq!(t.cols, want);
|
||||
assert!((t.width() - (before.iter().sum::<f64>() - gone)).abs() < 1e-6);
|
||||
let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
|
||||
assert!((x.w - t.width()).abs() < 1e-6, "frame {}", x.w);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_edits_past_the_cell_cap_are_refused_not_trimmed() {
|
||||
use deckcraft_model::table::{MAX_CELLS, Row};
|
||||
@@ -7900,101 +7624,3 @@ fn shape_adjust_and_quick_style_reject_invalid_index() {
|
||||
assert_eq!(s.doc().unwrap().shape(id).unwrap().style, before.style);
|
||||
s.execute("shape.adjust", &json!({"value": 0.4})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_document_transitions_invalidate_captures_without_edits() {
|
||||
let mut s = Session::new();
|
||||
let empty = s.active_generation();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let a = s.active_index().unwrap();
|
||||
let a_uid = s.doc().unwrap().uid;
|
||||
let a_revision = s.doc().unwrap().revision;
|
||||
let first = s.active_generation();
|
||||
assert_ne!(first, empty);
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let b = s.active_index().unwrap();
|
||||
let b_uid = s.doc().unwrap().uid;
|
||||
let second = s.active_generation();
|
||||
assert_ne!(second, first);
|
||||
for index in [a, b, a] {
|
||||
let before = s.active_generation();
|
||||
s.set_active(index);
|
||||
assert_ne!(s.active_generation(), before);
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().uid, a_uid);
|
||||
assert_eq!(s.doc().unwrap().revision, a_revision);
|
||||
let same = s.active_generation();
|
||||
s.set_active(a);
|
||||
s.set_active(usize::MAX);
|
||||
s.close_document(usize::MAX);
|
||||
assert_eq!(s.active_generation(), same);
|
||||
s.close_document(a);
|
||||
assert_ne!(s.active_generation(), same);
|
||||
assert_eq!(s.doc().unwrap().uid, b_uid);
|
||||
let remaining = s.active_generation();
|
||||
s.close_document(s.active_index().unwrap());
|
||||
assert!(s.active().is_none());
|
||||
assert_ne!(s.active_generation(), remaining);
|
||||
let closed = s.active_generation();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
assert_ne!(s.active_generation(), closed);
|
||||
assert_ne!(s.doc().unwrap().uid, a_uid);
|
||||
assert_ne!(s.doc().unwrap().uid, b_uid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_alt_text_updates_preserve_mixed_descriptions_and_decorative_values() {
|
||||
let (mut s, a, b) = two_shapes();
|
||||
for (id, text, decorative) in [(a, "A diagram", false), (b, "A caption", true)] {
|
||||
s.execute("shape.altText", &json!({"ids": [id.0], "text": text, "decorative": decorative})).unwrap();
|
||||
}
|
||||
let descriptions = |s: &Session| [a, b].map(|id| s.doc().unwrap().shape(id).unwrap().descr.clone());
|
||||
let flags = |s: &Session| [a, b].map(|id| s.doc().unwrap().shape(id).unwrap().decorative);
|
||||
let original = descriptions(&s);
|
||||
assert_ne!(original[0], original[1]);
|
||||
s.execute("shape.altText", &json!({"ids": [a.0, b.0], "decorative": true})).unwrap();
|
||||
assert_eq!(descriptions(&s), original);
|
||||
assert!(flags(&s).into_iter().all(|decorative| decorative));
|
||||
s.execute("shape.altText", &json!({"ids": [a.0], "decorative": false})).unwrap();
|
||||
assert_eq!(descriptions(&s), original);
|
||||
let mixed = flags(&s);
|
||||
assert_ne!(mixed[0], mixed[1]);
|
||||
s.execute("shape.altText", &json!({"ids": [a.0, b.0], "text": ""})).unwrap();
|
||||
assert!(descriptions(&s).iter().all(String::is_empty));
|
||||
assert_eq!(flags(&s), mixed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editor_replacements_report_autocorrection_and_cancel_only_the_open_session() {
|
||||
let mut s = session();
|
||||
let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0;
|
||||
let original = "(c)";
|
||||
s.execute("text.set", &json!({"id": title, "text": original})).unwrap();
|
||||
s.execute("text.edit", &json!({"id": title})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let at = original.chars().count();
|
||||
let corrected = cmd::text::correct_word(&s.prefs, original, true, true).unwrap();
|
||||
let expected = format!("{corrected} ");
|
||||
let written = s.replace_text_range(at..at, " ", crate::TextReplaceKind::Typed).unwrap();
|
||||
assert_eq!(title_text(&s), expected);
|
||||
assert_eq!(written.range, 0..expected.chars().count());
|
||||
assert_eq!(written.selection.caret, (0, expected.chars().count()));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let before = s.doc().unwrap().clone();
|
||||
assert!(s.replace_text_range(0..usize::MAX, "x", crate::TextReplaceKind::Typed).is_err());
|
||||
let after = s.doc().unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&before.doc, &after.doc));
|
||||
assert_eq!(after.selection, before.selection);
|
||||
assert_eq!(after.history.undo.len(), before.history.undo.len());
|
||||
s.finish_text_edit_session(true).unwrap();
|
||||
assert_eq!(title_text(&s), original);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
let restored = s.doc().unwrap().doc.clone();
|
||||
s.finish_text_edit_session(true).unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&restored, &s.doc().unwrap().doc));
|
||||
s.execute("text.exit", &json!({})).unwrap();
|
||||
s.execute("text.edit", &json!({"id": title})).unwrap();
|
||||
s.finish_text_edit_session(true).unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&restored, &s.doc().unwrap().doc));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
@@ -196,6 +196,10 @@ enum Drag {
|
||||
start: Point,
|
||||
add: bool,
|
||||
},
|
||||
/// Dragging drawing guide `index`.
|
||||
Guide {
|
||||
index: usize,
|
||||
},
|
||||
Create {
|
||||
start: Point,
|
||||
},
|
||||
@@ -274,9 +278,6 @@ pub struct ToolState {
|
||||
pub path_closing: bool,
|
||||
/// Whether the last freeform press added a vertex (it adds none at the point cap).
|
||||
pub press_added_vertex: bool,
|
||||
/// A smaller cap for tests that exercise freeform presses.
|
||||
#[cfg(test)]
|
||||
pub(crate) freeform_press_point_cap: Option<usize>,
|
||||
/// The shape in Edit Points: its vertices are handles instead of the box's.
|
||||
pub edit_points: Option<ShapeId>,
|
||||
/// The vertex (path, index) whose control handles show in Edit Points.
|
||||
@@ -288,8 +289,12 @@ pub struct ToolState {
|
||||
pub edit_segment_t: Option<f64>,
|
||||
/// The point type last chosen for a vertex (shape, path, index, type): handle drags follow it.
|
||||
pub vertex_kind: Option<(ShapeId, usize, usize, String)>,
|
||||
/// Drawing guides are shown (View › Guides): shapes snap to them.
|
||||
/// Drawing guides are shown (View › Guides): they can be dragged and shapes snap to them.
|
||||
pub guides_visible: bool,
|
||||
/// The guide being dragged and where it is now (slide points); `None` once dropped.
|
||||
pub guide_drag: Option<(usize, f64)>,
|
||||
/// The drawing guide under the pointer, for the cursor.
|
||||
pub guide_hover: Option<usize>,
|
||||
/// Pressure from the pointer event being handled, if the device reported one.
|
||||
pressure: Option<f32>,
|
||||
}
|
||||
@@ -313,15 +318,6 @@ impl ToolState {
|
||||
pub fn drawing_freeform(&self) -> bool {
|
||||
matches!(self.drag, Some(Drag::Freeform { .. }))
|
||||
}
|
||||
|
||||
/// Most vertices freeform presses place: [`MAX_GESTURE_POINTS`], or a smaller cap a test sets.
|
||||
pub(crate) fn press_point_cap(&self) -> usize {
|
||||
#[cfg(test)]
|
||||
if let Some(cap) = self.freeform_press_point_cap {
|
||||
return cap;
|
||||
}
|
||||
MAX_GESTURE_POINTS
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle positions in slide coordinates for a box (8 resize + rotate).
|
||||
|
||||
@@ -24,6 +24,13 @@ impl Session {
|
||||
}
|
||||
let Some(drag) = self.tool.drag.clone() else { return Ok(Value::Null) };
|
||||
match drag {
|
||||
Drag::Guide { index } => {
|
||||
let vertical = self.active().and_then(|d| d.doc.guides.get(index)).is_some_and(|g| g.vertical);
|
||||
let pos = if vertical { p.x } else { p.y };
|
||||
// Guides move in whole points unless snapping is off, as in PowerPoint.
|
||||
let pos = if self.prefs.snap_to_grid && !mods.alt { pos.round() } else { pos };
|
||||
self.tool.guide_drag = Some((index, pos));
|
||||
}
|
||||
Drag::Move { ids, start, origs, moved, duplicate, enter_text } => {
|
||||
return self.drag_move(MoveDrag { ids, start, origs, moved, duplicate, enter_text }, p, mods, tol);
|
||||
}
|
||||
|
||||
@@ -115,6 +115,22 @@ impl Session {
|
||||
})
|
||||
}
|
||||
|
||||
/// The drawing guide within `tol` of `p` (only while guides are shown).
|
||||
pub fn guide_at(&self, p: Point, tol: f64) -> Option<usize> {
|
||||
if !self.tool.guides_visible {
|
||||
return None;
|
||||
}
|
||||
let st = self.active()?;
|
||||
st.doc
|
||||
.guides
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, g)| (i, if g.vertical { (p.x - g.pos).abs() } else { (p.y - g.pos).abs() }))
|
||||
.filter(|(_, d)| *d <= tol.max(2.0))
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// Smart guides: snap `r` edges/centres to the slide and other shapes. Returns the offset to
|
||||
/// apply and the guides to draw.
|
||||
pub(super) fn snap_rect(&self, r: Rect, exclude: &[ShapeId], tol: f64, enabled: bool) -> (Vec2, Vec<Guide>) {
|
||||
|
||||
@@ -14,10 +14,6 @@ impl Session {
|
||||
|
||||
/// What's under `p` on the current slide.
|
||||
pub fn hit_test(&self, p: Point, tol: f64) -> Option<Hit> {
|
||||
self.hit_test_with_transform(p, tol, true)
|
||||
}
|
||||
|
||||
fn hit_test_with_transform(&self, p: Point, tol: f64, transform: bool) -> Option<Hit> {
|
||||
let st = self.active()?;
|
||||
// In Edit Points, the edited shape's vertices come first.
|
||||
if let Some(id) = self.tool.editing_points(st)
|
||||
@@ -65,15 +61,13 @@ impl Session {
|
||||
return Some(Hit::Warp { id: *id, index: hd.index });
|
||||
}
|
||||
}
|
||||
if transform {
|
||||
let (pts, rot) = box_handles(&x);
|
||||
if (rot - p).hypot() <= tol * 1.8 && st.selection.text.is_none() {
|
||||
return Some(Hit::Rotate { id: *id });
|
||||
}
|
||||
for (i, q) in pts.iter().enumerate() {
|
||||
if (*q - p).hypot() <= tol * 1.6 {
|
||||
return Some(Hit::Resize { id: *id, handle: i as u8 });
|
||||
}
|
||||
let (pts, rot) = box_handles(&x);
|
||||
if (rot - p).hypot() <= tol * 1.8 && st.selection.text.is_none() {
|
||||
return Some(Hit::Rotate { id: *id });
|
||||
}
|
||||
for (i, q) in pts.iter().enumerate() {
|
||||
if (*q - p).hypot() <= tol * 1.6 {
|
||||
return Some(Hit::Resize { id: *id, handle: i as u8 });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,10 +96,6 @@ impl Session {
|
||||
|
||||
/// Feed a pointer event to the active tool. Returns what happened (for agents).
|
||||
pub fn pointer(&mut self, ev: PointerEvent) -> Result<Value> {
|
||||
self.pointer_route(ev, None)
|
||||
}
|
||||
|
||||
fn pointer_route(&mut self, ev: PointerEvent, transform_hit: Option<Option<Hit>>) -> Result<Value> {
|
||||
let tol = if ev.tol > 0.0 { ev.tol } else { 4.0 };
|
||||
let p = Point::new(ev.x, ev.y);
|
||||
self.tool.pressure = ev.pressure.filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1.0));
|
||||
@@ -116,8 +106,7 @@ impl Session {
|
||||
if !matches!(ev.kind, PointerKind::Move) {
|
||||
self.settle_composition();
|
||||
}
|
||||
let before_target = self.text_selection().map(|(shape, cell, notes, _, _)| (shape, cell, notes));
|
||||
let result = match ev.kind {
|
||||
match ev.kind {
|
||||
PointerKind::Move => {
|
||||
if let Some(Drag::Freeform { points, mode, .. }) = &self.tool.drag {
|
||||
let closing = points.len() > 2 && points.first().is_some_and(|s| (*s - p).hypot() <= tol * 2.0);
|
||||
@@ -128,7 +117,9 @@ impl Session {
|
||||
self.tool.path_closing = closing;
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
self.tool.hover = self.pointer_hit(p, tol, transform_hit);
|
||||
self.tool.hover = self.hit_test(p, tol);
|
||||
self.tool.guide_hover =
|
||||
if self.tool.hover.is_none() && matches!(self.tool.kind, ToolKind::Select) { self.guide_at(p, tol) } else { None };
|
||||
let line_tool = matches!(&self.tool.kind, ToolKind::Shape { preset } if deckcraft_geom::preset::is_line_like(preset));
|
||||
if line_tool {
|
||||
self.update_sites(p, tol, None);
|
||||
@@ -138,7 +129,7 @@ impl Session {
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}
|
||||
PointerKind::Down => self.down(p, ev.mods, tol, transform_hit),
|
||||
PointerKind::Down => self.down(p, ev.mods, tol),
|
||||
PointerKind::Drag => self.drag(p, ev.mods, tol),
|
||||
PointerKind::Up => self.up(p, ev.mods),
|
||||
PointerKind::DoubleClick => {
|
||||
@@ -156,18 +147,6 @@ impl Session {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
}
|
||||
};
|
||||
let after_target = self.text_selection().map(|(shape, cell, notes, _, _)| (shape, cell, notes));
|
||||
if result.is_ok() && after_target.is_some() && after_target != before_target {
|
||||
self.begin_text_edit_session()?;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn pointer_hit(&self, p: Point, tol: f64, transform_hit: Option<Option<Hit>>) -> Option<Hit> {
|
||||
match transform_hit {
|
||||
Some(hit) => hit.or_else(|| self.hit_test_with_transform(p, tol, false)),
|
||||
None => self.hit_test(p, tol),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,29 +189,15 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancels a point or handle drag in Edit Points when Esc is pressed (`cancel_drag`). Returns whether a drag was
|
||||
/// cancelled.
|
||||
/// Cancels a point or handle drag in Edit Points when Esc is pressed: ends the drag, puts back the
|
||||
/// document and selection saved at the press, and adds no undo step. Returns whether a drag was cancelled.
|
||||
pub(crate) fn cancel_point_drag(&mut self) -> bool {
|
||||
if !matches!(self.tool.drag, Some(Drag::Vertex { .. } | Drag::Handle { .. })) {
|
||||
return false;
|
||||
}
|
||||
self.cancel_drag();
|
||||
true
|
||||
}
|
||||
|
||||
/// Abandons the pointer drag in progress, as a cancelled press does: ends the drag without committing it, clears
|
||||
/// its previews, puts back the document and selection saved at the press, and adds no undo step.
|
||||
pub fn cancel_drag(&mut self) {
|
||||
if self.tool.drag.take().is_none() {
|
||||
return;
|
||||
}
|
||||
self.tool.preview = None;
|
||||
self.tool.marquee = None;
|
||||
self.tool.guides.clear();
|
||||
self.tool.path_preview.clear();
|
||||
self.tool.path_closing = false;
|
||||
self.tool.ink_preview.clear();
|
||||
self.tool.drag = None;
|
||||
if let Some(st) = self.active_mut()
|
||||
&& st.interaction.as_ref().is_some_and(|i| i.label == "Edit Points")
|
||||
&& let Some(i) = st.interaction.take()
|
||||
{
|
||||
// A modifier held during the drag may have set a point type; the drag is undone, so is that.
|
||||
@@ -244,6 +209,7 @@ impl Session {
|
||||
}
|
||||
self.tool.vertex_kind = kind;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// End the interaction only when it is the one `label` started. A twist must not commit a drag.
|
||||
@@ -255,14 +221,14 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Handle a pointer press and start the applicable tool interaction.
|
||||
fn down(&mut self, p: Point, mods: Mods, tol: f64, transform_hit: Option<Option<Hit>>) -> Result<Value> {
|
||||
fn down(&mut self, p: Point, mods: Mods, tol: f64) -> Result<Value> {
|
||||
if let Some(Drag::Freeform { mode, mut points, .. }) = self.tool.drag.clone() {
|
||||
// Next click of a freeform: close on the start point, else add a vertex.
|
||||
if points.len() > 2 && points.first().is_some_and(|s| (*s - p).hypot() <= tol * 2.0) {
|
||||
self.tool.drag = Some(Drag::Freeform { mode, points, pressed: false });
|
||||
return self.finish_freeform(true);
|
||||
}
|
||||
self.tool.press_added_vertex = points.len() < self.tool.press_point_cap();
|
||||
self.tool.press_added_vertex = points.len() < super::MAX_GESTURE_POINTS;
|
||||
if self.tool.press_added_vertex {
|
||||
points.push(p);
|
||||
}
|
||||
@@ -300,13 +266,12 @@ impl Session {
|
||||
}
|
||||
// Clicking inside the text being edited moves the caret / starts a text selection.
|
||||
let before = self.text_selection();
|
||||
let canonical_transform = matches!(transform_hit, Some(Some(Hit::Resize { .. } | Hit::Rotate { .. })));
|
||||
if !canonical_transform && let Some((shape, pos)) = self.place_caret(p, tol, mods.shift)? {
|
||||
if let Some((shape, pos)) = self.place_caret(p, tol, mods.shift)? {
|
||||
let press = self.doc()?.selection.text.clone();
|
||||
self.tool.drag = Some(Drag::TextSelect { shape, before, press });
|
||||
return Ok(json!({"caret": [pos.0, pos.1]}));
|
||||
}
|
||||
let hit = self.pointer_hit(p, tol, transform_hit);
|
||||
let hit = self.hit_test(p, tol);
|
||||
// Edit Points: drag a vertex, Ctrl-click one to delete it or the outline to add one;
|
||||
// a click anywhere else leaves Edit Points.
|
||||
if let Some(eid) = self.doc().ok().and_then(|st| self.tool.editing_points(st)) {
|
||||
@@ -455,6 +420,14 @@ impl Session {
|
||||
let _ = self.execute("animation.painterApply", &json!({"ids": [id]}));
|
||||
}
|
||||
}
|
||||
None if self.guide_at(p, tol).is_some() => {
|
||||
// Away from every shape a press on a guide picks the guide up.
|
||||
if let Some(index) = self.guide_at(p, tol) {
|
||||
let pos = st.doc.guides.get(index).map(|g| g.pos).unwrap_or(0.0);
|
||||
self.tool.drag = Some(Drag::Guide { index });
|
||||
self.tool.guide_drag = Some((index, pos));
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let add = mods.shift || mods.cmd;
|
||||
self.select(|_, sel| {
|
||||
@@ -479,6 +452,18 @@ impl Session {
|
||||
self.tool.glue = None;
|
||||
let mut out = Value::Null;
|
||||
match drag {
|
||||
Some(Drag::Guide { index }) => {
|
||||
// Dropped off the slide: the guide is deleted.
|
||||
let (_, pos) = self.tool.guide_drag.take().unwrap_or((index, 0.0));
|
||||
let size = self.doc()?.doc.slide_size;
|
||||
let vertical = self.doc()?.doc.guides.get(index).is_some_and(|g| g.vertical);
|
||||
let limit = if vertical { size.width } else { size.height };
|
||||
out = if pos < 0.0 || pos > limit {
|
||||
self.execute("guide.delete", &json!({"index": index}))?
|
||||
} else {
|
||||
self.execute("guide.move", &json!({"index": index, "pos": pos}))?
|
||||
};
|
||||
}
|
||||
Some(Drag::Move { moved: false, enter_text: Some((id, at)), .. })
|
||||
// Plain click on text: caret at the click (in a table, in the clicked cell).
|
||||
if self.edit_text_at(id, at)? => {
|
||||
@@ -616,11 +601,3 @@ impl Session {
|
||||
self.active().and_then(|d| d.shape(id)).is_some_and(|s| matches!(s.kind, ShapeKind::Picture { .. } | ShapeKind::Media(_)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Uses the canvas's canonical resize/rotate hit for hover and press, preserving its chosen drag on drag/up.
|
||||
/// `None` suppresses transform re-hits while retaining ordinary shape, text and edit-point hits.
|
||||
pub fn pointer_with_hit(&mut self, ev: PointerEvent, transform_hit: Option<Hit>) -> Result<Value> {
|
||||
self.pointer_route(ev, Some(transform_hit))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ description = "DeckCraft fonts: font database (craft-fonts + system), substitute
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft = { workspace = true, features = ["font-catalog"] }
|
||||
kurbo = { workspace = true }
|
||||
skrifa = { workspace = true }
|
||||
harfrust = { workspace = true }
|
||||
|
||||
+446
-294
@@ -1,10 +1,10 @@
|
||||
//! Document font shaping and outlines over the shared font catalogue.
|
||||
//! Font database: bundled OFL fonts, user fonts, the installed system fonts (cataloged the first
|
||||
//! time a lookup needs them, native only), outline cache.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
use craft::font_catalog::{Catalog, FontEnv, Limits, Os, Source};
|
||||
use kurbo::BezPath;
|
||||
use skrifa::instance::{Location, LocationRef, Size};
|
||||
use skrifa::outline::{DrawSettings, OutlinePen};
|
||||
@@ -170,7 +170,7 @@ pub const MISSING_FONT_FAMILY: &str = "Calibri";
|
||||
#[derive(Clone)]
|
||||
enum FontBytes {
|
||||
Static(&'static [u8]),
|
||||
Owned(Arc<[u8]>),
|
||||
Owned(Arc<Vec<u8>>),
|
||||
}
|
||||
|
||||
/// One loaded font face.
|
||||
@@ -279,7 +279,7 @@ impl FontFace {
|
||||
pub fn data(&self) -> &[u8] {
|
||||
match &self.bytes {
|
||||
FontBytes::Static(b) => b,
|
||||
FontBytes::Owned(v) => v,
|
||||
FontBytes::Owned(v) => v.as_slice(),
|
||||
}
|
||||
}
|
||||
pub fn skrifa(&self) -> Option<skrifa::FontRef<'_>> {
|
||||
@@ -357,37 +357,47 @@ impl FontFace {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[derive(Clone, Debug)]
|
||||
struct CatalogEntry {
|
||||
family: String,
|
||||
style: String,
|
||||
path: std::path::PathBuf,
|
||||
}
|
||||
|
||||
/// Process-wide font database.
|
||||
pub struct FontDb {
|
||||
faces: RwLock<Vec<Arc<FontFace>>>,
|
||||
outlines: Mutex<OutlineCache>,
|
||||
catalog: Arc<Catalog>,
|
||||
scope: CatalogScope,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
catalog: RwLock<Vec<CatalogEntry>>,
|
||||
/// The folders the system font scan reads (the platform's font folders for [`FontDb::global`]).
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
font_dirs: Vec<std::path::PathBuf>,
|
||||
/// Set once the font folders have been scanned. Lookups by family name wait for the first
|
||||
/// scan, so what they find doesn't depend on what ran before them.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
cataloged: std::sync::OnceLock<()>,
|
||||
/// Families (lower case) whose cataloged files have all been loaded: a family's files load
|
||||
/// together, so a lookup never settles for the one face another name loaded ("Segoe UI
|
||||
/// Semibold" loads a face of the family "Segoe UI").
|
||||
loaded_families: Mutex<(u64, std::collections::HashSet<String>)>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
loaded_families: Mutex<std::collections::HashSet<String>>,
|
||||
/// System fallback state: enabled, and characters no system font covers.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
sys: Mutex<SysFallback>,
|
||||
/// Serializes broad coverage searches so parallel misses do not repeat file loads.
|
||||
/// Held while installed fonts are loaded, so threads that need the same family wait for one
|
||||
/// load instead of racing it: what a lookup finds doesn't depend on which thread got there
|
||||
/// first.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
loading: Mutex<()>,
|
||||
}
|
||||
|
||||
enum CatalogScope {
|
||||
Process,
|
||||
Isolated,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[derive(Default)]
|
||||
struct SysFallback {
|
||||
enabled: bool,
|
||||
misses: std::collections::HashSet<char>,
|
||||
plain_misses: std::collections::HashSet<char>,
|
||||
color_misses: std::collections::HashSet<char>,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
/// Does face `index` of `data` carry colour glyph tables?
|
||||
@@ -499,6 +509,213 @@ fn instance_legacy_names(family: &str, style: &str) -> Option<(String, String)>
|
||||
Some((format!("{family} {weight}"), if style_italic(style) { "Italic" } else { "Regular" }.into()))
|
||||
}
|
||||
|
||||
/// The tables skrifa reads glyph outlines from: `glyf` (TrueType), `CFF `, `CFF2` and `VARC`. For a
|
||||
/// face with none of them (bitmaps only, or outlines in Apple's `hvgl` table), [`FontDb::outline`]
|
||||
/// returns an empty path for every glyph.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const OUTLINE_TABLES: [&[u8; 4]; 4] = [b"glyf", b"CFF ", b"CFF2", b"VARC"];
|
||||
|
||||
/// (family, style) of every face in the font file at `path`, reading only its table directories
|
||||
/// and `name` tables: a scan opens hundreds of font files, many of them megabytes long. A
|
||||
/// variable font is cataloged under its default style; its named instances appear once it loads.
|
||||
/// Faces with none of the [`OUTLINE_TABLES`] are left out.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn file_face_names(path: &std::path::Path) -> Vec<(String, String)> {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
/// Caps on what a (possibly damaged) file can make the scan read.
|
||||
const MAX_FACES: u32 = 256;
|
||||
const MAX_NAME_TABLE: u32 = 1 << 20;
|
||||
let Ok(mut file) = std::fs::File::open(path) else { return vec![] };
|
||||
let mut read_at = |offset: u64, len: usize| -> Option<Vec<u8>> {
|
||||
let mut buf = vec![0; len];
|
||||
file.seek(SeekFrom::Start(offset)).ok()?;
|
||||
file.read_exact(&mut buf).ok()?;
|
||||
Some(buf)
|
||||
};
|
||||
let be32 = |b: &[u8], at: usize| b.get(at..at + 4).and_then(|s| s.try_into().ok()).map(u32::from_be_bytes);
|
||||
let Some(head) = read_at(0, 12) else { return vec![] };
|
||||
// A collection lists where each face's table directory starts.
|
||||
let starts: Vec<u32> = if head.starts_with(b"ttcf") {
|
||||
let n = be32(&head, 8).unwrap_or(0).min(MAX_FACES) as usize;
|
||||
read_at(12, n * 4).map(|b| b.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes(*c)).collect()).unwrap_or_default()
|
||||
} else {
|
||||
vec![0]
|
||||
};
|
||||
starts
|
||||
.into_iter()
|
||||
.filter_map(|start| {
|
||||
let dir = read_at(start.into(), 12)?;
|
||||
let tables = u16::from_be_bytes(dir.get(4..6)?.try_into().ok()?) as usize;
|
||||
let records = read_at(u64::from(start) + 12, tables * 16)?;
|
||||
if !records.as_chunks::<16>().0.iter().any(|r| OUTLINE_TABLES.iter().any(|t| r.starts_with(*t))) {
|
||||
return None;
|
||||
}
|
||||
let rec = records.as_chunks::<16>().0.iter().find(|r| r.starts_with(b"name"))?;
|
||||
let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?);
|
||||
if len > MAX_NAME_TABLE {
|
||||
return None;
|
||||
}
|
||||
let table = read_at(offset.into(), len as usize)?;
|
||||
// A one-table font holding just the `name` table, to read it as the font itself would.
|
||||
let mut font = Vec::with_capacity(28 + table.len());
|
||||
font.extend_from_slice(&0x0001_0000_u32.to_be_bytes());
|
||||
font.extend_from_slice(&[0, 1, 0, 16, 0, 0, 0, 0]);
|
||||
font.extend_from_slice(b"name");
|
||||
for v in [0, 28, len] {
|
||||
font.extend_from_slice(&u32::to_be_bytes(v));
|
||||
}
|
||||
font.extend_from_slice(&table);
|
||||
let f = skrifa::FontRef::new(&font).ok()?;
|
||||
let (family, style) = face_names(&f)?;
|
||||
// Cataloged under its Windows family too, so "Segoe UI Semibold" finds the file.
|
||||
let legacy = legacy_names(&f, &family);
|
||||
Some(std::iter::once((family, style)).chain(legacy))
|
||||
})
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Folder depth below a font folder that the system scan descends.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_SCAN_DEPTH: usize = 12;
|
||||
/// Directory entries the system scan looks at in all.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_SCAN_ENTRIES: usize = 200_000;
|
||||
/// The largest font file read (the biggest CJK collections are a few hundred MB).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub const MAX_FONT_FILE: u64 = 512 << 20;
|
||||
|
||||
/// A regular file of a size a font can have.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn font_file_ok(meta: &std::fs::Metadata) -> bool {
|
||||
meta.is_file() && meta.len() > 12 && meta.len() <= MAX_FONT_FILE
|
||||
}
|
||||
|
||||
/// The platform's font folders (the system's and the user's), scanned by [`FontDb::global`].
|
||||
/// Empty on wasm.
|
||||
pub fn system_font_dirs() -> Vec<std::path::PathBuf> {
|
||||
let mut dirs: Vec<std::path::PathBuf> = Vec::new();
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return dirs;
|
||||
}
|
||||
let home = std::env::var_os("HOME").map(std::path::PathBuf::from);
|
||||
if cfg!(target_os = "macos") {
|
||||
dirs.extend(["/System/Library/Fonts", "/Library/Fonts"].map(Into::into));
|
||||
if let Some(h) = &home {
|
||||
dirs.push(h.join("Library/Fonts"));
|
||||
// Fonts Microsoft Office downloads on demand (Aptos…), used where Office put them.
|
||||
dirs.push(h.join("Library/Group Containers/UBF8T346G9.Office/FontCache/4/CloudFonts"));
|
||||
}
|
||||
// Fonts Office installs inside its apps.
|
||||
for app in ["Microsoft PowerPoint", "Microsoft Word", "Microsoft Excel"] {
|
||||
dirs.push(std::path::PathBuf::from(format!("/Applications/{app}.app/Contents/Resources/DFonts")));
|
||||
}
|
||||
// Fonts macOS ships as assets (PingFang, Yu Mincho, …): com_apple_MobileAsset_Font<N>.
|
||||
for parent in ["/System/Library/AssetsV2", "/System/Library/AssetsV2/PreinstalledAssetsV2/InstallWithOs"] {
|
||||
let Ok(entries) = std::fs::read_dir(parent) else { continue };
|
||||
for e in entries.flatten() {
|
||||
if e.file_name().to_string_lossy().starts_with("com_apple_MobileAsset_Font") {
|
||||
dirs.push(e.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if cfg!(windows) {
|
||||
let root = std::env::var_os("WINDIR").map(std::path::PathBuf::from).unwrap_or_else(|| "C:\\Windows".into());
|
||||
dirs.push(root.join("Fonts"));
|
||||
if let Some(l) = std::env::var_os("LOCALAPPDATA") {
|
||||
let l = std::path::PathBuf::from(l);
|
||||
dirs.push(l.join("Microsoft\\Windows\\Fonts"));
|
||||
// Fonts Microsoft Office downloads on demand (Aptos…), used where Office put them;
|
||||
// DeckCraft never ships or needs them.
|
||||
dirs.push(l.join("Microsoft\\FontCache\\4\\CloudFonts"));
|
||||
}
|
||||
} else {
|
||||
dirs.extend(["/usr/share/fonts", "/usr/local/share/fonts"].map(Into::into));
|
||||
if let Some(h) = &home {
|
||||
dirs.push(h.join(".fonts"));
|
||||
dirs.push(h.join(".local/share/fonts"));
|
||||
}
|
||||
let env = |k: &str| std::env::var_os(k).map(|v| v.to_string_lossy().into_owned());
|
||||
dirs.extend(xdg_font_dirs(env("XDG_DATA_HOME").as_deref(), env("XDG_DATA_DIRS").as_deref(), home.as_deref()));
|
||||
// Inside Flatpak the host's fonts are mounted here.
|
||||
dirs.extend(["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"].map(Into::into));
|
||||
// Folders fontconfig is configured with (NixOS, Guix, custom setups).
|
||||
for conf in fontconfig_files() {
|
||||
if let Ok(text) = std::fs::read_to_string(&conf) {
|
||||
dirs.extend(fontconfig_dirs(&text, env("XDG_DATA_HOME").as_deref(), home.as_deref()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
dirs.retain(|d| seen.insert(d.clone()));
|
||||
dirs
|
||||
}
|
||||
|
||||
/// `<data dir>/fonts` for `XDG_DATA_HOME` (default `~/.local/share`) and each `XDG_DATA_DIRS`
|
||||
/// entry (default `/usr/local/share:/usr/share`).
|
||||
fn xdg_font_dirs(data_home: Option<&str>, data_dirs: Option<&str>, home: Option<&std::path::Path>) -> Vec<std::path::PathBuf> {
|
||||
let mut v = vec![];
|
||||
match data_home.filter(|d| !d.is_empty()) {
|
||||
Some(d) => v.push(std::path::Path::new(d).join("fonts")),
|
||||
None => {
|
||||
if let Some(h) = home {
|
||||
v.push(h.join(".local/share/fonts"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let dirs = data_dirs.filter(|d| !d.is_empty()).unwrap_or("/usr/local/share:/usr/share");
|
||||
v.extend(dirs.split(':').filter(|d| d.starts_with('/')).take(64).map(|d| std::path::Path::new(d).join("fonts")));
|
||||
v
|
||||
}
|
||||
|
||||
/// The fontconfig configuration files: `/etc/fonts/fonts.conf` and `/etc/fonts/conf.d/*.conf`.
|
||||
fn fontconfig_files() -> Vec<std::path::PathBuf> {
|
||||
let mut v = vec![std::path::PathBuf::from("/etc/fonts/fonts.conf"), std::path::PathBuf::from("/etc/fonts/local.conf")];
|
||||
if let Ok(entries) = std::fs::read_dir("/etc/fonts/conf.d") {
|
||||
let mut files: Vec<_> = entries.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "conf")).collect();
|
||||
files.sort();
|
||||
files.truncate(512);
|
||||
v.extend(files);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The `<dir>` folders of a fontconfig file (`prefix="xdg"` is under `XDG_DATA_HOME`, a leading
|
||||
/// `~` under home; relative and `cachedir` entries are skipped).
|
||||
fn fontconfig_dirs(text: &str, data_home: Option<&str>, home: Option<&std::path::Path>) -> Vec<std::path::PathBuf> {
|
||||
let mut v = vec![];
|
||||
let mut rest = text;
|
||||
while let Some(start) = rest.find("<dir") {
|
||||
let after = &rest[start + 4..];
|
||||
// `<dir>` or `<dir …>`, not `<dirname>`.
|
||||
if !(after.starts_with('>') || after.starts_with(' ')) {
|
||||
rest = after;
|
||||
continue;
|
||||
}
|
||||
let Some(gt) = after.find('>') else { break };
|
||||
let attrs = &after[..gt];
|
||||
let body = &after[gt + 1..];
|
||||
let Some(end) = body.find("</dir>") else { break };
|
||||
let path = body[..end].trim();
|
||||
rest = &body[end..];
|
||||
if attrs.trim_end().ends_with('/') || path.is_empty() || v.len() >= 64 {
|
||||
continue;
|
||||
}
|
||||
let p = if attrs.contains("prefix=\"xdg\"") {
|
||||
let base = data_home.filter(|d| !d.is_empty()).map(std::path::PathBuf::from).or_else(|| home.map(|h| h.join(".local/share")));
|
||||
base.map(|b| b.join(path))
|
||||
} else if let Some(r) = path.strip_prefix("~/") {
|
||||
home.map(|h| h.join(r))
|
||||
} else if path.starts_with('/') {
|
||||
Some(std::path::PathBuf::from(path))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
v.extend(p);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// One face found in a font file: index, family, style and (variable fonts) the named instance's
|
||||
/// axis settings.
|
||||
type Found = (u32, String, String, Vec<([u8; 4], f32)>);
|
||||
@@ -615,7 +832,7 @@ fn line_split(f: &skrifa::FontRef, ascent: f64, descent: f64, upem: f64) -> f64
|
||||
fn make_face(bytes: FontBytes, index: u32, family: String, style: String, coords: Vec<([u8; 4], f32)>) -> Option<FontFace> {
|
||||
let data: &[u8] = match &bytes {
|
||||
FontBytes::Static(b) => b,
|
||||
FontBytes::Owned(v) => v,
|
||||
FontBytes::Owned(v) => v.as_slice(),
|
||||
};
|
||||
let f = skrifa::FontRef::from_index(data, index).ok()?;
|
||||
let settings: Vec<(skrifa::Tag, f32)> = coords.iter().map(|(t, v)| (skrifa::Tag::new(t), *v)).collect();
|
||||
@@ -719,20 +936,12 @@ fn style_italic(style: &str) -> bool {
|
||||
}
|
||||
|
||||
impl FontDb {
|
||||
/// An isolated database of bundled fonts and fonts discovered only in `font_dirs`.
|
||||
/// Neither platform services nor the process catalogue contribute fixture fonts.
|
||||
/// A database holding the bundled fonts, then the craft-fonts Japanese faces (Mincho first,
|
||||
/// so they are the fallback for Japanese text after the requested and bundled fonts; empty
|
||||
/// without `CRAFT_FONTS_DIR`), whose system font scan reads `font_dirs`.
|
||||
pub fn with_font_dirs(font_dirs: Vec<std::path::PathBuf>) -> Self {
|
||||
let catalog = Arc::new(Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false));
|
||||
catalog.set_app_dirs(font_dirs.clone());
|
||||
catalog.set_confined_dirs(font_dirs);
|
||||
Self::with_catalog(catalog, CatalogScope::Isolated)
|
||||
}
|
||||
|
||||
fn with_catalog(catalog: Arc<Catalog>, scope: CatalogScope) -> Self {
|
||||
let mut faces = Vec::new();
|
||||
for data in bundled() {
|
||||
// Registration also makes the bundled faces available to the browser's picker.
|
||||
let _ = catalog.add_bytes(data.to_vec(), Source::Bundled, &Limits::default());
|
||||
for (i, family, style, coords) in enumerate_faces(data) {
|
||||
if let Some(f) = make_face(FontBytes::Static(data), i, family, style, coords) {
|
||||
faces.push(Arc::new(f));
|
||||
@@ -742,9 +951,13 @@ impl FontDb {
|
||||
Self {
|
||||
faces: RwLock::new(faces),
|
||||
outlines: Mutex::new(OutlineCache::default()),
|
||||
catalog,
|
||||
scope,
|
||||
loaded_families: Mutex::new((0, std::collections::HashSet::new())),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
catalog: RwLock::new(Vec::new()),
|
||||
font_dirs,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
cataloged: std::sync::OnceLock::new(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
loaded_families: Mutex::new(std::collections::HashSet::new()),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
sys: Mutex::new(SysFallback { enabled: true, ..Default::default() }),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -774,20 +987,30 @@ impl FontDb {
|
||||
false
|
||||
}
|
||||
|
||||
/// The document adapter over the same process catalogue used by the font picker.
|
||||
/// Process-wide database: the bundled fonts, then the installed system fonts, cataloged the
|
||||
/// first time a lookup by family name needs them (or ahead of time by
|
||||
/// [`FontDb::scan_in_background`]).
|
||||
pub fn global() -> &'static FontDb {
|
||||
static DB: std::sync::OnceLock<FontDb> = std::sync::OnceLock::new();
|
||||
DB.get_or_init(|| FontDb::with_catalog(Catalog::global().clone(), CatalogScope::Process))
|
||||
DB.get_or_init(|| FontDb::with_font_dirs(system_font_dirs()))
|
||||
}
|
||||
|
||||
pub(crate) fn read_faces(&self) -> std::sync::RwLockReadGuard<'_, Vec<Arc<FontFace>>> {
|
||||
self.faces.read().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// The system font catalog, scanned first if it hasn't been yet.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn read_catalog(&self) -> std::sync::RwLockReadGuard<'_, Vec<CatalogEntry>> {
|
||||
self.ensure_catalog();
|
||||
self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Family names available (loaded plus cataloged system fonts), sorted and deduplicated.
|
||||
pub fn families(&self) -> Vec<String> {
|
||||
let mut v: Vec<String> = self.read_faces().iter().map(|f| f.family.clone()).collect();
|
||||
v.extend(self.catalog.families().iter().cloned());
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
v.extend(self.read_catalog().iter().map(|c| c.family.clone()));
|
||||
v.sort_by_key(|a| a.to_lowercase());
|
||||
v.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
|
||||
v
|
||||
@@ -801,9 +1024,10 @@ impl FontDb {
|
||||
.filter(|f| f.family.eq_ignore_ascii_case(family) && !f.style.contains('{'))
|
||||
.map(|f| (f.italic, f.weight, f.style.clone()))
|
||||
.collect();
|
||||
for c in self.catalog.styles(family) {
|
||||
if !v.iter().any(|(_, _, s)| s.eq_ignore_ascii_case(&c.style)) {
|
||||
v.push((c.italic, c.weight, c.style));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
for c in self.read_catalog().iter() {
|
||||
if c.family.eq_ignore_ascii_case(family) && !v.iter().any(|(_, _, s)| s.eq_ignore_ascii_case(&c.style)) {
|
||||
v.push((style_italic(&c.style), style_weight(&c.style), c.style.clone()));
|
||||
}
|
||||
}
|
||||
v.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)).then(a.2.cmp(&b.2)));
|
||||
@@ -814,11 +1038,7 @@ impl FontDb {
|
||||
/// Add a user font (TTF/OTF/TTC bytes). Returns the number of faces added (0 if unparseable or
|
||||
/// every face was already present).
|
||||
pub fn add_font(&self, bytes: Vec<u8>) -> usize {
|
||||
let added = self.add_fonts(vec![bytes.clone()]);
|
||||
if added > 0 {
|
||||
let _ = self.catalog.add_bytes(bytes, Source::User, &Limits::default());
|
||||
}
|
||||
added
|
||||
self.add_fonts(vec![bytes])
|
||||
}
|
||||
|
||||
/// Add font files together: lookups see all of their faces or none, never part of a family.
|
||||
@@ -829,7 +1049,7 @@ impl FontDb {
|
||||
};
|
||||
let mut new = Vec::new();
|
||||
for bytes in files {
|
||||
let data: Arc<[u8]> = bytes.into();
|
||||
let data = Arc::new(bytes);
|
||||
for (i, family, style, coords) in enumerate_faces(&data) {
|
||||
if present(&self.read_faces(), &family, &style) {
|
||||
continue;
|
||||
@@ -851,79 +1071,110 @@ impl FontDb {
|
||||
added
|
||||
}
|
||||
|
||||
/// Starts the catalogue's shared background discovery.
|
||||
/// Catalog the installed fonts unless that has been done: the first caller scans the font
|
||||
/// folders, any other waits for that scan to finish.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn ensure_catalog(&self) {
|
||||
self.cataloged.get_or_init(|| {
|
||||
self.scan_font_dirs();
|
||||
});
|
||||
}
|
||||
|
||||
/// Catalog the installed fonts on a background thread, so the first lookup by family name
|
||||
/// (opening a file, the font menus) doesn't wait for the scan. A no-op once they are
|
||||
/// cataloged, and on wasm.
|
||||
pub fn scan_in_background(&'static self) {
|
||||
self.catalog.scan_in_background();
|
||||
}
|
||||
|
||||
/// Refresh the shared discovery lifecycle, or only this database's isolated catalogue.
|
||||
/// Font data is loaded when a catalogued family is first resolved.
|
||||
/// Returns the number of faces cataloged.
|
||||
pub fn load_system_fonts(&self) -> usize {
|
||||
let count = match self.scope {
|
||||
CatalogScope::Process => {
|
||||
craft::font_catalog::app::rescan_now();
|
||||
self.catalog.faces().len()
|
||||
}
|
||||
CatalogScope::Isolated => self.catalog.rescan(),
|
||||
};
|
||||
self.invalidate_catalog();
|
||||
count
|
||||
}
|
||||
|
||||
/// Invalidates derived family lookups and coverage misses after catalogue changes.
|
||||
pub fn invalidate_catalog(&self) {
|
||||
*self.loaded_families.lock().unwrap_or_else(std::sync::PoisonError::into_inner) =
|
||||
(self.catalog.generation(), std::collections::HashSet::new());
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.refresh_misses(true);
|
||||
if self.cataloged.get().is_none() {
|
||||
// A failed spawn leaves the scan to the first lookup that needs it.
|
||||
let _ = std::thread::Builder::new().name("font-scan".into()).spawn(move || self.ensure_catalog());
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan the font folders again (fonts installed or removed since), cataloging the faces
|
||||
/// found (native only). Font data is loaded when a cataloged family is first resolved.
|
||||
/// Returns the number of faces cataloged.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn load_system_fonts(&self) -> usize {
|
||||
// Families load again from the new catalog when next looked up.
|
||||
self.loaded_families.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clear();
|
||||
// The first scan, or a rescan once it is done (never both at once).
|
||||
let mut first = None;
|
||||
self.cataloged.get_or_init(|| first = Some(self.scan_font_dirs()));
|
||||
first.unwrap_or_else(|| self.scan_font_dirs())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn scan_font_dirs(&self) -> usize {
|
||||
let mut found = Vec::new();
|
||||
let mut stack: Vec<(std::path::PathBuf, usize)> = self.font_dirs.iter().map(|d| (d.clone(), 0)).collect();
|
||||
// Each folder once, however links lead back to it.
|
||||
let mut visited = std::collections::HashSet::new();
|
||||
let mut entries = 0usize;
|
||||
while let Some((d, depth)) = stack.pop() {
|
||||
if !visited.insert(std::fs::canonicalize(&d).unwrap_or_else(|_| d.clone())) {
|
||||
continue;
|
||||
}
|
||||
let Ok(rd) = std::fs::read_dir(&d) else { continue };
|
||||
for e in rd.flatten() {
|
||||
// A link to `/` or a vast tree mustn't turn start-up into a disk crawl.
|
||||
entries += 1;
|
||||
if entries > MAX_SCAN_ENTRIES {
|
||||
log::warn!("font scan stopped after {MAX_SCAN_ENTRIES} entries");
|
||||
stack.clear();
|
||||
break;
|
||||
}
|
||||
let p = e.path();
|
||||
// Follows links: what matters is what the entry leads to.
|
||||
let Ok(meta) = std::fs::metadata(&p) else { continue };
|
||||
if meta.is_dir() {
|
||||
if depth < MAX_SCAN_DEPTH {
|
||||
stack.push((p, depth + 1));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let ext = p.extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase);
|
||||
if !matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) {
|
||||
continue;
|
||||
}
|
||||
// Only regular files: opening a FIFO named like a font blocks until something
|
||||
// writes to it (start-up hung), and a device never ends.
|
||||
if !font_file_ok(&meta) {
|
||||
continue;
|
||||
}
|
||||
for (family, style) in file_face_names(&p) {
|
||||
found.push(CatalogEntry { family, style, path: p.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
let n = found.len();
|
||||
log::debug!("cataloged {n} system font faces");
|
||||
*self.catalog.write().unwrap_or_else(std::sync::PoisonError::into_inner) = found;
|
||||
n
|
||||
}
|
||||
|
||||
/// Load the files of the installed `family` (faces already loaded are kept). Returns whether
|
||||
/// it is loaded.
|
||||
fn load_cataloged(&self, family: &str) -> bool {
|
||||
let loaded = self.catalog.load_family(family);
|
||||
for face in loaded.iter() {
|
||||
self.add_catalog_face(&face.info, &face.data);
|
||||
}
|
||||
if loaded.is_empty() {
|
||||
// A Windows family name: only the files of its faces, not their whole family.
|
||||
for info in self.legacy_faces(family) {
|
||||
if let Ok(data) = self.catalog.load(&info) {
|
||||
self.add_catalog_face(&info, &data);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.is_loaded(family)
|
||||
}
|
||||
|
||||
fn add_catalog_face(&self, info: &craft::font_catalog::FaceInfo, data: &craft::font_catalog::FontData) {
|
||||
let present =
|
||||
|faces: &[Arc<FontFace>]| faces.iter().any(|f| f.family.eq_ignore_ascii_case(&info.family) && f.style.eq_ignore_ascii_case(&info.style));
|
||||
if present(&self.read_faces()) {
|
||||
return;
|
||||
}
|
||||
let Some(face) =
|
||||
make_face(FontBytes::Owned(data.bytes.clone()), data.index, info.family.clone(), info.style.clone(), info.variations.clone())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut faces = self.faces.write().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if !present(&faces) {
|
||||
faces.push(Arc::new(face));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn refresh_misses(&self, force: bool) {
|
||||
let generation = self.catalog.generation();
|
||||
let mut sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if force || sys.generation != generation {
|
||||
sys.generation = generation;
|
||||
sys.misses.clear();
|
||||
sys.plain_misses.clear();
|
||||
sys.color_misses.clear();
|
||||
}
|
||||
fn load_cataloged(&self, family: &str) -> bool {
|
||||
let loading = self.loading.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
self.load_family(family, &loading)
|
||||
}
|
||||
|
||||
/// [`FontDb::load_cataloged`] for a caller already holding `loading`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_family(&self, family: &str, _loading: &std::sync::MutexGuard<'_, ()>) -> bool {
|
||||
// Not skipped when some face of the family is loaded: a lookup by a Windows family name
|
||||
// loads only that style's file, and the family's other files must still load later.
|
||||
let paths: Vec<std::path::PathBuf> = {
|
||||
let cat = self.read_catalog();
|
||||
let mut p: Vec<_> = cat.iter().filter(|c| c.family.eq_ignore_ascii_case(family)).map(|c| c.path.clone()).collect();
|
||||
p.sort();
|
||||
p.dedup();
|
||||
p
|
||||
};
|
||||
self.add_fonts(paths.iter().filter(|p| std::fs::metadata(p).is_ok_and(|m| font_file_ok(&m))).filter_map(|p| std::fs::read(p).ok()).collect());
|
||||
self.is_loaded(family)
|
||||
}
|
||||
|
||||
/// Resolve a family + style to a face, falling back to the closest style of the family, then to
|
||||
@@ -972,24 +1223,16 @@ impl FontDb {
|
||||
// Every installed file of the family first, so the best style is among the candidates. The
|
||||
// lock is held while the files load, so another thread looking up the family waits for
|
||||
// them rather than finding none and falling back to another family.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let mut loaded = self.loaded_families.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
// Snapshot discovery before recording its generation, including the first lazy scan.
|
||||
let _ = self.catalog.families();
|
||||
let generation = self.catalog.generation();
|
||||
if loaded.0 != generation {
|
||||
*loaded = (generation, std::collections::HashSet::new());
|
||||
}
|
||||
let key = family.to_lowercase();
|
||||
if !loaded.1.contains(&key) {
|
||||
if !loaded.contains(&key) {
|
||||
self.load_cataloged(family);
|
||||
loaded.1.insert(key);
|
||||
loaded.insert(key);
|
||||
}
|
||||
}
|
||||
self.find(family, style).or_else(|| {
|
||||
let (info, _) = self.catalog.resolve(family, base_style(style))?;
|
||||
self.find(&info.family, if style.contains('{') { style } else { &info.style })
|
||||
})
|
||||
self.find(family, style)
|
||||
}
|
||||
|
||||
/// Is `family` available (loaded, or installed on the system)?
|
||||
@@ -997,14 +1240,11 @@ impl FontDb {
|
||||
if self.is_loaded(family) {
|
||||
return true;
|
||||
}
|
||||
self.catalog.family(family).is_some() || !self.legacy_faces(family).is_empty()
|
||||
}
|
||||
|
||||
/// The cataloged faces whose Windows family is `family` ("Segoe UI Semibold"): the catalogue
|
||||
/// lists them under their typographic family only.
|
||||
fn legacy_faces(&self, family: &str) -> Vec<craft::font_catalog::FaceInfo> {
|
||||
let key = norm(family);
|
||||
self.catalog.faces().iter().filter(|f| f.legacy_family.as_deref().is_some_and(|lf| norm(lf) == key)).cloned().collect()
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if self.read_catalog().iter().any(|c| c.family.eq_ignore_ascii_case(family)) {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn is_loaded(&self, family: &str) -> bool {
|
||||
@@ -1154,8 +1394,6 @@ impl FontDb {
|
||||
if c.is_control() || c.is_whitespace() {
|
||||
return false;
|
||||
}
|
||||
let cataloged = self.catalog.families();
|
||||
self.refresh_misses(false);
|
||||
let seen = self.read_faces().len();
|
||||
{
|
||||
let sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
@@ -1164,7 +1402,8 @@ impl FontDb {
|
||||
}
|
||||
}
|
||||
let covered = |db: &FontDb| db.read_faces().iter().any(|f| f.covers(c) && accept(f));
|
||||
let _loading = self.loading.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let cataloged: Vec<String> = self.read_catalog().iter().map(|e| e.family.clone()).collect();
|
||||
let loading = self.loading.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
// Another thread may have loaded a face for `c` (faces are only ever added), or found
|
||||
// there is none, while this one waited.
|
||||
if self.read_faces().len() != seen && covered(self) {
|
||||
@@ -1175,14 +1414,26 @@ impl FontDb {
|
||||
}
|
||||
for fam in SYSTEM_FALLBACKS {
|
||||
if !self.is_loaded(fam) && cataloged.iter().any(|f| f.eq_ignore_ascii_case(fam)) {
|
||||
self.load_cataloged(fam);
|
||||
self.load_family(fam, &loading);
|
||||
if covered(self) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.load_covering(c, 40 << 20, accept) {
|
||||
return true;
|
||||
let mut paths: Vec<std::path::PathBuf> =
|
||||
self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner).iter().map(|e| e.path.clone()).collect();
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
for p in paths {
|
||||
if std::fs::metadata(&p).map(|m| m.len() > 40 << 20).unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
let Ok(data) = std::fs::read(&p) else { continue };
|
||||
let hit =
|
||||
enumerate_faces(&data).iter().any(|(i, _, _, _)| skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some()));
|
||||
if hit && self.add_font(data) > 0 && covered(self) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if remember_miss {
|
||||
self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).misses.insert(c);
|
||||
@@ -1233,7 +1484,8 @@ impl FontDb {
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let cataloged = if self.system_fallback_enabled() { self.catalog.families().to_vec() } else { Vec::new() };
|
||||
let cataloged: Vec<String> =
|
||||
if self.system_fallback_enabled() { self.read_catalog().iter().map(|e| e.family.clone()).collect() } else { Vec::new() };
|
||||
for fam in SYSTEM_FALLBACKS.iter().filter(|f| f.contains("Symbol")) {
|
||||
if !self.is_loaded(fam) && cataloged.iter().any(|f| f.eq_ignore_ascii_case(fam)) {
|
||||
self.load_cataloged(fam);
|
||||
@@ -1254,67 +1506,67 @@ impl FontDb {
|
||||
/// Load an installed font without colour tables covering `c`. True if one was loaded.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn system_plain_fallback(&self, c: char) -> bool {
|
||||
static MISSES: Mutex<Option<std::collections::HashSet<char>>> = Mutex::new(None);
|
||||
if c.is_control() || c.is_whitespace() {
|
||||
return false;
|
||||
}
|
||||
let _ = self.catalog.families();
|
||||
self.refresh_misses(false);
|
||||
{
|
||||
let sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if !sys.enabled || sys.plain_misses.contains(&c) {
|
||||
return false;
|
||||
if !self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled {
|
||||
return false;
|
||||
}
|
||||
if MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).contains(&c) {
|
||||
return false;
|
||||
}
|
||||
let mut paths: Vec<std::path::PathBuf> = self.read_catalog().iter().map(|e| e.path.clone()).collect();
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
for p in paths {
|
||||
if std::fs::metadata(&p).map(|m| m.len() > 40 << 20).unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
let Ok(data) = std::fs::read(&p) else { continue };
|
||||
let hit = enumerate_faces(&data).iter().any(|(i, _, _, _)| {
|
||||
!has_color_tables(&data, *i) && skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some())
|
||||
});
|
||||
if hit && self.add_font(data) > 0 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if self.load_covering(c, 40 << 20, &|f| !f.is_color()) {
|
||||
return true;
|
||||
}
|
||||
self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).plain_misses.insert(c);
|
||||
MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).insert(c);
|
||||
false
|
||||
}
|
||||
|
||||
/// Load an installed colour font covering `c`. True if one was loaded.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn system_color_fallback(&self, c: char) -> bool {
|
||||
static MISSES: Mutex<Option<std::collections::HashSet<char>>> = Mutex::new(None);
|
||||
if c.is_control() || c.is_whitespace() {
|
||||
return false;
|
||||
}
|
||||
let _ = self.catalog.families();
|
||||
self.refresh_misses(false);
|
||||
{
|
||||
let sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if !sys.enabled || sys.color_misses.contains(&c) {
|
||||
if !sys.enabled {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if self.load_covering(c, 64 << 20, &FontFace::is_color) {
|
||||
return true;
|
||||
if MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).contains(&c) {
|
||||
return false;
|
||||
}
|
||||
self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).color_misses.insert(c);
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_covering(&self, c: char, max_bytes: u64, accept: &impl Fn(&FontFace) -> bool) -> bool {
|
||||
let faces = self.catalog.faces();
|
||||
let mut candidates: Vec<_> = faces.iter().collect();
|
||||
candidates.sort_by(|a, b| a.path.cmp(&b.path).then(a.index.cmp(&b.index)));
|
||||
// Keep one file alive between adjacent faces so the catalogue's weak byte cache shares
|
||||
// a collection or variable font's data instead of reading it once per named instance.
|
||||
let mut previous_bytes = None;
|
||||
for info in candidates {
|
||||
if info.file_bytes.is_some_and(|size| size > max_bytes) {
|
||||
let mut paths: Vec<std::path::PathBuf> = self.read_catalog().iter().map(|e| e.path.clone()).collect();
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
for p in paths {
|
||||
if std::fs::metadata(&p).map(|m| m.len() > 64 << 20).unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
let Ok(data) = self.catalog.load(info) else { continue };
|
||||
let _ = previous_bytes.replace(data.bytes.clone());
|
||||
if !skrifa::FontRef::from_index(&data.bytes, data.index).is_ok_and(|font| font.charmap().map(c).is_some()) {
|
||||
continue;
|
||||
}
|
||||
self.add_catalog_face(info, &data);
|
||||
if self.read_faces().iter().any(|face| face.covers(c) && accept(face)) {
|
||||
let Ok(data) = std::fs::read(&p) else { continue };
|
||||
let hit = enumerate_faces(&data).iter().any(|(i, _, _, _)| {
|
||||
has_color_tables(&data, *i) && skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some())
|
||||
});
|
||||
if hit && self.add_font(data) > 0 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).insert(c);
|
||||
false
|
||||
}
|
||||
|
||||
@@ -1393,64 +1645,10 @@ impl OutlinePen for FlipPen {
|
||||
|
||||
#[cfg(test)]
|
||||
mod font_dir_tests {
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
fn assert_fixture_discovered_after_rescan(env: FontEnv, directory: &std::path::Path) {
|
||||
let catalog = Arc::new(Catalog::new(env.clone()).with_font_service(false));
|
||||
catalog.set_confined_dirs(vec![env.root]);
|
||||
let db = FontDb::with_catalog(catalog.clone(), CatalogScope::Isolated);
|
||||
assert!(!db.has_family("DeckCraft Legacy"));
|
||||
let missing = db.face("DeckCraft Legacy", "Regular");
|
||||
std::fs::create_dir_all(directory).unwrap();
|
||||
let file = directory.join("regular.ttf");
|
||||
std::fs::write(&file, include_bytes!("../tests/fixtures/legacy-regular.ttf")).unwrap();
|
||||
db.load_system_fonts();
|
||||
let (info, _) = catalog.resolve("DeckCraft Legacy", "Regular").unwrap();
|
||||
assert!(db.families().contains(&info.family));
|
||||
let face = db.face(&info.family, &info.style);
|
||||
assert_ne!(face.family, missing.family);
|
||||
assert_eq!(face.family, info.family);
|
||||
assert_eq!(face.style, info.style);
|
||||
assert!(face.covers('A'));
|
||||
assert!(!db.outline(&face, face.glyph_for('A')).elements().is_empty());
|
||||
let loaded = db.read_faces().len();
|
||||
db.load_system_fonts();
|
||||
assert_eq!(db.face(&info.family, &info.style).id(), face.id());
|
||||
assert_eq!(db.read_faces().len(), loaded);
|
||||
std::fs::remove_file(file).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_font_registration_is_shared_with_the_adapter_catalogue_and_is_idempotent() {
|
||||
let catalog = Arc::new(Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false));
|
||||
let db = FontDb::with_catalog(catalog.clone(), CatalogScope::Isolated);
|
||||
let bytes = include_bytes!("../tests/fixtures/legacy-semibold.ttf");
|
||||
assert!(catalog.family("DeckCraft Legacy Semibold").is_none());
|
||||
assert!(db.add_font(bytes.to_vec()) > 0);
|
||||
let (info, _) = catalog.resolve("DeckCraft Legacy Semibold", "Regular").unwrap();
|
||||
let face = db.face("DeckCraft Legacy Semibold", "Regular");
|
||||
assert_eq!(face.family, info.family);
|
||||
assert_eq!(face.style, info.style);
|
||||
let before = catalog.faces().len();
|
||||
assert_eq!(db.add_font(bytes.to_vec()), 0);
|
||||
assert_eq!(catalog.faces().len(), before);
|
||||
assert_eq!(db.face(&info.family, &info.style).id(), face.id());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalogue_added_bytes_resolve_without_a_directory_scan() {
|
||||
let catalog = Arc::new(Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false));
|
||||
let db = FontDb::with_catalog(catalog.clone(), CatalogScope::Isolated);
|
||||
let family = "DeckCraft Legacy";
|
||||
let missing = db.face(family, "Regular");
|
||||
let infos = catalog.add_bytes(include_bytes!("../tests/fixtures/legacy-regular.ttf").to_vec(), Source::User, &Limits::default()).unwrap();
|
||||
let resolved = db.face(family, "Regular");
|
||||
assert_ne!(resolved.family, missing.family);
|
||||
assert!(infos.iter().any(|info| info.family == resolved.family && info.style == resolved.style));
|
||||
assert!(resolved.covers('A'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_collection_offsets_do_not_consume_face_cap() {
|
||||
let mut entries = vec![(0, 7); MAX_COLLECTION_FACES as usize];
|
||||
@@ -1518,33 +1716,18 @@ mod font_dir_tests {
|
||||
assert_eq!(cache.elements, before);
|
||||
}
|
||||
|
||||
// The catalogue keeps only host-absolute XDG entries, and `/nix/…` is absolute only on a Unix host.
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn xdg_data_dirs_contribute_their_fonts_folders() {
|
||||
let root = std::env::temp_dir().join(format!("deckcraft-fonts-xdg-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let home = root.join("home/ann");
|
||||
let env = FontEnv { os: Os::Unix, root: root.clone(), home: Some(home.clone()), ..FontEnv::default() };
|
||||
for directory in [home.join(".local/share/fonts"), root.join("usr/local/share/fonts"), root.join("usr/share/fonts")] {
|
||||
assert_fixture_discovered_after_rescan(env.clone(), &directory);
|
||||
}
|
||||
let data_home = root.join("data/ann");
|
||||
let env = FontEnv {
|
||||
xdg_data_home: Some(data_home.clone()),
|
||||
xdg_data_dirs: Some(std::env::join_paths(["/nix/profile/share", "relative", "/var/lib/flatpak/exports/share"]).unwrap()),
|
||||
..env
|
||||
};
|
||||
for directory in [data_home.join("fonts"), root.join("nix/profile/share/fonts"), root.join("var/lib/flatpak/exports/share/fonts")] {
|
||||
assert_fixture_discovered_after_rescan(env.clone(), &directory);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
let home = Path::new("/home/ann");
|
||||
assert_eq!(
|
||||
xdg_font_dirs(None, None, Some(home)),
|
||||
[home.join(".local/share/fonts"), "/usr/local/share/fonts".into(), "/usr/share/fonts".into()]
|
||||
);
|
||||
let v = xdg_font_dirs(Some("/data/ann"), Some("/nix/profile/share:relative:/var/lib/flatpak/exports/share"), Some(home));
|
||||
assert_eq!(v, [PathBuf::from("/data/ann/fonts"), "/nix/profile/share/fonts".into(), "/var/lib/flatpak/exports/share/fonts".into()]);
|
||||
}
|
||||
|
||||
// A `<dir>` of `/…` is absolute only on a Unix host; elsewhere it joins the configuration's folder.
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn fontconfig_dir_entries_are_read() {
|
||||
let conf = r#"<?xml version="1.0"?>
|
||||
<fontconfig>
|
||||
@@ -1556,54 +1739,23 @@ mod font_dir_tests {
|
||||
<dirname>ignored</dirname>
|
||||
<dir>/nix/store/abc-fonts/share/fonts</dir>
|
||||
</fontconfig>"#;
|
||||
let root = std::env::temp_dir().join(format!("deckcraft-fontconfig-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let home = root.join("home/ann");
|
||||
let file = root.join("fonts.conf");
|
||||
std::fs::write(&file, conf).unwrap();
|
||||
let env = FontEnv { os: Os::Unix, root: root.clone(), home: Some(home.clone()), fontconfig_file: Some(file.clone()), ..FontEnv::default() };
|
||||
for directory in [
|
||||
root.join("usr/share/fonts"),
|
||||
home.join(".local/share/fonts"),
|
||||
home.join(".fonts"),
|
||||
root.join("relative/fonts"),
|
||||
root.join("nix/store/abc-fonts/share/fonts"),
|
||||
] {
|
||||
assert_fixture_discovered_after_rescan(env.clone(), &directory);
|
||||
}
|
||||
std::fs::write(&file, "<dir>/never closed").unwrap();
|
||||
let relative = root.join("relative/fonts");
|
||||
std::fs::write(relative.join("regular.ttf"), include_bytes!("../tests/fixtures/legacy-regular.ttf")).unwrap();
|
||||
let catalog = Arc::new(Catalog::new(env).with_font_service(false));
|
||||
catalog.set_confined_dirs(vec![root.clone()]);
|
||||
let db = FontDb::with_catalog(catalog.clone(), CatalogScope::Isolated);
|
||||
assert!(!db.has_family("DeckCraft Legacy"));
|
||||
let missing = db.face("DeckCraft Legacy", "Regular");
|
||||
std::fs::write(&file, conf).unwrap();
|
||||
db.load_system_fonts();
|
||||
let (info, _) = catalog.resolve("DeckCraft Legacy", "Regular").unwrap();
|
||||
let face = db.face(&info.family, &info.style);
|
||||
assert_ne!(face.family, missing.family);
|
||||
assert_eq!(face.family, info.family);
|
||||
assert_eq!(face.style, info.style);
|
||||
assert!(face.covers('A'));
|
||||
assert!(!db.outline(&face, face.glyph_for('A')).elements().is_empty());
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
let home = Path::new("/home/ann");
|
||||
let v = fontconfig_dirs(conf, None, Some(home));
|
||||
assert_eq!(
|
||||
v,
|
||||
[PathBuf::from("/usr/share/fonts"), home.join(".local/share/fonts"), home.join(".fonts"), "/nix/store/abc-fonts/share/fonts".into()]
|
||||
);
|
||||
assert!(fontconfig_dirs("<dir>/never closed", None, Some(home)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "linux")]
|
||||
fn linux_dirs_include_flatpak_host_fonts_without_duplicates() {
|
||||
let root = std::env::temp_dir().join(format!("deckcraft-fonts-flatpak-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let file = root.join("fonts.conf");
|
||||
std::fs::write(&file, "<fontconfig><dir>/run/host/user-fonts</dir><dir>/run/host/user-fonts</dir></fontconfig>").unwrap();
|
||||
let env = FontEnv { os: Os::Unix, root: root.clone(), flatpak: true, fontconfig_file: Some(file), ..FontEnv::default() };
|
||||
for directory in ["run/host/fonts", "run/host/local-fonts", "run/host/user-fonts"] {
|
||||
assert_fixture_discovered_after_rescan(env.clone(), &root.join(directory));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
let d = system_font_dirs();
|
||||
assert!(d.contains(&PathBuf::from("/run/host/user-fonts")));
|
||||
let mut u = d.clone();
|
||||
u.sort();
|
||||
u.dedup();
|
||||
assert_eq!(u.len(), d.len());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ mod shape;
|
||||
pub use fallback::{bundled_families, covers_cluster, is_emoji_cluster, ligature_carets};
|
||||
pub use fontdb::{
|
||||
FALLBACK_FAMILY, FaceRef, FontDb, FontFace, LAST_RESORT_FAMILY, MISSING_FONT_FAMILY, base_style, bundled, is_monospace_family, substitutes,
|
||||
system_font_dirs,
|
||||
};
|
||||
pub use harfrust::Feature;
|
||||
use harfrust::Tag;
|
||||
|
||||
@@ -111,31 +111,6 @@ fn concurrent_lookups_all_find_an_installed_family() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn catalog_rescan_discovers_new_families_and_retries_missing_styles() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-fonts-rescan-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
let isolated = FontDb::with_font_dirs(Vec::new());
|
||||
assert!(!db.has_family("DeckCraft Legacy"));
|
||||
let missing = db.face("DeckCraft Legacy", "Semibold");
|
||||
std::fs::write(dir.join("regular.ttf"), include_bytes!("../tests/fixtures/legacy-regular.ttf")).unwrap();
|
||||
db.load_system_fonts();
|
||||
assert!(db.families().iter().any(|family| family == "DeckCraft Legacy"));
|
||||
let regular = db.face("DeckCraft Legacy", "Semibold");
|
||||
assert_ne!(regular.family, missing.family);
|
||||
assert!(!isolated.has_family(®ular.family));
|
||||
std::fs::write(dir.join("semibold.ttf"), include_bytes!("../tests/fixtures/legacy-semibold.ttf")).unwrap();
|
||||
db.load_system_fonts();
|
||||
let semibold = db.face("DeckCraft Legacy", "Semibold");
|
||||
assert_eq!(semibold.family, regular.family);
|
||||
assert!(semibold.weight > regular.weight);
|
||||
assert_ne!(semibold.id(), regular.id());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_family_names_find_their_faces() {
|
||||
// Documents name fonts by their Windows family ("Segoe UI Semibold"); the font's
|
||||
@@ -435,8 +410,7 @@ fn the_font_scan_skips_fifos_folders_and_link_loops() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("sub")).unwrap();
|
||||
std::fs::copy(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/legacy-semibold.ttf"), dir.join("sub/real.ttf")).unwrap();
|
||||
// Hosts without mkfifo still exercise the other hostile directory entries.
|
||||
let _ = std::process::Command::new("mkfifo").arg(dir.join("trap.ttf")).status();
|
||||
let fifo = std::process::Command::new("mkfifo").arg(dir.join("trap.ttf")).status().is_ok_and(|s| s.success());
|
||||
std::fs::create_dir(dir.join("folder.ttf")).unwrap();
|
||||
std::fs::write(dir.join("empty.otf"), b"").unwrap();
|
||||
std::os::unix::fs::symlink(&dir, dir.join("sub/loop")).unwrap();
|
||||
@@ -444,16 +418,11 @@ fn the_font_scan_skips_fifos_folders_and_link_loops() {
|
||||
let scan_dir = dir.clone();
|
||||
std::thread::spawn(move || {
|
||||
let db = FontDb::with_font_dirs(vec![scan_dir]);
|
||||
db.load_system_fonts();
|
||||
// Bundled faces also belong to the catalogue, so its size cannot prove discovery.
|
||||
let found = db.has_family("DeckCraft Legacy Semibold");
|
||||
let face = db.face("DeckCraft Legacy Semibold", "Regular");
|
||||
let drawable = face.covers('A') && !db.outline(&face, face.glyph_for('A')).elements().is_empty();
|
||||
let _ = tx.send((found, drawable));
|
||||
let _ = tx.send(db.load_system_fonts());
|
||||
});
|
||||
let (found, drawable) = rx.recv_timeout(std::time::Duration::from_secs(30)).expect("the font scan hung");
|
||||
assert!(found, "the real font was found");
|
||||
assert!(drawable, "the discovered face supplies a drawable glyph");
|
||||
let n = rx.recv_timeout(std::time::Duration::from_secs(30)).expect("the font scan hung");
|
||||
assert!(n >= 1, "the real font was found");
|
||||
assert!(fifo || n >= 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ description = "DeckCraft MCP server: JSON-RPC 2.0 over stdio, driving a running
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft = { workspace = true, features = ["automation"] }
|
||||
craft-mcp-server = { workspace = true }
|
||||
deckcraft-engine = { workspace = true }
|
||||
deckcraft-render = { workspace = true }
|
||||
|
||||
+282
-112
@@ -1,11 +1,14 @@
|
||||
//! Where MCP tool calls end up: a control-channel method call.
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::net::ToSocketAddrs;
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::time::Duration;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use craft::automation::client::{ConnectError, ControlClient};
|
||||
use serde_json::Value;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
// Includes the newline, matching the control server's request budget. In particular a peer
|
||||
// must not be able to grow a reply indefinitely by withholding its newline.
|
||||
const MAX_REPLY_BYTES: u64 = 16 * 1024 * 1024;
|
||||
|
||||
/// Something that answers control-channel methods (`engine.execute`, `document.inspect`,
|
||||
/// `ui.pointer`, `ui.render`, …). See `deckcraft_ui_egui::control` for the full list.
|
||||
@@ -18,64 +21,122 @@ pub trait Backend {
|
||||
fn describe(&self) -> String;
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// A running DeckCraft app, reached through its authenticated loopback control port.
|
||||
/// A running DeckCraft app, reached through its loopback control port.
|
||||
pub struct Remote {
|
||||
addr: String,
|
||||
token: String,
|
||||
client: Option<ControlClient>,
|
||||
conn: Option<(BufReader<TcpStream>, TcpStream)>,
|
||||
next_id: u64,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Remote {
|
||||
/// Authenticate with `token` at `addr` (`127.0.0.1:7979`), failing fast when nothing is listening.
|
||||
pub fn connect(addr: &str, token: &str) -> std::io::Result<Self> {
|
||||
let client = Self::connect_client(addr, token)?;
|
||||
Ok(Self { addr: addr.to_string(), token: token.to_string(), client: Some(client) })
|
||||
/// Connect to `addr` (`127.0.0.1:7979`), failing fast when nothing is listening.
|
||||
pub fn connect(addr: &str) -> std::io::Result<Self> {
|
||||
let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1 };
|
||||
r.reconnect()?;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// The control-channel address used for connections.
|
||||
pub fn addr(&self) -> &str {
|
||||
&self.addr
|
||||
}
|
||||
|
||||
fn connect_client(addr: &str, token: &str) -> std::io::Result<ControlClient> {
|
||||
let mut last = std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {addr}"));
|
||||
for address in addr.to_socket_addrs()? {
|
||||
match ControlClient::connect(address, token) {
|
||||
Ok(client) => return Ok(client),
|
||||
Err(error @ ConnectError::Refused(_)) => {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, error.to_string()));
|
||||
fn reconnect(&mut self) -> std::io::Result<()> {
|
||||
self.conn = None;
|
||||
let mut last = std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {}", self.addr));
|
||||
for sa in self.addr.to_socket_addrs()? {
|
||||
match TcpStream::connect_timeout(&sa, Duration::from_millis(800)) {
|
||||
Ok(s) => {
|
||||
s.set_nodelay(true).ok();
|
||||
// The app answers within 60 s (its own timeout); leave headroom.
|
||||
s.set_read_timeout(Some(Duration::from_secs(90))).ok();
|
||||
let read = s.try_clone()?;
|
||||
self.conn = Some((BufReader::new(read), s));
|
||||
return Ok(());
|
||||
}
|
||||
Err(error) => last = std::io::Error::other(error.to_string()),
|
||||
Err(e) => last = e,
|
||||
}
|
||||
}
|
||||
Err(last)
|
||||
}
|
||||
|
||||
/// Write one request line. A failure here means the app never got a complete line, so retrying is safe.
|
||||
/// A connection the app has already closed (it restarted since the last call) is replaced before writing.
|
||||
fn send(&mut self, line: &str) -> std::io::Result<()> {
|
||||
if self.conn.as_ref().is_none_or(|(reader, writer)| !reader.buffer().is_empty() || is_closed(writer)) {
|
||||
self.reconnect()?;
|
||||
}
|
||||
let Some((_, writer)) = self.conn.as_mut() else {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::NotConnected, "not connected"));
|
||||
};
|
||||
writer.write_all(format!("{line}\n").as_bytes())?;
|
||||
writer.flush()
|
||||
}
|
||||
|
||||
/// Read the reply to a request that was already sent.
|
||||
fn receive(&mut self, id: u64) -> std::io::Result<Result<Value, String>> {
|
||||
let Some((reader, _)) = self.conn.as_mut() else {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::NotConnected, "not connected"));
|
||||
};
|
||||
let mut reply = Vec::new();
|
||||
reader.take(MAX_REPLY_BYTES + 1).read_until(b'\n', &mut reply)?;
|
||||
if reply.len() as u64 > MAX_REPLY_BYTES {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "control reply exceeds 16 MiB"));
|
||||
}
|
||||
if reply.last() != Some(&b'\n') {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "control reply has no terminating newline"));
|
||||
}
|
||||
let invalid = |message| std::io::Error::new(std::io::ErrorKind::InvalidData, message);
|
||||
let v: Value = serde_json::from_slice(&reply).map_err(|e| invalid(format!("bad reply from app: {e}")))?;
|
||||
if v.get("id").and_then(Value::as_u64) != Some(id) {
|
||||
return Err(invalid("control reply has an unexpected request id".to_string()));
|
||||
}
|
||||
match v.get("ok").and_then(Value::as_bool) {
|
||||
Some(true) if v.get("error").is_none() => {
|
||||
v.get("result").cloned().map(Ok).ok_or_else(|| invalid("successful control reply has no result".to_string()))
|
||||
}
|
||||
Some(false) if v.get("result").is_none() => v
|
||||
.get("error")
|
||||
.and_then(Value::as_str)
|
||||
.map(|error| Err(error.to_string()))
|
||||
.ok_or_else(|| invalid("failed control reply has no error string".to_string())),
|
||||
_ => Err(invalid("control reply has an invalid envelope".to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the peer has closed or reset `stream`, or sent bytes nobody asked for. Between calls nothing
|
||||
/// should be waiting, so only "would block" means the connection is still good.
|
||||
fn is_closed(stream: &TcpStream) -> bool {
|
||||
if stream.set_nonblocking(true).is_err() {
|
||||
return true;
|
||||
}
|
||||
let mut byte = [0u8; 1];
|
||||
let open = matches!(stream.peek(&mut byte), Err(e) if e.kind() == std::io::ErrorKind::WouldBlock);
|
||||
stream.set_nonblocking(false).is_err() || !open
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Backend for Remote {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
// Replacing an unusable connection before sending cannot replay a mutation.
|
||||
if self.client.as_ref().is_none_or(|client| !client.is_usable()) {
|
||||
self.client = None;
|
||||
self.client = Some(
|
||||
Self::connect_client(&self.addr, &self.token).map_err(|error| format!("DeckCraft app at {} is not reachable: {error}", self.addr))?,
|
||||
);
|
||||
}
|
||||
let client = self.client.as_mut().ok_or_else(|| format!("DeckCraft app at {} is not connected", self.addr))?;
|
||||
match client.call(method, params) {
|
||||
Err(error) if client.is_broken() => {
|
||||
// Once sent, a lost reply leaves the outcome unknown; replay could apply the edit twice.
|
||||
self.client = None;
|
||||
Err(format!(
|
||||
"lost the reply from the DeckCraft app at {} ({error}); the command may or may not have run, check the document before retrying",
|
||||
self.addr
|
||||
))
|
||||
}
|
||||
result => result,
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
let line = json!({"id": id, "method": method, "params": params}).to_string();
|
||||
// One retry with a fresh connection (the app may have restarted), but only while the request
|
||||
// was not sent. Once it is out, a lost reply leaves the outcome unknown and a resend could
|
||||
// run an insert/delete/undo twice, so report that instead.
|
||||
if self.send(&line).is_err() {
|
||||
self.conn = None;
|
||||
self.send(&line).map_err(|e| {
|
||||
self.conn = None;
|
||||
format!("DeckCraft app at {} is not reachable: {e}", self.addr)
|
||||
})?;
|
||||
}
|
||||
self.receive(id).map_err(|e| {
|
||||
self.conn = None;
|
||||
format!(
|
||||
"lost the reply from the DeckCraft app at {} ({e}); the command may or may not have run, check the document before retrying",
|
||||
self.addr
|
||||
)
|
||||
})?
|
||||
}
|
||||
|
||||
fn has_ui(&self) -> bool {
|
||||
@@ -88,72 +149,172 @@ impl Backend for Remote {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::time::Duration;
|
||||
use std::net::TcpListener;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
fn authenticate(stream: TcpStream) -> BufReader<TcpStream> {
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("read timeout");
|
||||
stream.set_write_timeout(Some(Duration::from_secs(5))).expect("write timeout");
|
||||
let mut reader = BufReader::new(stream);
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).expect("auth request");
|
||||
reader.get_mut().write_all(b"{\"id\":1,\"ok\":true,\"result\":{\"authenticated\":true}}\n").expect("auth reply");
|
||||
reader
|
||||
}
|
||||
|
||||
fn request(reader: &mut BufReader<TcpStream>) -> Value {
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).expect("request");
|
||||
serde_json::from_str(&line).expect("request JSON")
|
||||
}
|
||||
|
||||
fn answer(reader: &mut BufReader<TcpStream>, request: &Value) {
|
||||
writeln!(reader.get_mut(), "{}", json!({"id": request["id"], "ok": true, "result": null})).expect("reply");
|
||||
}
|
||||
|
||||
fn answer_until_closed(mut reader: BufReader<TcpStream>) -> Vec<Value> {
|
||||
let mut calls = Vec::new();
|
||||
loop {
|
||||
fn reply_once(reply: Vec<u8>) -> (Remote, std::thread::JoinHandle<()>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let addr = listener.local_addr().expect("addr").to_string();
|
||||
let peer = std::thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().expect("accept");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
stream.set_write_timeout(Some(Duration::from_secs(5))).expect("write timeout");
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).expect("request or EOF") == 0 {
|
||||
return calls;
|
||||
}
|
||||
let call = serde_json::from_str(&line).expect("request JSON");
|
||||
answer(&mut reader, &call);
|
||||
calls.push(call);
|
||||
BufReader::new(&stream).read_line(&mut line).expect("request");
|
||||
assert_eq!(serde_json::from_str::<Value>(&line).expect("JSON")["id"], 1);
|
||||
// An oversized reply may be rejected before the peer finishes writing it.
|
||||
let _ = stream.write_all(&reply);
|
||||
});
|
||||
(Remote::connect(&addr).expect("connect"), peer)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_reply_id_is_not_command_success() {
|
||||
let (mut remote, peer) = reply_once(b"{\"id\":999,\"ok\":true,\"result\":\"unrelated\"}\n".to_vec());
|
||||
let result = remote.call("engine.execute", json!({"command":"slide.new"}));
|
||||
peer.join().expect("peer");
|
||||
let error = result.expect_err("an unrelated reply cannot confirm a mutation");
|
||||
assert!(error.contains("may or may not have run"), "{error}");
|
||||
assert!(remote.conn.is_none(), "discard the invalid connection without replaying");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_success_and_error_replies_keep_their_meaning() {
|
||||
for (reply, expected) in [
|
||||
("{\"id\":1,\"ok\":true,\"result\":null}\r\n", Ok(Value::Null)),
|
||||
("{\"id\":1,\"ok\":true,\"result\":{\"slides\":2}}\n", Ok(json!({"slides":2}))),
|
||||
("{\"id\":1,\"ok\":false,\"error\":\"disabled\"}\n", Err("disabled".into())),
|
||||
] {
|
||||
let (mut remote, peer) = reply_once(reply.as_bytes().to_vec());
|
||||
assert_eq!(remote.call("engine.execute", json!({})), expected);
|
||||
assert!(remote.conn.is_some(), "valid responses do not invalidate the connection");
|
||||
peer.join().expect("peer");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_reply_envelopes_leave_the_outcome_unknown() {
|
||||
for reply in [
|
||||
"not JSON\n",
|
||||
"[]\n",
|
||||
"{\"ok\":true,\"result\":null}\n",
|
||||
"{\"id\":\"1\",\"ok\":true,\"result\":null}\n",
|
||||
"{\"id\":1,\"ok\":1,\"result\":null}\n",
|
||||
"{\"id\":1,\"ok\":true}\n",
|
||||
"{\"id\":1,\"ok\":false}\n",
|
||||
"{\"id\":1,\"ok\":false,\"error\":42}\n",
|
||||
"{\"id\":1,\"ok\":true,\"result\":null,\"error\":\"failed\"}\n",
|
||||
"{\"id\":1,\"ok\":false,\"result\":null,\"error\":\"failed\"}\n",
|
||||
] {
|
||||
let (mut remote, peer) = reply_once(reply.as_bytes().to_vec());
|
||||
let result = remote.call("engine.execute", json!({}));
|
||||
peer.join().expect("peer");
|
||||
let error = result.expect_err(reply);
|
||||
assert!(error.contains("may or may not have run"), "{reply}: {error}");
|
||||
assert!(remote.conn.is_none(), "{reply}: discard the invalid connection");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eof_without_a_newline_is_not_a_complete_reply() {
|
||||
let (mut remote, peer) = reply_once(b"{\"id\":1,\"ok\":true,\"result\":null}".to_vec());
|
||||
let result = remote.call("engine.execute", json!({}));
|
||||
peer.join().expect("peer");
|
||||
assert!(result.is_err(), "a truncated frame cannot confirm a mutation");
|
||||
assert!(remote.conn.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_reply_is_rejected() {
|
||||
let reply = format!("{{\"id\":1,\"ok\":true,\"result\":\"{}\"}}\n", "x".repeat(16 * 1024 * 1024));
|
||||
let (mut remote, peer) = reply_once(reply.into_bytes());
|
||||
let result = remote.call("engine.execute", json!({}));
|
||||
let invalidated = remote.conn.is_none();
|
||||
// Close the socket before joining: the bounded reader need not drain the peer's reply.
|
||||
remote.conn = None;
|
||||
peer.join().expect("peer");
|
||||
assert!(result.is_err(), "a reply is limited to 16 MiB");
|
||||
let error = result.expect_err("checked above");
|
||||
assert!(error.contains("may or may not have run"), "{error}");
|
||||
assert!(invalidated, "discard the oversized reply's connection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reply_at_the_size_limit_is_accepted() {
|
||||
let prefix = "{\"id\":1,\"ok\":true,\"result\":\"";
|
||||
let suffix = "\"}\n";
|
||||
let payload_len = 16 * 1024 * 1024 - prefix.len() - suffix.len();
|
||||
let reply = format!("{prefix}{}{suffix}", "x".repeat(payload_len));
|
||||
let (mut remote, peer) = reply_once(reply.into_bytes());
|
||||
let result = remote.call("document.inspect", json!({})).expect("reply at the limit");
|
||||
assert_eq!(result.as_str().map(str::len), Some(payload_len));
|
||||
peer.join().expect("peer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buffered_unsolicited_reply_is_discarded_before_sending() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let addr = listener.local_addr().expect("addr").to_string();
|
||||
let peer = std::thread::spawn(move || {
|
||||
let (mut first, _) = listener.accept().expect("first connection");
|
||||
first.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let mut line = String::new();
|
||||
BufReader::new(&first).read_line(&mut line).expect("initial request");
|
||||
// Even a stale frame whose ID happens to match must not answer a new request.
|
||||
first
|
||||
.write_all(b"{\"id\":1,\"ok\":true,\"result\":\"first\"}\n{\"id\":2,\"ok\":true,\"result\":\"stale\"}\n")
|
||||
.expect("two replies together");
|
||||
line.clear();
|
||||
let sent_on_stale = BufReader::new(&first).read_line(&mut line).expect("first request") != 0;
|
||||
if !sent_on_stale {
|
||||
let (mut fresh, _) = listener.accept().expect("fresh connection");
|
||||
fresh.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
BufReader::new(&fresh).read_line(&mut line).expect("fresh request");
|
||||
fresh.write_all(b"{\"id\":2,\"ok\":false,\"error\":\"rejected\"}\n").expect("actual reply");
|
||||
}
|
||||
sent_on_stale
|
||||
});
|
||||
let mut remote = Remote::connect(&addr).expect("connect");
|
||||
assert_eq!(remote.call("document.inspect", json!({})), Ok(json!("first")));
|
||||
// Force the stale frame into BufReader, where a socket-only peek cannot see it.
|
||||
assert!(!remote.conn.as_mut().expect("connection").0.fill_buf().expect("buffer").is_empty());
|
||||
let result = remote.call("engine.execute", json!({"command":"slide.new"}));
|
||||
let sent_on_stale = peer.join().expect("peer");
|
||||
assert_eq!(result, Err("rejected".into()), "only the fresh peer's response counts");
|
||||
assert!(!sent_on_stale, "replace a connection with buffered unsolicited bytes before sending");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lost_reply_is_not_resent() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let addr = listener.local_addr().expect("addr").to_string();
|
||||
let peer = std::thread::spawn(move || {
|
||||
let mut first = authenticate(listener.accept().expect("first connection").0);
|
||||
let mutation = request(&mut first);
|
||||
drop(first);
|
||||
let fresh = authenticate(listener.accept().expect("fresh connection").0);
|
||||
let mut calls = vec![mutation];
|
||||
calls.extend(answer_until_closed(fresh));
|
||||
calls
|
||||
let executed = Arc::new(AtomicUsize::new(0));
|
||||
let count = Arc::clone(&executed);
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming().flatten() {
|
||||
let mut reader = BufReader::new(&stream);
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap_or(0) == 0 {
|
||||
continue;
|
||||
}
|
||||
let n = count.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
if n > 1 {
|
||||
let mut w = &stream;
|
||||
let _ = w.write_all(b"{\"id\":2,\"ok\":true,\"result\":null}\n");
|
||||
}
|
||||
// The first request is executed, then the connection drops without a reply.
|
||||
}
|
||||
});
|
||||
let mut remote = Remote::connect(&addr, TOKEN).expect("connect");
|
||||
let mutation = "engine.execute";
|
||||
let inspection = "document.inspect";
|
||||
let error = remote.call(mutation, json!({"command": "slide.new"})).expect_err("lost reply must be an error");
|
||||
assert!(error.contains("may or may not have run"), "{error}");
|
||||
assert!(remote.call(inspection, json!({})).is_ok());
|
||||
drop(remote);
|
||||
let calls = peer.join().expect("peer");
|
||||
let methods: Vec<_> = calls.iter().map(|call| call["method"].clone()).collect();
|
||||
assert_eq!(methods, vec![json!(mutation), json!(inspection)], "a lost mutation must not be replayed");
|
||||
let mut remote = Remote::connect(&addr).expect("connect");
|
||||
let err = remote.call("engine.execute", json!({})).expect_err("lost reply must be an error");
|
||||
assert!(err.contains("may or may not have run"), "{err}");
|
||||
assert_eq!(executed.load(Ordering::SeqCst), 1, "the command must not be replayed");
|
||||
// The next call opens a fresh connection and works.
|
||||
assert!(remote.call("document.inspect", json!({})).is_ok());
|
||||
assert_eq!(executed.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -161,23 +322,32 @@ mod tests {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let addr = listener.local_addr().expect("addr").to_string();
|
||||
let (closed_tx, closed_rx) = std::sync::mpsc::channel();
|
||||
let peer = std::thread::spawn(move || {
|
||||
let first = authenticate(listener.accept().expect("first connection").0);
|
||||
first.get_ref().shutdown(std::net::Shutdown::Both).expect("close first connection");
|
||||
drop(first);
|
||||
closed_tx.send(()).expect("closed notification");
|
||||
let fresh = authenticate(listener.accept().expect("fresh connection").0);
|
||||
answer_until_closed(fresh)
|
||||
let executed = Arc::new(AtomicUsize::new(0));
|
||||
let count = Arc::clone(&executed);
|
||||
std::thread::spawn(move || {
|
||||
let mut first = true;
|
||||
for stream in listener.incoming().flatten() {
|
||||
if first {
|
||||
// The app restarts: the first connection closes before any request arrives.
|
||||
first = false;
|
||||
drop(stream);
|
||||
let _ = closed_tx.send(());
|
||||
continue;
|
||||
}
|
||||
let mut reader = BufReader::new(&stream);
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap_or(0) == 0 {
|
||||
continue;
|
||||
}
|
||||
count.fetch_add(1, Ordering::SeqCst);
|
||||
let mut w = &stream;
|
||||
let _ = w.write_all(b"{\"id\":1,\"ok\":true,\"result\":null}\n");
|
||||
}
|
||||
});
|
||||
let mut remote = Remote::connect(&addr, TOKEN).expect("connect");
|
||||
let mut remote = Remote::connect(&addr).expect("connect");
|
||||
closed_rx.recv().expect("server closed the first connection");
|
||||
let method = "engine.execute";
|
||||
let params = json!({"command": "slide.new"});
|
||||
assert!(remote.call(method, params.clone()).is_ok(), "a request that never left must be sent on a fresh connection");
|
||||
drop(remote);
|
||||
let calls = peer.join().expect("peer");
|
||||
assert_eq!(calls.len(), 1, "only the unsent call is sent after reconnecting");
|
||||
assert_eq!(calls[0]["method"], method);
|
||||
assert_eq!(calls[0]["params"], params);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
assert!(remote.call("engine.execute", json!({})).is_ok(), "a request that never left must be sent on a fresh connection");
|
||||
assert_eq!(executed.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,8 +21,8 @@ impl Default for Headless {
|
||||
}
|
||||
|
||||
/// Hint appended to errors for methods that need a window.
|
||||
pub(crate) const NEEDS_APP: &str = "it needs the desktop app: start `deckcraft --control 7979 --control-token-file PATH` and run the MCP server \
|
||||
with `deckcraft-cli mcp --connect 7979 --control-token-file PATH`";
|
||||
pub(crate) const NEEDS_APP: &str = "it needs the desktop app: start `deckcraft --control 7979` and run the MCP server \
|
||||
with `deckcraft-cli mcp --connect 7979`";
|
||||
|
||||
fn s<'a>(p: &'a Value, k: &str) -> Option<&'a str> {
|
||||
p.get(k).and_then(Value::as_str)
|
||||
@@ -154,11 +154,11 @@ impl Headless {
|
||||
"engine.commands" => Ok(serde_json::to_value(self.session.commands()).unwrap_or_default()),
|
||||
"document.inspect" => self.exec("document.inspect", &json!({})),
|
||||
"ui.pointer" => self.pointer(p),
|
||||
"engine.key" => {
|
||||
"ui.key" => {
|
||||
let key = s(p, "key").ok_or("missing `key`")?;
|
||||
self.session.key(key, mods_from(p)).map_err(|e| e.to_string())
|
||||
}
|
||||
"engine.text" => {
|
||||
"ui.text" => {
|
||||
let t = s(p, "text").ok_or("missing `text`")?;
|
||||
self.session.type_text(t).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
//! JSON-RPC 2.0, hand-written (no async runtime). The server exposes DeckCraft as a set of MCP
|
||||
//! tools and resources and forwards everything to a [`Backend`]:
|
||||
//!
|
||||
//! - `Remote` authenticates with a running desktop app's per-launch token through the framework's
|
||||
//! JSON-lines control client. Start the app with `deckcraft --control 7979 --control-token-file PATH`
|
||||
//! and pass that file to the client with `--control-token-file PATH` (see `docs/control-protocol.md`).
|
||||
//! - [`Remote`] talks to a running desktop app through its loopback JSON-lines control channel
|
||||
//! (`deckcraft --control 7979`): one `{"id","method","params"}` line in, one
|
||||
//! `{"id","ok","result"|"error"}` line out (see `docs/control-protocol.md`).
|
||||
//! - [`Headless`] hosts an in-process [`deckcraft_engine::Session`] and implements the
|
||||
//! engine-level control-channel methods itself (rendering pages with `deckcraft-render`), so
|
||||
//! agents can build layouts and look at them without a window.
|
||||
@@ -20,9 +20,7 @@ mod headless;
|
||||
mod server;
|
||||
mod tools;
|
||||
|
||||
pub use backend::Backend;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use backend::Remote;
|
||||
pub use backend::{Backend, Remote};
|
||||
pub use headless::Headless;
|
||||
pub use server::{PROTOCOL_VERSION, Server};
|
||||
pub use tools::{ToolResult, call_tool, tool_definitions};
|
||||
|
||||
@@ -476,15 +476,15 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, a: &Value) -> ToolResult {
|
||||
"key" => {
|
||||
let mut p = a.get("mods").cloned().filter(Value::is_object).unwrap_or(json!({}));
|
||||
p["key"] = a.get("key").cloned().unwrap_or_default();
|
||||
wrap(b.call("engine.key", p))
|
||||
wrap(b.call("ui.key", p))
|
||||
}
|
||||
"type_text" => wrap(b.call("engine.text", a)),
|
||||
"type_text" => wrap(b.call("ui.text", a)),
|
||||
"screenshot" => {
|
||||
if !b.has_ui() {
|
||||
return ToolResult::error(format!("screenshot: {NEEDS_APP}. Use render_slide to see a slide headlessly."));
|
||||
}
|
||||
match b.call("ui.screenshot", json!({})) {
|
||||
Ok(v) => match v.get("base64").and_then(Value::as_str) {
|
||||
match b.call("ui.screenshot", json!({"base64": true})) {
|
||||
Ok(v) => match v.get("png").and_then(Value::as_str) {
|
||||
Some(png) => ToolResult::image(png.to_string(), &json!({"width": v.get("width"), "height": v.get("height")})),
|
||||
None => ToolResult::json(&v),
|
||||
},
|
||||
|
||||
+11
-106
@@ -7,9 +7,9 @@
|
||||
use std::io::Cursor;
|
||||
|
||||
use symphonia::core::audio::SampleBuffer;
|
||||
use symphonia::core::codecs::{CODEC_TYPE_NULL, Decoder, DecoderOptions};
|
||||
use symphonia::core::codecs::{CODEC_TYPE_NULL, DecoderOptions};
|
||||
use symphonia::core::errors::Error as SymError;
|
||||
use symphonia::core::formats::{FormatOptions, Track};
|
||||
use symphonia::core::formats::FormatOptions;
|
||||
use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions};
|
||||
use symphonia::core::meta::MetadataOptions;
|
||||
use symphonia::core::probe::Hint;
|
||||
@@ -172,21 +172,6 @@ fn contained<T>(f: impl FnOnce() -> Result<T>) -> Result<T> {
|
||||
const MAX_DEMUX_ERRORS: u32 = 64;
|
||||
|
||||
fn decode_symphonia(bytes: &Bytes, ext: &str) -> Result<Pcm> {
|
||||
decode_symphonia_capped(bytes, ext, MAX_PCM_SAMPLES)
|
||||
}
|
||||
|
||||
/// The track playback decodes, with its decoder: the first one a decoder can be made for (a
|
||||
/// video's audio track follows its video track). The duration probe measures the same track.
|
||||
fn playable_track(tracks: &[Track]) -> Option<(u32, Box<dyn Decoder>)> {
|
||||
let codecs = symphonia::default::get_codecs();
|
||||
tracks
|
||||
.iter()
|
||||
.filter(|t| t.codec_params.codec != CODEC_TYPE_NULL)
|
||||
.find_map(|t| codecs.make(&t.codec_params, &DecoderOptions::default()).ok().map(|d| (t.id, d)))
|
||||
}
|
||||
|
||||
/// [`decode_symphonia`] stopping once `max_samples` samples have been decoded.
|
||||
fn decode_symphonia_capped(bytes: &Bytes, ext: &str, max_samples: usize) -> Result<Pcm> {
|
||||
let mss = MediaSourceStream::new(Box::new(Cursor::new(Shared(bytes.clone()))), MediaSourceStreamOptions::default());
|
||||
let mut hint = Hint::new();
|
||||
match ext {
|
||||
@@ -204,7 +189,14 @@ fn decode_symphonia_capped(bytes: &Bytes, ext: &str, max_samples: usize) -> Resu
|
||||
other => sym_err(other),
|
||||
})?;
|
||||
let mut format = probed.format;
|
||||
let (track_id, mut decoder) = playable_track(format.tracks()).ok_or(MediaError::Missing("audio track we can decode"))?;
|
||||
let codecs = symphonia::default::get_codecs();
|
||||
// The first track we can decode (a video's audio track follows its video track).
|
||||
let (track_id, mut decoder) = format
|
||||
.tracks()
|
||||
.iter()
|
||||
.filter(|t| t.codec_params.codec != CODEC_TYPE_NULL)
|
||||
.find_map(|t| codecs.make(&t.codec_params, &DecoderOptions::default()).ok().map(|d| (t.id, d)))
|
||||
.ok_or(MediaError::Missing("audio track we can decode"))?;
|
||||
let mut out: Vec<f32> = Vec::new();
|
||||
let mut rate = 0;
|
||||
let mut channels = 0u16;
|
||||
@@ -253,15 +245,7 @@ fn decode_symphonia_capped(bytes: &Bytes, ext: &str, max_samples: usize) -> Resu
|
||||
}
|
||||
if let Some(b) = buf.as_mut() {
|
||||
b.copy_interleaved_ref(decoded);
|
||||
// stop at the cap with whole frames, keeping what fits, like the Opus paths
|
||||
let room = max_samples.saturating_sub(out.len());
|
||||
let s = b.samples();
|
||||
if s.len() > room {
|
||||
let fit = room - room % (ch.max(1) as usize);
|
||||
out.extend_from_slice(s.get(..fit).unwrap_or_default());
|
||||
break;
|
||||
}
|
||||
out.extend_from_slice(s);
|
||||
out.extend_from_slice(b.samples());
|
||||
}
|
||||
}
|
||||
Err(SymError::DecodeError(e)) => log::debug!("audio decode: {e}"),
|
||||
@@ -296,48 +280,6 @@ pub(crate) fn probe_symphonia(bytes: &Bytes, ext: &str) -> Option<(String, u32,
|
||||
Some((name, p.sample_rate.unwrap_or(0), p.channels.map(|c| c.count() as u16).unwrap_or(0), p.n_frames))
|
||||
}
|
||||
|
||||
/// Length in milliseconds of the track playback decodes, summed from its packet durations: the
|
||||
/// file is demuxed but not decoded. `None` when the demuxer reports no durations.
|
||||
pub(crate) fn demux_duration_ms(bytes: &Bytes, ext: &str) -> Option<u64> {
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
let mss = MediaSourceStream::new(Box::new(Cursor::new(Shared(bytes.clone()))), MediaSourceStreamOptions::default());
|
||||
let mut hint = Hint::new();
|
||||
if ext != "unknown" {
|
||||
hint.with_extension(ext);
|
||||
}
|
||||
let opts = FormatOptions { enable_gapless: true, ..Default::default() };
|
||||
let mut format = symphonia::default::get_probe().format(&hint, mss, &opts, &MetadataOptions::default()).ok()?.format;
|
||||
let (id, _) = playable_track(format.tracks())?;
|
||||
let tb = format.tracks().iter().find(|t| t.id == id)?.codec_params.time_base?;
|
||||
let mut ticks = 0u64;
|
||||
let mut errors = 0u32;
|
||||
loop {
|
||||
match format.next_packet() {
|
||||
Ok(p) => {
|
||||
errors = 0;
|
||||
if p.track_id() == id {
|
||||
ticks = ticks.saturating_add(p.dur);
|
||||
}
|
||||
}
|
||||
Err(SymError::DecodeError(_)) => {
|
||||
errors += 1;
|
||||
if errors > MAX_DEMUX_ERRORS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
if ticks == 0 {
|
||||
return None;
|
||||
}
|
||||
let t = tb.calc_time(ticks);
|
||||
Some(t.seconds.saturating_mul(1000).saturating_add((t.frac * 1000.0).round() as u64))
|
||||
}))
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Interleaved PCM resampled (linear) to `rate`.
|
||||
pub fn resample(pcm: &Pcm, rate: u32) -> Pcm {
|
||||
if pcm.rate == rate || pcm.rate == 0 || rate == 0 {
|
||||
@@ -374,43 +316,6 @@ mod tests {
|
||||
assert!((r.at(101, 0) - 0.505).abs() < 1e-3);
|
||||
}
|
||||
|
||||
/// A long decode stops at the sample cap and keeps what it has, like the Opus paths, so audio
|
||||
/// past the cap still plays (up to the cap) instead of failing.
|
||||
#[test]
|
||||
fn decode_stops_at_the_sample_cap() {
|
||||
let b: Bytes = std::sync::Arc::new(std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/tone.aac")).unwrap_or_default());
|
||||
let full = decode_symphonia_capped(&b, "aac", usize::MAX).unwrap();
|
||||
let capped = decode_symphonia_capped(&b, "aac", 1001).unwrap();
|
||||
assert!(full.samples.len() > 1001, "the fixture is longer than the cap");
|
||||
assert!(!capped.samples.is_empty() && capped.samples.len() <= 1001, "{}", capped.samples.len());
|
||||
assert_eq!(capped.samples.len() % capped.channels as usize, 0, "whole frames only");
|
||||
assert_eq!(capped.samples[..], full.samples[..capped.samples.len()], "the start is kept as decoded");
|
||||
}
|
||||
|
||||
/// The duration is measured on the track playback decodes: the first one a decoder can be made
|
||||
/// for, not the first one with any codec.
|
||||
#[test]
|
||||
fn duration_and_playback_pick_the_same_track() {
|
||||
use symphonia::core::audio::Channels;
|
||||
use symphonia::core::codecs::{CODEC_TYPE_AAC, CODEC_TYPE_OPUS, CodecParameters};
|
||||
let stereo = Channels::FRONT_LEFT | Channels::FRONT_RIGHT;
|
||||
let mut opus = CodecParameters::new();
|
||||
opus.for_codec(CODEC_TYPE_OPUS).with_sample_rate(48_000).with_channels(stereo);
|
||||
let mut aac = CodecParameters::new();
|
||||
aac.for_codec(CODEC_TYPE_AAC).with_sample_rate(44_100).with_channels(stereo);
|
||||
let tracks = [Track::new(1, opus), Track::new(2, aac)];
|
||||
// the first track has a codec but no decoder in this build (Symphonia has no Opus decoder)
|
||||
assert_ne!(tracks[0].codec_params.codec, CODEC_TYPE_NULL);
|
||||
assert_eq!(playable_track(&tracks).map(|(id, _)| id), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn demux_duration_matches_decoded_length() {
|
||||
let b: Bytes = std::sync::Arc::new(std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/tone.aac")).unwrap_or_default());
|
||||
let ms = demux_duration_ms(&b, "aac").unwrap_or(0) as i64;
|
||||
assert!((ms - 500).abs() <= 60, "{ms} ms");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wma_is_reported_unsupported() {
|
||||
let mut b = crate::ASF_HEADER.to_vec();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Media probing: container, duration, audio and video stream parameters — without decoding
|
||||
//! (audio files whose container doesn't state a length are demuxed, not decoded).
|
||||
//! (except for audio files whose container doesn't state a length).
|
||||
|
||||
use crate::video::{codec_name, mkv_codec_name};
|
||||
use crate::{ASF_HEADER, Bytes, Container, MediaError, Result};
|
||||
@@ -50,10 +50,9 @@ fn ms(secs: f64) -> u64 {
|
||||
pub fn probe(bytes: &Bytes) -> Result<MediaInfo> {
|
||||
let mut info = probe_headers(bytes)?;
|
||||
if info.duration_ms == 0 && info.audio.as_ref().is_some_and(|a| a.decodable) && info.video.is_none() {
|
||||
// No length in the header (raw MP3 / ADTS without an index): add up the packet
|
||||
// lengths. This only demuxes, so a long file neither allocates its PCM nor stalls the caller.
|
||||
if let Some(d) = crate::audio::demux_duration_ms(bytes, Container::sniff(bytes).name()) {
|
||||
info.duration_ms = d;
|
||||
// No length in the header (raw MP3 / ADTS without an index): decode to measure.
|
||||
if let Ok(pcm) = crate::audio::decode(bytes) {
|
||||
info.duration_ms = ms(pcm.duration());
|
||||
}
|
||||
}
|
||||
Ok(info)
|
||||
|
||||
@@ -1280,11 +1280,7 @@ fn chart_kept_from(k: cd_chart::ChartKept) -> dm_chart::ChartKept {
|
||||
}
|
||||
|
||||
fn chart_to(c: &dm_chart::Chart) -> cd_chart::Chart {
|
||||
// PLAN: plan error: the sheet assigns these Chart fields here, but their P3(unowned) marker forbids replacing their initializer.
|
||||
let mut out = cd_chart::Chart {
|
||||
// P3(unowned): earlier framework Chart fields (no contract id)
|
||||
category_format: Default::default(),
|
||||
date_1904: Default::default(),
|
||||
kind: chart_type_to(c.kind),
|
||||
title: c.title.clone(),
|
||||
categories: c.categories.clone(),
|
||||
@@ -1302,6 +1298,9 @@ 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),
|
||||
@@ -1341,8 +1340,6 @@ fn chart_to(c: &dm_chart::Chart) -> cd_chart::Chart {
|
||||
&& let Some(raw) = &c.raw
|
||||
&& let Some(parsed) = cd_chart::read::read_chart_xml(raw.as_bytes()).or_else(|| cd_chart::chartex::read_chartex_xml(raw.as_bytes()))
|
||||
{
|
||||
out.category_format = parsed.category_format;
|
||||
out.date_1904 = parsed.date_1904;
|
||||
out.data_table = parsed.data_table;
|
||||
out.first_slice_angle = parsed.first_slice_angle;
|
||||
out.pivot_source = parsed.pivot_source;
|
||||
@@ -2167,8 +2164,6 @@ pub(crate) fn pres_to_craft(p: &deckcraft_model::Presentation) -> craft_pptx::Pr
|
||||
media: p.media.iter().map(media_item_to).collect(),
|
||||
first_slide_number: p.first_slide_number,
|
||||
next_id: p.next_id,
|
||||
// The model keeps no subset choice: a save writes whole embedded faces, as before craft-pptx read the flag.
|
||||
save_subset_fonts: false,
|
||||
embedded_fonts: p
|
||||
.embedded_fonts
|
||||
.iter()
|
||||
|
||||
+4
-161
@@ -332,164 +332,10 @@ fn has_media_shapes(shapes: &[Shape]) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
fn has_unpreviewed_ole_shapes(shapes: &[Shape]) -> bool {
|
||||
shapes.iter().any(|s| match &s.kind {
|
||||
ShapeKind::Opaque { preview: None, .. } => true,
|
||||
ShapeKind::Group { children, .. } => has_unpreviewed_ole_shapes(children),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The VML part with Office conditional-comment markers (`<!--[if …]>`, `<![if …]>`, `<![endif]-->`) removed, so shapes wrapped in them are parsed.
|
||||
fn strip_vml_conditionals(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> {
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut at = 0;
|
||||
let mut changed = false;
|
||||
while at < bytes.len() {
|
||||
let rest = &bytes[at..];
|
||||
let marker = rest.iter().position(|b| *b == b'<').map(|i| at + i);
|
||||
let Some(start) = marker else {
|
||||
out.extend_from_slice(rest);
|
||||
break;
|
||||
};
|
||||
out.extend_from_slice(&bytes[at..start]);
|
||||
let rest = &bytes[start..];
|
||||
let conditional = rest.starts_with(b"<!--[if") || rest.starts_with(b"<![if") || rest.starts_with(b"<![endif");
|
||||
if conditional {
|
||||
let Some(end) = rest.iter().position(|b| *b == b'>') else {
|
||||
out.extend_from_slice(rest);
|
||||
break;
|
||||
};
|
||||
let mut next = start + end + 1;
|
||||
if bytes.get(next..next + 3) == Some(b"-->") {
|
||||
next += 3;
|
||||
}
|
||||
at = next;
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
out.push(b'<');
|
||||
at = start + 1;
|
||||
}
|
||||
if changed { std::borrow::Cow::Owned(out) } else { std::borrow::Cow::Borrowed(bytes) }
|
||||
}
|
||||
|
||||
fn collect_vml_shapes<'a>(e: &'a craft_xml::El, out: &mut Vec<&'a craft_xml::El>, depth: usize) {
|
||||
if depth > 64 || out.len() >= 10_000 {
|
||||
return;
|
||||
}
|
||||
if e.is(craft_xml::Local("shape")) {
|
||||
out.push(e);
|
||||
}
|
||||
for c in e.elements() {
|
||||
collect_vml_shapes(c, out, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
fn vml_index(pkg: &mut craft_opc::LazyPackage, vml: &str) -> std::collections::HashMap<String, String> {
|
||||
let mut out = std::collections::HashMap::new();
|
||||
let Ok(Some(raw)) = pkg.read_limited(vml, craft_pptx::MAX_XML_PART as u64) else {
|
||||
return out;
|
||||
};
|
||||
let cleaned = strip_vml_conditionals(&raw);
|
||||
let Ok(root) = craft_drawingml::xmlx::parse(&cleaned) else {
|
||||
return out;
|
||||
};
|
||||
let rels = pkg.rels(vml).unwrap_or_default();
|
||||
let mut shapes = Vec::new();
|
||||
collect_vml_shapes(&root, &mut shapes, 0);
|
||||
for s in shapes {
|
||||
let Some(img) = s.find(craft_xml::Local("imagedata")) else { continue };
|
||||
let Some(rid) = img.attr_local("relid").or_else(|| img.attr_local("id")) else { continue };
|
||||
let Some(target) = rels.target(rid) else { continue };
|
||||
let keys = [s.attr_local("spid"), s.attr_local("id")];
|
||||
for key in keys.into_iter().flatten().filter(|k| !k.is_empty()) {
|
||||
out.entry(key.to_string()).or_insert_with(|| target.to_string());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn collect_ole_spids(e: &craft_xml::El, out: &mut Vec<(u32, String)>, depth: usize) {
|
||||
if depth > 64 || out.len() >= 10_000 {
|
||||
return;
|
||||
}
|
||||
if e.is(craft_xml::Local("graphicFrame"))
|
||||
&& let Some(id) = e
|
||||
.path(&[craft_xml::Local("nvGraphicFramePr"), craft_xml::Local("cNvPr")])
|
||||
.and_then(|c| c.attr_local("id"))
|
||||
.and_then(craft_xml::value::to_u32_lossy)
|
||||
&& let Some(ole) = e.find(craft_xml::Local("oleObj"))
|
||||
&& let Some(spid) = ole.attr_local("spid").filter(|s| !s.is_empty())
|
||||
{
|
||||
out.push((id, spid.to_string()));
|
||||
}
|
||||
for c in e.elements() {
|
||||
collect_ole_spids(c, out, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
fn media_content_type(path: &str) -> &'static str {
|
||||
match path.rsplit_once('.').map(|(_, ext)| ext).unwrap_or("") {
|
||||
e if e.eq_ignore_ascii_case("png") => "image/png",
|
||||
e if e.eq_ignore_ascii_case("jpg") || e.eq_ignore_ascii_case("jpeg") => "image/jpeg",
|
||||
e if e.eq_ignore_ascii_case("gif") => "image/gif",
|
||||
e if e.eq_ignore_ascii_case("svg") => "image/svg+xml",
|
||||
e if e.eq_ignore_ascii_case("emf") => "image/x-emf",
|
||||
e if e.eq_ignore_ascii_case("wmf") => "image/x-wmf",
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_ole_vml_previews(pkg: &mut craft_opc::LazyPackage, slide_path: &str, se: &craft_xml::El, pres: &mut Presentation, slide_idx: usize) {
|
||||
let mut ole_spids = Vec::new();
|
||||
collect_ole_spids(se, &mut ole_spids, 0);
|
||||
if ole_spids.is_empty() {
|
||||
return;
|
||||
}
|
||||
let slide_rels = pkg.rels(slide_path).unwrap_or_default();
|
||||
let vml_targets: Vec<String> = slide_rels.all("vmlDrawing").filter(|r| !r.external).map(|r| r.target.clone()).collect();
|
||||
if vml_targets.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut indices = Vec::new();
|
||||
for vml in &vml_targets {
|
||||
indices.push(vml_index(pkg, vml));
|
||||
}
|
||||
for (shape_id, spid) in ole_spids {
|
||||
let needs_preview = pres
|
||||
.slides
|
||||
.get(slide_idx)
|
||||
.and_then(|sl| deckcraft_model::find_shape(&sl.shapes, deckcraft_model::ShapeId(shape_id)))
|
||||
.is_some_and(|sh| matches!(&sh.kind, ShapeKind::Opaque { preview: None, .. }));
|
||||
if !needs_preview {
|
||||
continue;
|
||||
}
|
||||
let Some(img_target) = indices.iter().find_map(|idx| idx.get(&spid)).cloned() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(Some(img_bytes)) = pkg.read_limited(&img_target, 64 << 20) else {
|
||||
continue;
|
||||
};
|
||||
let name = img_target.rsplit_once('/').map_or(img_target.as_str(), |(_, n)| n).to_string();
|
||||
let ct = media_content_type(&name);
|
||||
let Some(media_id) = pres.add_media(&name, ct, img_bytes) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(slide_arc) = pres.slides.get_mut(slide_idx)
|
||||
&& let Some(sh) = deckcraft_model::find_shape_mut(&mut std::sync::Arc::make_mut(slide_arc).shapes, deckcraft_model::ShapeId(shape_id))
|
||||
&& let ShapeKind::Opaque { preview, .. } = &mut sh.kind
|
||||
{
|
||||
*preview = Some(media_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn post_import_timing(bytes: &[u8], pres: &mut Presentation) {
|
||||
let need_builds = has_unfolded_paragraph_builds(pres);
|
||||
let need_media = pres.slides.iter().any(|s| has_media_shapes(&s.shapes));
|
||||
let need_ole = pres.slides.iter().any(|s| has_unpreviewed_ole_shapes(&s.shapes));
|
||||
if !need_builds && !need_media && !need_ole {
|
||||
if !need_builds && !need_media {
|
||||
return;
|
||||
}
|
||||
let Ok(mut pkg) = craft_opc::LazyPackage::open(bytes, &craft_pptx::LIMITS) else {
|
||||
@@ -508,13 +354,10 @@ fn post_import_timing(bytes: &[u8], pres: &mut Presentation) {
|
||||
return;
|
||||
};
|
||||
for (i, s) in list.children(craft_xml::Local("sldId")).take(MAX_SLIDE_ENTRIES).enumerate() {
|
||||
let Some(target) = s.attr_local("r:id").and_then(|rid| pres_rels.target(rid)).map(str::to_string) else { continue };
|
||||
let Ok(Some(sb)) = pkg.read_limited(&target, craft_pptx::MAX_XML_PART as u64) else { continue };
|
||||
let Ok(se) = craft_drawingml::xmlx::parse(&sb) else { continue };
|
||||
if need_ole && pres.slides.get(i).is_some_and(|sl| has_unpreviewed_ole_shapes(&sl.shapes)) {
|
||||
apply_ole_vml_previews(&mut pkg, &target, &se, pres, i);
|
||||
}
|
||||
let Some(slide_arc) = pres.slides.get_mut(i) else { break };
|
||||
let Some(target) = s.attr_local("r:id").and_then(|rid| pres_rels.target(rid)) else { continue };
|
||||
let Ok(Some(sb)) = pkg.read_limited(target, craft_pptx::MAX_XML_PART as u64) else { continue };
|
||||
let Ok(se) = craft_drawingml::xmlx::parse(&sb) else { continue };
|
||||
let Some(timing) = se.child(craft_xml::Local("timing")) else { continue };
|
||||
if need_media && has_media_shapes(&slide_arc.shapes) {
|
||||
apply_media_timing(timing, &mut std::sync::Arc::make_mut(slide_arc).shapes);
|
||||
|
||||
@@ -32,11 +32,6 @@ fn deck() -> Vec<u8> {
|
||||
|
||||
/// [`deck`] with `frames` in place of [`FRAME`].
|
||||
fn deck_with(frames: &str) -> Vec<u8> {
|
||||
deck_with_vml(frames, VML)
|
||||
}
|
||||
|
||||
/// [`deck`] with `frames` in place of [`FRAME`] and `vml` as the drawing.
|
||||
fn deck_with_vml(frames: &str, vml: &str) -> Vec<u8> {
|
||||
let bytes = deckcraft_pptx::export(&defaults::new_presentation(None)).expect("export");
|
||||
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).expect("zip");
|
||||
let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
@@ -60,7 +55,7 @@ fn deck_with_vml(frames: &str, vml: &str) -> Vec<u8> {
|
||||
out.write_all(&d).expect("write");
|
||||
}
|
||||
for (name, data) in [
|
||||
("ppt/drawings/vmlDrawing1.vml", vml.as_bytes().to_vec()),
|
||||
("ppt/drawings/vmlDrawing1.vml", VML.as_bytes().to_vec()),
|
||||
("ppt/drawings/_rels/vmlDrawing1.vml.rels", VML_RELS.as_bytes().to_vec()),
|
||||
("ppt/media/other.png", png(10)),
|
||||
("ppt/media/preview.png", png(200)),
|
||||
@@ -82,18 +77,6 @@ fn an_ole_object_without_a_picture_shows_its_vml_preview() {
|
||||
assert_eq!(media.name, "preview.png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vml_preview_inside_a_conditional_comment_is_found_by_its_o_spid() {
|
||||
let head = &VML[..VML.find('>').expect("xml start") + 1];
|
||||
let vml = format!(
|
||||
r#"{head}<!--[if gte vml 1]><v:shape id="_x0000_s1025" o:spid="_x0000_s2050"><v:imagedata o:relid="rIdB"/></v:shape><![endif]--></xml>"#
|
||||
);
|
||||
let p = deckcraft_pptx::import(&deck_with_vml(FRAME, &vml)).expect("import");
|
||||
let s = p.slides[0].shapes.iter().find(|s| s.name == "Object 3").expect("frame");
|
||||
let ShapeKind::Opaque { preview: Some(m), .. } = &s.kind else { panic!("{:?}", s.kind) };
|
||||
assert_eq!(p.media.iter().find(|x| x.id == *m).map(|x| x.name.as_str()), Some("preview.png"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn activex_controls_show_their_pictures() {
|
||||
let p = deckcraft_pptx::import(&deck()).expect("import");
|
||||
|
||||
@@ -167,20 +167,15 @@ impl Region {
|
||||
}
|
||||
}
|
||||
|
||||
/// How far from a whole pixel an edge may be and still count as on it.
|
||||
const EDGE_SLACK: f64 = 1e-3;
|
||||
|
||||
/// `r` (slide space) in pixels at `scale` pixels per point, rounded outwards; `None` when not finite.
|
||||
/// An edge within [`EDGE_SLACK`] of a whole pixel counts as on it, so the float noise of a zoom that is
|
||||
/// no exact binary fraction does not widen a slide-sized extent by a pixel.
|
||||
fn to_px(r: Rect, scale: f64) -> Option<(i64, i64, i64, i64)> {
|
||||
let lim = i32::MAX as f64 / 2.0;
|
||||
let px = |v: f64| if v.is_finite() { Some(v.clamp(-lim, lim)) } else { None };
|
||||
Some((
|
||||
px((r.x0 * scale + EDGE_SLACK).floor())? as i64,
|
||||
px((r.y0 * scale + EDGE_SLACK).floor())? as i64,
|
||||
px((r.x1 * scale - EDGE_SLACK).ceil())? as i64,
|
||||
px((r.y1 * scale - EDGE_SLACK).ceil())? as i64,
|
||||
px((r.x0 * scale).floor())? as i64,
|
||||
px((r.y0 * scale).floor())? as i64,
|
||||
px((r.x1 * scale).ceil())? as i64,
|
||||
px((r.y1 * scale).ceil())? as i64,
|
||||
))
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use deckcraft_color::Rgba;
|
||||
use deckcraft_geom::preset::FillMode;
|
||||
use deckcraft_model::resolve::Ctx;
|
||||
use deckcraft_model::style::{ColorRef, Fill, GradientFlip, GradientShape, PictureFill, PictureMode};
|
||||
use deckcraft_model::style::{ColorRef, Fill, GradientShape, PictureFill, PictureMode};
|
||||
use deckcraft_model::{PhType, Presentation};
|
||||
use kurbo::{Affine, BezPath, Point, Rect, Shape as _};
|
||||
use vello_cpu::{RenderContext, peniko};
|
||||
@@ -51,18 +51,16 @@ pub fn fill_path(
|
||||
// its edges); a radial one ends on the circle around it, from a focus placed in the
|
||||
// shape's own box (PowerPoint's "from corner" presets centre the tile on the corner).
|
||||
let tile = tile_box(bounds, g.tile);
|
||||
let stops: Vec<(f64, Rgba)> = g.stops.iter().map(|s| (s.pos, shade(rctx.color(&s.color, ph), mode))).collect();
|
||||
ctx.set_paint(gradient(&g.shape, stops, bounds, alpha));
|
||||
|
||||
let mut stops: Vec<(f64, Rgba)> = g.stops.iter().map(|s| (s.pos.clamp(0.0, 1.0), shade(rctx.color(&s.color, ph), mode))).collect();
|
||||
stops.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
// Rectangle and outline paths: rasterised (see `pathgrad`).
|
||||
if let GradientShape::Path { path: kind, focus } = &g.shape
|
||||
&& matches!(kind.as_str(), "rect" | "shape")
|
||||
{
|
||||
let ramp = crate::ramp::expand(&stops);
|
||||
if g.tile.iter().all(|v| *v == 0.0) {
|
||||
crate::pathgrad::fill(ctx, kind, *focus, &ramp, bounds, path, m, alpha);
|
||||
} else {
|
||||
crate::pathgrad::fill_tiled_flipped(ctx, kind, *focus, &ramp, bounds, tile, g.flip.unwrap_or(GradientFlip::None), path, m, alpha);
|
||||
}
|
||||
crate::pathgrad::fill(ctx, kind, *focus, &crate::ramp::expand(&stops), bounds, path, m, alpha);
|
||||
return;
|
||||
}
|
||||
// PowerPoint's ramp between stops (linear light, S-shaped), see `ramp`.
|
||||
|
||||
+12
-140
@@ -12,7 +12,6 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use deckcraft_color::Rgba;
|
||||
use deckcraft_model::style::GradientFlip;
|
||||
use kurbo::{Affine, BezPath, PathEl, Point, Rect};
|
||||
use vello_cpu::{Pixmap, RenderContext, peniko};
|
||||
|
||||
@@ -63,12 +62,6 @@ pub(crate) fn fit_raster(edges: usize, pw: u32, ph: u32) -> (u32, u32) {
|
||||
/// focus rect `focus` (fractions inset from left, top, right, bottom), `outline` being the
|
||||
/// shape's flattened polygon(s) for `shape`.
|
||||
pub fn position(kind: &str, bounds: Rect, focus: [f64; 4], outline: &[Vec<Point>], p: Point) -> f64 {
|
||||
position_in_tile(kind, bounds, bounds, focus, outline, p)
|
||||
}
|
||||
|
||||
/// [`position`] with the `rect` ramp ending on the edges of `tile` instead of `bounds`; the focus
|
||||
/// rect is still measured in `bounds`.
|
||||
fn position_in_tile(kind: &str, bounds: Rect, tile: Rect, focus: [f64; 4], outline: &[Vec<Point>], p: Point) -> f64 {
|
||||
let f = Rect::new(
|
||||
bounds.x0 + bounds.width() * focus[0].clamp(0.0, 1.0),
|
||||
bounds.y0 + bounds.height() * focus[1].clamp(0.0, 1.0),
|
||||
@@ -114,7 +107,7 @@ fn position_in_tile(kind: &str, bounds: Rect, tile: Rect, focus: [f64; 4], outli
|
||||
0.0
|
||||
}
|
||||
};
|
||||
axis(p.x, f.x0, f.x1, tile.x0, tile.x1).max(axis(p.y, f.y0, f.y1, tile.y0, tile.y1)).clamp(0.0, 1.0)
|
||||
axis(p.x, f.x0, f.x1, bounds.x0, bounds.x1).max(axis(p.y, f.y0, f.y1, bounds.y0, bounds.y1)).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -294,74 +287,15 @@ pub fn ramp(stops: &[(f64, Rgba)]) -> Vec<Rgba> {
|
||||
/// `ramp::expand`) over `bounds`, faded by `alpha`; `m` maps the path to the output.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn fill(ctx: &mut RenderContext, kind: &str, focus: [f64; 4], stops: &[(f64, Rgba)], bounds: Rect, path: &BezPath, m: Affine, alpha: f64) {
|
||||
fill_tiled(ctx, kind, focus, stops, bounds, bounds, path, m, alpha);
|
||||
}
|
||||
|
||||
/// [`fill`] with the gradient laid out in `tile` (the `a:tileRect` box in path units) and
|
||||
/// repeated across the shape where `tile` does not cover it; a `tile` equal to `bounds` draws
|
||||
/// as [`fill`] does.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn fill_tiled(
|
||||
ctx: &mut RenderContext,
|
||||
kind: &str,
|
||||
focus: [f64; 4],
|
||||
stops: &[(f64, Rgba)],
|
||||
bounds: Rect,
|
||||
tile: Rect,
|
||||
path: &BezPath,
|
||||
m: Affine,
|
||||
alpha: f64,
|
||||
) {
|
||||
fill_tiled_flipped(ctx, kind, focus, stops, bounds, tile, GradientFlip::None, path, m, alpha);
|
||||
}
|
||||
|
||||
/// The part of `tile` a tiled gradient raster covers, with whether it repeats across and down. On
|
||||
/// an axis where `tile` spans all of `cover` (the shape's box and path), the raster covers only
|
||||
/// `cover` and nothing repeats on that axis; on any other axis it covers the whole tile, which
|
||||
/// repeats.
|
||||
pub(crate) fn tiled_sample(cover: Rect, tile: Rect) -> (Rect, bool, bool) {
|
||||
let spans_x = tile.x0 <= cover.x0 && tile.x1 >= cover.x1;
|
||||
let spans_y = tile.y0 <= cover.y0 && tile.y1 >= cover.y1;
|
||||
let (x0, x1) = if spans_x { (cover.x0, cover.x1) } else { (tile.x0, tile.x1) };
|
||||
let (y0, y1) = if spans_y { (cover.y0, cover.y1) } else { (tile.y0, tile.y1) };
|
||||
(Rect::new(x0, y0, x1, y1), !spans_x, !spans_y)
|
||||
}
|
||||
|
||||
/// Fill `path` with repeated path-gradient tiles, reflecting alternate tiles along `flip` axes.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn fill_tiled_flipped(
|
||||
ctx: &mut RenderContext,
|
||||
kind: &str,
|
||||
focus: [f64; 4],
|
||||
stops: &[(f64, Rgba)],
|
||||
bounds: Rect,
|
||||
tile: Rect,
|
||||
flip: GradientFlip,
|
||||
path: &BezPath,
|
||||
m: Affine,
|
||||
alpha: f64,
|
||||
) {
|
||||
if bounds.width() <= 0.0 || bounds.height() <= 0.0 || !bounds.is_finite() || stops.is_empty() {
|
||||
return;
|
||||
}
|
||||
let tile = if tile.is_finite() && tile.width() > 0.0 && tile.height() > 0.0 { tile } else { bounds };
|
||||
let untiled = tile == bounds;
|
||||
let cover = kurbo::Shape::bounding_box(path);
|
||||
let cover = if cover.is_finite() { cover.union(bounds) } else { bounds };
|
||||
let (sample, repeat_x, repeat_y) = if untiled { (bounds, false, false) } else { tiled_sample(cover, tile) };
|
||||
let k = crate::scale_of(m);
|
||||
let k = if k.is_finite() && k > 0.0 { k } else { 1.0 };
|
||||
let s = if untiled { (MAX_SIDE / (sample.width().max(sample.height()) * k)).min(1.0) * k } else { k };
|
||||
let (sx, sy) = if untiled {
|
||||
(s, s)
|
||||
} else {
|
||||
let [a, b, c, d, _, _] = m.as_coeffs();
|
||||
let valid_scale = |v: f64| if v.is_finite() && v > 0.0 { v } else { 1.0 };
|
||||
(valid_scale(a.hypot(b)), valid_scale(c.hypot(d)))
|
||||
};
|
||||
let limit = if untiled { 4096.0 } else { MAX_SIDE };
|
||||
let (pw, ph) = ((sample.width() * sx).ceil().clamp(1.0, limit) as u32, (sample.height() * sy).ceil().clamp(1.0, limit) as u32);
|
||||
let (mut outline, pw, ph) = if kind == "shape" {
|
||||
let longest = bounds.width().max(bounds.height()) * k;
|
||||
let s = (MAX_SIDE / longest).min(1.0) * k;
|
||||
let (pw, ph) = (((bounds.width() * s).ceil() as u32).clamp(1, 4096), ((bounds.height() * s).ceil() as u32).clamp(1, 4096));
|
||||
let (outline, pw, ph) = if kind == "shape" {
|
||||
let max_edges = edge_budget(pw, ph);
|
||||
let pixel = (bounds.width() / f64::from(pw)).min(bounds.height() / f64::from(ph));
|
||||
let o = simplify(polygons(path), pixel, max_edges);
|
||||
@@ -375,21 +309,13 @@ pub(crate) fn fill_tiled_flipped(
|
||||
if kind == "shape" && outline.is_empty() {
|
||||
return;
|
||||
}
|
||||
if !untiled {
|
||||
for poly in &mut outline {
|
||||
for p in poly {
|
||||
p.x = tile.x0 + (p.x - bounds.x0) * tile.width() / bounds.width();
|
||||
p.y = tile.y0 + (p.y - bounds.y0) * tile.height() / bounds.height();
|
||||
}
|
||||
}
|
||||
}
|
||||
let lut = ramp(stops);
|
||||
let a = alpha.clamp(0.0, 1.0);
|
||||
let mut data = Vec::with_capacity((pw * ph) as usize);
|
||||
for j in 0..ph {
|
||||
for i in 0..pw {
|
||||
let p = Point::new(sample.x0 + (i as f64 + 0.5) / pw as f64 * sample.width(), sample.y0 + (j as f64 + 0.5) / ph as f64 * sample.height());
|
||||
let t = if untiled { position(kind, bounds, focus, &outline, p) } else { position_in_tile(kind, bounds, tile, focus, &outline, p) };
|
||||
let p = Point::new(bounds.x0 + (i as f64 + 0.5) / pw as f64 * bounds.width(), bounds.y0 + (j as f64 + 0.5) / ph as f64 * bounds.height());
|
||||
let t = position(kind, bounds, focus, &outline, p);
|
||||
let c = lut.get((t * 255.0).round().clamp(0.0, 255.0) as usize).copied().unwrap_or(Rgba::BLACK);
|
||||
let ca = (c.a as f64 * a).round().clamp(0.0, 255.0);
|
||||
let mul = |v: u8| (v as f64 * ca / 255.0).round().clamp(0.0, 255.0) as u8;
|
||||
@@ -398,24 +324,12 @@ pub(crate) fn fill_tiled_flipped(
|
||||
}
|
||||
let pm = Arc::new(Pixmap::from_parts(data, pw as u16, ph as u16));
|
||||
ctx.set_transform(m);
|
||||
let extend = |repeats: bool, reflected: bool| match (repeats, reflected) {
|
||||
(false, _) => peniko::Extend::Pad,
|
||||
(true, true) => peniko::Extend::Reflect,
|
||||
(true, false) => peniko::Extend::Repeat,
|
||||
};
|
||||
let sampler = if untiled {
|
||||
peniko::ImageSampler { quality: peniko::ImageQuality::Medium, ..Default::default() }
|
||||
} else {
|
||||
peniko::ImageSampler {
|
||||
x_extend: extend(repeat_x, matches!(flip, GradientFlip::X | GradientFlip::Xy)),
|
||||
y_extend: extend(repeat_y, matches!(flip, GradientFlip::Y | GradientFlip::Xy)),
|
||||
quality: peniko::ImageQuality::Medium,
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler });
|
||||
ctx.set_paint(vello_cpu::Image {
|
||||
image: vello_cpu::ImageSource::Pixmap(pm),
|
||||
sampler: peniko::ImageSampler { quality: peniko::ImageQuality::Medium, ..Default::default() },
|
||||
});
|
||||
ctx.set_paint_transform(
|
||||
Affine::translate(sample.origin().to_vec2()) * Affine::scale_non_uniform(sample.width() / pw as f64, sample.height() / ph as f64),
|
||||
Affine::translate(bounds.origin().to_vec2()) * Affine::scale_non_uniform(bounds.width() / pw as f64, bounds.height() / ph as f64),
|
||||
);
|
||||
ctx.fill_path(path);
|
||||
ctx.reset_paint_transform();
|
||||
@@ -541,48 +455,6 @@ mod tests {
|
||||
assert!(px.chunks(4).all(|p| p[3] == 0), "nothing was painted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tile_reaching_past_the_shape_samples_only_the_shape() {
|
||||
let b = Rect::new(0.0, 0.0, 400.0, 200.0);
|
||||
// A corner preset's tile reaches a box up and left: nothing repeats, the shape is sampled.
|
||||
assert_eq!(tiled_sample(b, Rect::new(-400.0, -200.0, 400.0, 200.0)), (b, false, false));
|
||||
// A tile inside the shape repeats on both axes.
|
||||
let inner = Rect::new(100.0, 50.0, 200.0, 150.0);
|
||||
assert_eq!(tiled_sample(b, inner), (inner, true, true));
|
||||
// A tile as tall as the shape and narrower repeats across only.
|
||||
assert_eq!(tiled_sample(b, Rect::new(100.0, -10.0, 200.0, 210.0)), (Rect::new(100.0, 0.0, 200.0, 200.0), true, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_off_centre_tile_keeps_the_focus_in_the_shape_box() {
|
||||
// The tile is the right half of the shape. A centred focus rect sits at the shape's centre,
|
||||
// on the tile's left edge, and the ramp ends on the tile's right edge.
|
||||
let b = Rect::new(0.0, 0.0, 400.0, 200.0);
|
||||
let tile = Rect::new(200.0, 0.0, 400.0, 200.0);
|
||||
let at = |x: f64| position_in_tile("rect", b, tile, CENTRE, &[], Point::new(x, 100.0));
|
||||
assert_eq!(at(200.0), 0.0, "the focus is at the shape's centre");
|
||||
assert!((at(300.0) - 0.5).abs() < 1e-9, "half way to the tile's right edge: {}", at(300.0));
|
||||
assert_eq!(at(400.0), 1.0, "the ramp ends on the tile's right edge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tile_reaching_past_the_shape_keeps_its_detail() {
|
||||
// The tile is four boxes wide; the hard stop half way sits 200 pt in. The raster covers the
|
||||
// shape only, so the edge stays within about a point.
|
||||
let b = Rect::new(0.0, 0.0, 400.0, 200.0);
|
||||
let tile = Rect::new(-1200.0, -200.0, 400.0, 200.0);
|
||||
let (w, k) = (800u16, 2.0);
|
||||
let stops = [(0.0, Rgba::WHITE), (0.5, Rgba::WHITE), (0.5, Rgba::BLACK), (1.0, Rgba::BLACK)];
|
||||
let mut ctx = RenderContext::new(w, 400);
|
||||
fill_tiled(&mut ctx, "rect", [0.0, 0.0, 1.0, 1.0], &stops, b, tile, &b.to_path(0.1), Affine::scale(k), 1.0);
|
||||
ctx.flush();
|
||||
let mut px = vec![0u8; usize::from(w) * 400 * 4];
|
||||
ctx.render(vello_cpu::PixmapMut::new(w, 400, &mut px).unwrap(), &mut vello_cpu::Resources::new());
|
||||
let red = |x: usize, y: usize| px[(y * usize::from(w) + x) * 4];
|
||||
assert!(red(397, 20) > 240, "before the edge {}", red(397, 20));
|
||||
assert!(red(403, 20) < 15, "after the edge {}", red(403, 20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ramp_runs_through_the_stops() {
|
||||
let stops = [(0.0, Rgba::rgb(0, 0, 0)), (0.5, Rgba::rgb(128, 128, 128)), (1.0, Rgba::rgb(255, 255, 255))];
|
||||
|
||||
+12
-25
@@ -3256,33 +3256,20 @@ fn line_chart_value_labels_are_drawn_above_their_points() {
|
||||
let sh = Shape { id: ShapeId(633), xfrm: Some(Xfrm::new(0.0, 0.0, 400.0, 300.0)), kind: ShapeKind::Chart(Box::new(c)), ..Default::default() };
|
||||
render_slide(&deck_with(vec![sh]), 0, &RenderOpts { scale: 1.0, ..Default::default() })
|
||||
};
|
||||
let is_red = |p: [u8; 4]| p[0] > 200 && p[1] < 60 && p[2] < 60;
|
||||
let red = |img: &Image| (0..400u32).flat_map(|x| (0..300u32).map(move |y| (x, y))).filter(|(x, y)| is_red(img.pixel(*x, *y))).count();
|
||||
// The labels' own ink, counted as separate runs of columns, so the check holds in any interface face: every
|
||||
// point gets a label of its own, whatever its glyphs weigh.
|
||||
let label_runs = |off: &Image, on: &Image| {
|
||||
let added: Vec<bool> = (0..400u32).map(|x| (0..300u32).any(|y| is_red(on.pixel(x, y)) && !is_red(off.pixel(x, y)))).collect();
|
||||
let mut runs = 0;
|
||||
let mut gap = usize::MAX;
|
||||
for inked in added {
|
||||
if inked {
|
||||
if gap >= 3 {
|
||||
runs += 1;
|
||||
}
|
||||
gap = 0;
|
||||
} else {
|
||||
gap = gap.saturating_add(1);
|
||||
}
|
||||
}
|
||||
runs
|
||||
let red = |img: &Image| {
|
||||
(0..400u32)
|
||||
.flat_map(|x| (0..300u32).map(move |y| (x, y)))
|
||||
.filter(|(x, y)| {
|
||||
let p = img.pixel(*x, *y);
|
||||
p[0] > 200 && p[1] < 60 && p[2] < 60
|
||||
})
|
||||
.count()
|
||||
};
|
||||
for kind in [ChartType::Line, ChartType::LineMarkers] {
|
||||
let points = Chart::sample(kind).categories.len();
|
||||
let (off, on) = (draw(kind, false, false), draw(kind, true, false));
|
||||
assert!(red(&on) > red(&off), "{kind:?}: labels add red ink");
|
||||
assert!(label_runs(&off, &on) >= points, "{kind:?}: every point has its label ({} runs, {points} points)", label_runs(&off, &on));
|
||||
let own = draw(kind, true, true);
|
||||
assert!(label_runs(&off, &own) >= points, "{kind:?}: a series' own showVal labels each of its points");
|
||||
let (off, on) = (red(&draw(kind, false, false)), red(&draw(kind, true, false)));
|
||||
assert!(on > off + 100, "{kind:?}: labels add red ink ({off} → {on})");
|
||||
let own = red(&draw(kind, true, true));
|
||||
assert!(own > off + 30, "{kind:?}: a series' own showVal shows its labels ({off} → {own})");
|
||||
}
|
||||
// Area series keep none, and scatter and bubble series (drawn by the same code) are unchanged.
|
||||
for kind in [ChartType::Area, ChartType::Scatter, ChartType::Bubble] {
|
||||
|
||||
@@ -6,7 +6,7 @@ use super::{
|
||||
render_slide, trim_ends,
|
||||
};
|
||||
use deckcraft_color::Rgba;
|
||||
use deckcraft_model::style::{ColorRef, GradientFlip};
|
||||
use deckcraft_model::style::ColorRef;
|
||||
use deckcraft_model::{CustomPath, Geom, Presentation, Shape, ShapeId, Xfrm};
|
||||
use kurbo::Shape as _;
|
||||
|
||||
@@ -397,92 +397,6 @@ fn a_linear_gradient_spans_its_tile_rect() {
|
||||
assert!(img.pixel(305, 150)[0] < 15 && img.pixel(495, 150)[0] < 15, "{:?}", img.pixel(305, 150));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rectangular_gradient_spans_its_tile_rect() {
|
||||
let mut sh = radial([0.5; 4]);
|
||||
if let Some(Fill::Gradient(g)) = &mut sh.fill {
|
||||
g.shape = deckcraft_model::style::GradientShape::Path { path: "rect".into(), focus: [0.5; 4] };
|
||||
g.tile = [0.25, 0.0, 0.25, 0.0];
|
||||
}
|
||||
let img = render(vec![sh]);
|
||||
assert!(img.pixel(300, 200)[0] > 240, "center {:?}", img.pixel(300, 200));
|
||||
assert!(img.pixel(395, 200)[0] < 80, "tile edge {:?}", img.pixel(395, 200));
|
||||
assert!(img.pixel(450, 200)[0] > 80, "next tile {:?}", img.pixel(450, 200));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_gradient_spans_its_tile_rect() {
|
||||
let mut sh = radial([0.5; 4]);
|
||||
sh.geom = Geom::Preset { name: "ellipse".into(), adj: vec![] };
|
||||
if let Some(Fill::Gradient(g)) = &mut sh.fill {
|
||||
g.shape = deckcraft_model::style::GradientShape::Path { path: "shape".into(), focus: [0.5; 4] };
|
||||
g.tile = [0.25, 0.0, 0.25, 0.0];
|
||||
}
|
||||
let img = render(vec![sh]);
|
||||
assert!(img.pixel(300, 200)[0] > 240, "center {:?}", img.pixel(300, 200));
|
||||
assert!(img.pixel(395, 200)[0] < 80, "tile edge {:?}", img.pixel(395, 200));
|
||||
assert!(img.pixel(450, 200)[0] > 80, "next tile {:?}", img.pixel(450, 200));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rectangular_gradient_reflects_alternate_tiles() {
|
||||
let mut sh = radial([0.5; 4]);
|
||||
if let Some(Fill::Gradient(g)) = &mut sh.fill {
|
||||
g.shape = deckcraft_model::style::GradientShape::Path { path: "rect".into(), focus: [0.25, 0.5, 0.75, 0.5] };
|
||||
g.tile = [0.25, 0.0, 0.25, 0.0];
|
||||
}
|
||||
let repeated = render(vec![sh.clone()]).pixel(450, 200)[0];
|
||||
if let Some(Fill::Gradient(g)) = &mut sh.fill {
|
||||
g.flip = Some(GradientFlip::X);
|
||||
}
|
||||
let reflected = render(vec![sh]).pixel(450, 200)[0];
|
||||
assert!(repeated > reflected + 60, "repeat {repeated}, reflected {reflected}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_rectangular_gradient_tiles_remain_distinct_in_a_large_shape() {
|
||||
let mut sh = radial([0.5; 4]);
|
||||
sh.xfrm = Some(Xfrm::new(100.0, 100.0, 4000.0, 200.0));
|
||||
if let Some(Fill::Gradient(g)) = &mut sh.fill {
|
||||
g.shape = deckcraft_model::style::GradientShape::Path { path: "rect".into(), focus: [0.5; 4] };
|
||||
g.tile = [0.4995, 0.0, 0.4995, 0.0];
|
||||
}
|
||||
let img = render(vec![sh]);
|
||||
let edge = img.pixel(150, 200)[0];
|
||||
let center = img.pixel(152, 200)[0];
|
||||
assert!(i32::from(center) > i32::from(edge) + 100, "edge {edge}, center {center}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_rectangular_gradient_tiles_keep_their_horizontal_ramp() {
|
||||
let mut sh = radial([0.5; 4]);
|
||||
sh.xfrm = Some(Xfrm::new(100.0, 100.0, 400.0, 4000.0));
|
||||
if let Some(Fill::Gradient(g)) = &mut sh.fill {
|
||||
g.shape = deckcraft_model::style::GradientShape::Path { path: "rect".into(), focus: [0.5, 0.025, 0.5, 0.975] };
|
||||
g.tile = [0.495, 0.0, 0.495, 0.0];
|
||||
}
|
||||
let img = render(vec![sh]);
|
||||
let edge = img.pixel(150, 200)[0];
|
||||
let center = img.pixel(152, 200)[0];
|
||||
assert!(i32::from(center) > i32::from(edge) + 100, "edge {edge}, center {center}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scaled_group_keeps_detail_across_a_narrow_gradient_tile() {
|
||||
let img = in_a_scaled_group(8.0, 0.125, Presentation::default(), |w, h| {
|
||||
let mut sh = radial([0.5, 0.025, 0.5, 0.975]);
|
||||
sh.xfrm = Some(Xfrm::new(0.0, 0.0, w, h));
|
||||
if let Some(Fill::Gradient(g)) = &mut sh.fill {
|
||||
g.shape = deckcraft_model::style::GradientShape::Path { path: "rect".into(), focus: [0.5, 0.025, 0.5, 0.975] };
|
||||
g.tile = [0.491_666_666_666_666_64, 0.0, 0.491_666_666_666_666_64, 0.0];
|
||||
}
|
||||
sh
|
||||
});
|
||||
let edge = img.pixel(110, 130)[0];
|
||||
let center = img.pixel(112, 130)[0];
|
||||
assert!(i32::from(center) > i32::from(edge) + 60, "edge {edge}, center {center}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_3d_pictures_border_stays_centred_on_its_edge() {
|
||||
let mut p = picture_deck(Some(Line::solid(ColorRef::rgb(RED), 8.0)));
|
||||
|
||||
@@ -9,7 +9,6 @@ description = "DeckCraft text layout: runs to shaped glyph lines with bullets, i
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft = { workspace = true, features = ["text"] }
|
||||
deckcraft-model = { workspace = true }
|
||||
deckcraft-geom = { workspace = true }
|
||||
deckcraft-color = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
fn roman(mut n: u32, upper: bool) -> String {
|
||||
let table = [
|
||||
(1000, "m"),
|
||||
(900, "cm"),
|
||||
(500, "d"),
|
||||
(400, "cd"),
|
||||
(100, "c"),
|
||||
(90, "xc"),
|
||||
(50, "l"),
|
||||
(40, "xl"),
|
||||
(10, "x"),
|
||||
(9, "ix"),
|
||||
(5, "v"),
|
||||
(4, "iv"),
|
||||
(1, "i"),
|
||||
];
|
||||
let mut s = String::new();
|
||||
if n == 0 || n > 3999 {
|
||||
return n.to_string();
|
||||
}
|
||||
for (v, r) in table {
|
||||
while n >= v {
|
||||
s.push_str(r);
|
||||
n -= v;
|
||||
}
|
||||
}
|
||||
if upper { s.to_uppercase() } else { s }
|
||||
}
|
||||
|
||||
fn alpha_num(n: u32, upper: bool) -> String {
|
||||
if n == 0 {
|
||||
return String::new();
|
||||
}
|
||||
let n = n - 1;
|
||||
let c = (b'a' + (n % 26) as u8) as char;
|
||||
let reps = (n / 26 + 1).min(50);
|
||||
let s: String = std::iter::repeat_n(c, reps as usize).collect();
|
||||
if upper { s.to_uppercase() } else { s }
|
||||
}
|
||||
|
||||
/// Letters of a numbering alphabet: 1 → the first, past the end the letter doubles ("aa"), as
|
||||
/// the Latin alphabetic schemes do.
|
||||
fn letters(list: &[char], n: u32) -> String {
|
||||
let len = list.len().max(1) as u32;
|
||||
let Some(i) = n.checked_sub(1) else { return String::new() };
|
||||
let c = list.get((i % len) as usize).copied().unwrap_or('?');
|
||||
std::iter::repeat_n(c, (i / len + 1).min(50) as usize).collect()
|
||||
}
|
||||
|
||||
/// `n` written with the digits `zero..zero+9` (Thai, Devanagari, full-width digits).
|
||||
fn digits_in(n: u32, zero: char) -> String {
|
||||
n.to_string().chars().map(|d| d.to_digit(10).and_then(|v| char::from_u32(zero as u32 + v)).unwrap_or(d)).collect()
|
||||
}
|
||||
|
||||
const CJK_DIGITS: [char; 10] = ['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
|
||||
|
||||
/// Chinese numerals: 10 → 十, 11 → 十一, 25 → 二十五, 105 → 一百零五.
|
||||
pub(crate) fn chinese_num(n: u32) -> String {
|
||||
if n == 0 || n > 99_999 {
|
||||
return n.to_string();
|
||||
}
|
||||
let units = ['\0', '十', '百', '千', '万'];
|
||||
let ds: Vec<u32> = n.to_string().chars().filter_map(|c| c.to_digit(10)).collect();
|
||||
let mut out = String::new();
|
||||
let mut zero = false;
|
||||
for (i, d) in ds.iter().enumerate() {
|
||||
let place = ds.len() - 1 - i;
|
||||
if *d == 0 {
|
||||
zero = true;
|
||||
continue;
|
||||
}
|
||||
if zero {
|
||||
out.push('零');
|
||||
zero = false;
|
||||
}
|
||||
// "十" alone for 10–19, not "一十".
|
||||
if !(*d == 1 && place == 1 && i == 0) {
|
||||
out.push(CJK_DIGITS.get(*d as usize).copied().unwrap_or('?'));
|
||||
}
|
||||
if let Some(u) = units.get(place).filter(|u| **u != '\0') {
|
||||
out.push(*u);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Text of an auto-number bullet: `arabicPeriod` 3 → "3.". The East Asian, Thai, Hindi, Arabic
|
||||
/// and Hebrew schemes are written as PowerPoint draws them: `ea1ChsPeriod` 10 → "十.",
|
||||
/// `ea1JpnKorPeriod` 10 → "一〇." (digit by digit), `arabicDbPeriod` 13 → "13.",
|
||||
/// `thaiAlphaParenR` 4 → "ง)", `hindiAlpha1Period` 1 → "क.", `arabic2Minus` 10 → "ي-"
|
||||
/// (abjad order), `circleNumWdWhitePlain` 13 → "③" (those circles go to ten).
|
||||
pub fn autonum(scheme: &str, n: u32) -> String {
|
||||
const THAI: [char; 41] = [
|
||||
'ก', 'ข', 'ค', 'ง', 'จ', 'ฉ', 'ช', 'ซ', 'ฌ', 'ญ', 'ฎ', 'ฏ', 'ฐ', 'ฑ', 'ฒ', 'ณ', 'ด', 'ต', 'ถ', 'ท', 'ธ', 'น', 'บ', 'ป', 'ผ', 'ฝ', 'พ', 'ฟ',
|
||||
'ภ', 'ม', 'ย', 'ร', 'ล', 'ว', 'ศ', 'ษ', 'ส', 'ห', 'ฬ', 'อ', 'ฮ',
|
||||
];
|
||||
const HINDI_VOWELS: [char; 11] = ['अ', 'आ', 'इ', 'ई', 'उ', 'ऊ', 'ऋ', 'ए', 'ऐ', 'ओ', 'औ'];
|
||||
const HINDI_CONSONANTS: [char; 33] = [
|
||||
'क', 'ख', 'ग', 'घ', 'ङ', 'च', 'छ', 'ज', 'झ', 'ञ', 'ट', 'ठ', 'ड', 'ढ', 'ण', 'त', 'थ', 'द', 'ध', 'न', 'प', 'फ', 'ब', 'भ', 'म', 'य', 'र', 'ल',
|
||||
'व', 'श', 'ष', 'स', 'ह',
|
||||
];
|
||||
const ARABIC_ALPHABET: [char; 28] =
|
||||
['ا', 'ب', 'ت', 'ث', 'ج', 'ح', 'خ', 'د', 'ذ', 'ر', 'ز', 'س', 'ش', 'ص', 'ض', 'ط', 'ظ', 'ع', 'غ', 'ف', 'ق', 'ك', 'ل', 'م', 'ن', 'ه', 'و', 'ي'];
|
||||
const ARABIC_ABJAD: [char; 28] =
|
||||
['ا', 'ب', 'ج', 'د', 'ه', 'و', 'ز', 'ح', 'ط', 'ي', 'ك', 'ل', 'م', 'ن', 'س', 'ع', 'ف', 'ص', 'ق', 'ر', 'ش', 'ت', 'ث', 'خ', 'ذ', 'ض', 'ظ', 'غ'];
|
||||
const HEBREW: [char; 22] = ['א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק', 'ר', 'ש', 'ת'];
|
||||
let circled = |first: u32, count: u32| char::from_u32(first + n.saturating_sub(1) % count).map(String::from).unwrap_or_else(|| n.to_string());
|
||||
let core = if scheme.starts_with("romanUc") {
|
||||
roman(n, true)
|
||||
} else if scheme.starts_with("romanLc") {
|
||||
roman(n, false)
|
||||
} else if scheme.starts_with("alphaUc") {
|
||||
alpha_num(n, true)
|
||||
} else if scheme.starts_with("alphaLc") {
|
||||
alpha_num(n, false)
|
||||
} else if scheme.starts_with("circleNumWdWhite") {
|
||||
return circled(0x2460, 10);
|
||||
} else if scheme.starts_with("circleNumWdBlack") {
|
||||
return circled(0x2776, 10);
|
||||
} else if scheme.starts_with("circleNum") {
|
||||
return char::from_u32(0x2460 + n.saturating_sub(1).min(19)).map(String::from).unwrap_or_else(|| n.to_string());
|
||||
} else if scheme.starts_with("ea1Chs") || scheme.starts_with("ea1Cht") {
|
||||
chinese_num(n)
|
||||
} else if scheme.starts_with("ea1Jpn") {
|
||||
n.to_string().chars().map(|d| d.to_digit(10).and_then(|v| CJK_DIGITS.get(v as usize).copied()).unwrap_or(d)).collect()
|
||||
} else if scheme.starts_with("arabicDb") {
|
||||
digits_in(n, '0')
|
||||
} else if scheme.starts_with("thaiAlpha") {
|
||||
letters(&THAI, n)
|
||||
} else if scheme.starts_with("thaiNum") {
|
||||
digits_in(n, '๐')
|
||||
} else if scheme.starts_with("hindiAlpha1") {
|
||||
letters(&HINDI_CONSONANTS, n)
|
||||
} else if scheme.starts_with("hindiAlpha") {
|
||||
letters(&HINDI_VOWELS, n)
|
||||
} else if scheme.starts_with("hindiNum") {
|
||||
digits_in(n, '०')
|
||||
} else if scheme.starts_with("arabic1") {
|
||||
letters(&ARABIC_ALPHABET, n)
|
||||
} else if scheme.starts_with("arabic2") {
|
||||
letters(&ARABIC_ABJAD, n)
|
||||
} else if scheme.starts_with("hebrew2") {
|
||||
letters(&HEBREW, n)
|
||||
} else {
|
||||
n.to_string()
|
||||
};
|
||||
// East Asian schemes end with a full-width full stop.
|
||||
let wide = scheme.starts_with("ea1") || scheme.starts_with("arabicDb");
|
||||
if scheme.ends_with("ParenBoth") {
|
||||
format!("({core})")
|
||||
} else if scheme.ends_with("ParenR") {
|
||||
format!("{core})")
|
||||
} else if scheme.ends_with("Period") {
|
||||
format!("{core}{}", if wide { '.' } else { '.' })
|
||||
} else if scheme.ends_with("Minus") {
|
||||
format!("{core}-")
|
||||
} else {
|
||||
core
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,7 @@ use deckcraft_model::text::{Align, Anchor, AutoFit, BodyProps, Bullet, Caps, Par
|
||||
use deckcraft_model::{Fill, Shape};
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
mod autonum;
|
||||
mod breaking;
|
||||
mod layout;
|
||||
mod run;
|
||||
@@ -41,9 +42,11 @@ mod shape;
|
||||
mod style;
|
||||
mod symbol;
|
||||
|
||||
pub use autonum::autonum;
|
||||
#[cfg(test)]
|
||||
use autonum::chinese_num;
|
||||
#[cfg(test)]
|
||||
use breaking::{LINE_PITCH, break_opportunities, measure_str};
|
||||
pub use craft::text::lists::autonum;
|
||||
#[cfg(test)]
|
||||
pub(crate) use layout::LAYOUT_PASSES;
|
||||
pub use layout::layout;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::autonum;
|
||||
use super::autonum::autonum;
|
||||
use super::run::{RunEffects, TextShadow};
|
||||
use super::style::{Cell, Opts, ParaShaped, Style, face_chain, make_style};
|
||||
use super::symbol::{covers_symbol, is_symbol_font, map_symbol_bullet, symbol_fallback_char, symbol_font_char, symbol_map_char};
|
||||
use super::symbol::{covers_symbol, is_symbol_font, map_symbol_bullet, symbol_font_char, symbol_map_char};
|
||||
use super::{
|
||||
Arc, Bullet, Caps, Ctx, Fill, FontDb, FontFace, FontSlot, HashMap, ParaProps, RunKind, RunProps, ScriptTag, Shape, ShapeParams, TextBody,
|
||||
UnicodeSegmentation, bidi, resolve, script,
|
||||
@@ -201,15 +201,6 @@ fn shape_cells(
|
||||
.filter(|f| db.has_family(f))
|
||||
.map(|f| db.face(f, st.style_name))
|
||||
.filter(|f| covers_symbol(f, cluster.first().copied().unwrap_or(' ')));
|
||||
// Without that font, the code draws as the Unicode look-alike (not a missing-glyph box).
|
||||
let mapped: Vec<char>;
|
||||
let cluster = match cluster.first().and_then(|c| symbol_fallback_char(*c, st.sym.as_deref())).filter(|_| sym_face.is_none()) {
|
||||
Some(m) => {
|
||||
mapped = std::iter::once(m).chain(cluster.iter().skip(1).copied()).collect();
|
||||
mapped.as_slice()
|
||||
}
|
||||
None => cluster,
|
||||
};
|
||||
let face = match (sym_face, prev.as_ref()) {
|
||||
(Some(f), _) => f,
|
||||
(None, Some(p))
|
||||
@@ -255,13 +246,12 @@ fn shape_cells(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Items: maximal ranges of one level, face, script and shaping style (case mapping, language, a:sym symbol font).
|
||||
// Items: maximal ranges of one level, face, script and shaping style (case mapping, language).
|
||||
let upper = |i: usize| styles.get(char_style.get(i).copied().unwrap_or(0)).is_some_and(|st| st.caps != Caps::None);
|
||||
let lang = |i: usize| styles.get(char_style.get(i).copied().unwrap_or(0)).and_then(|st| st.lang.as_deref());
|
||||
let kern = |i: usize| styles.get(char_style.get(i).copied().unwrap_or(0)).is_some_and(|st| st.kern);
|
||||
let up = |i: usize| cells.get(i).is_some_and(|c| c.upright);
|
||||
let sym = |i: usize| styles.get(char_style.get(i).copied().unwrap_or(0)).and_then(|st| st.sym.as_deref());
|
||||
let key = |i: usize| (levels.get(i).copied(), char_face.get(i).copied(), scripts.get(i).map(|s| s.0), upper(i), lang(i), kern(i), up(i), sym(i));
|
||||
let key = |i: usize| (levels.get(i).copied(), char_face.get(i).copied(), scripts.get(i).map(|s| s.0), upper(i), lang(i), kern(i), up(i));
|
||||
let mut items: Vec<(usize, usize)> = Vec::new();
|
||||
let mut a = 0;
|
||||
while a < n {
|
||||
@@ -401,8 +391,7 @@ fn shape_item(
|
||||
let sym = styles.get(first.style).and_then(|st| st.sym.as_deref());
|
||||
let glyphs = deckcraft_fonts::shape_range(face, text, b0..b1, ¶ms, |ch| {
|
||||
let ch = if upper { caps_char(ch) } else { ch };
|
||||
let own_font = sym.is_some_and(|s| face.family.eq_ignore_ascii_case(s));
|
||||
symbol_map_char(face, ch, sym).or_else(|| symbol_fallback_char(ch, sym).filter(|_| !own_font)).unwrap_or(ch)
|
||||
symbol_map_char(face, ch, sym).unwrap_or(ch)
|
||||
});
|
||||
let upem = face.upem.max(1.0);
|
||||
let scale_of = |cell: &Cell| {
|
||||
|
||||
@@ -3,7 +3,7 @@ use super::{FontFace, UnicodeSegmentation};
|
||||
/// Is `family` a symbol font (characters at U+F000 + code)?
|
||||
pub(crate) fn is_symbol_font(family: &str) -> bool {
|
||||
let f = family.to_ascii_lowercase();
|
||||
f.starts_with("wingdings") || f == "symbol" || f.starts_with("webdings") || f.starts_with("marlett") || f.starts_with("monotype sorts")
|
||||
f.starts_with("wingdings") || f == "symbol" || f.starts_with("webdings") || f.starts_with("marlett")
|
||||
}
|
||||
|
||||
/// Does `face` draw the symbol-font character `c` (a U+F0xx private-use code)? Either directly at
|
||||
@@ -30,29 +30,6 @@ pub(crate) fn symbol_map_char(face: &FontFace, ch: char, sym: Option<&str>) -> O
|
||||
symbol_font_draw(face, code)
|
||||
}
|
||||
|
||||
/// The Unicode look-alike that draws `ch`, a U+F0xx private-use code of the `a:sym` symbol font
|
||||
/// `sym`, when that font is not installed (or does not draw the code): the characters bullets use
|
||||
/// for these fonts. `None` when `ch` is not such a code, `sym` is not a symbol font, or a Symbol-font code
|
||||
/// has no standard Unicode character (its fragment glyphs); Wingdings and Webdings codes without a look-alike draw as a bullet.
|
||||
pub(crate) fn symbol_fallback_char(ch: char, sym: Option<&str>) -> Option<char> {
|
||||
let code = ch as u32;
|
||||
if !(0xF000..=0xF0FF).contains(&code) {
|
||||
return None;
|
||||
}
|
||||
let sym = sym?;
|
||||
if !is_symbol_font(sym) {
|
||||
return None;
|
||||
}
|
||||
let low = code & 0xFF;
|
||||
if low == 0x20 {
|
||||
return Some(' ');
|
||||
}
|
||||
if sym.eq_ignore_ascii_case("symbol") {
|
||||
return symbol_unicode(low).or_else(|| (0x21..=0x7E).contains(&low).then_some(low)).and_then(char::from_u32);
|
||||
}
|
||||
map_symbol_bullet(&ch.to_string(), Some(sym)).chars().next()
|
||||
}
|
||||
|
||||
/// The real-Unicode character the Symbol font's code `code` (0x00–0xFF) maps to, in the Adobe
|
||||
/// Symbol encoding (Unicode, Inc.'s `MAPPINGS/VENDORS/ADOBE/symbol.txt`; Apple's Mac OS Symbol
|
||||
/// shares this layout, with a few alternative Unicode choices — see `symbol_unicode_alts`): the
|
||||
@@ -300,11 +277,7 @@ pub fn map_symbol_bullet(c: &str, font: Option<&str>) -> String {
|
||||
}
|
||||
// Only the legacy symbol fonts: "Noto Sans Symbols" and the like are Unicode fonts whose
|
||||
// characters (❑ ❖) are drawn as they are. Private-use codes are mapped only when no font is named.
|
||||
if f.contains("wingdings")
|
||||
|| (f.starts_with("monotype sorts") && ((first as u32) < 0x100 || ('\u{f000}'..='\u{f0ff}').contains(&first)))
|
||||
|| f == "symbol"
|
||||
|| (font.is_none() && ('\u{f000}'..='\u{f0ff}').contains(&first))
|
||||
{
|
||||
if f.contains("wingdings") || f == "symbol" || (font.is_none() && ('\u{f000}'..='\u{f0ff}').contains(&first)) {
|
||||
let code = (first as u32) & 0xff;
|
||||
// Wingdings 2 and 3 put different shapes at the same codes.
|
||||
if f.starts_with("wingdings 2") {
|
||||
@@ -331,11 +304,8 @@ pub fn map_symbol_bullet(c: &str, font: Option<&str>) -> String {
|
||||
return m.to_string();
|
||||
}
|
||||
let m = match code {
|
||||
0x6d if f.starts_with("monotype sorts") => '○',
|
||||
0xf0 if f.contains("wingdings") => '⇨',
|
||||
0xa7 => '▪',
|
||||
0xd8 => '➢',
|
||||
0xe8 => '➔',
|
||||
0xfc => '✓',
|
||||
0x76 => '❖',
|
||||
0x71 => '❑',
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::{
|
||||
Affinity, Align, Anchor, Arc, AutoFit, BodyProps, Bullet, Caps, Cell, Ctx, Dash, Deco, DecoLine, FontDb, FontFace, GlyphRun, LINE_PITCH,
|
||||
MoveMode, NoFields, Opts, ParaProps, Point, Pos, Rect, Rgba, SUB_SUPER, Shape, Spacing, Strike, TextBody, TextLayout, break_opportunities,
|
||||
caps_char, covers_symbol, is_symbol_font, is_upright, layout, layout_scaled, map_symbol_bullet, measure_str, resolve, shaping_features,
|
||||
symbol_char, symbol_font_char, symbol_font_draw, symbol_unicode, symbol_unicode_alts,
|
||||
MoveMode, NoFields, Opts, ParaProps, Point, Pos, Rect, Rgba, SUB_SUPER, Shape, Spacing, Strike, TextBody, TextLayout, autonum,
|
||||
break_opportunities, caps_char, chinese_num, covers_symbol, is_symbol_font, is_upright, layout, layout_scaled, map_symbol_bullet, measure_str,
|
||||
resolve, shaping_features, symbol_char, symbol_font_char, symbol_font_draw, symbol_unicode, symbol_unicode_alts,
|
||||
};
|
||||
use deckcraft_model::Fill;
|
||||
use deckcraft_model::defaults;
|
||||
@@ -413,6 +413,16 @@ fn empty_and_hostile_bodies_never_panic() {
|
||||
let _ = l.selection_rects(Pos { para: 5, ch: 0 }, Pos { para: 0, ch: 3 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autonum_formats() {
|
||||
assert_eq!(autonum("arabicPeriod", 3), "3.");
|
||||
assert_eq!(autonum("romanUcPeriod", 4), "IV.");
|
||||
assert_eq!(autonum("alphaLcParenR", 2), "b)");
|
||||
assert_eq!(autonum("arabicParenBoth", 1), "(1)");
|
||||
assert_eq!(autonum("alphaUcPeriod", 27), "AA.");
|
||||
assert_eq!(autonum("alphaUcPeriod", u32::MAX).len(), 51); // 50 letters + '.'
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbered_list_counts() {
|
||||
let (p, mut sh) = setup("a\nb\nc", 400.0, 300.0);
|
||||
@@ -1635,6 +1645,41 @@ fn small_kana_and_closing_brackets_follow_powerpoint_kinsoku() {
|
||||
assert_eq!(lines[0], "あいうえ", "{lines:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autonumber_schemes_follow_powerpoint() {
|
||||
// As PowerPoint's export draws them (start values as in the probe deck).
|
||||
for (scheme, n, want) in [
|
||||
("ea1ChsPlain", 4, "四"),
|
||||
("ea1ChsPeriod", 10, "十."),
|
||||
("ea1ChtPeriod", 21, "二十一."),
|
||||
("ea1JpnKorPeriod", 10, "一〇."),
|
||||
("ea1JpnChsDbPeriod", 13, "一三."),
|
||||
("arabicDbPlain", 10, "10"),
|
||||
("arabicDbPeriod", 13, "13."),
|
||||
("circleNumDbPlain", 13, "⑬"),
|
||||
("circleNumWdWhitePlain", 13, "③"),
|
||||
("circleNumWdBlackPlain", 2, "❷"),
|
||||
("thaiAlphaPeriod", 1, "ก."),
|
||||
("thaiAlphaParenR", 4, "ง)"),
|
||||
("thaiAlphaParenBoth", 7, "(ช)"),
|
||||
("thaiNumPeriod", 10, "๑๐."),
|
||||
("hindiAlphaPeriod", 4, "ई."),
|
||||
("hindiAlpha1Period", 1, "क."),
|
||||
("hindiNumParenR", 13, "१३)"),
|
||||
("hebrew2Minus", 1, "א-"),
|
||||
("arabic1Minus", 13, "ش-"),
|
||||
("arabic2Minus", 10, "ي-"),
|
||||
("arabicPlain", 10, "10"),
|
||||
] {
|
||||
assert_eq!(autonum(scheme, n), want, "{scheme} {n}");
|
||||
}
|
||||
assert_eq!(chinese_num(105), "一百零五");
|
||||
assert_eq!(chinese_num(20), "二十");
|
||||
// Past the end of an alphabet the letter doubles, like "aa".
|
||||
assert_eq!(autonum("hebrew2Minus", 23), "אא-");
|
||||
assert_eq!(autonum("thaiAlphaPeriod", 0), ".");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn east_asian_vertical_text_marks_cjk_upright() {
|
||||
let (p, mut sh) = setup("日本、ABC 12", 300.0, 600.0);
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
use deckcraft_fonts::FontDb;
|
||||
use deckcraft_geom::Rect;
|
||||
use deckcraft_model::defaults;
|
||||
use deckcraft_model::resolve::Ctx;
|
||||
use deckcraft_model::text::{Bullet, TextBody};
|
||||
use deckcraft_model::{LayoutType, Presentation, Xfrm};
|
||||
use deckcraft_text::{GlyphRun, NoFields, Opts, layout};
|
||||
|
||||
fn lay_sym(text: &str, sym: &str) -> Vec<GlyphRun> {
|
||||
let mut p = Presentation::default();
|
||||
let lay = defaults::layout_of_kind(&p, LayoutType::TitleAndContent).expect("layout");
|
||||
let mut s = defaults::new_slide(&mut p, lay).expect("slide");
|
||||
let mut body = s.shapes.remove(1);
|
||||
body.xfrm = Some(Xfrm::new(0.0, 0.0, 600.0, 300.0));
|
||||
body.text = Some(TextBody::from_text(text));
|
||||
let para = &mut body.text.as_mut().expect("text").paragraphs[0];
|
||||
para.props.bullet = Some(Bullet::None);
|
||||
para.runs[0].props.font = Some("Arial".into());
|
||||
para.runs[0].props.font_sym = Some(sym.into());
|
||||
s.shapes = vec![body.clone()];
|
||||
p.slides = vec![std::sync::Arc::new(s)];
|
||||
let ctx = Ctx::for_slide(&p, &p.slides[0]).expect("ctx");
|
||||
let rect = Rect::new(0.0, 0.0, 600.0, 300.0);
|
||||
layout(&ctx, &body, body.text.as_ref().expect("text"), &Opts { rect, fields: &NoFields, prompt_color: None, no_shrink: false }).runs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wingdings_arrow_without_the_sym_font_draws_the_unicode_arrow() {
|
||||
let db = FontDb::global();
|
||||
if db.has_family("Wingdings") {
|
||||
eprintln!("skipped: Wingdings is installed");
|
||||
return;
|
||||
}
|
||||
let arrow = '\u{2794}';
|
||||
let has_arrow = ["DejaVu Sans", "Noto Sans Symbols", "Noto Sans Symbols2", "Apple Symbols", "Segoe UI Symbol"]
|
||||
.iter()
|
||||
.any(|f| db.has_family(f) && db.face(f, "Regular").covers(arrow));
|
||||
if !has_arrow {
|
||||
eprintln!("skipped: no installed font draws U+2794");
|
||||
return;
|
||||
}
|
||||
// U+F0E8 is Wingdings' right arrow (the issue's "F0 E8" box).
|
||||
let runs = lay_sym("\u{F0E8} x", "Wingdings");
|
||||
let (run, i) = runs.iter().find_map(|r| r.cells.iter().position(|c| c.0 == 0).map(|i| (r, i))).expect("the symbol is drawn");
|
||||
let gid = run.glyphs.get(i).map(|g| g.0).expect("a glyph");
|
||||
assert_ne!(gid, 0, "the private-use code drew a missing-glyph box");
|
||||
assert_eq!(gid, run.face.glyph_for(arrow), "the code draws the arrow, not another character");
|
||||
// The Symbol font's bullet code (U+F0B7) draws its bullet, U+2022.
|
||||
let runs = lay_sym("\u{F0B7} x", "Symbol");
|
||||
if let Some((run, i)) = runs.iter().find_map(|r| r.cells.iter().position(|c| c.0 == 0).map(|i| (r, i)))
|
||||
&& !db.has_family("Symbol")
|
||||
{
|
||||
assert_eq!(run.glyphs.get(i).map(|g| g.0), Some(run.face.glyph_for('\u{2022}')));
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user