mirror of
https://github.com/storytold/designcraft.git
synced 2026-12-06 14:04:13 -05:00
Merge main into docs/roadmap-2026-11-15
Combine the Nov 15 additions into the single existing status block in each file: keep the November 19 ROADMAP date and main's entries, and leave the Nov 15 parity history row separate.
This commit is contained in:
commit
faa97dff9b
284 files changed
+80756
-32070
No files matched your search
@@ -1,2 +1,7 @@
|
||||
# Local builds pick up the optional craft-fonts checkout next to this repo (Inter etc.). When the
|
||||
# directory is missing the build warns and carries on with egui's bundled fonts and system fonts.
|
||||
[env]
|
||||
CRAFT_FONTS_DIR = { value = "../craft-fonts", relative = true }
|
||||
|
||||
[alias]
|
||||
xtask = "run --package xtask --"
|
||||
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1400018213,
|
||||
"producer_workflow_id": 429745945,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_tooling_revision": "main",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"signer_tooling_revision": "main",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
@@ -83,7 +83,9 @@
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [],
|
||||
"automatic_signer_actors": [
|
||||
"github-actions[bot]"
|
||||
],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
@@ -95,7 +97,15 @@
|
||||
"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",
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
name: Dispatch release-ref nightly
|
||||
|
||||
# Transport only, never authorization. No checkout, payload parsing or release environment.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [DesignCraft unsigned nightly]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
if: >-
|
||||
github.repository == 'storytold/designcraft' &&
|
||||
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/designcraft', '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/designcraft', 'wrong event repository')
|
||||
producer = event.get('workflow_run', {})
|
||||
require(producer.get('head_repository', {}).get('full_name') == 'storytold/designcraft', '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/designcraft/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': 'designcraft-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,12 +34,26 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: main
|
||||
app-name: designcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the release environment and export its keys; that environment must
|
||||
# admit nightly-signer alongside release before the first dispatch.
|
||||
@@ -1,8 +1,9 @@
|
||||
name: DesignCraft unsigned nightly
|
||||
|
||||
# Enabled for supervised manual runs by the reviewed manual actors only; no schedule yet.
|
||||
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
|
||||
# Automated daily schedule at 01:30 UTC plus supervised manual runs by the reviewed manual actors.
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 1 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -22,9 +23,9 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: main
|
||||
app-name: designcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
@@ -32,3 +33,4 @@ 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: sonarcloud-${{ github.ref }}
|
||||
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', 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' }}
|
||||
|
||||
|
||||
Generated
+1301
-141
File diff suppressed because it is too large.
Load diff
+76
-59
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/designcraft", "apps/designcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.21.1"
|
||||
version = "0.22.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -12,36 +12,40 @@ repository = "https://github.com/storytold/designcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
# Shared RFC 4648 encoding; document decoding policies remain local.
|
||||
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" }
|
||||
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
# Shared JSON-RPC 2.0 / MCP server framing and lifecycle.
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
# Shared reader and writer; publish the immutable revision before this consumer.
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0", default-features = false }
|
||||
craft-designcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0", features = ["read"] }
|
||||
craft-epub = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-idml = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-indd = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0", features = ["tree-render", "tree-text"] }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-file-formats = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
# Shared keyboard bindings: chords, overrides, conflicts, egui dispatch, the Keyboard Shortcuts dialog.
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0", features = ["egui", "ui"] }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0", default-features = false }
|
||||
craft-designcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0", features = ["read"] }
|
||||
craft-epub = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-idml = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-indd = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0", features = ["tree-render", "tree-text"] }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-file-formats = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
# Shared keyboard bindings: chords, overrides, conflicts, key matching. On the next pin, so the framework's Keyboard
|
||||
# Shortcuts dialog (craft-menu) edits the same `Keymap` type the app dispatches from.
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0", features = ["egui"] }
|
||||
craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
# Separations, ink coverage and the ink manager; same revision as craft-pdf and the krilla patch.
|
||||
craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0", features = ["flatten"] }
|
||||
craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0", features = ["flatten"] }
|
||||
# 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 = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", features = ["ui"] }
|
||||
# Shared nightly-v1 profile isolation, launch protocol, and security fence (craft-libs).
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
# internal
|
||||
designcraft-geom = { path = "crates/geom" }
|
||||
designcraft-color = { path = "crates/color" }
|
||||
@@ -99,20 +103,33 @@ qrcodegen = "1.8"
|
||||
quick-xml = "0.41"
|
||||
zip = { version = "3", default-features = false, features = ["deflate"] }
|
||||
# Which paths stored in documents may be followed (craft-libs).
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
# Atomic file replacement for saves and exports (craft-libs).
|
||||
craft-atomic = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" }
|
||||
craft-atomic = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
# File › Print through the system print spooler (craft-libs).
|
||||
craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" }
|
||||
craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
|
||||
# ICC colour management: working spaces, transforms, black point compensation (craft-libs).
|
||||
craft-cms = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" }
|
||||
craft-cms = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
|
||||
# ui
|
||||
# The craft UI framework, the whole interface on every target, from the SDK crates the components name rather than
|
||||
# the `craft` facade: the facade's `ui` feature pulls `craft-ui-patterns`, which depends on craft-pdf at that rev and
|
||||
# so resolves a second `craft-pdf` beside the app's pinned one (xtask's pdf-deps gate allows exactly one). These
|
||||
# crates pull none of that.
|
||||
craft-ui-widgets = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
craft-ui-panels = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
# The shell's title bar, which draws the application bar's frame and moves the window by it.
|
||||
craft-ui-shell = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
# The framework's colour components: the Color Picker, colour wells and their popover.
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", features = ["ui"] }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", default-features = false }
|
||||
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
craft-host = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
craft-window-sdk = { package = "craft-window", git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", features = ["ui", "appkit"] }
|
||||
# Shared frontend components; keep this dependency above the engine boundary.
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["serde"] }
|
||||
# The application bar as the window's title bar (craft-libs).
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["egui"] }
|
||||
# The craft UI framework umbrella (contract, widgets, panels, patterns, shell).
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
egui = "0.37"
|
||||
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
|
||||
egui_extras = { version = "0.37", default-features = false }
|
||||
@@ -122,7 +139,7 @@ egui_kittest = "0.37"
|
||||
web-time = "1"
|
||||
rfd = "0.17"
|
||||
# Native file and message dialogs that never block the event loop (craft-libs).
|
||||
craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" }
|
||||
craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
raw-window-handle = "0.6"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
|
||||
@@ -156,30 +173,30 @@ debug = 0
|
||||
|
||||
# Opt-in cancelable macOS termination on the pinned winit 0.30 line.
|
||||
[patch.crates-io]
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.8.2" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.8.2" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
# The hayro crates from craft-libs' vendor/ directory (pdfcraft's, plus the plate mode and decode
|
||||
# limits craft-pdf and craft-prepress need); same revision as craft-pdf.
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.7.1" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.7.0" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.7.2" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.3.0" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" }
|
||||
vello_common = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" }
|
||||
vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.7.1" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.7.0" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.7.2" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.3.0" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
vello_common = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
@@ -130,6 +130,22 @@ list (author, source, license) is in ASSETS.md.
|
||||
AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
- Indic hyphenation patterns, embedded through the hypher crate (features "hindi", "marathi",
|
||||
"bengali", "assamese", "gujarati", "panjabi", "oriya", "tamil", "telugu", "kannada",
|
||||
"malayalam"): hyph-hi.tex, hyph-mr.tex, hyph-bn.tex, hyph-as.tex, hyph-gu.tex, hyph-pa.tex,
|
||||
hyph-or.tex, hyph-ta.tex, hyph-te.tex, hyph-kn.tex and hyph-ml.tex 0.9.0 (2016-01-16) from
|
||||
hyph-utf8, https://github.com/hyphenation/tex-hyphen. Copyright (C) 2016 Santhosh Thottingal.
|
||||
Available under the MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this
|
||||
software and associated documentation files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following conditions: The above copyright notice
|
||||
and this permission notice shall be included in all copies or substantial portions of the
|
||||
Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
||||
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
|
||||
AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
- German hyphenation patterns, embedded through the hypher crate (feature "german"):
|
||||
hyph-de-1996.tex 2024-02-28, German reformed orthography (2006), from hyph-utf8,
|
||||
https://github.com/typst/hypher/blob/d81cc506416bffef2a75ee2dc969d4b41bc36613/patterns/hyph-de-1996.tex.
|
||||
|
||||
+5
-2
@@ -11,8 +11,7 @@
|
||||
- 2026-10-23: placed-artwork layer options survive IDML and native round trips per placement, independently of shared assets. Unsupported visibility overrides are explicit import/preflight/PDF warnings; format 4 prevents older native readers from silently discarding them. Rendering parity is still open; see [graphic-layer-options.md](docs/graphic-layer-options.md).
|
||||
- FID1: PDF export normalizes mixed emitted gradient color spaces to RGB with an explicit warning; homogeneous device-space gradients retain their components. Linear/radial, midpoint, archival and print policies have synthetic regression coverage.
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-19 · **Change:** minor (hidden characters follow frame, group and layer visibility (#1994); obsolete CI gap removed; tracked-change selection mapping; Croatian hyphenation (hyph-hr); Pages panel parents and alternate layouts; File ▸ Export Layouts and Versions; placed graphic layer-option preservation and explicit rendering warnings; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text; automation roots refuse superscript COM/LPT names and a device name before a colon) · **Target:** Adobe InDesign 2026
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-15 · **Change:** minor (DesignCraft v0.21.0 version preparation; links and buttons accept only web and mail schemes, and PDF export writes only http, https and mailto link targets; a save asked for while open-time link checks run waits for them, then writes linked files, with `links.progress`; the MCP server caps one request line at 4 MiB; `table.setCell` is a no-op when every value already matches, preserving character formats and a shared-edge stroke; File ▸ Place and `edit.pasteImage` size a raster by its stored resolution; live captions refresh on a committed gesture, inside groups, with the caret clamped; drop caps and vertical justification skip a baseline grid the lines cannot count; image warm accounting counts an image's cached levels once; parity scores unchanged; previous: obsolete CI gap removed; tracked-change selection mapping; Pages panel parents and alternate layouts; File ▸ Export Layouts and Versions; placed graphic layer-option preservation and explicit rendering warnings; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text; automation roots refuse superscript COM/LPT names and a device name before a colon) · **Target:** Adobe InDesign 2026
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-19 · **Change:** minor (DesignCraft v0.21.0 version preparation; links and buttons accept only web and mail schemes, and PDF export writes only http, https and mailto link targets; a save asked for while open-time link checks run waits for them, then writes linked files, with `links.progress`; the MCP server caps one request line at 4 MiB; `table.setCell` is a no-op when every value already matches, preserving character formats and a shared-edge stroke; File ▸ Place and `edit.pasteImage` size a raster by its stored resolution; live captions refresh on a committed gesture, inside groups, with the caret clamped; drop caps and vertical justification skip a baseline grid the lines cannot count; image warm accounting counts an image's cached levels once; parity scores unchanged; hidden characters follow frame, group and layer visibility (#1994); obsolete CI gap removed; tracked-change selection mapping; Croatian hyphenation (hyph-hr); Pages panel parents and alternate layouts; File ▸ Export Layouts and Versions; placed graphic layer-option preservation and explicit rendering warnings; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text; automation roots refuse superscript COM/LPT names and a device name before a colon) · **Target:** Adobe InDesign 2026
|
||||
- AR1.1: Kashida justification tests verify space fallback without Tatweel fonts using an isolated font database, while retaining elongation assertions when fonts support it.
|
||||
|
||||
- AR1: Arabic IDML controls now retain character direction, kashida switches, diacritic offsets/forms, paragraph policy values and independent story/table directions. Shaping preserves joining context and script/language selection; paragraph-level bidi, contextual digit conversion, mark-safe elongation, RTL columns/tables and physical column insertion have regression coverage. Vendor-specific justification and diacritic presets remain explicit preflight warnings; see docs/arabic-typography.md.
|
||||
@@ -20,6 +19,7 @@
|
||||
|
||||
DesignCraft aims at full Adobe InDesign parity — and to be better: faster, open (documented JSON format + IDML), scriptable by agents (MCP), and available on the web.
|
||||
|
||||
- **2026-11-30** · Hindi, Marathi, Bengali, Assamese, Gujarati, Punjabi, Odia, Tamil, Telugu, Kannada and Malayalam text hyphenates with Santhosh Thottingal's MIT-licensed hyph-utf8 patterns through `hypher`, between syllables and never inside a conjunct. A word of these scripts split at a line end takes no hyphen and keeps no room for one; Sinhala and other scripts keep theirs. Hyphenate Across Column off now also holds when a syllable ends in a glyph drawn out of order (the vowel sign of वि). Original work by dileep2in (#3048). No readiness percentage change.
|
||||
- **2026-11-15** · Story targets are checked before they are used: `story.setDirection`, `story.get`,
|
||||
`type.fillWithPlaceholder` and `file.exportText` refuse a `story` or `frame` the document doesn't have instead
|
||||
of acting on the selected frame's story, so an edit can no longer land on the wrong story and an export cannot
|
||||
@@ -408,6 +408,8 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m
|
||||
|
||||
## Progress log
|
||||
|
||||
- **2026-11-30** · The view follows the caret (#3405): when typing, the arrow keys, undo or a command such as Insert Footnote takes the caret to where its line isn't in view, the view scrolls just enough to show the whole line, keeping zoom, as in InDesign. Scrolling away by hand, or showing another document, doesn't pull the view back. No readiness percentage change.
|
||||
- **2026-11-29** · With the Type tool, a click (Shift or not) on empty page or on the pasteboard deselects, dropping the caret and the frame holding it, as in InDesign; before, the frame stayed selected until another frame was clicked or the tool changed. Deselecting is not an undo step, and a drag from empty canvas still draws a new text frame. No readiness percentage change.
|
||||
- **2026-11-18** · View › Extras › Show/Hide Link Badge: frames showing a linked picture carry a link badge on their top edge, a warning when the file changed and a stop when it is missing; hidden in Preview. No readiness percentage change.
|
||||
- **2026-11-16** · Fitting a bottom-aligned text frame from its top handle keeps its bottom edge and text in place (#2880): double-clicking any selection handle passes the opposite local reference point (`ref` 0..=8) to `object.fit`, menu/panel/scripting fits without `ref` anchor to vertical justification (`Bottom`/`Center`/`Top`/`Justify`), and `transform.resize` keeps unchanged edges pinned across its `1e-3` scale clamp and flips. No readiness percentage change.
|
||||
- **2026-11-13** · A placed Photoshop file comes in at its own resolution (ResolutionInfo), as other rasters do since #1991: a 300 ppi PSD was placed four times too large at 72 ppi. No readiness percentage change.
|
||||
@@ -620,6 +622,7 @@ Newest first.
|
||||
- **2026-10-17** · Cross-references keep text typed over their generated text (IDML import and export), with the page number still live, as InDesign shows them until updated; a cross-reference whose destination is gone shows its saved text and page instead of "??"; and a cross-reference's text breaks at its spaces instead of inside words. No readiness percentage change.
|
||||
- **2026-10-17** · Parent pages: while parents are edited, the document pages' hidden characters, spelling squiggles and other overlays no longer pile onto the right parent page. No readiness percentage change.
|
||||
- **2026-10-16** · A Direct Selection click on an image whose frame is already selected selects the image, so Delete removes only the image and leaves the empty frame, as in InDesign. No readiness percentage change.
|
||||
- **2026-10-16** · Inline and other anchored objects can be selected and resized on the page: the Selection tool clicks one where it sits in the text and shows its handles, a handle drag shows an outline and the size, and on release the frame takes it (cropping from the sides that moved; Cmd scales the content, Shift keeps proportions) and the text reflows, and Delete removes it from the text. Anchored Object Options and Release act on the selected object. Before, a click selected the text frame around it. No readiness percentage change.
|
||||
- **2026-10-18** · Web build: linked graphics relink from files handed over — Links › Relink… opens the browser's file picker for one graphic, Relink to Folder… its folder picker (each missing graphic takes the file whose path in the folder ends like its link; same-named files nothing tells apart are left missing and reported); one undo step per batch. New `links.relinkFiles`. Before, both buttons did nothing in the browser, so an IDML opened without its Links folder had no way to get its pictures. No readiness percentage change.
|
||||
- **2026-10-16** · Type › Reload Fonts (`font.reload`): fonts installed, edited or removed while DesignCraft runs are read again without a restart, and the open documents recompose with them (#328, #547). An edited font file is noticed by its length and modification time; bundled, added and document fonts stay as they are. InDesign does this by itself, so noticing changes automatically is still open (gap 6). No readiness percentage change.
|
||||
- **2026-10-16** · Parents can be deleted from their Pages-panel context menu or `layout.parents.delete {id}`. Applied-page and based-on references are cleared, local override copies survive, and Undo restores the parent. Addresses the deletion portion of #956; no readiness percentage change.
|
||||
|
||||
@@ -82,6 +82,10 @@ pub fn start() {
|
||||
app.session.prefs = prefs;
|
||||
}
|
||||
let prefs_sync = PrefsSync::new(stored);
|
||||
|
||||
// The craft UI framework's runtime, before the context's first pass (it refuses to install inside
|
||||
// one): the whole interface is the framework's, in the browser as on the desktop.
|
||||
app.install_framework(&cc.egui_ctx);
|
||||
if has_query_flag(&query(), "sample") {
|
||||
let _ = app.run("file.newSample", serde_json::json!({}));
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ default-run = "designcraft"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-nightly = { workspace = true }
|
||||
designcraft-engine = { workspace = true }
|
||||
designcraft-ui-egui = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "links", "clipboard"] }
|
||||
@@ -56,7 +57,6 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["std",
|
||||
# Files dragged in from the Finder: the pointer's place on the screen (src/pointer.rs).
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSGeometry"] }
|
||||
# The window's `movable` flag follows the application bar's controls.
|
||||
craft-window = { workspace = true }
|
||||
# Finder double-clicks, Open With, Dock drops and `open -a DesignCraft brochure.idml` arrive as a
|
||||
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle. This crate (also used by PhotoCraft,
|
||||
# PdfCraft and WordCraft) registers the handler behind a safe API (Objective-C interop needs unsafe,
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
|
||||
use crate::launch_profile::Profile;
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuildFlavor {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
pub use craft_nightly::BuildFlavor;
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(designcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
@@ -16,14 +12,6 @@ pub const VERSION: &str = env!("DESIGNCRAFT_BUILT_VERSION");
|
||||
/// The plain `designcraft --version` line, unchanged for stable.
|
||||
pub const STABLE_VERSION_LINE: &str = concat!("designcraft ", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
|
||||
match (flavor, profile.is_nightly()) {
|
||||
(BuildFlavor::NightlyV1, false) => Err("Open DesignCraft Nightly from ArtCraft Launcher".into()),
|
||||
(BuildFlavor::Stable, true) => Err("This is a stable DesignCraft 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
|
||||
}
|
||||
@@ -42,7 +30,7 @@ pub fn version_line(flavor: BuildFlavor, stable: &str, version: &str) -> String
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::{BuildFlavor, COMPILED, VERSION, needs_native_error, version_line, version_query};
|
||||
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
@@ -52,22 +40,6 @@ mod tests {
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_build_without_a_profile_is_refused_before_startup() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
|
||||
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
|
||||
assert!(!started.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
|
||||
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
|
||||
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
|
||||
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
let version = "0.2.1-nightly.20261124.17.1.gabcdef012345";
|
||||
|
||||
@@ -1,127 +1,94 @@
|
||||
//! 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.
|
||||
//! DesignCraft's `craft-nightly` isolation specification.
|
||||
//!
|
||||
//! Nightly builds self-isolate into `craft_nightly::canonical_profile_root("designcraft")` on
|
||||
//! direct launch and also accept ArtCraft Launcher's `--launch-profile nightly-v1 --profile-root`
|
||||
//! arguments, fenced away from stable settings, installs, and portable layouts.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
use std::path::{Component, PathBuf};
|
||||
|
||||
pub const VERSION: &str = "nightly-v1";
|
||||
use craft_nightly::AppProfileSpec;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Profile {
|
||||
Stable,
|
||||
NightlyV1(PathBuf),
|
||||
const FOLDER_ONLY_ENTRIES: &[&str] = &["Recovery", "logs"];
|
||||
|
||||
/// Builds DesignCraft's [`AppProfileSpec`] for `craft-nightly` startup parsing and fencing.
|
||||
pub fn spec() -> AppProfileSpec {
|
||||
AppProfileSpec {
|
||||
app_id: "designcraft",
|
||||
display_name: "DesignCraft",
|
||||
stable_dir_names: &["DesignCraft", "designcraft"],
|
||||
stable_package_id: designcraft_ui_egui::channel::APP_ID,
|
||||
nightly_package_id: designcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID,
|
||||
profile_root_env: None,
|
||||
forbidden_env_vars: &["DESIGNCRAFT_CONFIG_DIR"],
|
||||
portable_markers: &[crate::profile::PORTABLE_MARKER],
|
||||
folder_only_entries: FOLDER_ONLY_ENTRIES,
|
||||
extra_forbidden_roots: extra_forbidden_roots_with(|key| std::env::var_os(key)),
|
||||
}
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
pub fn is_nightly(&self) -> bool {
|
||||
matches!(self, Self::NightlyV1(_))
|
||||
}
|
||||
fn abs_env(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
|
||||
let value = env(key).filter(|v| !v.is_empty())?;
|
||||
let path = PathBuf::from(value);
|
||||
(path.is_absolute() && !path.components().any(|c| matches!(c, Component::ParentDir))).then_some(path)
|
||||
}
|
||||
|
||||
pub fn root(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Stable => None,
|
||||
Self::NightlyV1(root) => Some(root),
|
||||
fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let mut roots = Vec::new();
|
||||
if let Some(local) = abs_env(&env, "LOCALAPPDATA") {
|
||||
roots.push(local.join("Programs").join("ArtCraft").join("DesignCraft"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Launch {
|
||||
pub profile: Profile,
|
||||
pub args: Vec<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = OnceLock::new();
|
||||
|
||||
pub fn current() -> &'static Profile {
|
||||
PROFILE.get().unwrap_or(&Profile::Stable)
|
||||
}
|
||||
|
||||
pub fn install(profile: Profile) -> Result<(), String> {
|
||||
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
|
||||
}
|
||||
|
||||
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
|
||||
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
|
||||
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
|
||||
let mut selector = None;
|
||||
let mut root = None;
|
||||
let mut other = Vec::new();
|
||||
let mut files = Vec::new();
|
||||
let mut iter = args.iter();
|
||||
let mut delimiter = false;
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg == "--" {
|
||||
delimiter = true;
|
||||
files.extend(iter.cloned());
|
||||
break;
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = abs_env(&env, key) {
|
||||
roots.push(base.join("ArtCraft").join("DesignCraft"));
|
||||
}
|
||||
}
|
||||
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());
|
||||
roots
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let mut roots = vec![PathBuf::from("/usr/bin/designcraft"), PathBuf::from("/usr/local/bin/designcraft"), PathBuf::from("/opt/designcraft")];
|
||||
if let Some(home) = abs_env(&env, "HOME") {
|
||||
roots.push(home.join(".var/app/ai.storyteller.designcraft"));
|
||||
}
|
||||
roots
|
||||
}
|
||||
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() })
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let mut roots = vec![PathBuf::from("/Applications/DesignCraft.app")];
|
||||
if let Some(home) = abs_env(&env, "HOME") {
|
||||
let library = home.join("Library");
|
||||
roots.push(library.join("Preferences/DesignCraft.plist"));
|
||||
roots.push(library.join("Preferences/ai.storyteller.designcraft.plist"));
|
||||
roots.push(library.join("Saved Application State/ai.storyteller.designcraft.savedState"));
|
||||
roots.push(home.join("Applications/DesignCraft.app"));
|
||||
}
|
||||
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
|
||||
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
|
||||
roots
|
||||
}
|
||||
}
|
||||
|
||||
/// 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;
|
||||
#[cfg(not(any(unix, target_os = "windows")))]
|
||||
{
|
||||
let _ = env;
|
||||
Vec::new()
|
||||
}
|
||||
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 portable/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. DesignCraft has no
|
||||
/// agent SDK folder of its own, so the stable boundary is its settings folder, install folders and
|
||||
/// portable data only.
|
||||
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::profile::ensure_writable)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
use std::ffi::OsString;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use craft_nightly::{
|
||||
BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, launch_arguments, parse_startup,
|
||||
validate_and_prepare_root,
|
||||
};
|
||||
|
||||
use super::{FOLDER_ONLY_ENTRIES, spec};
|
||||
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
@@ -131,87 +98,118 @@ mod tests {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\designcraft" } else { "/nightly-data/profiles/designcraft" }
|
||||
}
|
||||
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
#[test]
|
||||
fn spec_preserves_designcraft_isolation_boundaries() {
|
||||
let s = spec();
|
||||
assert_eq!(s.app_id, "designcraft");
|
||||
assert_eq!(s.display_name, "DesignCraft");
|
||||
assert_eq!(s.stable_dir_names, &["DesignCraft", "designcraft"]);
|
||||
assert_eq!(s.stable_package_id, designcraft_ui_egui::channel::APP_ID);
|
||||
assert_eq!(s.nightly_package_id, designcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID);
|
||||
assert_eq!(s.profile_root_env, None);
|
||||
assert_eq!(s.forbidden_env_vars, &["DESIGNCRAFT_CONFIG_DIR"]);
|
||||
assert_eq!(s.portable_markers, &[crate::profile::PORTABLE_MARKER]);
|
||||
assert_eq!(s.folder_only_entries, FOLDER_ONLY_ENTRIES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
fn direct_nightly_launch_self_isolates_into_canonical_profile_root() {
|
||||
let s = spec();
|
||||
let expected_root = canonical_profile_root("designcraft").unwrap();
|
||||
let user_args = args(&["brochure.designcraft", "poster.idml"]);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &s, user_args.clone(), &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
|
||||
assert_eq!(launch.passthrough_args, user_args);
|
||||
assert!(launch.leading_flags.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_launcher_arguments_are_parsed_without_reinterpreting_file_names() {
|
||||
let s = spec();
|
||||
let root = Path::new(absolute());
|
||||
let user_args = args(&["--profile-root", "design with spaces.designcraft"]);
|
||||
let argv = launch_arguments(root, &user_args);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &s, argv, &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(root.to_path_buf()));
|
||||
assert_eq!(launch.passthrough_args, user_args);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_build_keeps_normal_args_and_refuses_nightly_flags() {
|
||||
let s = spec();
|
||||
for argv in [args(&[]), args(&["--sample", "a.idml"]), args(&["--", "--launch-profile", "file.designcraft"])] {
|
||||
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 });
|
||||
let launch = parse_startup(BuildFlavor::Stable, &s, argv.clone(), &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::Stable);
|
||||
assert_eq!(launch.passthrough_args, argv);
|
||||
}
|
||||
let nightly_argv = launch_arguments(Path::new(absolute()), &[]);
|
||||
let err = parse_startup(BuildFlavor::Stable, &s, nightly_argv, &StartupOptions::new()).unwrap_err();
|
||||
assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "design with spaces.designcraft"]));
|
||||
let launch = parse(argv).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "design with spaces.designcraft"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
|
||||
for argv in [
|
||||
args(&["--launch-profile", VERSION]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile=", VERSION, "--profile-root", absolute(), "--"]),
|
||||
] {
|
||||
assert!(parse(argv).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
|
||||
fn version_queries_are_recognized_for_plain_and_launcher_invocations() {
|
||||
let s = spec();
|
||||
let root = Path::new(absolute());
|
||||
for flag in ["--version", "-V"] {
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
}
|
||||
let plain = parse_startup(BuildFlavor::NightlyV1, &s, args(&[flag]), &StartupOptions::new()).unwrap();
|
||||
assert!(plain.is_version_query(), "plain {flag}");
|
||||
|
||||
let via_launcher = parse_startup(BuildFlavor::NightlyV1, &s, launch_arguments(root, &args(&[flag])), &StartupOptions::new()).unwrap();
|
||||
assert!(via_launcher.is_version_query(), "launcher {flag}");
|
||||
|
||||
let without_sep = parse_startup(
|
||||
BuildFlavor::NightlyV1,
|
||||
&s,
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), flag]),
|
||||
&StartupOptions::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(without_sep.is_version_query(), "launcher without separator {flag}");
|
||||
}
|
||||
for argv in [
|
||||
args(&["--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
|
||||
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
|
||||
] {
|
||||
assert!(!version_query(&argv), "{argv:?}");
|
||||
}
|
||||
// Outside the query the strict protocol still refuses the version flag.
|
||||
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
|
||||
let file_named_version = parse_startup(BuildFlavor::NightlyV1, &s, args(&["--", "--version"]), &StartupOptions::new()).unwrap();
|
||||
assert!(!file_named_version.is_version_query());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
|
||||
let reached = Cell::new(false);
|
||||
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
|
||||
assert!(result.is_err());
|
||||
assert!(!reached.get());
|
||||
}
|
||||
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir());
|
||||
let root = base.join(format!("designcraft-nightly-reopen-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let s = spec();
|
||||
|
||||
#[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());
|
||||
let confirmed = validate_and_prepare_root(&root, &s).unwrap();
|
||||
assert_eq!(confirmed, root);
|
||||
for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(confirmed.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in FOLDER_ONLY_ENTRIES {
|
||||
std::fs::create_dir(confirmed.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(validate_and_prepare_root(&root, &s).unwrap(), confirmed);
|
||||
for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
assert_eq!(std::fs::read(confirmed.join(name)).unwrap(), b"saved profile data", "{name} changed when reopening");
|
||||
}
|
||||
|
||||
for name in FOLDER_ONLY_ENTRIES {
|
||||
let path = confirmed.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(validate_and_prepare_root(&root, &s).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
|
||||
let invalid = confirmed.join("ordinary-file");
|
||||
std::fs::write(&invalid, b"existing file").unwrap();
|
||||
let argv = launch_arguments(&invalid, &[]);
|
||||
assert!(craft_nightly::current().is_none());
|
||||
let result = craft_nightly::prepare_launch(BuildFlavor::NightlyV1, &s, argv, &StartupOptions::new());
|
||||
assert!(matches!(result, Err(ProfileError::NotADirectory(_))));
|
||||
assert!(craft_nightly::current().is_none());
|
||||
assert_eq!(std::fs::read(invalid).unwrap(), b"existing file");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,6 @@ mod nightly_session;
|
||||
mod pointer;
|
||||
mod process_identity;
|
||||
mod profile;
|
||||
mod profile_root;
|
||||
mod window_frame;
|
||||
|
||||
use designcraft_engine::Session;
|
||||
@@ -47,9 +46,6 @@ struct App {
|
||||
/// Documents and quit requests from Finder, the Dock and Open With.
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events: fmv_macos_events::Inbox,
|
||||
/// The window's `movable` flag as last set; see `craft_window::title_bar`.
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: Option<bool>,
|
||||
/// Frames begun so far.
|
||||
frames: u32,
|
||||
/// The device whose uncaptured errors are logged once the window is past its start-up frames
|
||||
@@ -104,14 +100,14 @@ impl eframe::App for App {
|
||||
self.startup.opening(apple_events::poll(&self.apple_events, &mut self.app, ui.ctx()));
|
||||
}
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
self.app.set_input_source(selected_input_source());
|
||||
self.app.ui(ui);
|
||||
self.startup.leave();
|
||||
#[cfg(target_os = "macos")]
|
||||
if self.app.take_ime_discard() {
|
||||
discard_marked_text();
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
craft_window::title_bar::sync_movable(ui.ctx(), &mut self.movable);
|
||||
// After the frame, never inside it: the dialog answers on a later frame. On macOS Save and
|
||||
// message boxes are sheets on this window.
|
||||
self.app.show_file_dialogs(Some(&*frame));
|
||||
@@ -140,6 +136,15 @@ fn discard_marked_text() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The keyboard input source macOS has selected (its ID), or `None` without a key window. Space
|
||||
/// in a Japanese input mode types an ideographic space, which winit reports as a plain one.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn selected_input_source() -> Option<String> {
|
||||
let mtm = objc2::MainThreadMarker::new()?;
|
||||
let id = objc2_app_kit::NSTextInputContext::currentInputContext(mtm)?.selectedKeyboardInputSource()?;
|
||||
Some(id.to_string())
|
||||
}
|
||||
|
||||
/// Orderly OS termination can bypass egui's cancelable close event. Finish only a complete,
|
||||
/// current quit plan; otherwise preserve every live document, including edits after the timer.
|
||||
fn preserve_documents_on_exit(app: &mut DesignApp) -> Result<(), String> {
|
||||
@@ -322,41 +327,37 @@ fn report_launch_profile_error(error: &str) {
|
||||
}
|
||||
|
||||
/// Select the immutable launch profile before any start-up service or side effect: the version
|
||||
/// answer first, then the profile, the Windows identity, the fenced root and the session record.
|
||||
/// answer first, then `craft-nightly` startup/fencing (self-isolating direct nightly launches into
|
||||
/// the canonical profile root and honoring Launcher `--launch-profile`/`--profile-root` flags),
|
||||
/// the Windows identity, channel selection, and the session record.
|
||||
fn prepare_launch() -> Option<Launched> {
|
||||
let argv: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`: answered before logging, root validation, process identity or any window. A
|
||||
// headless runner otherwise hung on macOS and exited 2 on Linux.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
|
||||
{
|
||||
// Plain `--version`/`-V` on Nightly: answered before root resolution, process identity, or any
|
||||
// window, even in minimal environments without a home directory.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
|
||||
use std::io::Write as _;
|
||||
let line = build_flavor::version_line(build_flavor::COMPILED, build_flavor::STABLE_VERSION_LINE, build_flavor::VERSION);
|
||||
let _ = writeln!(std::io::stdout(), "{line}");
|
||||
return None;
|
||||
}
|
||||
let spec = launch_profile::spec();
|
||||
let launch = craft_nightly::prepare_launch(build_flavor::COMPILED, &spec, argv, &craft_nightly::StartupOptions::new()).unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2)
|
||||
});
|
||||
if launch.is_version_query() {
|
||||
use std::io::Write as _;
|
||||
let line = build_flavor::version_line(build_flavor::COMPILED, build_flavor::STABLE_VERSION_LINE, build_flavor::VERSION);
|
||||
let _ = writeln!(std::io::stdout(), "{line}");
|
||||
return None;
|
||||
}
|
||||
let launch = launch_profile::parse(argv)
|
||||
.and_then(|launch| {
|
||||
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
|
||||
if launch.profile.is_nightly() {
|
||||
process_identity::initialize(true, designcraft_ui_egui::channel::NIGHTLY_APP_ID).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 nightly = launch.profile.is_nightly();
|
||||
if nightly && let Err(error) = process_identity::initialize(true, designcraft_ui_egui::channel::NIGHTLY_APP_ID) {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2);
|
||||
}
|
||||
let channel = if nightly { designcraft_ui_egui::channel::Channel::NightlyV1 } else { designcraft_ui_egui::channel::Channel::Stable };
|
||||
if let Err(error) = launch_profile::install(launch.profile)
|
||||
.and_then(|()| designcraft_ui_egui::channel::select(channel, build_flavor::VERSION, option_env!("DESIGNCRAFT_NIGHTLY_COMMIT")))
|
||||
{
|
||||
if let Err(error) = designcraft_ui_egui::channel::select(channel, build_flavor::VERSION, option_env!("DESIGNCRAFT_NIGHTLY_COMMIT")) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
@@ -365,7 +366,7 @@ fn prepare_launch() -> Option<Launched> {
|
||||
let mut session_unavailable = false;
|
||||
if nightly {
|
||||
match nightly_session::Session::begin_with_health(
|
||||
launch_profile::current().root(),
|
||||
craft_nightly::current_root(),
|
||||
build_flavor::VERSION,
|
||||
option_env!("DESIGNCRAFT_NIGHTLY_COMMIT"),
|
||||
) {
|
||||
@@ -381,7 +382,7 @@ fn prepare_launch() -> Option<Launched> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Launched { args: launch.args, nightly, session, unclean, session_unavailable })
|
||||
Some(Launched { args: launch.passthrough_args, nightly, session, unclean, session_unavailable })
|
||||
}
|
||||
|
||||
/// The ordinary command line, once the launch profile was selected.
|
||||
@@ -399,16 +400,14 @@ struct AppCommand {
|
||||
skip: Vec<String>,
|
||||
}
|
||||
|
||||
/// Read the arguments left after the launch profile. A Nightly start's first argument is the
|
||||
/// separator `launch_profile::parse` put there: it is never a document, and an option after it was
|
||||
/// named by the Launcher as a file. Stable keeps its control, sample and version options and drops
|
||||
/// a user's own separator, so a literal `--` is never opened as a document.
|
||||
/// Read the arguments left after `craft-nightly` strips any launcher protocol header and `--`
|
||||
/// separator. A direct Nightly launch may still start with a user-supplied `--`, which is dropped
|
||||
/// once so it is never opened as a document. Stable keeps its control, sample and version options
|
||||
/// and drops a user's own separator, so a literal `--` is never opened as a document.
|
||||
fn app_command(args: impl IntoIterator<Item = std::ffi::OsString>, nightly: bool) -> AppCommand {
|
||||
let mut command = AppCommand::default();
|
||||
let mut args = args.into_iter();
|
||||
if nightly {
|
||||
// `parse` puts the protocol's separator first; skipping it keeps a restart's `--gpu-skip=`
|
||||
// (appended after that separator) in the ordinary arm below.
|
||||
let mut args = args.into_iter().peekable();
|
||||
if nightly && args.peek().is_some_and(|a| a == "--") {
|
||||
args.next();
|
||||
}
|
||||
while let Some(a) = args.next() {
|
||||
@@ -606,6 +605,12 @@ fn main() -> std::process::ExitCode {
|
||||
session.recovery_dir = profile::recovery_dir();
|
||||
let recovered = session.execute("file.recovery.open", &serde_json::json!({})).ok();
|
||||
let mut app = DesignApp::new(session, services());
|
||||
// The window's frame, which the framework's title bar follows: set once, before the runtime is installed.
|
||||
app.integrated_titlebar = cfg!(target_os = "macos");
|
||||
app.custom_titlebar = cfg!(target_os = "windows");
|
||||
// The craft UI framework's runtime, before the context's first pass (it refuses to install
|
||||
// inside one): the whole interface is the framework's.
|
||||
app.install_framework(&cc.egui_ctx);
|
||||
if nightly {
|
||||
// Installed and updated by the Launcher: never check the stable feed from here.
|
||||
app.set_updates_managed(Some("ArtCraft Launcher"));
|
||||
@@ -631,8 +636,6 @@ fn main() -> std::process::ExitCode {
|
||||
} else if session_unavailable && nightly {
|
||||
log::warn!("another DesignCraft Nightly holds this profile's session record");
|
||||
}
|
||||
app.integrated_titlebar = cfg!(target_os = "macos");
|
||||
app.custom_titlebar = cfg!(target_os = "windows");
|
||||
// The custom title bar's undecorated window must stay borderless, or its caption
|
||||
// and border offset the content and the pointer on some Windows systems (#1295).
|
||||
app.services.window_frame = window_frame::service(cc, app.custom_titlebar);
|
||||
@@ -657,8 +660,6 @@ fn main() -> std::process::ExitCode {
|
||||
startup: created,
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events: events.connect(&cc.egui_ctx),
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: None,
|
||||
frames: 0,
|
||||
log_errors_after_startup: device,
|
||||
session: app_session,
|
||||
@@ -710,6 +711,9 @@ mod tests {
|
||||
assert!(!nightly.version, "a flag after the separator is a document");
|
||||
assert_eq!(nightly.control_port, None);
|
||||
assert!(!nightly.sample);
|
||||
|
||||
let direct = super::app_command(["a.dc", "b.idml"].map(std::ffi::OsString::from), true);
|
||||
assert_eq!(direct.files, ["a.dc", "b.idml"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -717,6 +721,10 @@ mod tests {
|
||||
let nightly = super::app_command(["--", "a.dc", "--gpu-skip=vulkan,gl"].map(std::ffi::OsString::from), true);
|
||||
assert_eq!(nightly.files, ["a.dc"]);
|
||||
assert_eq!(nightly.skip, ["vulkan", "gl"]);
|
||||
|
||||
let direct = super::app_command(["a.dc", "--gpu-skip=vulkan,gl"].map(std::ffi::OsString::from), true);
|
||||
assert_eq!(direct.files, ["a.dc"]);
|
||||
assert_eq!(direct.skip, ["vulkan", "gl"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -6,21 +6,20 @@ use std::path::{Path, PathBuf};
|
||||
/// A file with this name next to the executable makes the install portable: settings, logs and
|
||||
/// recovery data are kept in [`PORTABLE_DATA_DIR`] beside it. The Windows portable zip ships one.
|
||||
pub(crate) const PORTABLE_MARKER: &str = "portable.txt";
|
||||
pub(crate) const PORTABLE_DATA_DIR: &str = "DesignCraftData";
|
||||
const PORTABLE_DATA_DIR: &str = "DesignCraftData";
|
||||
|
||||
/// The settings folder. A Launcher nightly profile replaces every data root at once: settings,
|
||||
/// logs, GPU state and recovery all live under it, so the fence in `profile_root` covers the
|
||||
/// whole of Nightly's user state (the engine's `Prefs`, `ui.json` and `recovery` included).
|
||||
/// The settings folder. A nightly profile replaces every data root at once: settings, logs, GPU
|
||||
/// state and recovery all live under it, so the `craft-nightly` fence covers the whole of
|
||||
/// Nightly's user state (the engine's `Prefs`, `ui.json` and `recovery` included).
|
||||
pub fn config_dir() -> Option<PathBuf> {
|
||||
if let Some(root) = crate::launch_profile::current().root() {
|
||||
if let Some(root) = craft_nightly::current_root() {
|
||||
return Some(root.to_path_buf());
|
||||
}
|
||||
config_dir_with(std::env::consts::OS, |key| std::env::var_os(key), executable_dir().as_deref())
|
||||
}
|
||||
|
||||
/// Whether `dir` exists, or can be created, and takes a new file. The nightly profile validator
|
||||
/// uses this same probe (`profile_root`), so a profile is accepted only where settings can land.
|
||||
pub(crate) fn ensure_writable(dir: &Path) -> std::io::Result<()> {
|
||||
/// Whether `dir` exists, or can be created, and takes a new file.
|
||||
fn ensure_writable(dir: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let probe = dir.join(format!(".write-test-{}", std::process::id()));
|
||||
let result = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe).map(drop);
|
||||
@@ -95,7 +94,7 @@ fn executable_dir() -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
pub fn recovery_dir() -> Option<PathBuf> {
|
||||
if let Some(root) = crate::launch_profile::current().root() {
|
||||
if let Some(root) = craft_nightly::current_root() {
|
||||
// Recovery stays inside the profile, including the per-run folder's lock.
|
||||
return own_run(root.join("Recovery"));
|
||||
}
|
||||
|
||||
@@ -1,492 +0,0 @@
|
||||
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use crate::profile::{PORTABLE_DATA_DIR, PORTABLE_MARKER};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
fn current() -> Result<Self, String> {
|
||||
match std::env::consts::OS {
|
||||
"windows" => Ok(Self::Windows),
|
||||
"linux" => Ok(Self::Linux),
|
||||
"macos" => Ok(Self::Mac),
|
||||
_ => Err("nightly-v1 is not defined for this operating system".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn ignores_case(self) -> bool {
|
||||
self != Self::Linux
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
|
||||
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err(format!("{label} must be absolute and contain no parent traversal"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
|
||||
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
|
||||
absolute(PathBuf::from(value), key)
|
||||
}
|
||||
|
||||
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
|
||||
match env(key).filter(|v| !v.is_empty()) {
|
||||
Some(value) => absolute(PathBuf::from(value), key),
|
||||
None => Ok(required_base(env, "HOME")?.join(fallback)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
|
||||
/// is not a missing directory that may be replaced or followed later.
|
||||
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
let mut parent = path;
|
||||
let mut missing = Vec::new();
|
||||
loop {
|
||||
match std::fs::symlink_metadata(parent) {
|
||||
Ok(_) => break,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
|
||||
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
|
||||
}
|
||||
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
|
||||
}
|
||||
}
|
||||
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
|
||||
for part in missing.into_iter().rev() {
|
||||
resolved.push(part);
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
|
||||
let parts = |p: &Path| {
|
||||
p.components()
|
||||
.map(|c| {
|
||||
let value = c.as_os_str().to_string_lossy().into_owned();
|
||||
if platform.ignores_case() { value.to_lowercase() } else { value }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.starts_with(&b) || b.starts_with(&a)
|
||||
}
|
||||
|
||||
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
|
||||
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
|
||||
if platform == Platform::Mac {
|
||||
// A profile in Resources is still inside the versioned install, not beside MacOS.
|
||||
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
|
||||
return Ok(bundle.to_path_buf());
|
||||
}
|
||||
}
|
||||
Ok(parent.to_path_buf())
|
||||
}
|
||||
|
||||
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let mut roots = match platform {
|
||||
Platform::Windows => {
|
||||
let mut roots = ["APPDATA", "LOCALAPPDATA"]
|
||||
.into_iter()
|
||||
.map(|key| required_base(env, key).map(|p| p.join("DesignCraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// The MSI's per-machine folder (install-policy.wxi, ProgramFiles6432Folder) and a
|
||||
// per-user install folder. A custom folder is not known here; the executable's own
|
||||
// folder is fenced below.
|
||||
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("DesignCraft"));
|
||||
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("DesignCraft"));
|
||||
}
|
||||
}
|
||||
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("designcraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
roots.extend(["/usr/bin/designcraft", "/usr/local/bin/designcraft", "/opt/designcraft"].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.designcraft"));
|
||||
roots
|
||||
}
|
||||
Platform::Mac => {
|
||||
let home = required_base(env, "HOME")?;
|
||||
let library = home.join("Library");
|
||||
vec![
|
||||
library.join("Application Support/DesignCraft"),
|
||||
library.join("Caches/DesignCraft"),
|
||||
library.join("Caches/ai.storyteller.designcraft"),
|
||||
library.join("Preferences/DesignCraft.plist"),
|
||||
library.join("Preferences/ai.storyteller.designcraft.plist"),
|
||||
library.join("Saved Application State/ai.storyteller.designcraft.savedState"),
|
||||
home.join("Applications/DesignCraft.app"),
|
||||
PathBuf::from("/Applications/DesignCraft.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 (logs, settings and so on) must resolve inside it,
|
||||
/// so a link there cannot point Nightly's writes at another app's data.
|
||||
fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
let entries = match std::fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Recognise the shared portable data namespace in both the supplied and resolved path.
|
||||
/// This is not an inventory of arbitrary custom stable overrides or a Launcher ownership proof.
|
||||
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
|
||||
// A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a
|
||||
// marker only counts beside a DesignCraft executable, so an unrelated portable.txt higher up
|
||||
// (in a user folder or at a drive root) does not refuse the profile.
|
||||
path.ancestors().enumerate().any(|(depth, ancestor)| {
|
||||
ancestor.join(PORTABLE_MARKER).is_file()
|
||||
&& (depth == 0 || ["designcraft.exe", "designcraft", "DesignCraft.app"].iter().any(|exe| ancestor.join(exe).exists()))
|
||||
}) || 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 probe (`profile::ensure_writable`). 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 env("DESIGNCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) {
|
||||
// The stable override would silently point every write at another app's data.
|
||||
return Err("nightly-v1 cannot be combined with DESIGNCRAFT_CONFIG_DIR".into());
|
||||
}
|
||||
// The nightly bundle's own sandbox is the one Flatpak that may reach this code: its per-app
|
||||
// home is private. Any other id means a native package (or the stable bundle) started here,
|
||||
// whose runtime socket namespace is not this profile's.
|
||||
let foreign_sandbox =
|
||||
env("FLATPAK_ID").filter(|value| !value.is_empty()).is_some_and(|id| id != designcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID);
|
||||
if platform != Platform::Windows && foreign_sandbox {
|
||||
return Err("nightly-v1 starts only in its own Flatpak bundle, not inside another app's sandbox".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 DesignCraft installation or its DesignCraftData 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());
|
||||
}
|
||||
// Existing aliases under the profile must not redirect a write outside it.
|
||||
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")?;
|
||||
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")?;
|
||||
entries_stay_inside(&confirmed)?;
|
||||
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate =
|
||||
std::env::temp_dir().join(format!("designcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
};
|
||||
let home = root.join("home");
|
||||
let exe = root.join("install/designcraft");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&exe, b"fixture executable, never run").unwrap();
|
||||
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value.into_os_string()))
|
||||
.collect();
|
||||
Self { root, env, exe }
|
||||
}
|
||||
|
||||
fn get(&self, key: &str) -> Option<OsString> {
|
||||
self.env.get(key).cloned()
|
||||
}
|
||||
|
||||
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
|
||||
validate_for(
|
||||
platform,
|
||||
root,
|
||||
|key| self.get(key),
|
||||
Some(&self.exe),
|
||||
|dir| {
|
||||
let probe = dir.join("exclusive-test-probe");
|
||||
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
|
||||
drop(file);
|
||||
std::fs::remove_file(probe)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn home(&self) -> PathBuf {
|
||||
PathBuf::from(self.get("HOME").unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
// Only the directory successfully created by this fixture is owned for removal.
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_stable_data_root_is_refused_on_every_platform() {
|
||||
let fixture = Fixture::new();
|
||||
let home = fixture.home();
|
||||
let cases = [
|
||||
(Platform::Windows, fixture.root.join("roaming/DesignCraft")),
|
||||
(Platform::Windows, fixture.root.join("local/DesignCraft")),
|
||||
(Platform::Windows, fixture.root.join("local/Programs/ArtCraft/DesignCraft")),
|
||||
(Platform::Linux, home.join(".config/designcraft")),
|
||||
(Platform::Linux, home.join(".local/share/designcraft")),
|
||||
(Platform::Linux, home.join(".cache/designcraft")),
|
||||
(Platform::Linux, home.join(".local/state/designcraft")),
|
||||
(Platform::Linux, home.join(".var/app/ai.storyteller.designcraft")),
|
||||
(Platform::Linux, PathBuf::from("/opt/designcraft")),
|
||||
(Platform::Mac, home.join("Library/Application Support/DesignCraft")),
|
||||
(Platform::Mac, home.join("Library/Caches/DesignCraft")),
|
||||
(Platform::Mac, home.join("Library/Preferences/ai.storyteller.designcraft.plist")),
|
||||
(Platform::Mac, home.join("Library/Saved Application State/ai.storyteller.designcraft.savedState")),
|
||||
(Platform::Mac, home.join("Applications/DesignCraft.app")),
|
||||
];
|
||||
for (platform, stable) in cases {
|
||||
for candidate in [stable.clone(), stable.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(), "{platform:?} accepted {candidate:?}");
|
||||
assert!(!probed.get(), "a refused root must not be probed for writing");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_installation_folder_and_grandparent_overlaps_are_refused() {
|
||||
let fixture = Fixture::new();
|
||||
let install = fixture.exe.parent().unwrap().to_path_buf();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert!(fixture.check(platform, &install).is_err(), "the install folder itself");
|
||||
assert!(fixture.check(platform, &install.join("profile")).is_err(), "a folder inside the install");
|
||||
assert!(fixture.check(platform, &fixture.root.join("nightly")).is_ok(), "a sibling of the install is private");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefix_and_case_lookalikes_are_not_stable_overlaps() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
// `DesignCraftBackups` only starts with the stable folder's name.
|
||||
assert!(fixture.check(platform, &fixture.home().join("Library/Application Support/DesignCraftBackups/nightly")).is_ok());
|
||||
assert!(fixture.check(platform, &fixture.root.join("data-craft/nightly")).is_ok());
|
||||
}
|
||||
// Case folding differs by platform: Windows and macOS fold, Linux does not.
|
||||
let folded = fixture.root.join("roaming/designcraft");
|
||||
assert!(fixture.check(Platform::Windows, &folded).is_err());
|
||||
assert!(fixture.check(Platform::Linux, &folded).is_ok(), "a different case is a different Linux path");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portable_settings_from_another_install_are_refused_before_any_probe() {
|
||||
let fixture = Fixture::new();
|
||||
let stable_install = fixture.root.join("stable portable install");
|
||||
let stable_data = stable_install.join(PORTABLE_DATA_DIR);
|
||||
std::fs::create_dir_all(&stable_data).unwrap();
|
||||
std::fs::write(stable_install.join(PORTABLE_MARKER), b"owned portable fixture").unwrap();
|
||||
std::fs::write(stable_data.join("ui.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("ui.json")).unwrap(), b"stable settings must not change");
|
||||
}
|
||||
}
|
||||
let private = fixture.root.join("DesignCraftData-backup-name/nightly");
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stable_settings_override_and_a_flatpak_instance_are_refused() {
|
||||
let fixture = Fixture::new();
|
||||
let target = fixture.root.join("nightly");
|
||||
for value in ["/somewhere/else", ""] {
|
||||
let env = |key: &str| if key == "DESIGNCRAFT_CONFIG_DIR" { Some(OsString::from(value)) } else { fixture.get(key) };
|
||||
let result = validate_for(Platform::Linux, &target, env, Some(&fixture.exe), |_| Ok(()));
|
||||
if value.is_empty() {
|
||||
assert!(result.is_ok(), "an empty override is not a stable data redirection");
|
||||
} else {
|
||||
let error = result.unwrap_err();
|
||||
assert!(error.contains("DESIGNCRAFT_CONFIG_DIR"), "{error}");
|
||||
}
|
||||
}
|
||||
let flatpak = |key: &str| if key == "FLATPAK_ID" { Some(OsString::from("ai.storyteller.designcraft")) } else { fixture.get(key) };
|
||||
assert!(validate_for(Platform::Linux, &target, flatpak, Some(&fixture.exe), |_| Ok(())).is_err());
|
||||
assert!(validate_for(Platform::Windows, &target, flatpak, Some(&fixture.exe), |_| Ok(())).is_ok(), "Windows has no Flatpak namespace");
|
||||
// The nightly bundle's own sandbox is private; a lookalike id is still another app's.
|
||||
let nightly_bundle =
|
||||
|key: &str| if key == "FLATPAK_ID" { Some(OsString::from(designcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID)) } else { fixture.get(key) };
|
||||
assert!(validate_for(Platform::Linux, &target, nightly_bundle, Some(&fixture.exe), |_| Ok(())).is_ok());
|
||||
let lookalike =
|
||||
|key: &str| if key == "FLATPAK_ID" { Some(OsString::from("ai.storyteller.designcraft.nightly-v1")) } else { fixture.get(key) };
|
||||
assert!(validate_for(Platform::Linux, &target, lookalike, Some(&fixture.exe), |_| Ok(())).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recovery_aliases_cannot_redirect_to_stable_or_outward_data() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".local/share/designcraft/Recovery");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
|
||||
for target in [stable.clone(), fixture.root.to_path_buf(), fixture.root.join("Recovery/../../elsewhere")] {
|
||||
let profile = fixture.root.join(format!("profile-{}", target.file_name().unwrap().to_string_lossy().replace('.', "_")));
|
||||
std::fs::create_dir_all(&profile).unwrap();
|
||||
std::os::unix::fs::symlink(&target, profile.join("Recovery")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &profile).is_err(), "{target:?}");
|
||||
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_created_profile_is_private_and_a_failed_write_probe_never_falls_back() {
|
||||
let fixture = Fixture::new();
|
||||
let probe = fixture.root.join("profile for probe");
|
||||
let error = validate_for(Platform::Linux, &probe, |key| fixture.get(key), Some(&fixture.exe), |_| Err(std::io::Error::other("read-only")))
|
||||
.unwrap_err();
|
||||
assert!(error.contains("not writable"), "{error}");
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(std::fs::metadata(&probe).unwrap().permissions().mode() & 0o777, 0o700);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_and_parent_traversing_are_refused_and_link_ancestors_are_resolved() {
|
||||
let fixture = Fixture::new();
|
||||
for candidate in [PathBuf::from("relative/nightly"), fixture.root.join("a/../nightly")] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).is_err(), "{candidate:?}");
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let elsewhere = fixture.root.join("elsewhere");
|
||||
std::fs::create_dir_all(&elsewhere).unwrap();
|
||||
std::os::unix::fs::symlink(&elsewhere, fixture.root.join("linked")).unwrap();
|
||||
// `canonical_future` resolves the existing ancestors before anything is created, so a
|
||||
// root reached through a link is validated and created at the link's real location.
|
||||
// That location is what the fence checks, and it is where every write then lands.
|
||||
let resolved = fixture.check(Platform::Linux, &fixture.root.join("linked/nightly")).unwrap();
|
||||
assert_eq!(resolved, std::fs::canonicalize(elsewhere.join("nightly")).unwrap());
|
||||
assert!(resolved.is_dir());
|
||||
assert_eq!(std::fs::canonicalize(fixture.root.join("linked")).unwrap(), elsewhere);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_valid_profile_is_returned_resolved_and_created() {
|
||||
let fixture = Fixture::new();
|
||||
let chosen = fixture.root.join("launcher data/profiles/designcraft");
|
||||
let resolved = fixture.check(Platform::Linux, &chosen).unwrap();
|
||||
assert_eq!(resolved, std::fs::canonicalize(&chosen).unwrap());
|
||||
assert!(resolved.is_dir());
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ log = { workspace = true }
|
||||
regex = { workspace = true }
|
||||
fancy-regex = { workspace = true }
|
||||
miniz_oxide = "0.8"
|
||||
hypher = { version = "0.1.8", default-features = false, features = ["alloc", "croatian", "dutch", "french", "german", "greek", "italian", "portuguese", "spanish", "norwegian", "danish"] }
|
||||
hypher = { version = "0.1.8", default-features = false, features = ["alloc", "croatian", "dutch", "french", "german", "greek", "italian", "portuguese", "spanish", "norwegian", "danish", "hindi", "marathi", "bengali", "assamese", "gujarati", "panjabi", "oriya", "tamil", "telugu", "kannada", "malayalam"] }
|
||||
|
||||
[dev-dependencies]
|
||||
designcraft-fonts = { workspace = true, features = ["testing"] }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Line breaking: the paragraph composer (Knuth–Plass total fit), the single-line composer
|
||||
//! (greedy first fit) and balanced ragged lines. All work on a paragraph's glyphs and a per-line
|
||||
//! measure function.
|
||||
//! measure function. Where a breaker needs source text, pass the full story because glyph byte
|
||||
//! offsets are story-relative.
|
||||
//!
|
||||
//! Justification uses *prioritised* elastic material (plan: typography §5.2): word spaces first,
|
||||
//! then letter spacing (every glyph gets elastic width from the paragraph's letter-spacing range),
|
||||
@@ -360,13 +361,50 @@ fn right_hang(g: &Glyph, sp: &Spacing) -> f64 {
|
||||
g.cjk_hang.max(hang_right(g, sp)) - g.moji.end
|
||||
}
|
||||
|
||||
/// May a line break after the dot at glyph `i`, as in a web address? It takes three letters right
|
||||
/// before the dot and two right after it, so that abbreviations ("e.g.", "U.S.A.", "Ph.D.") and
|
||||
/// decimals stay whole.
|
||||
pub(super) fn dot_break(text: &str, glyphs: &[Glyph], i: usize) -> bool {
|
||||
let dot = &glyphs[i];
|
||||
if dot.ch != '.' || dot.generated_text.is_some() || dot.list_label || glyphs.get(i + 1).is_some_and(|next| next.byte == dot.byte) {
|
||||
return false;
|
||||
}
|
||||
// Only the first glyph owns the source bytes. Generated glyphs stop the letter run.
|
||||
let owns_text = |g: &&Glyph| g.len > 0 || g.generated_text.is_some() || g.list_label;
|
||||
let source = |g: &Glyph| {
|
||||
if g.generated_text.is_some() || g.list_label {
|
||||
return None;
|
||||
}
|
||||
text.get(g.byte..g.byte.checked_add(g.len)?)
|
||||
};
|
||||
let before = glyphs[..i].iter().rev().skip_while(|g| g.byte == dot.byte).filter(owns_text).map_while(source).flat_map(|s| s.chars().rev());
|
||||
let after = glyphs[i + 1..].iter().filter(owns_text).map_while(source).flat_map(str::chars);
|
||||
has_dot_letters(before, 3) && has_dot_letters(after, 2)
|
||||
}
|
||||
|
||||
fn has_dot_letters(chars: impl Iterator<Item = char>, minimum: usize) -> bool {
|
||||
// Some combining marks have the Unicode Alphabetic property as well.
|
||||
static MARK: std::sync::LazyLock<Option<regex::Regex>> = std::sync::LazyLock::new(|| regex::Regex::new(r"\A\p{M}\z").ok());
|
||||
let Some(mark) = MARK.as_ref() else { return false };
|
||||
chars
|
||||
.filter(|&c| c.is_ascii() || !mark.is_match(c.encode_utf8(&mut [0; 4])))
|
||||
.take_while(|&c| c.is_alphabetic() && !is_cjk(c))
|
||||
.take(minimum)
|
||||
.count()
|
||||
== minimum
|
||||
}
|
||||
|
||||
/// The part of a hyphen after `g` (of width `hw`) that hangs past the line's end.
|
||||
fn hyphen_hang(g: &Glyph, hw: f64, sp: &Spacing) -> f64 {
|
||||
if sp.optical { hw * hang('-').1 * optical_scale(g, sp) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Advance of the hyphen glyph that would follow `g` (cached per face).
|
||||
/// Advance of the hyphen glyph that would follow `g` (cached per face); none after a letter of
|
||||
/// an Indian script, whose broken words take no hyphen ([`crate::shape::breaks_without_hyphen`]).
|
||||
fn hyphen_width(g: &Glyph, cache: &mut Vec<(u32, f64)>) -> f64 {
|
||||
if crate::shape::breaks_without_hyphen(g) {
|
||||
return 0.0;
|
||||
}
|
||||
let id = g.face.id();
|
||||
let units = match cache.iter().find(|c| c.0 == id) {
|
||||
Some(c) => c.1,
|
||||
@@ -398,7 +436,7 @@ fn push_inword(it: &mut Vec<Item>, ig: &mut Vec<usize>, p: Item, g: usize, sp: &
|
||||
|
||||
/// Build Knuth items. `item_glyph[k]` = glyph index of item k (penalties: the glyph *before* which the break happens).
|
||||
/// `emergency_after[i]` allows an emergency break after glyph `i` (see [`overlong_words`]).
|
||||
fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &Spacing) -> (Vec<Item>, Vec<usize>) {
|
||||
fn items(text: &str, glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &Spacing) -> (Vec<Item>, Vec<usize>) {
|
||||
let mut it: Vec<Item> = Vec::with_capacity(glyphs.len() * 2 + 2);
|
||||
let mut ig = Vec::with_capacity(glyphs.len() * 2 + 2);
|
||||
let n = glyphs.len();
|
||||
@@ -487,7 +525,10 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S
|
||||
p.hang = right_hang(g, sp);
|
||||
p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only());
|
||||
push_inword(&mut it, &mut ig, p, i + 1, sp);
|
||||
} else if matches!(g.ch, '\u{2013}' | '\u{2014}' | '/') || g.break_after.unwrap_or_else(|| cjk_break(g, &glyphs[i + 1], sp)) {
|
||||
} else if matches!(g.ch, '\u{2013}' | '\u{2014}' | '/')
|
||||
|| dot_break(text, glyphs, i)
|
||||
|| g.break_after.unwrap_or_else(|| cjk_break(g, &glyphs[i + 1], sp))
|
||||
{
|
||||
let mut p = Item::penalty(0.0, 0.0, false);
|
||||
p.hang = right_hang(g, sp);
|
||||
p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only());
|
||||
@@ -535,17 +576,17 @@ struct Node {
|
||||
}
|
||||
|
||||
/// Knuth–Plass total-fit line breaking. `width(line)` gives each line's measure.
|
||||
pub fn knuth_plass(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing, width: &dyn Fn(usize) -> f64) -> Vec<Break> {
|
||||
pub fn knuth_plass(text: &str, glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing, width: &dyn Fn(usize) -> f64) -> Vec<Break> {
|
||||
if glyphs.is_empty() {
|
||||
return vec![Break { start: 0, end: 0, next: 0, hyphen: false, forced: true }];
|
||||
}
|
||||
let (mut items, mut ig) = items(glyphs, hyph_after, &[], sp);
|
||||
let (mut items, mut ig) = items(text, glyphs, hyph_after, &[], sp);
|
||||
// A word gets emergency breaks only when no line could hold it: beside a wrap object some
|
||||
// lines are slivers much narrower than the measure, and a word that fits a full line goes
|
||||
// there instead of being split.
|
||||
let widest = (0..=glyphs.len().min(64)).map(width).fold(1.0, f64::max);
|
||||
if let Some(emergency_after) = overlong_words(&items, &ig, glyphs, widest) {
|
||||
(items, ig) = self::items(glyphs, hyph_after, &emergency_after, sp);
|
||||
(items, ig) = self::items(text, glyphs, hyph_after, &emergency_after, sp);
|
||||
}
|
||||
for tolerance in [2.5, 12.0, f64::INFINITY] {
|
||||
if let Some(b) =
|
||||
@@ -554,15 +595,15 @@ pub fn knuth_plass(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing, width: &
|
||||
return b;
|
||||
}
|
||||
}
|
||||
greedy(glyphs, hyph_after, sp, width, &|_, _, _| 0.0)
|
||||
greedy(text, glyphs, hyph_after, sp, width, &|_, _, _| 0.0)
|
||||
}
|
||||
|
||||
/// Width of the first word of `glyphs` after any leading spaces, fully shrunk (the boxes up to
|
||||
/// the first break opportunity, emergency breaks aside, and the hyphen a break there adds).
|
||||
pub fn first_word_width(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing) -> f64 {
|
||||
pub fn first_word_width(text: &str, glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing) -> f64 {
|
||||
// A word this long is wider than any line; the rest of the paragraph doesn't matter.
|
||||
let n = glyphs.len().min(256);
|
||||
let (items, _) = items(glyphs.get(..n).unwrap_or(glyphs), hyph_after.get(..n).unwrap_or(hyph_after), &[], sp);
|
||||
let (items, _) = items(text, glyphs.get(..n).unwrap_or(glyphs), hyph_after.get(..n).unwrap_or(hyph_after), &[], sp);
|
||||
let mut w = 0.0;
|
||||
let mut started = false;
|
||||
for it in &items {
|
||||
@@ -887,9 +928,12 @@ fn breaks_from_positions(items: &[Item], ig: &[usize], glyphs: &[Glyph], chain:
|
||||
let (end, hyphen, forced) = match it.kind {
|
||||
Kind::Penalty => {
|
||||
let e = ig[b].min(n);
|
||||
// A flagged penalty with width = an inserted hyphen (not an explicit '-').
|
||||
// A flagged penalty with width = an inserted hyphen (not an explicit '-'). A
|
||||
// hyphenation point after a letter of an Indian script inserts one of no width
|
||||
// (no hyphen is drawn there) but is still a hyphenated break: `auto` tells it from
|
||||
// the break after an explicit '-'.
|
||||
let explicit = e > 0 && matches!(glyphs[e - 1].ch, '-' | '\u{2010}');
|
||||
(e, it.flagged && it.w > 0.0 && !explicit || (it.flagged && e > 0 && glyphs[e - 1].ch == SOFT_HYPHEN), it.p <= -INF)
|
||||
(e, it.flagged && (it.w > 0.0 || it.auto) && !explicit || (it.flagged && e > 0 && glyphs[e - 1].ch == SOFT_HYPHEN), it.p <= -INF)
|
||||
}
|
||||
Kind::Glue | Kind::Box => (ig[b], false, false),
|
||||
};
|
||||
@@ -929,6 +973,7 @@ fn emergency_split(glyphs: &[Glyph], start: usize, i: usize) -> usize {
|
||||
/// `tab(line, x, i)` is the advance of the tab glyph `i` when it starts `x` from the start of
|
||||
/// line `line`: tabs have no width until they reach their stop, which depends on where they sit.
|
||||
pub fn greedy(
|
||||
text: &str,
|
||||
glyphs: &[Glyph],
|
||||
hyph_after: &[bool],
|
||||
sp: &Spacing,
|
||||
@@ -954,8 +999,14 @@ pub fn greedy(
|
||||
let mut last_space: Option<(usize, f64)> = None; // (break position, line width there)
|
||||
let mut i = start;
|
||||
let mut brk: Option<(usize, bool, bool)> = None;
|
||||
// The last glyph before `i` that is not a soft hyphen, kept as `i` advances.
|
||||
let mut plain = glyphs[..start].iter().rposition(|p| p.ch != SOFT_HYPHEN);
|
||||
while i < n {
|
||||
let g = &glyphs[i];
|
||||
let before = plain;
|
||||
if g.ch != SOFT_HYPHEN {
|
||||
plain = Some(i);
|
||||
}
|
||||
if is_forced(g.ch) {
|
||||
brk = Some((i + 1, false, true));
|
||||
break;
|
||||
@@ -1005,13 +1056,18 @@ pub fn greedy(
|
||||
if i + 1 < n && !glyphs[i + 1].is_space() && !g.no_break && g.break_after != Some(false) {
|
||||
if g.ch == SOFT_HYPHEN {
|
||||
if may_hyphenate(hyphens) {
|
||||
let hw = hyphen_width(g, &mut hy_cache);
|
||||
// Line layout draws the hyphen after `line.last()`, this soft hyphen, in its
|
||||
// face and size, so it is measured with it. None is drawn after a word of
|
||||
// an Indian script (the letter before the soft hyphens).
|
||||
let indic = before.is_some_and(|b| crate::shape::breaks_without_hyphen(&glyphs[b]));
|
||||
let hw = if indic { 0.0 } else { hyphen_width(g, &mut hy_cache) };
|
||||
let hy = (hw - hyphen_hang(g, hw, sp)).max(0.0);
|
||||
if x + hy <= w + shrink + FIT_EPS {
|
||||
last_ok = Some((i + 1, true));
|
||||
}
|
||||
}
|
||||
} else if matches!(g.ch, '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | '/')
|
||||
|| dot_break(text, glyphs, i)
|
||||
|| g.break_after.unwrap_or_else(|| cjk_break(g, &glyphs[i + 1], sp))
|
||||
{
|
||||
last_ok = Some((i + 1, false));
|
||||
@@ -1064,15 +1120,15 @@ pub fn line_width(glyphs: &[Glyph], b: &Break) -> f64 {
|
||||
|
||||
/// Balance Ragged Lines: keep the composer's line count but make the lines as even as possible,
|
||||
/// by composing against the narrowest measure that still yields that many lines.
|
||||
pub fn balanced(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing, width: &dyn Fn(usize) -> f64) -> Vec<Break> {
|
||||
let base = knuth_plass(glyphs, hyph_after, sp, width);
|
||||
pub fn balanced(text: &str, glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing, width: &dyn Fn(usize) -> f64) -> Vec<Break> {
|
||||
let base = knuth_plass(text, glyphs, hyph_after, sp, width);
|
||||
let n = base.len();
|
||||
if n < 2 || glyphs.len() > 3000 || base[..n - 1].iter().any(|b| b.forced) {
|
||||
return base;
|
||||
}
|
||||
let ok = |f: f64| -> Option<Vec<Break>> {
|
||||
let w = |j: usize| width(j) * f;
|
||||
let br = knuth_plass(glyphs, hyph_after, sp, &w);
|
||||
let br = knuth_plass(text, glyphs, hyph_after, sp, &w);
|
||||
(br.len() == n && br.iter().enumerate().all(|(j, b)| line_width(glyphs, b) <= w(j) + 0.01)).then_some(br)
|
||||
};
|
||||
let (mut lo, mut hi) = (0.3, 1.0);
|
||||
|
||||
@@ -114,6 +114,7 @@ fn doc_signature(doc: &Document) -> u64 {
|
||||
(Arc::as_ptr(sp) as usize).hash(&mut h);
|
||||
}
|
||||
(Arc::as_ptr(&doc.styles) as usize).hash(&mut h);
|
||||
doc.title.hash(&mut h);
|
||||
format!("{:?}", doc.text_variables).hash(&mut h);
|
||||
sections_hash(doc).hash(&mut h);
|
||||
// The compositions the indexes are built from also depend on these (see `signature`).
|
||||
@@ -169,6 +170,15 @@ fn numbering_signature(starts: &NumberStarts, story: &Story) -> Vec<usize> {
|
||||
sig
|
||||
}
|
||||
|
||||
/// Document-level state a story's text variables depend on.
|
||||
fn vars_signature(doc: &Document) -> usize {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
format!("{:?}", doc.text_variables).hash(&mut h);
|
||||
doc.title.hash(&mut h);
|
||||
h.finish() as usize
|
||||
}
|
||||
|
||||
/// Everything page names and section markers are made from.
|
||||
fn sections_hash(doc: &Document) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
@@ -255,6 +265,9 @@ impl Cache {
|
||||
if let Some(starts) = &starts {
|
||||
sig.push(hash_of(&numbering_signature(starts, ns)));
|
||||
}
|
||||
if crate::vars::has_vars(ns) {
|
||||
sig.extend([doc.page_count(), vars_signature(doc)]);
|
||||
}
|
||||
keep_items.extend(k.into_iter().filter(|it| kept.insert(Arc::as_ptr(it))));
|
||||
keep_stories.push(ns.clone());
|
||||
}
|
||||
@@ -302,12 +315,9 @@ impl Cache {
|
||||
let with_vars = crate::vars::has_vars(story);
|
||||
let running = with_vars && crate::vars::has_running(doc, story);
|
||||
if with_vars {
|
||||
// Variables depend on the page count, sections and definitions (and running headers on
|
||||
// the whole document).
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
format!("{:?}", doc.text_variables).hash(&mut h);
|
||||
sig.extend([doc.page_count(), h.finish() as usize]);
|
||||
// Variables depend on the page count, title, sections and definitions (and running
|
||||
// headers on the whole document).
|
||||
sig.extend([doc.page_count(), vars_signature(doc)]);
|
||||
if running {
|
||||
sig.push(doc_signature(doc) as usize);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,10 @@
|
||||
//! Flipo, Bernard Gaulle, Arthur Reutenauer), MIT; Italian is `hyph-it.tex` 4.9 from hyph-utf8
|
||||
//! (Claudio Beccari), LPPL or MIT, taken under MIT. A word with an elision (`l'imprimerie`)
|
||||
//! hyphenates after its apostrophe.
|
||||
//! Hindi, Marathi, Bengali, Assamese, Gujarati, Punjabi, Odia, Tamil, Telugu, Kannada and
|
||||
//! Malayalam are Santhosh Thottingal's `hyph-{hi,mr,bn,as,gu,pa,or,ta,te,kn,ml}.tex` 0.9.0 from
|
||||
//! hyph-utf8, MIT. Viramas, nuktas and the zero-width (non-)joiner count as word characters
|
||||
//! ([`is_indic_joiner`]), so a word is not split at its conjuncts.
|
||||
//! German uses `hyph-de-1996.tex` (2024-02-28, Deutschsprachige Trennmustermannschaft, MIT):
|
||||
//! despite the filename, these are the reformed 2006 spelling patterns. Only the two 2006 reform
|
||||
//! names and German locale codes without a reform year or with 2006 use this set. Traditional,
|
||||
@@ -138,7 +142,21 @@ fn is_apostrophe(c: char) -> bool {
|
||||
}
|
||||
|
||||
fn is_word_char(c: char) -> bool {
|
||||
c.is_alphabetic() || is_apostrophe(c)
|
||||
c.is_alphabetic() || is_apostrophe(c) || is_indic_joiner(c)
|
||||
}
|
||||
|
||||
/// Signs inside Indic words that Unicode doesn't class as alphabetic: each script's virama (which
|
||||
/// joins consonants into conjuncts), its nukta, Malayalam's vertical and circular viramas, and the
|
||||
/// zero-width joiner and non-joiner that select conjunct and chillu forms. Without them a word
|
||||
/// such as विद्यार्थी splits at every conjunct into fragments too short to hyphenate.
|
||||
fn is_indic_joiner(c: char) -> bool {
|
||||
matches!(
|
||||
c,
|
||||
'\u{094D}' | '\u{09CD}' | '\u{0A4D}' | '\u{0ACD}' | '\u{0B4D}' | '\u{0BCD}' | '\u{0C4D}' | '\u{0CCD}' | '\u{0D4D}' // viramas
|
||||
| '\u{0D3B}' | '\u{0D3C}' // Malayalam vertical and circular viramas
|
||||
| '\u{093C}' | '\u{09BC}' | '\u{0A3C}' | '\u{0ABC}' | '\u{0B3C}' | '\u{0C3C}' | '\u{0CBC}' // nuktas
|
||||
| '\u{200C}' | '\u{200D}' // ZWNJ, ZWJ
|
||||
)
|
||||
}
|
||||
|
||||
/// Unrestricted break points of one lowercase core (letters and `'` only, no leading/trailing `'`).
|
||||
@@ -821,6 +839,64 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indic_languages_use_the_hyph_utf8_patterns() {
|
||||
for (name, code, lang) in [
|
||||
("Hindi", "hi", hypher::Lang::Hindi),
|
||||
("Marathi", "mr", hypher::Lang::Marathi),
|
||||
("Bengali", "bn", hypher::Lang::Bengali),
|
||||
("Assamese", "as", hypher::Lang::Assamese),
|
||||
("Gujarati", "gu", hypher::Lang::Gujarati),
|
||||
("Punjabi", "pa", hypher::Lang::Panjabi),
|
||||
("Odia", "or", hypher::Lang::Oriya),
|
||||
("Oriya", "or_IN", hypher::Lang::Oriya),
|
||||
("Tamil", "ta", hypher::Lang::Tamil),
|
||||
("Telugu", "te", hypher::Lang::Telugu),
|
||||
("Kannada", "kn", hypher::Lang::Kannada),
|
||||
("Malayalam", "ml_IN", hypher::Lang::Malayalam),
|
||||
] {
|
||||
assert_eq!(Lang::for_language(name), Some(Lang::Patterns(lang)), "{name}");
|
||||
assert_eq!(Lang::for_language(code), Some(Lang::Patterns(lang)), "{code}");
|
||||
}
|
||||
assert_eq!(Lang::for_language("Sanskrit"), None, "no Sanskrit patterns are built in");
|
||||
}
|
||||
|
||||
/// A virama joins consonants inside a word: the word is hyphenated whole, between syllables,
|
||||
/// never inside a conjunct. Before viramas counted as word characters, विद्यार्थी was
|
||||
/// hyphenated as the fragments वि, द, यार and थी, which gave it no break at all.
|
||||
#[test]
|
||||
fn indic_words_hyphenate_between_syllables_across_their_conjuncts() {
|
||||
let lang = |name: &str| Lang::for_language(name).unwrap();
|
||||
assert_eq!(marked("विद्यार्थी", lang("Hindi")), "वि-द्या-र्थी");
|
||||
assert_eq!(marked("प्रधानमंत्री", lang("Hindi")), "प्र-धा-न-मं-त्री");
|
||||
assert_eq!(marked("महाराष्ट्र", lang("Marathi")), "महा-रा-ष्ट्र");
|
||||
assert_eq!(marked("വിദ്യാർത്ഥി", lang("Malayalam")), "വി-ദ്യാർ-ത്ഥി");
|
||||
assert_eq!(marked("തിരുവനന്തപുരം", lang("Malayalam")), "തി-രു-വ-ന-ന്ത-പു-രം");
|
||||
assert_eq!(marked("தொழில்நுட்பம்", lang("Tamil")), "தொ-ழில்-நுட்-பம்");
|
||||
// The default Before Last limit keeps the final য় with the ল before it.
|
||||
assert_eq!(marked("বিশ্ববিদ্যালয়", lang("Bengali")), "বি-শ্ব-বি-দ্যা-লয়");
|
||||
assert_eq!(marked("విశ్వవిద్యాలయం", lang("Telugu")), "వి-శ్వ-వి-ద్యా-ల-యం");
|
||||
assert_eq!(marked("ವಿಶ್ವವಿದ್ಯಾಲಯ", lang("Kannada")), "ವಿ-ಶ್ವ-ವಿ-ದ್ಯಾ-ಲಯ");
|
||||
assert_eq!(marked("વિશ્વવિદ્યાલય", lang("Gujarati")), "વિ-શ્વ-વિ-દ્યા-લય");
|
||||
}
|
||||
|
||||
/// A zero-width joiner or non-joiner (old-style Malayalam chillus, explicit half forms) and a
|
||||
/// nukta stay inside the word they're in, so no break lands next to them.
|
||||
#[test]
|
||||
fn indic_joiners_and_nuktas_do_not_split_words() {
|
||||
for c in ['\u{094D}', '\u{0D4D}', '\u{0BCD}', '\u{093C}', '\u{200C}', '\u{200D}'] {
|
||||
assert!(is_word_char(c), "U+{:04X}", c as u32);
|
||||
}
|
||||
let hi = Lang::for_language("Hindi").unwrap();
|
||||
let (pts, _) = word_breaks_in("पढ़ना", hi);
|
||||
assert!(!pts.contains(&2), "no break between ढ and its nukta: {pts:?}");
|
||||
assert!(pts.contains(&3), "पढ़-ना: {pts:?}");
|
||||
// Old chillu encoding (ന + virama + ZWJ): the word stays one word.
|
||||
let ml = Lang::for_language("Malayalam").unwrap();
|
||||
let (pts, _) = word_breaks_in("അവന്\u{200D}റെ", ml);
|
||||
assert!(pts.iter().all(|&p| !matches!("അവന്\u{200D}റെ".chars().nth(p), Some('\u{200D}' | '\u{0D4D}'))), "{pts:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn norwegian_uses_the_hyph_no_patterns() {
|
||||
let nb = Lang::for_language("Norwegian: Bokmål").unwrap();
|
||||
|
||||
+201
-46
@@ -1749,11 +1749,11 @@ fn apply_nested_line_styles(input: NestedLineStyleInput<'_, '_, '_>) {
|
||||
let ind = pp.left_indent + if j == 0 { pp.first_line_indent } else { 0.0 };
|
||||
tab_advance(&pp.tabs, pp.left_indent, ind + x, gl.get(i + 1..).unwrap_or_default()).0
|
||||
};
|
||||
breaker::greedy(&gl, &hy, &spacing, &width, &tab)
|
||||
breaker::greedy(&story.text, &gl, &hy, &spacing, &width, &tab)
|
||||
} else if pp.balance_ragged && !spacing.justify {
|
||||
breaker::balanced(&gl, &hy, &spacing, &width)
|
||||
breaker::balanced(&story.text, &gl, &hy, &spacing, &width)
|
||||
} else {
|
||||
breaker::knuth_plass(&gl, &hy, &spacing, &width)
|
||||
breaker::knuth_plass(&story.text, &gl, &hy, &spacing, &width)
|
||||
};
|
||||
// Byte where line `k` starts (the paragraph end past the last line).
|
||||
let byte_at =
|
||||
@@ -1832,6 +1832,7 @@ struct ParagraphLines<'a> {
|
||||
drop_cap: Option<&'a DropCap>,
|
||||
base_chars: &'a designcraft_doc::CharProps,
|
||||
mark_chars: &'a designcraft_doc::CharProps,
|
||||
mark_em: &'a MarkEm,
|
||||
mark_leading: f64,
|
||||
base_leading: f64,
|
||||
last_line_mark: Option<f64>,
|
||||
@@ -1856,6 +1857,7 @@ enum LinePlacement {
|
||||
}
|
||||
|
||||
struct PositionLineInput<'a, 'font> {
|
||||
text: &'a str,
|
||||
frame: &'a FrameSpec,
|
||||
column: Rect,
|
||||
glyphs: &'a [Glyph],
|
||||
@@ -1886,6 +1888,7 @@ struct PositionLineInput<'a, 'font> {
|
||||
db: &'a ScopedFonts<'font>,
|
||||
mark_leading: f64,
|
||||
mark_chars: &'a designcraft_doc::CharProps,
|
||||
mark_em: &'a MarkEm,
|
||||
last_line_mark: Option<f64>,
|
||||
}
|
||||
|
||||
@@ -1899,6 +1902,7 @@ struct LinePosition {
|
||||
|
||||
fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition {
|
||||
let PositionLineInput {
|
||||
text,
|
||||
frame: f,
|
||||
column: col,
|
||||
glyphs,
|
||||
@@ -1929,6 +1933,7 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition {
|
||||
db,
|
||||
mark_leading,
|
||||
mark_chars,
|
||||
mark_em,
|
||||
last_line_mark,
|
||||
} = input;
|
||||
let (mut x0, mut x1) = (col.x0, col.x1);
|
||||
@@ -1936,7 +1941,7 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition {
|
||||
let need = if f.exclusions.is_empty() && f.outline.is_none() {
|
||||
0.0
|
||||
} else {
|
||||
let w = breaker::first_word_width(glyphs.get(s..).unwrap_or_default(), hyph_after.get(s..).unwrap_or_default(), spacing);
|
||||
let w = breaker::first_word_width(text, glyphs.get(s..).unwrap_or_default(), hyph_after.get(s..).unwrap_or_default(), spacing);
|
||||
if w > col.width() - ind { 0.0 } else { w }
|
||||
};
|
||||
let holds = |&(a, b): &(f64, f64)| b - a - ind + 0.01 >= need;
|
||||
@@ -1981,7 +1986,7 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition {
|
||||
Some(mark) if j + 1 == breaks.len() => next_lead.max(mark),
|
||||
_ => next_lead,
|
||||
};
|
||||
let (next_reference, next_model) = cjk_line_reference(next_glyphs);
|
||||
let (next_reference, next_model) = line_reference(next_glyphs, mark_em, pp, f.vertical);
|
||||
down += prev_aki.unwrap_or(next_lead) + prev - next_reference;
|
||||
prev = next_reference;
|
||||
prev_aki = aki_below(next_model, next_lead);
|
||||
@@ -2036,6 +2041,7 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition {
|
||||
}
|
||||
|
||||
struct BreakInput<'a> {
|
||||
text: &'a str,
|
||||
glyphs: &'a [Glyph],
|
||||
hyphens: &'a [bool],
|
||||
props: &'a designcraft_doc::ParaProps,
|
||||
@@ -2050,7 +2056,7 @@ struct BreakInput<'a> {
|
||||
}
|
||||
|
||||
fn choose_paragraph_breaks(input: BreakInput<'_>) -> Vec<Break> {
|
||||
let BreakInput { glyphs, hyphens, props: pp, slots, column: col, drop_cap, line_no, col_first_line, rtl, has_tabs, spacing } = input;
|
||||
let BreakInput { text, glyphs, hyphens, props: pp, slots, column: col, drop_cap, line_no, col_first_line, rtl, has_tabs, spacing } = input;
|
||||
let width = |j: usize| -> f64 {
|
||||
let (x0, x1) = slots.get(j).copied().unwrap_or((col.x0, col.x1));
|
||||
let indent = pp.left_indent
|
||||
@@ -2079,11 +2085,11 @@ fn choose_paragraph_breaks(input: BreakInput<'_>) -> Vec<Break> {
|
||||
};
|
||||
tab_advance(&pp.tabs, pp.left_indent, x0 + indent + x - col.x0, glyphs.get(i + 1..).unwrap_or_default()).0
|
||||
};
|
||||
breaker::greedy(glyphs, hyphens, spacing, &width, &tab)
|
||||
breaker::greedy(text, glyphs, hyphens, spacing, &width, &tab)
|
||||
} else if pp.balance_ragged && !spacing.justify {
|
||||
breaker::balanced(glyphs, hyphens, spacing, &width)
|
||||
breaker::balanced(text, glyphs, hyphens, spacing, &width)
|
||||
} else {
|
||||
breaker::knuth_plass(glyphs, hyphens, spacing, &width)
|
||||
breaker::knuth_plass(text, glyphs, hyphens, spacing, &width)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2395,6 +2401,7 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi
|
||||
drop_cap,
|
||||
base_chars,
|
||||
mark_chars,
|
||||
mark_em,
|
||||
mark_leading,
|
||||
base_leading,
|
||||
last_line_mark,
|
||||
@@ -2479,6 +2486,7 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi
|
||||
let est_jump = cur.jump(f, base_leading, est_asc, est_tops);
|
||||
let slots = estimate_slots(f, col, est_first, est_jump, base_leading, base_chars.size, est_band, &glyphs[g0..], rtl, &carry);
|
||||
let breaks = choose_paragraph_breaks(BreakInput {
|
||||
text: &story.text,
|
||||
glyphs: &glyphs[g0..],
|
||||
hyphens: &hyph_after[g0..],
|
||||
props: pp,
|
||||
@@ -2502,9 +2510,10 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi
|
||||
Some(m) if k + 1 == breaks.len() => lead.max(m),
|
||||
_ => lead,
|
||||
};
|
||||
let (reference, model) = cjk_line_reference(line_glyphs);
|
||||
let (reference, model) = line_reference(line_glyphs, mark_em, pp, f.vertical);
|
||||
let advance = if cur.last_baseline.is_some() { cur.aki_below.unwrap_or(lead) } else { lead };
|
||||
let position = position_line(PositionLineInput {
|
||||
text: &story.text,
|
||||
frame: f,
|
||||
column: col,
|
||||
glyphs,
|
||||
@@ -2535,6 +2544,7 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi
|
||||
db,
|
||||
mark_leading,
|
||||
mark_chars,
|
||||
mark_em,
|
||||
last_line_mark,
|
||||
});
|
||||
let LinePosition { x0, x1, baseline, grid_end, continues } = position;
|
||||
@@ -2717,8 +2727,13 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi
|
||||
cur.last_descent = desc;
|
||||
cur.pending = 0.0;
|
||||
cur.grid_next = grid_end.map(|end| (baseline, end));
|
||||
hyphen_at =
|
||||
e.checked_sub(1).filter(|&i| b.hyphen && hyph_after.get(i) == Some(&true)).and_then(|i| glyphs.get(i)).map(|g| g.byte + g.len);
|
||||
// The end of the cluster that owns the break glyph (a glyph without bytes of its own is
|
||||
// part of the cluster before it), which is what `suppress_hyphens` compares against.
|
||||
hyphen_at = e
|
||||
.checked_sub(1)
|
||||
.filter(|&i| b.hyphen && hyph_after.get(i) == Some(&true))
|
||||
.and_then(|i| glyphs.get(..=i)?.iter().rev().find(|g| g.len > 0))
|
||||
.map(|g| g.byte + g.len);
|
||||
line_no += 1;
|
||||
// An Indent to Here character in this line moves the start of the lines after it:
|
||||
// break them again with that indent (it holds into the next columns too).
|
||||
@@ -2788,6 +2803,7 @@ struct ShapedParagraph {
|
||||
base_size: f64,
|
||||
spacing: Spacing,
|
||||
mark_chars: designcraft_doc::CharProps,
|
||||
mark_em: MarkEm,
|
||||
mark_leading: f64,
|
||||
last_line_mark: Option<f64>,
|
||||
para_box: Option<ParaBox>,
|
||||
@@ -2989,8 +3005,19 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph {
|
||||
suppress_hyphens(&mut hyph_after, &glyphs, suppressed_hyphens);
|
||||
let base_size = base_chars.size;
|
||||
let spacing = spacing_for(pp, base_size, story, cjk);
|
||||
// An empty paragraph takes its height from its paragraph mark's character format.
|
||||
let mark_chars = if glyphs.is_empty() { doc.styles.resolve_char(base_chars, story.char_format_of(prange.start)) } else { base_chars.clone() };
|
||||
// An empty line takes its height from its paragraph mark's character format, the one character
|
||||
// it holds: an empty paragraph's line, the line left once a drop cap that is the whole
|
||||
// paragraph is split off, and the line a trailing forced line break leaves.
|
||||
let mark_chars = if glyphs.is_empty() || glyphs.last().is_some_and(|g| g.ch == designcraft_doc::story::FORCED_LINE_BREAK) {
|
||||
doc.styles.resolve_char(base_chars, story.char_format_of(prange.end))
|
||||
} else {
|
||||
base_chars.clone()
|
||||
};
|
||||
let mark_em = {
|
||||
let mark = story.text.get(prange.end..).and_then(|t| t.chars().next()).unwrap_or('\n');
|
||||
let (face, height) = shape::em_face(db, &doc.styles, &mark_chars, mark, &doc.settings.advanced_type);
|
||||
MarkEm { face, height, model: mark_chars.leading_model }
|
||||
};
|
||||
let mark_leading = match mark_chars.leading {
|
||||
designcraft_doc::Leading::Auto => mark_chars.size * pp.auto_leading,
|
||||
designcraft_doc::Leading::Points(v) => v,
|
||||
@@ -3022,6 +3049,7 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph {
|
||||
base_size,
|
||||
spacing,
|
||||
mark_chars,
|
||||
mark_em,
|
||||
mark_leading,
|
||||
last_line_mark,
|
||||
para_box,
|
||||
@@ -3472,6 +3500,7 @@ fn compose_run(
|
||||
base_size,
|
||||
spacing,
|
||||
mark_chars,
|
||||
mark_em,
|
||||
mark_leading,
|
||||
last_line_mark,
|
||||
para_box: _,
|
||||
@@ -3641,6 +3670,7 @@ fn compose_run(
|
||||
drop_cap: drop_cap.as_ref(),
|
||||
base_chars: &base_chars,
|
||||
mark_chars: &mark_chars,
|
||||
mark_em: &mark_em,
|
||||
mark_leading,
|
||||
base_leading,
|
||||
last_line_mark,
|
||||
@@ -4114,6 +4144,7 @@ fn apply_desired_spacing(glyphs: &mut [Glyph], pp: &ParaProps) {
|
||||
g.adv += g.space * (ws - 1.0);
|
||||
} else if !g.is_space() && g.adv > 0.0 {
|
||||
g.adv = g.adv * gs + ls * g.space;
|
||||
g.track *= gs;
|
||||
g.sx *= gs;
|
||||
g.dx *= gs;
|
||||
}
|
||||
@@ -4754,8 +4785,12 @@ fn em_box_top(face: &designcraft_fonts::FontFace, size: f64) -> f64 {
|
||||
/// Em box relative to the baseline. Font ascender/descender proportions locate it;
|
||||
/// the box's total extent is the em, rather than the font's optional line gap.
|
||||
fn cjk_em_box(g: &Glyph) -> (f64, f64) {
|
||||
let height = g.face.units_per_em() * g.sy.abs();
|
||||
let top = -height * g.ascent / (g.ascent + g.descent).max(1e-9);
|
||||
em_box(g.face.units_per_em() * g.sy.abs(), g.ascent, g.descent)
|
||||
}
|
||||
/// An em box `height` tall relative to the baseline, placed by the font's `ascent` and `descent`
|
||||
/// proportions (see [`cjk_em_box`]).
|
||||
fn em_box(height: f64, ascent: f64, descent: f64) -> (f64, f64) {
|
||||
let top = -height * ascent / (ascent + descent).max(1e-9);
|
||||
(top, top + height)
|
||||
}
|
||||
/// The ideographic character face (ICF) box relative to the baseline: the em box of
|
||||
@@ -4797,16 +4832,53 @@ fn cjk_alignment_shift(g: &Glyph, reference: &Glyph) -> f64 {
|
||||
fn cjk_line_reference(line: &[Glyph]) -> (f64, designcraft_doc::cjk::LeadingModel) {
|
||||
use designcraft_doc::cjk::LeadingModel as L;
|
||||
let Some(g) = line.iter().max_by(|a, b| a.size.total_cmp(&b.size)) else { return (0.0, L::Roman) };
|
||||
let (top, bottom) = cjk_em_box(g);
|
||||
let reference = match g.leading_model {
|
||||
(leading_reference(g.leading_model, cjk_em_box(g)), g.leading_model)
|
||||
}
|
||||
|
||||
/// The paragraph mark's em box, which an empty line measures leading from: the face and em box
|
||||
/// height the mark is shaped with (a composite font's entry, a superscript or subscript at its
|
||||
/// Advanced Type size; see [`shape::em_face`]) and its leading model.
|
||||
struct MarkEm {
|
||||
face: std::sync::Arc<designcraft_fonts::FontFace>,
|
||||
height: f64,
|
||||
model: designcraft_doc::cjk::LeadingModel,
|
||||
}
|
||||
|
||||
/// [`cjk_line_reference`] of a line of paragraph `pp`. An empty line (an empty paragraph, or the
|
||||
/// line a trailing forced line break leaves) has no character to measure from: it measures from
|
||||
/// its paragraph mark's em box under the mark's leading model (`mark`), as in InDesign, so it
|
||||
/// keeps the leading like any other line instead of moving by the em box's offset from the
|
||||
/// baseline. In `vertical` text that is the upright em box, as for the upright characters around
|
||||
/// it. Only the Japanese composers use a leading model.
|
||||
fn line_reference(line: &[Glyph], mark: &MarkEm, pp: &ParaProps, vertical: bool) -> (f64, designcraft_doc::cjk::LeadingModel) {
|
||||
use designcraft_doc::cjk::LeadingModel as L;
|
||||
if !line.is_empty() {
|
||||
return cjk_line_reference(line);
|
||||
}
|
||||
if !pp.composer.japanese() || mark.model == L::Roman {
|
||||
return (0.0, L::Roman);
|
||||
}
|
||||
// Placed by the proportions the shaper gives the glyphs: upright ones fill the em box.
|
||||
let (ascent, descent) = if vertical {
|
||||
let (top, bottom) = mark.face.em_box();
|
||||
(top, -bottom)
|
||||
} else {
|
||||
(mark.face.ascent, mark.face.descent)
|
||||
};
|
||||
(leading_reference(mark.model, em_box(mark.height, ascent, descent)), mark.model)
|
||||
}
|
||||
|
||||
/// Where `model` measures leading from, for an em box at `top..bottom` from the baseline.
|
||||
fn leading_reference(model: designcraft_doc::cjk::LeadingModel, (top, bottom): (f64, f64)) -> f64 {
|
||||
use designcraft_doc::cjk::LeadingModel as L;
|
||||
match model {
|
||||
L::Roman => 0.0,
|
||||
// "Space below" measures from the em box top (Em Box Top/Right), "space above" from its
|
||||
// bottom (Em Box Bottom/Left).
|
||||
L::AkiBelow => top,
|
||||
L::AkiAbove => bottom,
|
||||
L::Center | L::CenterDown => (top + bottom) / 2.0,
|
||||
};
|
||||
(reference, g.leading_model)
|
||||
}
|
||||
}
|
||||
|
||||
fn line_metrics(
|
||||
@@ -5270,7 +5342,12 @@ fn layout_line(
|
||||
g.shift += cjk_alignment_shift(g, &reference);
|
||||
}
|
||||
}
|
||||
if hyphen && let Some(g) = line.last() {
|
||||
// No hyphen after a word of an Indian script (its last letter before any soft hyphens).
|
||||
let marked = line.iter().rev().find(|g| g.ch != shape::SOFT_HYPHEN).is_none_or(|g| !shape::breaks_without_hyphen(g));
|
||||
if hyphen
|
||||
&& marked
|
||||
&& let Some(g) = line.last()
|
||||
{
|
||||
let h = shape::hyphen_after(g);
|
||||
line.push(h);
|
||||
}
|
||||
@@ -5381,9 +5458,12 @@ fn layout_line(
|
||||
let mut x = x0 + offset;
|
||||
let bidi = bidi_info.has_rtl();
|
||||
let mut pens = Vec::with_capacity(if bidi { line.len() } else { 0 });
|
||||
// The tracking each placed advance carries, scaled with it.
|
||||
let mut tracks = Vec::with_capacity(if bidi { line.len() } else { 0 });
|
||||
for (i, g) in line.iter().enumerate() {
|
||||
if bidi {
|
||||
pens.push(x);
|
||||
tracks.push(g.track * scale[i]);
|
||||
}
|
||||
let mut p = place(g, x);
|
||||
if scale[i] != 1.0 {
|
||||
@@ -5406,7 +5486,7 @@ fn layout_line(
|
||||
}
|
||||
if bidi {
|
||||
pens.push(x);
|
||||
reorder_visual(&line, &mut out, &pens, x0 + offset, bidi_info);
|
||||
reorder_visual(&line, &mut out, &pens, &tracks, x0 + offset, bidi_info);
|
||||
}
|
||||
for (i, leader) in &leaders {
|
||||
if let Some((g, p)) = line.get(*i).zip(out.get(*i)) {
|
||||
@@ -5432,13 +5512,45 @@ fn joins_prev(c: char) -> bool {
|
||||
| 0x06C0 | 0x06C3..=0x06CB | 0x06CD | 0x06CF | 0x06D2 | 0x06D3)
|
||||
}
|
||||
|
||||
/// Where kashidas go on a line: one join per word, after a seen or sad when there is one, else the
|
||||
/// word's last join (indices of the glyph before the join).
|
||||
/// Arabic combining marks, which sit on a letter and never take part in a join.
|
||||
fn is_arabic_mark(c: char) -> bool {
|
||||
matches!(c as u32, 0x064B..=0x065F | 0x0670)
|
||||
}
|
||||
|
||||
/// Letters whose initial and medial forms are a tooth (ب ت ث ن ي ئ).
|
||||
fn is_tooth(c: char) -> bool {
|
||||
matches!(c as u32, 0x0626 | 0x0628 | 0x062A | 0x062B | 0x0646 | 0x064A)
|
||||
}
|
||||
|
||||
/// How well Arabic typography takes a kashida at the join of `g` and `n`, from 0 (best) to 4, or
|
||||
/// `None` where one must not go. `prev` is the letter before `g` and `next` the one after `n`.
|
||||
fn kashida_rank(prev: Option<char>, g: char, n: char, next: Option<char>) -> Option<u8> {
|
||||
let medial = prev.is_some_and(joins_next);
|
||||
let last = !(joins_next(n) && next.is_some_and(joins_prev));
|
||||
let forbidden = n == '\u{0648}'
|
||||
|| (last && matches!(n as u32, 0x0649 | 0x064A | 0x0646))
|
||||
|| (is_tooth(g) && matches!(n as u32, 0x0631 | 0x0632 | 0x0635 | 0x0636 | 0x0639 | 0x063A | 0x0641 | 0x0642))
|
||||
|| g == '\u{0643}'
|
||||
|| (g == '\u{0644}' && (!medial || matches!(n as u32, 0x0644 | 0x062F)));
|
||||
if forbidden {
|
||||
return None;
|
||||
}
|
||||
Some(match n as u32 {
|
||||
0x0629 | 0x0647 if last => 0,
|
||||
0x0627 if last => 1,
|
||||
0x0631 | 0x0632 => 2,
|
||||
_ if !last && is_tooth(g) && is_tooth(n) => 3,
|
||||
_ => 4,
|
||||
})
|
||||
}
|
||||
|
||||
/// Where kashidas go on a line: one join per word, the best by [`kashida_rank`] and the later in
|
||||
/// the word among equals (indices of the glyph before the join).
|
||||
fn kashida_points(line: &[Glyph]) -> Vec<usize> {
|
||||
let mut out = Vec::new();
|
||||
let mut best: Option<(bool, usize)> = None;
|
||||
let mut best: Option<(u8, usize)> = None;
|
||||
for (i, g) in line.iter().enumerate() {
|
||||
if g.is_space() {
|
||||
if g.is_space() || g.ch == '\t' || g.ch == story::RIGHT_INDENT_TAB {
|
||||
if let Some((_, k)) = best.take() {
|
||||
out.push(k);
|
||||
}
|
||||
@@ -5456,9 +5568,12 @@ fn kashida_points(line: &[Glyph]) -> Vec<usize> {
|
||||
if !joins_next(g.ch) || !joins_prev(n.ch) || (g.ch == '\u{0644}' && matches!(n.ch, '\u{0622}' | '\u{0623}' | '\u{0625}' | '\u{0627}')) {
|
||||
continue;
|
||||
}
|
||||
let seen = matches!(g.ch as u32, 0x0633..=0x0636);
|
||||
if best.is_none_or(|(s, _)| !s || seen) {
|
||||
best = Some((seen, i));
|
||||
let letter = |p: &&Glyph, cluster: &Glyph| p.byte != cluster.byte && !is_arabic_mark(p.ch);
|
||||
let prev = line.get(..i).and_then(|l| l.iter().rev().find(|p| letter(p, g))).map(|p| p.ch);
|
||||
let next = line.get(i + 2..).and_then(|l| l.iter().find(|p| letter(p, n))).map(|p| p.ch);
|
||||
let Some(rank) = kashida_rank(prev, g.ch, n.ch, next) else { continue };
|
||||
if best.is_none_or(|(r, _)| rank <= r) {
|
||||
best = Some((rank, i));
|
||||
}
|
||||
}
|
||||
out.extend(best.map(|b| b.1));
|
||||
@@ -5466,9 +5581,9 @@ fn kashida_points(line: &[Glyph]) -> Vec<usize> {
|
||||
}
|
||||
|
||||
/// Bidi: put a laid-out line (glyphs in text order, `pens` their pen positions and then the end
|
||||
/// position) into visual order from `start`, cluster by cluster (Unicode Bidirectional
|
||||
/// Algorithm, rule L2).
|
||||
fn reorder_visual(line: &[Glyph], out: &mut [PlacedGlyph], pens: &[f64], start: f64, info: &unicode_bidi::BidiInfo<'_>) {
|
||||
/// position, `tracks` the tracking in their placed advances) into visual order from `start`,
|
||||
/// cluster by cluster (Unicode Bidirectional Algorithm, rule L2).
|
||||
fn reorder_visual(line: &[Glyph], out: &mut [PlacedGlyph], pens: &[f64], tracks: &[f64], start: f64, info: &unicode_bidi::BidiInfo<'_>) {
|
||||
use unicode_bidi::{BidiInfo, Level};
|
||||
// Clusters: runs of glyphs from the same source character.
|
||||
let mut units: Vec<std::ops::Range<usize>> = Vec::new();
|
||||
@@ -5487,13 +5602,30 @@ fn reorder_visual(line: &[Glyph], out: &mut [PlacedGlyph], pens: &[f64], start:
|
||||
let width = |u: &std::ops::Range<usize>| pens[u.end] - pens[u.start];
|
||||
let mut cur = start;
|
||||
let mut shifts = vec![0.0; line.len()];
|
||||
// The glyph whose advance ends at `cur`: the last one of the cluster drawn there.
|
||||
let mut left: Option<usize> = None;
|
||||
for &k in &order {
|
||||
let u = &units[k];
|
||||
let rtl = levels[k].is_rtl();
|
||||
// Tracking is space after the character in reading order (#2884): right-to-left, that
|
||||
// is at its left. The space leaves the cluster's advance for the advance of whatever is
|
||||
// drawn left of it (at the start of the line, nothing), so advances stay end to end.
|
||||
let track: f64 = if rtl { u.clone().filter_map(|i| tracks.get(i)).sum() } else { 0.0 };
|
||||
if track != 0.0 {
|
||||
if let Some(o) = left.and_then(|l| out.get_mut(l)) {
|
||||
o.adv += track;
|
||||
}
|
||||
for i in u.clone() {
|
||||
out[i].adv -= tracks.get(i).copied().unwrap_or(0.0);
|
||||
}
|
||||
cur += track;
|
||||
}
|
||||
for i in u.clone() {
|
||||
shifts[i] = cur - pens[u.start];
|
||||
out[i].rtl = levels[k].is_rtl();
|
||||
out[i].rtl = rtl;
|
||||
}
|
||||
cur += width(u);
|
||||
cur += width(u) - track;
|
||||
left = u.end.checked_sub(1);
|
||||
}
|
||||
for (p, d) in out.iter_mut().zip(shifts) {
|
||||
p.x += d;
|
||||
@@ -5785,6 +5917,7 @@ fn split_drop_cap(
|
||||
let k = if k.is_finite() && k > 0.0 { k.min(1000.0) } else { 1.0 };
|
||||
for g in dc.iter_mut().chain(after.iter_mut()) {
|
||||
g.adv *= k;
|
||||
g.track *= k;
|
||||
g.dx *= k;
|
||||
g.dy *= k;
|
||||
g.sx *= k;
|
||||
@@ -5835,10 +5968,22 @@ impl DropCap {
|
||||
/// The drop cap's glyphs set from `at` (right to left: mirrored, its first character on the right).
|
||||
fn place_drop_cap(dc: &DropCap, at: f64, rtl: bool) -> Vec<PlacedGlyph> {
|
||||
let mut x = at;
|
||||
// Right to left, the edge the next letter ends at and the tracking of the letter before it in
|
||||
// reading order: that space is at its left (#2884), so in the advance of the letter drawn there.
|
||||
let mut right = at + dc.width;
|
||||
let mut carried = 0.0;
|
||||
let mut out = Vec::with_capacity(dc.glyphs.len());
|
||||
for g in &dc.glyphs {
|
||||
let pen = if rtl { at + at + dc.width - x - g.adv } else { x };
|
||||
let (pen, adv) = if rtl {
|
||||
let adv = g.adv - g.track + carried;
|
||||
carried = g.track;
|
||||
right -= adv;
|
||||
(right, adv)
|
||||
} else {
|
||||
(x, g.adv)
|
||||
};
|
||||
let mut p = place(g, pen);
|
||||
p.adv = adv;
|
||||
p.y += dc.drop;
|
||||
p.rtl = rtl;
|
||||
out.push(p);
|
||||
@@ -5965,13 +6110,18 @@ fn foreign_ranges(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Leave out the hyphenation points after the glyphs that end at story bytes `at`.
|
||||
/// Leave out the hyphenation points after the glyphs that end at story bytes `at`. A glyph
|
||||
/// without bytes of its own (len 0) is part of the cluster before it and ends where that does.
|
||||
fn suppress_hyphens(hy: &mut [bool], glyphs: &[Glyph], at: &[usize]) {
|
||||
if at.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut end = 0;
|
||||
for (h, g) in hy.iter_mut().zip(glyphs) {
|
||||
if *h && at.contains(&(g.byte + g.len)) {
|
||||
if g.len > 0 || end == 0 {
|
||||
end = g.byte + g.len;
|
||||
}
|
||||
if *h && at.contains(&end) {
|
||||
*h = false;
|
||||
}
|
||||
}
|
||||
@@ -6059,7 +6209,7 @@ fn hyphenation_points(
|
||||
}
|
||||
// A discretionary hyphen in a word (or right before it) replaces automatic hyphenation.
|
||||
let discretionary = glyphs[i..j].iter().any(|g| g.ch == shape::SOFT_HYPHEN) || (i > 0 && glyphs[i - 1].ch == shape::SOFT_HYPHEN);
|
||||
let (a, b) = (glyphs[i].byte, glyphs[j - 1].byte + glyphs[j - 1].len);
|
||||
let (a, b) = (glyphs[i].byte, glyphs[i..j].iter().map(|g| g.byte + g.len).max().unwrap_or(glyphs[i].byte));
|
||||
if !discretionary && b > a && b <= text.len() && text.is_char_boundary(a) && text.is_char_boundary(b) {
|
||||
let word = &text[a..b];
|
||||
// The whitespace-delimited token the word sits in: a Latin run with a Korean particle
|
||||
@@ -6095,13 +6245,17 @@ fn hyphenation_points(
|
||||
}
|
||||
};
|
||||
if !pts.is_empty() {
|
||||
// char index p → byte → the first glyph whose cluster ends at that byte. Both
|
||||
// indexed once per word: looking each point up by scanning was quadratic in
|
||||
// a long word's length.
|
||||
// char index p → byte → the last glyph of the cluster that ends at that byte.
|
||||
// A cluster's first glyph owns its bytes and the glyphs after it (len 0) are
|
||||
// the rest of it: a Devanagari syllable such as वि is drawn as the ि sign
|
||||
// before the व, so the break goes after the last of them, not between them.
|
||||
// Both indexed once per word: looking each point up by scanning was quadratic
|
||||
// in a long word's length.
|
||||
let char_bytes: Vec<usize> = word.char_indices().map(|(bi, _)| bi).collect();
|
||||
let mut glyph_ending_at: HashMap<usize, usize> = HashMap::new();
|
||||
for k in (i..j).filter(|&k| glyphs[k].len > 0) {
|
||||
glyph_ending_at.entry(glyphs[k].byte + glyphs[k].len).or_insert(k);
|
||||
let last = (k + 1..j).take_while(|&m| glyphs[m].len == 0).last().unwrap_or(k);
|
||||
glyph_ending_at.entry(glyphs[k].byte + glyphs[k].len).or_insert(last);
|
||||
}
|
||||
for &p in pts.iter() {
|
||||
let byte = a + char_bytes.get(p).copied().unwrap_or(word.len());
|
||||
@@ -6135,8 +6289,9 @@ fn rule_decos(doc: &Document, r: &designcraft_doc::Rule, rect: Rect, (color, tin
|
||||
let mut line = designcraft_geom::BezPath::new();
|
||||
line.move_to((rect.x0, y));
|
||||
line.line_to((rect.x1, y));
|
||||
let path = match &kind {
|
||||
StrokeType::Dashed { pattern } if StrokeType::expandable_dashes(pattern, len) => {
|
||||
let dashes = kind.dashes(w).filter(|p| StrokeType::expandable_dashes(p, len));
|
||||
let path = match (&kind, dashes) {
|
||||
(StrokeType::Dashed { .. }, Some(pattern)) => {
|
||||
let mut p = designcraft_geom::BezPath::new();
|
||||
let (mut x, mut k, mut on) = (rect.x0, 0, true);
|
||||
while x < rect.x1 {
|
||||
@@ -6151,7 +6306,7 @@ fn rule_decos(doc: &Document, r: &designcraft_doc::Rule, rect: Rect, (color, tin
|
||||
}
|
||||
Some(p)
|
||||
}
|
||||
StrokeType::Dotted if StrokeType::expandable_dashes(&[w, w], len) => {
|
||||
(StrokeType::Dotted, _) if StrokeType::expandable_dashes(&[w, w], len) => {
|
||||
let mut p = designcraft_geom::BezPath::new();
|
||||
let mut x = rect.x0 + w / 2.0;
|
||||
while x <= rect.x1 - w / 2.0 + 1e-9 {
|
||||
@@ -6160,7 +6315,7 @@ fn rule_decos(doc: &Document, r: &designcraft_doc::Rule, rect: Rect, (color, tin
|
||||
}
|
||||
Some(p)
|
||||
}
|
||||
k => k.outline(&line, w, 0.05),
|
||||
(k, _) => k.outline(&line, w, 0.05),
|
||||
};
|
||||
out.push(Deco { rect, color, tint, path, ..Deco::default() });
|
||||
out
|
||||
|
||||
@@ -354,10 +354,7 @@ fn stroke_outline(path: &BezPath, w: f64, kind: &StrokeType, cap: Cap, join: Joi
|
||||
Join::Bevel => kurbo::Join::Bevel,
|
||||
});
|
||||
let dashes: Option<Vec<f64>> = match kind {
|
||||
StrokeType::Dashed { pattern } => {
|
||||
let p: Vec<f64> = pattern.iter().copied().filter(|v| v.is_finite() && *v >= 0.0).collect();
|
||||
Some(if p.iter().sum::<f64>() > 1e-3 { p } else { vec![3.0 * w, 2.0 * w] })
|
||||
}
|
||||
StrokeType::Dashed { .. } => kind.dashes(w),
|
||||
StrokeType::Dotted => match dots(path, w) {
|
||||
Some(d) => return d,
|
||||
None => None,
|
||||
|
||||
@@ -71,6 +71,9 @@ pub struct Glyph {
|
||||
pub allow_kashidas: bool,
|
||||
pub safe_tatweel_before: bool,
|
||||
pub shaping_rtl: bool,
|
||||
/// Tracking and manual kerning included in `adv`, the space after the character in reading
|
||||
/// order. Right-to-left, that is at the glyph's left (see `reorder_visual`).
|
||||
pub track: f64,
|
||||
/// The character's language as a BCP 47 tag ([`designcraft_doc::language_tag`]).
|
||||
pub lang: Option<&'static str>,
|
||||
/// Upright in a vertical frame: shaped top to bottom (`adv` is its vertical advance) and hung
|
||||
@@ -929,6 +932,10 @@ fn shape_run_raw(
|
||||
}
|
||||
designcraft_doc::OBJECT_MARK => {
|
||||
let mut g = control_glyph(&primary, p, auto_leading, styles.at(i), i, c);
|
||||
// Bidi-neutral like U+FFFC (the object replacement character), not a strong
|
||||
// left-to-right character as its private-use mark is: an inline object in
|
||||
// right-to-left text keeps its place in the reading order.
|
||||
g.display_char = '\u{FFFC}';
|
||||
if let Some(o) = sub.objects.get(&i).filter(|o| !o.custom) {
|
||||
let auto = matches!(p.leading, Leading::Auto);
|
||||
match o.y_offset {
|
||||
@@ -1074,6 +1081,35 @@ fn shape_cached(
|
||||
out
|
||||
}
|
||||
|
||||
/// Size of a small capital drawn by us, as a fraction of the type size, close to InDesign's own.
|
||||
const SMALL_CAPS_SIZE: f64 = 0.7;
|
||||
|
||||
/// Faces whose small caps we must draw, by face id. Reading a font's feature list parses its GSUB,
|
||||
/// which is not something to do once per run per line.
|
||||
static SMALL_CAPS_MISSING: RwLock<Vec<(u32, bool)>> = RwLock::new(Vec::new());
|
||||
|
||||
/// How much a glyph shrinks when we draw its small caps: the lowercase letters of a Small Caps run,
|
||||
/// and nothing else. Only the glyph and its advance change — the
|
||||
/// line box is measured from the unscaled size, so turning it on never moves the leading.
|
||||
fn small_caps_shrink(small: bool, ch: char) -> f64 {
|
||||
if small && ch.is_lowercase() { SMALL_CAPS_SIZE } else { 1.0 }
|
||||
}
|
||||
|
||||
/// Whether this run's Small Caps have to be drawn instead of taken from the font: the font's own
|
||||
/// `smcp` is used whenever it has one. OpenType All Small Caps only applies a font's own small caps.
|
||||
fn small_caps_drawn_by_us(face: &FontFace, p: &CharProps) -> bool {
|
||||
if p.capitalization != Capitalization::SmallCaps {
|
||||
return false;
|
||||
}
|
||||
let id = face.id();
|
||||
if let Some((_, missing)) = SMALL_CAPS_MISSING.read().unwrap_or_else(std::sync::PoisonError::into_inner).iter().find(|e| e.0 == id) {
|
||||
return *missing;
|
||||
}
|
||||
let missing = !designcraft_fonts::font_features(face).tags.contains("smcp");
|
||||
SMALL_CAPS_MISSING.write().unwrap_or_else(std::sync::PoisonError::into_inner).push((id, missing));
|
||||
missing
|
||||
}
|
||||
|
||||
fn metrics(face: &FontFace, p: &CharProps, auto_leading: TypeEnv) -> (f64, f64, f64, f64, f64, f64, f64, f64) {
|
||||
let (size, shift) = effective_size(p, &auto_leading.adv);
|
||||
let k = size / face.upem;
|
||||
@@ -1094,6 +1130,23 @@ pub struct TypeEnv {
|
||||
pub glyph_fallback: bool,
|
||||
}
|
||||
|
||||
/// The face and em box height a character `c` with `p` is shaped with: a composite font
|
||||
/// resolved to its entry for `c` (font, size and vertical scale), and a superscript or subscript
|
||||
/// at its Advanced Type size, as [`shape_para`] shapes it. A shaped glyph's em box is
|
||||
/// `units_per_em * sy`, which is this height.
|
||||
pub(crate) fn em_face(db: &ScopedFonts<'_>, styles: &Styles, p: &CharProps, c: char, adv: &designcraft_doc::AdvancedType) -> (Arc<FontFace>, f64) {
|
||||
let resolved;
|
||||
let p = match styles.composite_font(&p.font_family) {
|
||||
Some(font) => {
|
||||
resolved = composite_props(db, p, font.entry(c));
|
||||
&resolved
|
||||
}
|
||||
None => p,
|
||||
};
|
||||
let (size, _) = effective_size(p, adv);
|
||||
(db.face(&p.font_family, &p.font_style), size * p.v_scale)
|
||||
}
|
||||
|
||||
/// Synthesised super/subscript: size and shift from Advanced Type (percent of the font size).
|
||||
fn effective_size(p: &CharProps, adv: &designcraft_doc::AdvancedType) -> (f64, f64) {
|
||||
match p.position {
|
||||
@@ -1145,6 +1198,7 @@ fn control_glyph(face: &Arc<FontFace>, p: &CharProps, auto_leading: TypeEnv, sty
|
||||
allow_kashidas: p.allow_kashidas,
|
||||
safe_tatweel_before: false,
|
||||
shaping_rtl: false,
|
||||
track: 0.0,
|
||||
lang: designcraft_doc::language_tag(&p.language),
|
||||
upright: false,
|
||||
list_label: false,
|
||||
@@ -1199,7 +1253,11 @@ fn shape_segment(
|
||||
let tracking = p.tracking / 1000.0 * p.size;
|
||||
let manual = if let Kerning::Manual(v) = p.kerning { v / 1000.0 * p.size } else { 0.0 };
|
||||
let src = replacement.unwrap_or(&text[range.clone()]);
|
||||
let caps = p.capitalization == Capitalization::AllCaps;
|
||||
// A font with no small caps of its own gets them drawn: the letter is uppercased and set
|
||||
// smaller, the way InDesign does it, which is why All Caps worked on such a font and Small
|
||||
// Caps looked like nothing happened (#2438).
|
||||
let small = small_caps_drawn_by_us(face, p);
|
||||
let caps = p.capitalization == Capitalization::AllCaps || small;
|
||||
let feats = features_for(p);
|
||||
// Upright in vertical text, Horizontal Kana takes the vertical kana alternates instead.
|
||||
let mut upright_feats = feats.clone();
|
||||
@@ -1253,19 +1311,22 @@ fn shape_segment(
|
||||
let end = shaped[gi + 1..].iter().map(|r| r.cluster).find(|&c| c > sg.cluster).unwrap_or(src.len());
|
||||
Box::from(src.get(sg.cluster..end).unwrap_or(""))
|
||||
});
|
||||
let shrink = small_caps_shrink(small, src.get(sg.cluster..).and_then(|s| s.chars().next()).unwrap_or(ch));
|
||||
// Upright: down the line is the shaper's -y, across it (text space -y) its x.
|
||||
let mut adv = if up { -(sg.y_advance as f64) * k_v } else { sg.x_advance as f64 * k * hs };
|
||||
let mut adv = if up { -(sg.y_advance as f64) * k_v * shrink } else { sg.x_advance as f64 * k * hs * shrink };
|
||||
let (dx, dy) = if up {
|
||||
(-(sg.y_offset as f64) * k_v, -(sg.x_offset as f64) * k * hs)
|
||||
(-(sg.y_offset as f64) * k_v * shrink, -(sg.x_offset as f64) * k * hs * shrink)
|
||||
} else {
|
||||
(sg.x_offset as f64 * k * hs, -(sg.y_offset as f64) * k * p.v_scale)
|
||||
(sg.x_offset as f64 * k * hs * shrink, -(sg.y_offset as f64) * k * p.v_scale * shrink)
|
||||
};
|
||||
let (ascent, descent) = if up { (em_top * k_v, -em_bottom * k_v) } else { (ascent, descent) };
|
||||
let body = adv;
|
||||
let mut track = 0.0;
|
||||
if ch == SOFT_HYPHEN {
|
||||
adv = 0.0;
|
||||
} else if last_in_cluster {
|
||||
adv += tracking + manual;
|
||||
track = tracking + manual;
|
||||
adv += track;
|
||||
}
|
||||
let mark = face.glyph_is_mark(sg.gid);
|
||||
let mark_x = if mark { p.diacritic_x_offset.clamp(-1000.0, 1000.0) / 1000.0 * p.size * hs } else { 0.0 };
|
||||
@@ -1280,8 +1341,8 @@ fn shape_segment(
|
||||
adv,
|
||||
dx: dx + mark_x,
|
||||
dy: dy - mark_y,
|
||||
sx: k * hs,
|
||||
sy: k * p.v_scale,
|
||||
sx: k * hs * shrink,
|
||||
sy: k * p.v_scale * shrink,
|
||||
shift,
|
||||
ascent,
|
||||
typo_ascent: face.typo_ascent * k,
|
||||
@@ -1319,6 +1380,7 @@ fn shape_segment(
|
||||
allow_kashidas: p.allow_kashidas,
|
||||
safe_tatweel_before: sg.safe_tatweel_before,
|
||||
shaping_rtl: sg.rtl,
|
||||
track,
|
||||
lang,
|
||||
upright: up,
|
||||
list_label: false,
|
||||
@@ -1427,12 +1489,21 @@ fn fit_auto_tcy(glyphs: &mut [Glyph], auto: &[std::ops::Range<usize>]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a word broken after `g` takes no hyphen mark: Indian scripts (Devanagari, Bengali,
|
||||
/// Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada and Malayalam). Their words split between
|
||||
/// syllables at a line end without a hyphen, so nothing is drawn there and no room is kept for
|
||||
/// one. Latin and other scripts keep the hyphen.
|
||||
pub(crate) fn breaks_without_hyphen(g: &Glyph) -> bool {
|
||||
matches!(g.ch as u32, 0x0900..=0x0D7F)
|
||||
}
|
||||
|
||||
/// A hyphen glyph in the face/size of `g`, placed after it (zero source length).
|
||||
pub(crate) fn hyphen_after(g: &Glyph) -> Glyph {
|
||||
let gid = designcraft_fonts::first_glyph(&g.face, &['-', '\u{2010}']);
|
||||
let mut h = g.clone();
|
||||
h.gid = gid;
|
||||
h.adv = g.face.advance(gid) * g.sx;
|
||||
h.track = 0.0;
|
||||
h.dx = 0.0;
|
||||
h.dy = 0.0;
|
||||
h.byte = g.byte + g.len;
|
||||
|
||||
+148
-15
@@ -304,8 +304,10 @@ pub(crate) fn place_table(
|
||||
let sum = |a: usize, b: usize| heights[a..b].iter().sum::<f64>();
|
||||
let footer_h = sum(body_end, nr);
|
||||
let o = &table.options;
|
||||
// InDesign measures Space Before from the previous line's baseline (the descenders may hang
|
||||
// into it), as it measures text after the table from the table's bottom.
|
||||
let mut y = match cur.last_baseline {
|
||||
Some(b) => b + cur.last_descent + cur.pending + o.space_before,
|
||||
Some(b) => b + cur.pending + o.space_before,
|
||||
None => col.y0,
|
||||
};
|
||||
let mut frag_rows: Vec<(usize, f64, bool)> = Vec::new(); // (row, y, repeated)
|
||||
@@ -328,22 +330,24 @@ pub(crate) fn place_table(
|
||||
let mut reserve = column_reserve(notes, cur, col);
|
||||
let mut r = header;
|
||||
loop {
|
||||
if r >= body_end {
|
||||
break;
|
||||
}
|
||||
let ge = group_end[r].min(body_end).max(r + 1);
|
||||
let gh = sum(r, ge);
|
||||
let bottom = col.y1 - reserve;
|
||||
let at_col_top = cur.last_baseline.is_none() && (top - col.y0).abs() < 1e-6;
|
||||
if y + gh + footer_h <= bottom + 0.01 || (body_placed == 0 && at_col_top && reserve == 0.0) {
|
||||
if y + gh + footer_h > bottom + 0.01 && body_placed == 0 && at_col_top && y + gh > bottom + 0.01 {
|
||||
// A row group taller than an empty column can never fit.
|
||||
return false;
|
||||
if r >= body_end {
|
||||
// A table with no body rows still has to fit its header and footer rows inside the column.
|
||||
if y + footer_h <= bottom + 0.01 {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
let ge = group_end[r].min(body_end).max(r + 1);
|
||||
let gh = sum(r, ge);
|
||||
// A non-final fragment without repeating footers does not emit the footer rows;
|
||||
// every other fragment must keep its footer rows inside the column too.
|
||||
let need_footer = if o.repeat_footer || ge == body_end { footer_h } else { 0.0 };
|
||||
if y + gh + need_footer <= bottom + 0.01 {
|
||||
place_rows(r..ge, &mut y, false, &mut frag_rows);
|
||||
body_placed += 1;
|
||||
r = ge;
|
||||
continue;
|
||||
}
|
||||
place_rows(r..ge, &mut y, false, &mut frag_rows);
|
||||
body_placed += 1;
|
||||
r = ge;
|
||||
continue;
|
||||
}
|
||||
// Continue in the next column / frame.
|
||||
if body_placed > 0 {
|
||||
@@ -391,6 +395,7 @@ fn clip_overset(lay: &CellLayout, clip_height: f64) -> Arc<ComposedStory> {
|
||||
frame.lines.truncate(keep);
|
||||
frame.objects.retain(|o| o.line < keep);
|
||||
frame.tables.retain(|table| table.line < keep);
|
||||
frame.notes.retain(|note| keep > 0 && note.rect.y1 <= clip_height + 0.01);
|
||||
frame.range.end = frame.lines.last().map_or(frame.range.start, |l| l.range.end);
|
||||
}
|
||||
if let Some(at) = overset_at {
|
||||
@@ -1144,6 +1149,134 @@ mod height_tests {
|
||||
assert!(placed.text.frames[0].tables.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn footer_rows_never_overflow_the_frame() {
|
||||
for repeat_footer in [false, true] {
|
||||
// Single body row (70 pt) fits alone in a 100 pt frame, but body + footer (110 pt) does not.
|
||||
let mut table = Table::new(77, 1, 1, 0, 1, 100.0);
|
||||
table.options.repeat_footer = repeat_footer;
|
||||
table.rows[0].mode = RowHeightMode::Exactly;
|
||||
table.rows[0].height = 70.0;
|
||||
table.rows[1].mode = RowHeightMode::Exactly;
|
||||
table.rows[1].height = 40.0;
|
||||
let composed = compose_table(table, 100.0);
|
||||
assert!(composed.is_overset(), "repeat_footer={repeat_footer}: body+footer taller than frame must overset");
|
||||
assert!(
|
||||
composed.frames[0].tables.is_empty(),
|
||||
"repeat_footer={repeat_footer}: must not emit rows past the frame bottom: {:?}",
|
||||
composed.frames[0].tables.first().map(|t| t.rect)
|
||||
);
|
||||
}
|
||||
|
||||
// Multiple body rows with repeating footer: first body row fits alone, but adding the
|
||||
// repeated footer exceeds the frame.
|
||||
let mut table = Table::new(78, 2, 1, 0, 1, 100.0);
|
||||
table.options.repeat_footer = true;
|
||||
table.rows[0].mode = RowHeightMode::Exactly;
|
||||
table.rows[0].height = 70.0;
|
||||
table.rows[1].mode = RowHeightMode::Exactly;
|
||||
table.rows[1].height = 70.0;
|
||||
table.rows[2].mode = RowHeightMode::Exactly;
|
||||
table.rows[2].height = 40.0;
|
||||
let composed = compose_table(table, 100.0);
|
||||
assert!(composed.is_overset());
|
||||
assert!(
|
||||
composed.frames[0].tables.is_empty(),
|
||||
"repeating footer must not overflow the frame: {:?}",
|
||||
composed.frames[0].tables.first().map(|t| t.rect)
|
||||
);
|
||||
|
||||
// Threaded frames: when frame 0 is too short for body + footer, the table flows to frame 1.
|
||||
let mut doc = Document::new(&NewDocument::default());
|
||||
let layer = doc.default_layer();
|
||||
let (f1, sid) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 200.0, 100.0), layer, "", ParaFormat::default()).unwrap();
|
||||
let (f2, _) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 150.0, 200.0, 350.0), layer, "", ParaFormat::default()).unwrap();
|
||||
doc.thread(f1, f2).unwrap();
|
||||
let mut table = Table::new(79, 1, 1, 0, 1, 100.0);
|
||||
table.rows[0].mode = RowHeightMode::Exactly;
|
||||
table.rows[0].height = 70.0;
|
||||
table.rows[1].mode = RowHeightMode::Exactly;
|
||||
table.rows[1].height = 40.0;
|
||||
doc.story_mut(sid).unwrap().insert_table(0, table);
|
||||
let composed = crate::compose_story(&doc, sid, &ComposeOptions::default());
|
||||
assert!(!composed.is_overset());
|
||||
assert!(composed.frames[0].tables.is_empty());
|
||||
assert_eq!(composed.frames[1].tables.len(), 1);
|
||||
assert!(composed.frames[1].tables[0].rect.y1 <= 350.0 + 0.01);
|
||||
|
||||
// Non-repeating footer: frame 0 takes a body row without reserving footer space, and
|
||||
// frame 1 takes the final body row plus the footer.
|
||||
let mut doc = Document::new(&NewDocument::default());
|
||||
let layer = doc.default_layer();
|
||||
let (f1, sid) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 200.0, 100.0), layer, "", ParaFormat::default()).unwrap();
|
||||
let (f2, _) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 150.0, 200.0, 250.0), layer, "", ParaFormat::default()).unwrap();
|
||||
doc.thread(f1, f2).unwrap();
|
||||
let mut table = Table::new(80, 2, 1, 0, 1, 100.0);
|
||||
table.options.repeat_footer = false;
|
||||
table.rows[0].mode = RowHeightMode::Exactly;
|
||||
table.rows[0].height = 70.0;
|
||||
table.rows[1].mode = RowHeightMode::Exactly;
|
||||
table.rows[1].height = 20.0;
|
||||
table.rows[2].mode = RowHeightMode::Exactly;
|
||||
table.rows[2].height = 30.0;
|
||||
doc.story_mut(sid).unwrap().insert_table(0, table);
|
||||
let composed = crate::compose_story(&doc, sid, &ComposeOptions::default());
|
||||
assert!(!composed.is_overset());
|
||||
assert_eq!(composed.frames[0].tables.len(), 1);
|
||||
assert!(composed.frames[0].tables[0].rect.y1 <= 100.0 + 0.01);
|
||||
assert!(composed.frames[0].tables[0].cell(2, 0).is_none());
|
||||
assert_eq!(composed.frames[1].tables.len(), 1);
|
||||
assert!(composed.frames[1].tables[0].rect.y1 <= 250.0 + 0.01);
|
||||
assert!(composed.frames[1].tables[0].cell(1, 0).is_some());
|
||||
assert!(composed.frames[1].tables[0].cell(2, 0).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_and_footer_only_table_never_overflows_the_frame() {
|
||||
let mut table = Table::new(81, 2, 1, 0, 0, 100.0);
|
||||
table.rows[0].kind = designcraft_doc::RowKind::Header;
|
||||
table.rows[0].mode = RowHeightMode::Exactly;
|
||||
table.rows[0].height = 70.0;
|
||||
table.rows[1].kind = designcraft_doc::RowKind::Footer;
|
||||
table.rows[1].mode = RowHeightMode::Exactly;
|
||||
table.rows[1].height = 50.0;
|
||||
|
||||
let composed = compose_table(table.clone(), 100.0);
|
||||
assert!(composed.is_overset(), "header+footer table taller than frame must overset");
|
||||
assert!(
|
||||
composed.frames[0].tables.is_empty(),
|
||||
"must not emit header/footer rows past the frame bottom: {:?}",
|
||||
composed.frames[0].tables.first().map(|t| t.rect)
|
||||
);
|
||||
|
||||
let mut doc = Document::new(&NewDocument::default());
|
||||
let layer = doc.default_layer();
|
||||
let (f1, sid) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 200.0, 100.0), layer, "", ParaFormat::default()).unwrap();
|
||||
let (f2, _) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 150.0, 200.0, 350.0), layer, "", ParaFormat::default()).unwrap();
|
||||
doc.thread(f1, f2).unwrap();
|
||||
doc.story_mut(sid).unwrap().insert_table(0, table);
|
||||
let composed = crate::compose_story(&doc, sid, &ComposeOptions::default());
|
||||
assert!(!composed.is_overset());
|
||||
assert!(composed.frames[0].tables.is_empty());
|
||||
assert_eq!(composed.frames[1].tables.len(), 1);
|
||||
assert!(composed.frames[1].tables[0].rect.y1 <= 350.0 + 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overset_exact_cell_hides_overflowing_cell_footnotes() {
|
||||
let mut cell = text_cell("Reference.", 4.0);
|
||||
cell.text.insert_note(5, "Cell footnote that does not fit.", ParaFormat::default());
|
||||
let full = measure(&cell, 92.0);
|
||||
assert_eq!(full.text.frames[0].notes.len(), 1);
|
||||
let mut table = single_table(cell);
|
||||
table.rows[0].mode = RowHeightMode::Exactly;
|
||||
table.rows[0].height = 24.0;
|
||||
let composed = compose_table(table, 200.0);
|
||||
let placed = composed.frames[0].tables[0].cell(0, 0).unwrap();
|
||||
assert!(placed.overset);
|
||||
assert!(placed.text.frames[0].notes.is_empty(), "overset cell footnote must not extend below the cell");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -2434,6 +2434,20 @@ fn table_rows_fit_their_content() {
|
||||
assert!(tf.strokes.len() >= 4 * 3 + 4);
|
||||
}
|
||||
|
||||
/// A table starts Space Before below the previous line's baseline, as in InDesign (not below its
|
||||
/// descenders).
|
||||
#[test]
|
||||
fn table_starts_space_before_below_the_previous_baseline() {
|
||||
let mut t = designcraft_doc::Table::new(77, 2, 2, 0, 0, 100.0);
|
||||
t.options.space_before = 4.0;
|
||||
let (d, sid, _) = table_doc(Rect::new(0.0, 0.0, 300.0, 600.0), t);
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
let f = &cs.frames[0];
|
||||
let above = f.lines.iter().filter(|l| l.baseline < f.tables[0].rect.y0).map(|l| l.baseline).fold(f64::NEG_INFINITY, f64::max);
|
||||
assert!(above.is_finite(), "a line above the table");
|
||||
assert!((f.tables[0].rect.y0 - (above + 4.0)).abs() < 1e-6, "{} vs {}", f.tables[0].rect.y0, above);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_columns_scale_to_the_text_column() {
|
||||
let (d, sid, _) = table_doc(Rect::new(0.0, 0.0, 200.0, 1000.0), filled(2, 4, 0, 600.0));
|
||||
@@ -3702,6 +3716,110 @@ fn right_to_left_runs_are_ordered_visually() {
|
||||
assert!(g.windows(2).all(|w| w[0].cluster <= w[1].cluster), "{:?}", g.iter().map(|g| g.cluster).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
/// #2884: tracking is space after the character in reading order. Right to left that is at its
|
||||
/// left, between it and the character read after it, mirroring left to right.
|
||||
#[test]
|
||||
fn tracking_in_right_to_left_text_follows_the_character_in_reading_order() {
|
||||
use designcraft_doc::TextDirection;
|
||||
let lines = |text: &str, direction: TextDirection, align: Align, tracked: std::ops::Range<usize>| {
|
||||
let para = ParaAttrs { direction: Some(direction), align: Some(align), ..Default::default() };
|
||||
let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 500.0, 200.0), para);
|
||||
d.story_mut(sid).unwrap().format_chars(tracked, |f| f.over.tracking = Some(1000.0));
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
all_lines(&cs)[0].clone()
|
||||
};
|
||||
let x_of = |l: &Line, byte: usize| l.glyphs.iter().find(|g| g.byte == byte && g.len > 0).map(|g| g.x).unwrap();
|
||||
let width = |l: &Line| l.glyphs.iter().map(|g| g.adv).sum::<f64>();
|
||||
// Alef, bet, gimel, dalet, he (two bytes each); tracking on bet.
|
||||
let text = "\u{5D0}\u{5D1}\u{5D2}\u{5D3}\u{5D4}";
|
||||
let bytes = [0, 2, 4, 6, 8];
|
||||
for align in [Align::Right, Align::Left] {
|
||||
let plain = lines(text, TextDirection::RightToLeft, align, 0..0);
|
||||
let tracked = lines(text, TextDirection::RightToLeft, align, 2..4);
|
||||
// Tracking 1000 is one em: what it adds to the line.
|
||||
let em = width(&tracked) - width(&plain);
|
||||
assert!(em > 1.0, "{align:?}: the tracking widens the line by {em}");
|
||||
// The space opens between bet and gimel (read after it); every other pair keeps its gap.
|
||||
for w in bytes.windows(2) {
|
||||
let gap = |l: &Line| x_of(l, w[0]) - x_of(l, w[1]);
|
||||
let want = if w[0] == 2 { gap(&plain) + em } else { gap(&plain) };
|
||||
assert!((gap(&tracked) - want).abs() < 0.01, "{align:?}: bytes {w:?} are {} apart, not {want}", gap(&tracked));
|
||||
}
|
||||
// Advances stay end to end on the line, so carets, selections and rules have no gap.
|
||||
let mut drawn: Vec<&PlacedGlyph> = tracked.glyphs.iter().filter(|g| g.len > 0).collect();
|
||||
drawn.sort_by(|a, b| a.x.total_cmp(&b.x));
|
||||
for w in drawn.windows(2) {
|
||||
assert!((w[0].x + w[0].adv - w[1].x).abs() < 0.01, "{align:?}: advances of bytes {} and {} don't meet", w[0].byte, w[1].byte);
|
||||
}
|
||||
// The caret after bet is at bet's left edge, the one before it at its right edge.
|
||||
assert!((crate::caret_x(&tracked, 4) - x_of(&tracked, 2)).abs() < 0.01, "{align:?}: caret after bet");
|
||||
assert!((crate::caret_x(&tracked, 2) - x_of(&tracked, 0)).abs() < 0.01, "{align:?}: caret before bet");
|
||||
}
|
||||
// Left to right, the same: the space opens between b and c.
|
||||
let plain = lines("abcde", TextDirection::LeftToRight, Align::Left, 0..0);
|
||||
let tracked = lines("abcde", TextDirection::LeftToRight, Align::Left, 1..2);
|
||||
let em = width(&tracked) - width(&plain);
|
||||
for (a, b) in [(0, 1), (1, 2), (2, 3), (3, 4)] {
|
||||
let gap = |l: &Line| x_of(l, b) - x_of(l, a);
|
||||
let want = if a == 1 { gap(&plain) + em } else { gap(&plain) };
|
||||
assert!((gap(&tracked) - want).abs() < 0.01, "left to right: bytes {a}, {b}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #2884 review: a justified line whose glyphs are scaled moves the tracking as scaled, so every
|
||||
/// advance keeps the glyph's own share; and a right-to-left drop cap puts a letter's tracking at
|
||||
/// its left, as the line does.
|
||||
#[test]
|
||||
fn right_to_left_tracking_follows_glyph_scaling_and_drop_caps() {
|
||||
use designcraft_doc::TextDirection;
|
||||
let rtl = |align: Align| ParaAttrs { direction: Some(TextDirection::RightToLeft), align: Some(align), ..Default::default() };
|
||||
let text = "\u{5D0}\u{5D1}\u{5D2}\u{5D3}\u{5D4}";
|
||||
// Two words, then a third the measure leaves for the next line.
|
||||
let words = format!("{text} \u{5D5}\u{5D6} {text}");
|
||||
let line = |para: ParaAttrs, width: f64, tracked: std::ops::Range<usize>| {
|
||||
let (mut d, sid, _) = doc_with(&words, Rect::new(0.0, 0.0, width, 200.0), para);
|
||||
d.story_mut(sid).unwrap().format_chars(tracked, |f| f.over.tracking = Some(1000.0));
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
all_lines(&cs)[0].clone()
|
||||
};
|
||||
let glyph = |l: &Line, byte: usize| l.glyphs.iter().find(|g| g.byte == byte && g.len > 0).cloned().unwrap();
|
||||
// The first two words on a line of their own, justified by scaling their glyphs about a third
|
||||
// (the word space is fixed).
|
||||
let plain = line(rtl(Align::Right), 500.0, 2..4);
|
||||
let two: f64 = plain.glyphs.iter().filter(|g| g.byte < 15).map(|g| g.adv).sum();
|
||||
let scaled = ParaAttrs {
|
||||
glyph_scale_min: Some(1.0),
|
||||
glyph_scale_max: Some(2.0),
|
||||
word_space_max: Some(1.0),
|
||||
word_space_min: Some(1.0),
|
||||
..rtl(Align::RightJustified)
|
||||
};
|
||||
let just = line(scaled, two * 1.3, 2..4);
|
||||
assert!(just.range.end <= 16, "the first two words are a line of their own: {:?}", just.range);
|
||||
for byte in [0, 2, 4, 6, 8, 11, 13] {
|
||||
let (p, j) = (glyph(&plain, byte), glyph(&just, byte));
|
||||
let k = j.sx / p.sx;
|
||||
assert!(k > 1.05, "byte {byte}: the glyph is scaled by {k}");
|
||||
assert!((j.adv - p.adv * k).abs() < 0.01, "byte {byte}: advance {} is not {} scaled by {k}", j.adv, p.adv);
|
||||
}
|
||||
// A two-letter drop cap with tracking on its first letter (alef): the space opens between alef
|
||||
// and bet, read after it, and their advances still meet.
|
||||
let cap = |tracked: std::ops::Range<usize>| {
|
||||
let para = ParaAttrs { drop_cap_lines: Some(2), drop_cap_chars: Some(2), ..rtl(Align::Right) };
|
||||
let (mut d, sid, _) = doc_with(&format!("{text} {}", "\u{5D5}".repeat(200)), Rect::new(0.0, 0.0, 300.0, 400.0), para);
|
||||
d.story_mut(sid).unwrap().format_chars(tracked, |f| f.over.tracking = Some(1000.0));
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
all_lines(&cs)[0].clone()
|
||||
};
|
||||
let (untracked, tracked) = (cap(0..0), cap(0..2));
|
||||
let (a0, b0, a1, b1) = (glyph(&untracked, 0), glyph(&untracked, 2), glyph(&tracked, 0), glyph(&tracked, 2));
|
||||
assert!(a1.x > b1.x, "alef is right of bet");
|
||||
let em = (a1.x - b1.x) - (a0.x - b0.x);
|
||||
assert!(em > 1.0, "the tracking opens a space between alef and bet: {em}");
|
||||
assert!((b1.x + b1.adv - a1.x).abs() < 0.01, "bet's advance meets alef: {} vs {}", b1.x + b1.adv, a1.x);
|
||||
assert!((a1.adv - a0.adv).abs() < 0.01, "alef's advance is its own: {} vs {}", a1.adv, a0.adv);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bidi_matches_the_reference_order() {
|
||||
use unicode_bidi::{BidiInfo, Level};
|
||||
@@ -4475,6 +4593,33 @@ fn inline_objects_still_clear_the_bottom_edge() {
|
||||
assert_eq!(cs.line_count(), 0);
|
||||
}
|
||||
|
||||
/// An inline object is bidi-neutral, as U+FFFC is: in a right-to-left paragraph it keeps its place
|
||||
/// in the reading order between Latin text and the Arabic after it. Its private-use mark is a
|
||||
/// strong left-to-right character, which joined it to the Latin run before it, so it was drawn on
|
||||
/// the far side of that run.
|
||||
#[test]
|
||||
fn an_inline_object_keeps_its_place_in_right_to_left_text() {
|
||||
let text = "ab \u{0628}";
|
||||
let para = ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), ..Default::default() };
|
||||
let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), para);
|
||||
d.settings.glyph_fallback = true;
|
||||
let it = designcraft_doc::Item::new(
|
||||
ItemId(d.alloc()),
|
||||
d.default_layer(),
|
||||
designcraft_doc::Shape::Rectangle,
|
||||
designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 6.0, 6.0)),
|
||||
);
|
||||
let at = 3;
|
||||
d.story_mut(sid).unwrap().insert_object(at, designcraft_doc::AnchoredObject::new(it, designcraft_doc::AnchorPosition::Inline { y_offset: 0.0 }));
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
let line = &cs.frames[0].lines[0];
|
||||
let x = |byte: usize| line.glyphs.iter().find(|g| g.byte == byte).map(|g| g.x).unwrap();
|
||||
let beh = text.find('\u{0628}').unwrap() + designcraft_doc::OBJECT_MARK.len_utf8();
|
||||
let (latin, object, arabic) = (x(0), x(at), x(beh));
|
||||
// Read right to left: the Latin text, the object, then the Arabic letter.
|
||||
assert!(arabic < object && object < latin, "arabic {arabic}, object {object}, latin {latin}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_anchors_do_not_change_bottom_baseline_fitting() {
|
||||
let (mut d, sid, _) = baseline_fit_doc("Text", 10.0);
|
||||
@@ -5703,6 +5848,203 @@ fn empty_paragraph_uses_its_own_mark_not_the_previous_one() {
|
||||
assert!((lines[1].baseline - lines[0].baseline - 8.0).abs() < 1e-6, "{} {}", lines[0].baseline, lines[1].baseline);
|
||||
}
|
||||
|
||||
/// Under a leading model an empty paragraph keeps the leading like any other line: its line
|
||||
/// measures from its paragraph mark's em box, as in InDesign. It used to measure from its
|
||||
/// baseline, so the empty line moved by the em box's offset and the line after it back by as
|
||||
/// much. The other composers set lines baseline to baseline whatever the model.
|
||||
#[test]
|
||||
fn an_empty_paragraph_keeps_the_leading_under_a_leading_model() {
|
||||
use designcraft_doc::cjk::LeadingModel;
|
||||
let text = "Aaa\n\nBbb\nCcc";
|
||||
for model in [LeadingModel::AkiBelow, LeadingModel::AkiAbove, LeadingModel::Center] {
|
||||
for para in [japanese(), ParaAttrs::default()] {
|
||||
let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 300.0), para);
|
||||
d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {
|
||||
f.over.leading = Some(designcraft_doc::Leading::Points(16.0));
|
||||
f.over.leading_model = Some(model);
|
||||
});
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
let base: Vec<f64> = all_lines(&cs).iter().map(|l| l.baseline).collect();
|
||||
assert_eq!(base.len(), 4, "{model:?}");
|
||||
for w in base.windows(2) {
|
||||
assert!((w[1] - w[0] - 16.0).abs() < 1e-6, "{model:?}: {base:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Baselines of `text` set in a Hangul test font under the Japanese composer with Aki Below and
|
||||
/// 20 pt leading.
|
||||
fn hangul_lines(text: &str) -> Vec<f64> {
|
||||
let chars: Vec<char> = "가나".chars().collect();
|
||||
let font = designcraft_fonts::testing::font_with("DC Test Korean Lines", &chars).unwrap();
|
||||
designcraft_fonts::FontDb::global().add_font(font);
|
||||
let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 500.0), japanese());
|
||||
d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {
|
||||
f.over.font_family = Some("DC Test Korean Lines".into());
|
||||
f.over.language = Some("Korean".into());
|
||||
f.over.leading = Some(designcraft_doc::Leading::Points(20.0));
|
||||
f.over.leading_model = Some(designcraft_doc::cjk::LeadingModel::AkiBelow);
|
||||
});
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
all_lines(&cs).iter().map(|l| l.baseline).collect()
|
||||
}
|
||||
|
||||
/// Hangul text under Aki Below: an empty paragraph between two lines keeps the leading, so the
|
||||
/// baselines match those of three lines of text. The empty paragraph rose and the line after it
|
||||
/// dropped back by as much.
|
||||
#[test]
|
||||
fn an_empty_hangul_paragraph_keeps_the_leading_under_aki_below() {
|
||||
let (text, empty) = (hangul_lines("가나\n가나\n가나"), hangul_lines("가나\n\n가나"));
|
||||
assert_eq!(empty.len(), 3);
|
||||
for (a, b) in text.iter().zip(&empty) {
|
||||
assert!((a - b).abs() < 1e-6, "{text:?} vs {empty:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The empty line a trailing forced line break leaves measures from its paragraph mark's em box,
|
||||
/// like an empty paragraph, so it keeps the leading too. It measured from the paragraph style's
|
||||
/// characters: text formatted with a leading model the style doesn't have moved that line by the
|
||||
/// em box's offset from the baseline, and the line after it back by as much.
|
||||
#[test]
|
||||
fn a_trailing_forced_line_breaks_empty_line_keeps_the_leading_under_a_leading_model() {
|
||||
use designcraft_doc::cjk::LeadingModel;
|
||||
use designcraft_doc::story::FORCED_LINE_BREAK;
|
||||
let text = format!("Aaa{FORCED_LINE_BREAK}\nBbb\nCcc");
|
||||
for model in [LeadingModel::AkiBelow, LeadingModel::AkiAbove, LeadingModel::Center] {
|
||||
let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 300.0), japanese());
|
||||
d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {
|
||||
f.over.leading = Some(designcraft_doc::Leading::Points(16.0));
|
||||
f.over.leading_model = Some(model);
|
||||
});
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
let base: Vec<f64> = all_lines(&cs).iter().map(|l| l.baseline).collect();
|
||||
assert_eq!(base.len(), 4, "{model:?}");
|
||||
for w in base.windows(2) {
|
||||
assert!((w[1] - w[0] - 16.0).abs() < 1e-6, "{model:?}: {base:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An empty line whose paragraph mark is larger than the text around it takes its auto leading
|
||||
/// from the mark: an empty paragraph's line, and the line a trailing forced line break leaves.
|
||||
/// The line after it goes back to the text's own leading.
|
||||
#[test]
|
||||
fn an_empty_line_takes_its_auto_leading_from_a_larger_paragraph_mark() {
|
||||
use designcraft_doc::story::FORCED_LINE_BREAK;
|
||||
for text in ["Aaa\n\nBbb".to_string(), format!("Aaa{FORCED_LINE_BREAK}\nBbb")] {
|
||||
let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default());
|
||||
let mark = text.find("\nB").unwrap();
|
||||
let story = d.story_mut(sid).unwrap();
|
||||
story.format_chars(0..text.len(), |f| f.over.size = Some(10.0));
|
||||
story.format_chars(mark..mark + 1, |f| f.over.size = Some(20.0));
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
let base: Vec<f64> = all_lines(&cs).iter().map(|l| l.baseline).collect();
|
||||
assert_eq!(base.len(), 3, "{text:?}: {base:?}");
|
||||
assert!((base[1] - base[0] - 24.0).abs() < 1e-6, "{text:?}: {base:?}");
|
||||
assert!((base[2] - base[1] - 12.0).abs() < 1e-6, "{text:?}: {base:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph that holds only a drop cap is left with an empty line once the drop cap is split
|
||||
/// off: that line takes its auto leading from the paragraph mark, as an empty paragraph's does. It
|
||||
/// read the format of the paragraph's first character, the drop cap.
|
||||
#[test]
|
||||
fn a_drop_cap_only_paragraph_takes_its_leading_from_the_mark() {
|
||||
let text = "Aaa\nW\nBbb";
|
||||
let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default());
|
||||
let cap = text.find('W').unwrap();
|
||||
let story = d.story_mut(sid).unwrap();
|
||||
story.format_chars(0..text.len(), |f| f.over.size = Some(10.0));
|
||||
story.format_chars(cap..cap + 1, |f| f.over.size = Some(40.0));
|
||||
story.format_chars(cap + 1..cap + 2, |f| f.over.size = Some(20.0));
|
||||
story.paras[1].para.drop_cap_lines = Some(2);
|
||||
story.paras[1].para.drop_cap_chars = Some(1);
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
let base: Vec<f64> = all_lines(&cs).iter().map(|l| l.baseline).collect();
|
||||
assert!(base.len() >= 2, "{base:?}");
|
||||
// The 20 pt mark's auto leading (24 pt), not the 40 pt drop cap's (48 pt).
|
||||
assert!((base[1] - base[0] - 24.0).abs() < 1e-6, "{base:?}");
|
||||
}
|
||||
|
||||
/// Under a leading model the lines of `text` (all formatted by `format`, with a 16 pt leading)
|
||||
/// are 16 pt apart, empty lines included.
|
||||
fn assert_leading_kept(text: &str, mut d: Document, sid: StoryId, format: impl Fn(&mut designcraft_doc::CharFormat)) {
|
||||
use designcraft_doc::cjk::LeadingModel;
|
||||
for model in [LeadingModel::AkiBelow, LeadingModel::AkiAbove, LeadingModel::Center] {
|
||||
d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {
|
||||
format(f);
|
||||
f.over.leading = Some(designcraft_doc::Leading::Points(16.0));
|
||||
f.over.leading_model = Some(model);
|
||||
});
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
let base: Vec<f64> = all_lines(&cs).iter().map(|l| l.baseline).collect();
|
||||
assert_eq!(base.len(), 4, "{model:?}");
|
||||
for w in base.windows(2) {
|
||||
assert!((w[1] - w[0] - 16.0).abs() < 1e-6, "{model:?}: {base:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A superscript or subscript paragraph mark is shaped at the Advanced Type size, like the text
|
||||
/// around it: an empty line measures from that em box, so it keeps the leading. It measured from
|
||||
/// the em box at the full size, so it moved against the superscript lines beside it.
|
||||
#[test]
|
||||
fn an_empty_superscript_paragraph_keeps_the_leading_under_a_leading_model() {
|
||||
use designcraft_doc::Position;
|
||||
let text = "Aaa\n\nBbb\nCcc";
|
||||
for position in [Position::Superscript, Position::Subscript] {
|
||||
let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 300.0), japanese());
|
||||
assert_leading_kept(text, d, sid, |f| f.over.position = Some(position));
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph mark in a composite font is measured with the composite font's entry (its font,
|
||||
/// relative size and vertical scale), as shaping sets the text around it, so an empty line keeps
|
||||
/// the leading. It measured the composite font's name, a substitute face, at the plain size.
|
||||
#[test]
|
||||
fn an_empty_paragraph_in_a_composite_font_keeps_the_leading_under_a_leading_model() {
|
||||
use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry};
|
||||
let text = "Aaa\n\nBbb\nCcc";
|
||||
let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 300.0), japanese());
|
||||
std::sync::Arc::make_mut(&mut d.styles).composite_fonts.push(CompositeFont {
|
||||
name: "Scaled".into(),
|
||||
entries: vec![CompositeFontEntry {
|
||||
family: designcraft_fonts::DEFAULT_FAMILY.into(),
|
||||
relative_size: 1.5,
|
||||
vertical_scale: 1.2,
|
||||
..Default::default()
|
||||
}],
|
||||
});
|
||||
assert_leading_kept(text, d, sid, |f| f.over.font_family = Some("CompositeFont/Scaled".into()));
|
||||
}
|
||||
|
||||
/// In a vertical frame an empty paragraph measures from the upright em box (the font's
|
||||
/// ideographic em box), as the upright characters around it do. It measured from the font's
|
||||
/// ascender and descender, so it moved against the lines beside it.
|
||||
#[test]
|
||||
fn an_empty_paragraph_keeps_the_leading_under_a_leading_model_in_vertical_text() {
|
||||
use designcraft_doc::cjk::LeadingModel;
|
||||
let family = vertical_test_font();
|
||||
let text = "一\n\n二\n日";
|
||||
for model in [LeadingModel::AkiBelow, LeadingModel::AkiAbove, LeadingModel::Center] {
|
||||
let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 300.0), japanese());
|
||||
d.story_mut(sid).unwrap().vertical = true;
|
||||
d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {
|
||||
f.over.font_family = Some(family.into());
|
||||
f.over.leading = Some(designcraft_doc::Leading::Points(16.0));
|
||||
f.over.leading_model = Some(model);
|
||||
});
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
assert!(cs.frames[0].vertical);
|
||||
let base: Vec<f64> = all_lines(&cs).iter().map(|l| l.baseline).collect();
|
||||
assert_eq!(base.len(), 4, "{model:?}");
|
||||
for w in base.windows(2) {
|
||||
assert!((w[1] - w[0] - 16.0).abs() < 1e-6, "{model:?}: {base:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn german_2006_text_gets_german_hyphenation() {
|
||||
let text = "Silbentrennung Fußgänger Bäcker Fenster Donaudampfschifffahrt Silbentrennung";
|
||||
@@ -5811,6 +6153,85 @@ fn croatian_text_gets_croatian_hyphenation() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Hindi and Malayalam text set in its language hyphenates between syllables, never inside a
|
||||
/// conjunct: each hyphenated line ends in a prefix the patterns allow, with no hyphen drawn
|
||||
/// after it (Indian scripts split words at a line end without one).
|
||||
#[test]
|
||||
fn indian_language_text_hyphenates_between_syllables() {
|
||||
for (language, word, prefixes) in [("Hindi", "विद्यार्थी", &["वि", "विद्या"][..]), ("Malayalam", "വിദ്യാർത്ഥി", &["വി", "വിദ്യാർ"][..])]
|
||||
{
|
||||
let text = [word; 8].join(" ");
|
||||
let (mut d, sid, _) = doc_with(&text, Rect::new(36.0, 36.0, 76.0, 700.0), ParaAttrs::default());
|
||||
let st = d.story_mut(sid).unwrap();
|
||||
let n = st.len();
|
||||
st.format_chars(0..n, |f| f.over.language = Some(language.into()));
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
// The part of the word before each hyphenated line end: a line can start inside the word
|
||||
// (वि / द्या / र्थी), so it is read from the word's start, not the line's.
|
||||
let breaks: Vec<&str> = all_lines(&cs)
|
||||
.into_iter()
|
||||
.filter(|l| l.hyphenated)
|
||||
.map(|l| {
|
||||
let end = text[..l.range.end].trim_end().len();
|
||||
&text[text[..end].rfind(' ').map_or(0, |s| s + 1)..end]
|
||||
})
|
||||
.collect();
|
||||
assert!(!breaks.is_empty(), "{language} text is hyphenated");
|
||||
for b in breaks {
|
||||
assert!(prefixes.contains(&b), "{language}: {b:?} is a syllable prefix of {word}");
|
||||
}
|
||||
for l in all_lines(&cs).into_iter().filter(|l| l.hyphenated) {
|
||||
assert!(l.glyphs.iter().all(|g| g.rendered_char != '-'), "{language}: no hyphen drawn on {:?}", &text[l.range.clone()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// With hyphenation across columns off, no column of Hindi text ends in a hyphenated break. The
|
||||
/// break goes after a syllable's last glyph, which has no bytes of its own (the vowel sign of वि
|
||||
/// is drawn before the consonant), so the rejected break is recorded at its cluster's end.
|
||||
#[test]
|
||||
fn hyphenate_across_column_off_holds_for_indian_scripts() {
|
||||
let text = ["विद्यार्थी विश्वविद्यालय अंतरराष्ट्रीय प्रधानमंत्री स्वतंत्रता"; 6].join(" ");
|
||||
let ends = |across: bool, composer: designcraft_doc::Composer| {
|
||||
let mut ends = 0;
|
||||
for h in (20..240).step_by(3) {
|
||||
let para = ParaAttrs {
|
||||
align: Some(Align::Left),
|
||||
hyph_weight: Some(0.0),
|
||||
hyph_across_column: Some(across),
|
||||
composer: Some(composer),
|
||||
..Default::default()
|
||||
};
|
||||
let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 120.0, h as f64), para);
|
||||
d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;
|
||||
let st = d.story_mut(sid).unwrap();
|
||||
let n = st.len();
|
||||
st.format_chars(0..n, |f| f.over.language = Some("Hindi".into()));
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
let col0: Vec<&Line> = all_lines(&cs).into_iter().filter(|l| l.column == 0).collect();
|
||||
ends += usize::from(col0.last().is_some_and(|l| l.hyphenated));
|
||||
}
|
||||
ends
|
||||
};
|
||||
for c in [designcraft_doc::Composer::Paragraph, designcraft_doc::Composer::SingleLine] {
|
||||
assert!(ends(true, c) > 0, "{c:?}: Hindi columns end in hyphenated breaks with it on");
|
||||
assert_eq!(ends(false, c), 0, "{c:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Latin text keeps its hyphen at a hyphenated line end.
|
||||
#[test]
|
||||
fn latin_text_still_draws_its_hyphen() {
|
||||
let text = "internationalization internationalization internationalization";
|
||||
let (d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 106.0, 700.0), ParaAttrs::default());
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
let hyphenated: Vec<&Line> = all_lines(&cs).into_iter().filter(|l| l.hyphenated).collect();
|
||||
assert!(!hyphenated.is_empty(), "English text is hyphenated");
|
||||
for l in hyphenated {
|
||||
assert_eq!(l.glyphs.iter().rev().find(|g| g.visible).map(|g| g.rendered_char), Some('-'), "{:?}", &text[l.range.clone()]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cjk_aki_adds_space_without_scaling_outlines() {
|
||||
let (mut d, sid, _) = doc_with("AB", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());
|
||||
@@ -7596,6 +8017,42 @@ fn mojikumi_does_not_restore_fullwidth_blanks_to_narrow_tracked_punctuation() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Taking a closing bracket into a line (push-in) closes up the middle dot's quarter ems first,
|
||||
/// then the comma's half em, and never the full stop's (JLREQ 3.8.3).
|
||||
#[test]
|
||||
fn mojikumi_push_in_reduces_middle_dots_first_and_never_a_full_stop() {
|
||||
let family = "Mojikumi Reduction";
|
||||
let font = designcraft_fonts::testing::font_mapping(family, &[('漢', '‰'), ('・', '‰'), ('、', '‰'), ('。', '‰'), ('」', '‰')]).unwrap();
|
||||
designcraft_fonts::FontDb::global().add_font(font);
|
||||
let first = "漢・漢、漢。漢漢」";
|
||||
let para = ParaAttrs { mojikumi: Some("LineEndAllOneHalfEmEnum".into()), kinsoku_type: Some("KinsokuPushInFirst".into()), ..Default::default() };
|
||||
let compose = |text: &str, width: f64| {
|
||||
let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, width, 300.0), para.clone());
|
||||
d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.font_family = Some(family.into()));
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
let line = all_lines(&cs)[0].clone();
|
||||
let em = line.glyphs[0].face.units_per_em() * line.glyphs[0].sx;
|
||||
(line, em)
|
||||
};
|
||||
let (natural, em) = compose(first, 500.0);
|
||||
let width = natural.end_x - natural.x0;
|
||||
let quarter = em / 4.0;
|
||||
// How far each glyph of the first line moved, for a line `less` points short.
|
||||
let moved = |less: f64| {
|
||||
let (line, _) = compose(&format!("{first}漢漢漢"), width - less);
|
||||
assert_eq!(line.range.end, first.len(), "the bracket is taken in");
|
||||
line.glyphs.iter().zip(&natural.glyphs).map(|(a, b)| a.x - b.x).collect::<Vec<f64>>()
|
||||
};
|
||||
let near = |a: f64, b: f64| (a - b).abs() < 0.01;
|
||||
// Less than the middle dot's two quarter ems: all of it comes from around the dot.
|
||||
let d = moved(quarter);
|
||||
assert!(near(d[2], -quarter) && d[2..].iter().all(|&x| near(x, -quarter)), "{d:?}");
|
||||
// More: the dot's half em, then the comma's; the full stop's half em stays.
|
||||
let d = moved(2.0 * quarter + 3.0);
|
||||
assert!(near(d[2], -2.0 * quarter) && near(d[4], -2.0 * quarter - 3.0), "{d:?}");
|
||||
assert!(d[4..].iter().all(|&x| near(x, -2.0 * quarter - 3.0)), "{d:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mojikumi_one_em_line_end_set_sets_closing_punctuation_full_width_at_line_end() {
|
||||
let family = "Mojikumi Full Stop";
|
||||
@@ -8125,6 +8582,74 @@ fn a_word_longer_than_the_line_breaks_at_the_column_edge() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_web_address_breaks_after_a_dot_between_letters_but_a_decimal_stays_whole() {
|
||||
use designcraft_doc::Composer;
|
||||
let width = |t: &str| {
|
||||
let l = &tracked_lines(t, 1e5, ParaAttrs::default(), 0.0)[0];
|
||||
l.end_x - l.x0
|
||||
};
|
||||
let host = "visit example.org/x1";
|
||||
let measure = width("visit example.") + 1.0;
|
||||
for composer in [Composer::Paragraph, Composer::SingleLine] {
|
||||
let para = ParaAttrs { composer: Some(composer), ..Default::default() };
|
||||
let lines = tracked_lines(host, measure, para.clone(), 0.0);
|
||||
assert_eq!(&host[lines[0].range.clone()].trim_end(), &"visit example.", "{composer:?}");
|
||||
let dec = "pay 12.50 now";
|
||||
let lines = tracked_lines(dec, width("pay 12.") + 1.0, para.clone(), 0.0);
|
||||
assert!(lines.iter().all(|l| !dec[l.range.clone()].trim().ends_with('.')), "{composer:?}");
|
||||
let para = ParaAttrs { hyphenate: Some(false), ..para };
|
||||
for (text, head) in
|
||||
[("see the e.g. note", "see the e."), ("made in the U.S.A. today", "made in the U."), ("she holds a Ph.D. now", "she holds a Ph.")]
|
||||
{
|
||||
let lines = tracked_lines(text, width(head) + 1.0, para.clone(), 0.0);
|
||||
let words: Vec<_> = lines.iter().flat_map(|l| text[l.range.clone()].split_whitespace()).collect();
|
||||
assert_eq!(words, text.split_whitespace().collect::<Vec<_>>(), "{composer:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accented_abbreviations_stay_whole_in_both_composers() {
|
||||
use designcraft_doc::Composer;
|
||||
for composer in [Composer::Paragraph, Composer::SingleLine] {
|
||||
let para = ParaAttrs { composer: Some(composer), hyphenate: Some(false), ..Default::default() };
|
||||
for prefix in ["Pé", "Pe\u{301}"] {
|
||||
let head = format!("read {prefix}.");
|
||||
let wide = tracked_lines(&head, 1e5, para.clone(), 0.0);
|
||||
let width = wide[0].end_x - wide[0].x0 + 1.0;
|
||||
let text = format!("{head}Do now");
|
||||
let lines = tracked_lines(&text, width, para.clone(), 0.0);
|
||||
let words: Vec<_> = lines.iter().flat_map(|l| text[l.range.clone()].split_whitespace()).collect();
|
||||
assert_eq!(words, text.split_whitespace().collect::<Vec<_>>(), "{composer:?}: {text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dot_break_counts_source_letters_once_per_shaping_cluster() {
|
||||
// Model a ligature on either side of the dot, including a multibyte letter.
|
||||
let text = "aéb.De";
|
||||
let mut glyphs = shape_for_script_test(text);
|
||||
glyphs.retain(|g| g.len > 0 && !matches!(g.byte, 1 | 6));
|
||||
glyphs[0].len = "aé".len();
|
||||
glyphs[3].len = "De".len();
|
||||
assert!(breaker::dot_break(text, &glyphs, 2));
|
||||
glyphs[0].len = 2; // Ends inside é.
|
||||
assert!(!breaker::dot_break(text, &glyphs, 2));
|
||||
|
||||
let text = "Pe\u{301}.Do";
|
||||
let mut glyphs = shape_for_script_test(text);
|
||||
glyphs.retain(|g| g.len > 0 && g.byte != 2);
|
||||
let base = glyphs.iter().position(|g| g.byte == 1 && g.len > 0).unwrap();
|
||||
glyphs[base].len = "e\u{301}".len();
|
||||
let mut extra = glyphs[base].clone();
|
||||
extra.len = 0;
|
||||
glyphs.insert(base + 1, extra);
|
||||
let dot = glyphs.iter().position(|g| g.ch == '.').unwrap();
|
||||
assert!(!breaker::dot_break(text, &glyphs, dot));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_that_exactly_fills_the_measure_fits() {
|
||||
use designcraft_doc::Composer;
|
||||
@@ -10511,6 +11036,49 @@ fn cross_reference_text_breaks_at_its_spaces() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A font with small caps of its own keeps them (Source Sans 3 has `smcp`), and one without gets
|
||||
/// them drawn: the lowercase letters are set as capitals at 70%, while a capital already in the run
|
||||
/// keeps its size. That is the case the report hit, where All Caps worked and Small Caps did nothing.
|
||||
#[test]
|
||||
fn small_caps_come_from_the_font_or_are_drawn_when_it_has_none() {
|
||||
use designcraft_doc::Capitalization;
|
||||
let text = "ab A";
|
||||
|
||||
let composed = |family: &str, caps: Capitalization| {
|
||||
let (mut d, sid, _) = doc_with(text, Rect::new(72.0, 36.0, 372.0, 136.0), ParaAttrs::default());
|
||||
d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {
|
||||
f.over.font_family = Some(family.into());
|
||||
f.over.size = Some(20.0);
|
||||
f.over.capitalization = Some(caps);
|
||||
});
|
||||
let cs = compose_story(&d, sid, &Default::default());
|
||||
cs.frames[0].lines[0].glyphs.iter().map(|g| (g.byte, g.gid, g.adv, g.sx, g.rendered_char)).collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
// Inter ships without `smcp`; Source Sans 3 has it.
|
||||
let plain = composed("Inter", Capitalization::Normal);
|
||||
let small = composed("Inter", Capitalization::SmallCaps);
|
||||
let at = |gs: &[(usize, u32, f64, f64, char)], byte: usize| gs.iter().find(|g| g.0 == byte).cloned().unwrap();
|
||||
let (_, a_plain, _adv_plain, _, _) = at(&plain, 0);
|
||||
let (_, cap_plain, adv_cap, _, _) = at(&plain, 3);
|
||||
let (_, small_a, adv_a, sx_a, ch_a) = at(&small, 0);
|
||||
let (_, small_cap, adv_upper, sx_cap, _) = at(&small, 3);
|
||||
assert_eq!(ch_a, 'a', "the run still reads a");
|
||||
assert_eq!(small_a, cap_plain, "the a is drawn with the glyph of an A");
|
||||
assert_eq!(small_a, small_cap, "the same glyph the run's own A uses");
|
||||
assert!((adv_a / adv_cap - 0.7).abs() < 1e-6, "the small a takes 70%: {} / {}", adv_a, adv_cap);
|
||||
assert!((adv_upper - adv_cap).abs() < 1e-9, "the capital keeps its advance: {} vs {}", adv_upper, adv_cap);
|
||||
assert!((sx_a / sx_cap - 0.7).abs() < 1e-6, "and its drawing is scaled by the same 0.7");
|
||||
assert_ne!(a_plain, cap_plain, "in the plain run the two letters differ");
|
||||
|
||||
// With Source Sans 3 the font sets them: its `smcp` gives a small-capital glyph of its own,
|
||||
// not the uppercased A we would draw.
|
||||
let named = composed("Source Sans 3", Capitalization::SmallCaps);
|
||||
let (_, a_named, _, _, _) = at(&named, 0);
|
||||
assert_ne!(a_named, cap_plain, "the a takes the font's small capital, not an uppercased A");
|
||||
assert_ne!(a_named, a_plain, "and it is not the plain a either");
|
||||
}
|
||||
|
||||
/// A story numbering list `list` (continuing across stories; Upper Roman, no tab after the
|
||||
/// number) in a frame at `r` on `page`.
|
||||
fn listed_story(d: &mut Document, page: usize, r: Rect, text: &str, list: &str) -> StoryId {
|
||||
@@ -10575,6 +11143,66 @@ fn a_neighbours_numbering_moves_the_text_its_objects_wrap() {
|
||||
assert_eq!(line_layout(&cache.get(&d, b, None)), fresh);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_neighbours_file_name_variable_moves_the_text_its_objects_wrap() {
|
||||
// Regression: a variable-free story wrapped by a neighbour's anchored object kept its cached
|
||||
// lines when the document title changed, though a longer File Name pushed the object's anchor
|
||||
// onto the next line.
|
||||
let long = [LOREM; 3].join(" ");
|
||||
let mut d = Document::new(&NewDocument { pages: 1, facing_pages: false, title: "A".into(), ..Default::default() });
|
||||
let lid = d.default_layer();
|
||||
let var = designcraft_doc::vars::var_char(d.variable("File Name").unwrap()).unwrap();
|
||||
let (fa, a) =
|
||||
d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 80.0, 400.0), lid, &format!("{var} Anchor"), ParaFormat::default()).unwrap();
|
||||
let (_, b) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(320.0, 0.0, 620.0, 400.0), lid, &long, ParaFormat::default()).unwrap();
|
||||
let left = all_lines(&compose_story(&d, b, &ComposeOptions::default()))[0].x0;
|
||||
let area = d.item(fa).unwrap().text_area();
|
||||
let end = d.story(a).unwrap().len();
|
||||
anchor_box(&mut d, a, end, left - area.x0, 20.0, true, WrapMode::BoundingBox);
|
||||
let cache = Cache::new();
|
||||
let before = line_layout(&cache.get(&d, b, None));
|
||||
assert_eq!(before, line_layout(&compose_story(&d, b, &ComposeOptions::default())));
|
||||
d.title = "A Much Longer Document File Name".into();
|
||||
let fresh = line_layout(&compose_story(&d, b, &ComposeOptions::default()));
|
||||
assert_ne!(fresh, before, "the longer file name moves the wrapping object");
|
||||
assert_eq!(line_layout(&cache.get(&d, b, None)), fresh);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_cell_and_footnote_file_name_variables_update_on_rename() {
|
||||
// Regression: a story whose only File Name variable sits in a table cell or footnote kept its
|
||||
// cached composition after a title change because `has_vars` inspected only outer `story.text`.
|
||||
let glyphs = |cs: &ComposedStory| -> usize {
|
||||
cs.frames.iter().flat_map(|f| f.lines.iter()).map(|l| l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).count()).sum()
|
||||
};
|
||||
|
||||
// Table cell only.
|
||||
let (mut d, sid, _) = table_doc(Rect::new(0.0, 0.0, 400.0, 400.0), designcraft_doc::Table::new(77, 1, 1, 0, 0, 300.0));
|
||||
d.title = "Short".into();
|
||||
let var = designcraft_doc::vars::var_char(d.variable("File Name").unwrap()).unwrap().to_string();
|
||||
Arc::make_mut(d.story_mut(sid).unwrap().tables.values_mut().next().unwrap()).cell_mut(0, 0).unwrap().text.insert(0, &var);
|
||||
let cache = Cache::new();
|
||||
let before = glyphs(&cache.get(&d, sid, None).frames[0].tables[0].cells[0].text);
|
||||
d.title = "CatalogEdition".into();
|
||||
let fresh = glyphs(&compose_story(&d, sid, &ComposeOptions::default()).frames[0].tables[0].cells[0].text);
|
||||
let after = glyphs(&cache.get(&d, sid, None).frames[0].tables[0].cells[0].text);
|
||||
assert!(fresh > before, "rename lengthens the cell text: {before} -> {fresh}");
|
||||
assert_eq!(after, fresh);
|
||||
|
||||
// Footnote only.
|
||||
let (mut d, sid, _) = doc_with("Body text.", Rect::new(36.0, 36.0, 400.0, 400.0), ParaAttrs::default());
|
||||
d.title = "Short".into();
|
||||
let var = designcraft_doc::vars::var_char(d.variable("File Name").unwrap()).unwrap().to_string();
|
||||
d.story_mut(sid).unwrap().insert_note(4, &var, ParaFormat::default());
|
||||
let cache = Cache::new();
|
||||
let before = glyphs(&cache.get(&d, sid, None).frames[0].notes[0].text);
|
||||
d.title = "CatalogEdition".into();
|
||||
let fresh = glyphs(&compose_story(&d, sid, &ComposeOptions::default()).frames[0].notes[0].text);
|
||||
let after = glyphs(&cache.get(&d, sid, None).frames[0].notes[0].text);
|
||||
assert!(fresh > before, "rename lengthens the footnote text: {before} -> {fresh}");
|
||||
assert_eq!(after, fresh);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_stories_in_continuing_lists_compose_quickly() {
|
||||
// Regression: each story's cache lookup searched the whole item tree per story and per list
|
||||
|
||||
@@ -9,14 +9,31 @@ use designcraft_doc::{Document, SpreadRef, Story, StoryId};
|
||||
|
||||
use crate::ComposedStory;
|
||||
|
||||
/// Does the story contain any text variable instance?
|
||||
pub fn has_vars(st: &Story) -> bool {
|
||||
st.text.chars().any(|c| var_index(c).is_some())
|
||||
const MAX_NESTING: usize = 32;
|
||||
|
||||
fn story_any(st: &Story, depth: usize, f: &impl Fn(&Story) -> bool) -> bool {
|
||||
if f(st) {
|
||||
return true;
|
||||
}
|
||||
if depth >= MAX_NESTING {
|
||||
return false;
|
||||
}
|
||||
st.tables.values().flat_map(|t| &t.cells).any(|c| story_any(&c.text, depth + 1, f))
|
||||
|| st.notes.iter().chain(&st.endnotes).any(|n| story_any(&n.text, depth + 1, f))
|
||||
}
|
||||
|
||||
/// Does the story contain a running-header variable instance?
|
||||
/// Does the story (or any embedded table cell, footnote or endnote) contain a text variable
|
||||
/// instance?
|
||||
pub fn has_vars(st: &Story) -> bool {
|
||||
story_any(st, 0, &|s| s.text.chars().any(|c| var_index(c).is_some()))
|
||||
}
|
||||
|
||||
/// Does the story (or any embedded table cell, footnote or endnote) contain a running-header
|
||||
/// variable instance?
|
||||
pub fn has_running(doc: &Document, st: &Story) -> bool {
|
||||
st.text.chars().filter_map(var_index).any(|i| matches!(doc.text_variables.get(i).map(|v| &v.kind), Some(VarKind::RunningHeader { .. })))
|
||||
story_any(st, 0, &|s| {
|
||||
s.text.chars().filter_map(var_index).any(|i| matches!(doc.text_variables.get(i).map(|v| &v.kind), Some(VarKind::RunningHeader { .. })))
|
||||
})
|
||||
}
|
||||
|
||||
/// Absolute page showing story byte `pos` of a composed story.
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
//! Justified Arabic puts its one kashida per word at the join typography prefers, and none where
|
||||
//! every join is forbidden (#2486).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use designcraft_compose::{ComposeOptions, compose_story};
|
||||
use designcraft_doc::build::NewDocument;
|
||||
use designcraft_doc::{Align, Document, ParaAttrs, ParaFormat, SpreadRef, TextDirection};
|
||||
use designcraft_fonts::FontDb;
|
||||
use designcraft_fonts::testing::font_mapping;
|
||||
use designcraft_geom::Rect;
|
||||
|
||||
const FAMILY: &str = "DC Kashida Rules";
|
||||
|
||||
/// Installs a font that draws every Arabic letter used below as a Latin letter, and the tatweel as
|
||||
/// an underscore, so the test does not depend on the fonts of the machine.
|
||||
fn install_font() {
|
||||
let letters = "ابتثحدرزسصضعغفقكلمنهةوىي";
|
||||
let mut glyphs: Vec<(char, char)> = letters.chars().zip('a'..='z').collect();
|
||||
glyphs.extend([('\u{0640}', '_'), (' ', ' ')]);
|
||||
FontDb::global().add_font(font_mapping(FAMILY, &glyphs).unwrap());
|
||||
}
|
||||
|
||||
/// The positions (in letters) of the letters before which kashidas are drawn when `word`, repeated
|
||||
/// on justified lines of several widths, is stretched.
|
||||
fn kashida_letters(word: &str) -> BTreeSet<usize> {
|
||||
let text = vec![word; 40].join(" ");
|
||||
let mut found = BTreeSet::new();
|
||||
for width in (60..=140).step_by(4) {
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
let lid = d.default_layer();
|
||||
let para = ParaAttrs { align: Some(Align::RightJustified), direction: Some(TextDirection::RightToLeft), ..Default::default() };
|
||||
let rect = Rect::new(0.0, 0.0, f64::from(width), 800.0);
|
||||
let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), rect, lid, &text, ParaFormat { para, ..Default::default() }).unwrap();
|
||||
d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.font_family = Some(FAMILY.into()));
|
||||
let cs = compose_story(&d, sid, &ComposeOptions::default());
|
||||
assert!(cs.frames[0].lines.len() > 2, "{word} at {width}");
|
||||
for g in cs.frames[0].lines.iter().flat_map(|l| &l.glyphs) {
|
||||
if g.len == 0 && g.gid == g.face.glyph_for('\u{0640}') {
|
||||
let start = text[..g.byte].rfind(' ').map_or(0, |s| s + 1);
|
||||
found.insert(text[start..g.byte].chars().count());
|
||||
}
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kashidas_follow_the_typographic_rules() {
|
||||
install_font();
|
||||
let words = [
|
||||
("تصوم", None),
|
||||
("نقود", None),
|
||||
("يوم", None),
|
||||
("لبني", Some(1)),
|
||||
("هين", Some(0)),
|
||||
("الكتاب", Some(3)),
|
||||
("مدرسة", Some(3)),
|
||||
("بكر", Some(0)),
|
||||
("بلد", Some(0)),
|
||||
("بتم", Some(0)),
|
||||
("بيت", Some(0)),
|
||||
("بنت", Some(0)),
|
||||
("كبير", Some(1)),
|
||||
("تبر", Some(0)),
|
||||
("سير", Some(0)),
|
||||
];
|
||||
for (word, expected) in words {
|
||||
assert_eq!(kashida_letters(word), expected.into_iter().collect::<BTreeSet<usize>>(), "{word}");
|
||||
}
|
||||
}
|
||||
@@ -89,6 +89,17 @@ pub fn language_tag(language: &str) -> Option<&'static str> {
|
||||
"hebrew" => "he",
|
||||
"georgian" => "ka",
|
||||
"esperanto" => "eo",
|
||||
"hindi" => "hi",
|
||||
"marathi" => "mr",
|
||||
"bengali" | "bangla" => "bn",
|
||||
"assamese" => "as",
|
||||
"gujarati" => "gu",
|
||||
"punjabi" | "panjabi" => "pa",
|
||||
"odia" | "oriya" => "or",
|
||||
"tamil" => "ta",
|
||||
"telugu" => "te",
|
||||
"kannada" => "kn",
|
||||
"malayalam" => "ml",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -94,6 +94,32 @@ fn language_names_map_to_bcp47_tags() {
|
||||
assert_eq!(language_tag(""), None);
|
||||
}
|
||||
|
||||
/// Indian languages by the names the Language menu and IDML use, so their text gets the font's
|
||||
/// localized forms (Marathi ल and श) and hyphenates with its own patterns.
|
||||
#[test]
|
||||
fn indian_language_names_map_to_their_tags() {
|
||||
for (name, tag) in [
|
||||
("Hindi", "hi"),
|
||||
("Marathi", "mr"),
|
||||
("Bengali", "bn"),
|
||||
("Bangla", "bn"),
|
||||
("Assamese", "as"),
|
||||
("Gujarati", "gu"),
|
||||
("Punjabi", "pa"),
|
||||
("Panjabi", "pa"),
|
||||
("Odia", "or"),
|
||||
("Oriya", "or"),
|
||||
("Tamil", "ta"),
|
||||
("Telugu", "te"),
|
||||
("Kannada", "kn"),
|
||||
("Malayalam", "ml"),
|
||||
("$ID/Malayalam", "ml"),
|
||||
] {
|
||||
assert_eq!(language_tag(name), Some(tag), "{name}");
|
||||
}
|
||||
assert_eq!(language_tag("hi_IN"), Some("hi-IN"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chinese_japanese_and_korean_names_map_in_their_common_spellings() {
|
||||
for (name, tag) in [
|
||||
|
||||
@@ -191,6 +191,27 @@ impl StrokeType {
|
||||
&& length / period <= MAX_DASH_PERIODS
|
||||
}
|
||||
|
||||
/// The dash pattern to draw for a dashed stroke `weight` points wide, or `None` for a type
|
||||
/// that is not dashed.
|
||||
///
|
||||
/// A dashed stroke with no pattern of its own is drawn three weights on, two off: that is
|
||||
/// what `type: "dashed"` on a table cell stroke and a dashed paragraph border have always
|
||||
/// resolved to, and it is the only pattern an IDML `StrokeStyle/$ID/Dashed` carries (the
|
||||
/// built-in dashed styles name no array). Without it such a stroke drew solid (#1467).
|
||||
pub fn dashes(&self, weight: f64) -> Option<Vec<f64>> {
|
||||
let StrokeType::Dashed { pattern } = self else { return None };
|
||||
let kept: Vec<f64> = pattern.iter().copied().filter(|v| v.is_finite() && *v >= 0.0).collect();
|
||||
// No pattern at all (or only zeros, which no command accepts and only a file can carry):
|
||||
// the dashes come from the weight. A pattern that is there but degenerate is left alone,
|
||||
// so [`StrokeType::expandable_dashes`] still draws it solid rather than expanding 10^8
|
||||
// dashes along an edge.
|
||||
if kept.iter().all(|v| *v == 0.0) {
|
||||
let w = weight.max(1.0);
|
||||
return Some(vec![w * 3.0, w * 2.0]);
|
||||
}
|
||||
Some(kept)
|
||||
}
|
||||
|
||||
/// The bands of a striped type (start, width as fractions of the weight).
|
||||
pub fn bands(&self) -> Option<Vec<(f64, f64)>> {
|
||||
Some(match self {
|
||||
@@ -355,3 +376,27 @@ impl Stroke {
|
||||
self.swatch == designcraft_color::swatch::NONE || self.weight <= 0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// A dashed stroke with no pattern of its own — an IDML `StrokeStyle/$ID/Dashed`, or
|
||||
/// `type: "dashed"` with no array — dashes by its weight instead of drawing solid (#1467).
|
||||
#[test]
|
||||
fn a_dashed_stroke_without_a_pattern_dashes_by_its_weight() {
|
||||
let dashed = |p: Vec<f64>| StrokeType::Dashed { pattern: p };
|
||||
assert_eq!(dashed(vec![]).dashes(1.0), Some(vec![3.0, 2.0]));
|
||||
assert_eq!(dashed(vec![]).dashes(4.0), Some(vec![12.0, 8.0]));
|
||||
// A hairline still dashes visibly: the weight counts as at least a point.
|
||||
assert_eq!(dashed(vec![]).dashes(0.25), Some(vec![3.0, 2.0]));
|
||||
// Only zeros is nothing specified too (no command accepts such a pattern).
|
||||
assert_eq!(dashed(vec![0.0, 0.0]).dashes(2.0), Some(vec![6.0, 4.0]));
|
||||
// A pattern of its own is kept, as are the entries of a degenerate one, which
|
||||
// `expandable_dashes` then refuses so that it draws solid rather than expanding forever.
|
||||
assert_eq!(dashed(vec![6.0, 3.0]).dashes(2.0), Some(vec![6.0, 3.0]));
|
||||
assert_eq!(dashed(vec![1e-6, 1e-6]).dashes(2.0), Some(vec![1e-6, 1e-6]));
|
||||
assert!(!StrokeType::expandable_dashes(&[1e-6, 1e-6], 200.0));
|
||||
// Negative and non-finite entries are dropped, as every drawing site did before.
|
||||
assert_eq!(dashed(vec![6.0, -1.0, f64::NAN, 3.0]).dashes(1.0), Some(vec![6.0, 3.0]));
|
||||
// Nothing else has dashes.
|
||||
assert_eq!(StrokeType::Solid.dashes(1.0), None);
|
||||
assert_eq!(StrokeType::Dotted.dashes(1.0), None);
|
||||
assert_eq!(StrokeType::Style { name: "x".into() }.dashes(1.0), None);
|
||||
}
|
||||
@@ -146,7 +146,25 @@ impl<'a> Rules<'a> {
|
||||
}
|
||||
let punctuation = trailing(left).max(leading(right));
|
||||
if punctuation > 0.0 {
|
||||
return Aki { min: 0.0, desired: punctuation, max: punctuation, priority: 1, discrete: false };
|
||||
// The Japanese sets take a line in at the quarter ems of middle dots (・:;) first, then
|
||||
// at the half ems of brackets and commas, and don't reduce the space after a full stop
|
||||
// (JLREQ 3.8.3). !? share the first tier: JLREQ sets them solid (Table 1) and
|
||||
// gives the quarter em only as an alternative (3.1.6), so reducing it first returns
|
||||
// to that default. The tier follows the character classes, not the blank's size. The
|
||||
// Chinese sets reduce all punctuation blanks together.
|
||||
let japanese = self.base != Base::Chinese;
|
||||
// After: closing brackets (2, 28 」, 29 )), full stops (6 。, 31 .) and commas
|
||||
// (21 、, 30 ,). Before: opening brackets (1, 26 「, 27 ().
|
||||
let bracket_or_comma = matches!(left, 2 | 6 | 21 | 28..=31) || matches!(right, 1 | 26 | 27);
|
||||
// Full stops: 6 。 and 31 ..
|
||||
let full_stop = matches!(left, 6 | 31);
|
||||
return Aki {
|
||||
min: if japanese && full_stop { punctuation } else { 0.0 },
|
||||
desired: punctuation,
|
||||
max: punctuation,
|
||||
priority: if japanese && bracket_or_comma { 2 } else { 1 },
|
||||
discrete: false,
|
||||
};
|
||||
}
|
||||
let roman = |c| matches!(c, 18 | 25);
|
||||
let ideograph = |c| matches!(c, 3 | 7..=9 | 11 | 12 | 24 | 33);
|
||||
@@ -331,4 +349,38 @@ mod tests {
|
||||
assert_eq!((a.min, a.desired, a.max, a.priority), (b.min, b.desired, b.max, b.priority), "{l}/{r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn middle_dots_reduce_first_and_a_full_stops_space_never() {
|
||||
let styles = Styles::default();
|
||||
for set in ["LineEndAllOneHalfEmEnum", "LineEndAllOneEmEnum"] {
|
||||
let rules = Rules::resolve(&styles, set).unwrap().unwrap();
|
||||
let aki = |a: char, b: char| rules.pair(class(a), class(b));
|
||||
// Middle dots' quarter ems, then brackets' and commas' half ems, then wa-ō aki.
|
||||
let (dot, after_dot, comma, close, open, wa_ou) =
|
||||
(aki('漢', '・'), aki('・', '漢'), aki('、', '漢'), aki('」', '漢'), aki('漢', '「'), aki('漢', 'A'));
|
||||
assert!(dot.priority == after_dot.priority && dot.priority < comma.priority, "{set}");
|
||||
assert!(comma.priority == close.priority && close.priority == open.priority && open.priority < wa_ou.priority, "{set}");
|
||||
assert_eq!((dot.min, comma.min, close.min, open.min), (0.0, 0.0, 0.0, 0.0), "{set}");
|
||||
// The tier follows the class: :;!? share the middle dots' tier, and a bracket's half
|
||||
// em beside one of them stays with the brackets.
|
||||
for (a, b) in [('漢', ':'), (';', '漢'), ('漢', '!'), ('?', '漢')] {
|
||||
assert_eq!(aki(a, b).priority, dot.priority, "{set}: {a}{b}");
|
||||
}
|
||||
assert_eq!(aki('!', '「').priority, open.priority, "{set}: !「");
|
||||
// After a full stop the half em stays, before an opening bracket too.
|
||||
for b in ['漢', '「'] {
|
||||
let a = aki('。', b);
|
||||
assert_eq!((a.min, a.desired), (0.5, 0.5), "{set}: 。{b}");
|
||||
}
|
||||
}
|
||||
// The Chinese sets are unchanged: every punctuation blank reduces together, to nothing.
|
||||
for set in ["SimpChineseDefault", "TradChineseDefault"] {
|
||||
let rules = Rules::resolve(&styles, set).unwrap().unwrap();
|
||||
for (a, b) in [('漢', '・'), ('、', '漢'), ('」', '漢'), ('漢', '「'), ('。', '漢')] {
|
||||
let aki = rules.pair(class(a), class(b));
|
||||
assert_eq!((aki.min, aki.priority), (0.0, 1), "{set}: {a}{b}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,6 +71,16 @@ impl TextSel {
|
||||
}
|
||||
}
|
||||
|
||||
/// An anchored object (inline, above line or custom) selected as an object: the `index`-th of
|
||||
/// `story`'s [`crate::Story::objects`]. It lives in the text, not on a spread, so it isn't one of
|
||||
/// [`Selection::items`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AnchoredSel {
|
||||
pub story: StoryId,
|
||||
pub index: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Selection {
|
||||
@@ -100,11 +110,14 @@ pub struct Selection {
|
||||
/// the other.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub guides: Vec<GuideSel>,
|
||||
/// An anchored object selected with the Selection tool.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub anchored: Option<AnchoredSel>,
|
||||
}
|
||||
|
||||
impl Selection {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.items.is_empty() && self.text.is_none() && self.cells.is_none()
|
||||
self.items.is_empty() && self.text.is_none() && self.cells.is_none() && self.anchored.is_none()
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.items.len()
|
||||
|
||||
@@ -85,6 +85,13 @@ use crate::{EngineError, Result, Session};
|
||||
pub type Run = fn(&mut Session, &Value) -> Result<Value>;
|
||||
pub type Enabled = fn(&Session) -> std::result::Result<(), String>;
|
||||
|
||||
/// Internal success-postpass policy; no command-info/serialized API change.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum SuccessPasses {
|
||||
Always,
|
||||
IfDocumentChanged(fn(&Session, &Value) -> Option<Value>),
|
||||
}
|
||||
|
||||
pub struct CommandSpec {
|
||||
pub id: &'static str,
|
||||
pub label: &'static str,
|
||||
@@ -97,6 +104,8 @@ pub struct CommandSpec {
|
||||
pub journal: bool,
|
||||
/// Record an undo step when the document changes.
|
||||
pub undoable: bool,
|
||||
/// Opt-in only: an unchanged handler must not trigger unrelated pending layout work.
|
||||
pub(crate) success_passes: SuccessPasses,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
@@ -147,6 +156,12 @@ pub fn has_selection(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)?;
|
||||
if s.active().is_some_and(|d| !d.selection.items.is_empty()) { Ok(()) } else { Err(NOTHING_SELECTED.into()) }
|
||||
}
|
||||
/// Objects or ruler guides: Step and Repeat copies either, so a page with only a guide selected
|
||||
/// keeps the command awake.
|
||||
pub fn has_selection_or_guides(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)?;
|
||||
if s.active().is_some_and(|d| !d.selection.items.is_empty() || !d.selection.guides.is_empty()) { Ok(()) } else { Err(NOTHING_SELECTED.into()) }
|
||||
}
|
||||
pub fn has_text(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)?;
|
||||
if s.active().is_some_and(|d| d.selection.text.is_some()) { Ok(()) } else { Err("no text insertion point".into()) }
|
||||
@@ -161,14 +176,20 @@ pub fn has_text_or_frames(s: &Session) -> std::result::Result<(), String> {
|
||||
}
|
||||
|
||||
macro_rules! cmd {
|
||||
(on_document_change($noop:expr) $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
|
||||
$crate::cmd::CommandSpec {
|
||||
success_passes: $crate::cmd::SuccessPasses::IfDocumentChanged($noop),
|
||||
..$crate::cmd::cmd!($id, $label, [$($m),*], $sc, $params, $en, $run)
|
||||
}
|
||||
};
|
||||
($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
|
||||
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, undoable: true }
|
||||
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, undoable: true, success_passes: $crate::cmd::SuccessPasses::Always }
|
||||
};
|
||||
(query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
|
||||
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false, undoable: false }
|
||||
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false, undoable: false, success_passes: $crate::cmd::SuccessPasses::Always }
|
||||
};
|
||||
(noundo $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
|
||||
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, undoable: false }
|
||||
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, undoable: false, success_passes: $crate::cmd::SuccessPasses::Always }
|
||||
};
|
||||
}
|
||||
pub(crate) use cmd;
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use designcraft_doc::{AnchorPosition, AnchoredObject, Document, Item, ItemId, OBJECT_MARK, SpreadRef, StoryId, TextSel, anchored::AnchorAlign};
|
||||
use designcraft_doc::{
|
||||
AnchorPosition, AnchoredObject, AnchoredSel, Content, Document, Item, ItemId, OBJECT_MARK, SpreadRef, StoryId, TextSel, anchored::AnchorAlign,
|
||||
};
|
||||
use designcraft_geom::Affine;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -25,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Anchored Object Options…",
|
||||
["Object", "Anchored Object"],
|
||||
None,
|
||||
"{story?, index? (default: the object at the insertion point), position?: inline|aboveLine|custom, yOffset?, align?: left|center|right, spaceBefore?, spaceAfter?, xRelative? | yRelative?: anchor|textFrame|columnEdge|pageMargin|pageEdge, xOffset?, objectPoint? | refPoint?: 0..8, keepWithinColumn?, spineRelative? (custom: the settings describe a left-hand page and mirror on a right-hand page)}",
|
||||
"{story?, index? (default: the selected anchored object, else the one at the insertion point), position?: inline|aboveLine|custom, yOffset?, align?: left|center|right, spaceBefore?, spaceAfter?, xRelative? | yRelative?: anchor|textFrame|columnEdge|pageMargin|pageEdge, xOffset?, objectPoint? | refPoint?: 0..8, keepWithinColumn?, spineRelative? (custom: the settings describe a left-hand page and mirror on a right-hand page)}",
|
||||
has_doc,
|
||||
options
|
||||
),
|
||||
@@ -34,10 +36,28 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Release",
|
||||
["Object", "Anchored Object"],
|
||||
None,
|
||||
"{story?, index? (default: the object at the insertion point)} — puts the object back on the page where it is now and removes it from the text",
|
||||
"{story?, index? (default: the selected anchored object, else the one at the insertion point)} — puts the object back on the page where it is now and removes it from the text",
|
||||
has_doc,
|
||||
release
|
||||
),
|
||||
cmd!(
|
||||
noundo "anchored.select",
|
||||
"Select Anchored Object",
|
||||
[],
|
||||
None,
|
||||
"{story, index} — selects the anchored object as an object (the Selection tool clicking it); Delete removes it from the text, anchored.resize / options / release act on it",
|
||||
has_doc,
|
||||
select
|
||||
),
|
||||
cmd!(
|
||||
"anchored.resize",
|
||||
"Resize Anchored Object",
|
||||
[],
|
||||
None,
|
||||
"{story?, index? (default: the selected anchored object), from: rect, to: rect (the object's bounds before and after, in its own space: [x0, y0, x1, y1]), content?: bool (scale its content with it; default: the frame alone resizes and crops it from the sides that moved)} — the text then places it again and reflows around it",
|
||||
has_doc,
|
||||
resize
|
||||
),
|
||||
cmd!(query "anchored.list", "Anchored Objects", [], None, "{story?} → [{story, index, pos, position, size}]", has_doc, |s, p| {
|
||||
let d = &s.doc()?.doc;
|
||||
let only = p.get("story").and_then(Value::as_u64).map(StoryId);
|
||||
@@ -174,12 +194,43 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// `{story, index}`, or the anchored object at (or just before) the text insertion point.
|
||||
/// Whether the `k`-th anchored object of story `sid` can't be selected or changed: it, or the text
|
||||
/// frame holding it, is locked or on a locked layer (as for other page items).
|
||||
fn is_locked(s: &Session, sid: StoryId, k: usize) -> Result<bool> {
|
||||
let d = &s.doc()?.doc;
|
||||
let locked = |it: &designcraft_doc::Item| it.locked || d.layer(it.layer).is_some_and(|l| l.locked);
|
||||
let o = d.story(sid).and_then(|st| st.objects.get(k)).ok_or_else(|| bad("anchored", "no such anchored object"))?;
|
||||
if locked(&o.item) {
|
||||
return Ok(true);
|
||||
}
|
||||
// The frame composition placed it in; before it is placed, any of the story's frames.
|
||||
let cs = s.cache.get(d, sid, None);
|
||||
let host = cs.frames.iter().find(|ft| ft.objects.iter().any(|x| x.index == k)).map(|ft| ft.frame);
|
||||
let frames: Vec<designcraft_doc::ItemId> = match host {
|
||||
Some(f) => vec![f],
|
||||
None => d.story(sid).map(|st| st.frames.clone()).unwrap_or_default(),
|
||||
};
|
||||
Ok(frames.iter().filter_map(|f| d.item(*f)).any(locked))
|
||||
}
|
||||
|
||||
/// [`is_locked`] as the error a command returns.
|
||||
fn check_unlocked(s: &Session, sid: StoryId, k: usize, cmd: &str) -> Result<()> {
|
||||
if is_locked(s, sid, k)? {
|
||||
return Err(bad(cmd, "the anchored object or its frame is locked, or on a locked layer"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `{story, index}`, else the selected anchored object, else the one at (or just before) the text
|
||||
/// insertion point.
|
||||
fn object_ref(s: &Session, p: &Value, cmd: &str) -> Result<(StoryId, usize)> {
|
||||
if let (Some(sid), Some(k)) = (p.get("story").and_then(Value::as_u64), p.get("index").and_then(Value::as_u64)) {
|
||||
return Ok((StoryId(sid), k as usize));
|
||||
return Ok((StoryId(sid), usize::try_from(k).map_err(|_| bad(cmd, "index out of range"))?));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
if let Some(a) = st.selection.anchored {
|
||||
return Ok((a.story, a.index));
|
||||
}
|
||||
let t = st
|
||||
.selection
|
||||
.text
|
||||
@@ -195,8 +246,90 @@ fn object_ref(s: &Session, p: &Value, cmd: &str) -> Result<(StoryId, usize)> {
|
||||
Ok((t.story, story.text[..at].matches(OBJECT_MARK).count()))
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sid = p.get("story").and_then(Value::as_u64).map(StoryId).ok_or_else(|| bad("anchored.select", "missing story"))?;
|
||||
let k = p.get("index").and_then(Value::as_u64).and_then(|k| usize::try_from(k).ok()).ok_or_else(|| bad("anchored.select", "missing index"))?;
|
||||
if s.doc()?.doc.story(sid).and_then(|x| x.objects.get(k)).is_none() {
|
||||
return Err(bad("anchored.select", "no such anchored object"));
|
||||
}
|
||||
check_unlocked(s, sid, k, "anchored.select")?;
|
||||
let st = s.doc_mut()?;
|
||||
st.selection = designcraft_doc::Selection { anchored: Some(AnchoredSel { story: sid, index: k }), ..Default::default() };
|
||||
st.bump_revision();
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Resize an anchored object's frame from its bounds `from` to `to` (its own space): the content
|
||||
/// keeps its place while the edges move, so a frame made narrower from the left crops the
|
||||
/// picture's left side. Its top-left then returns to the origin, where composition places it,
|
||||
/// and the text reflows around the new size.
|
||||
fn resize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (sid, k) = object_ref(s, p, "anchored.resize")?;
|
||||
check_unlocked(s, sid, k, "anchored.resize")?;
|
||||
let from = super::rect_param(p, "from").ok_or_else(|| bad("anchored.resize", "missing from"))?;
|
||||
let to = super::rect_param(p, "to").ok_or_else(|| bad("anchored.resize", "missing to"))?;
|
||||
let finite = |r: designcraft_geom::Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite());
|
||||
if !finite(from) || !finite(to) || from.width().abs() < 1e-9 || from.height().abs() < 1e-9 {
|
||||
return Err(bad("anchored.resize", "degenerate or non-finite rect"));
|
||||
}
|
||||
// At least a point each way, at most the largest page InDesign allows.
|
||||
const MIN: f64 = 1.0;
|
||||
const MAX: f64 = 15552.0;
|
||||
let sx = to.width().abs().clamp(MIN, MAX) / from.width().abs();
|
||||
let sy = to.height().abs().clamp(MIN, MAX) / from.height().abs();
|
||||
// The dragged edges move and the content stays where it was on the page (InDesign crops a
|
||||
// picture from the side whose handle moved). Then the text places the object again by its
|
||||
// top-left, so after a left or top handle the frame and picture shift together.
|
||||
let m = Affine::translate((to.x0.min(to.x1), to.y0.min(to.y1))) * Affine::scale_non_uniform(sx, sy) * Affine::translate((-from.x0, -from.y0));
|
||||
let content = p.get("content").and_then(Value::as_bool).unwrap_or(false);
|
||||
let strokes = s.prefs.scale_strokes;
|
||||
s.edit(|d, _| {
|
||||
let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?;
|
||||
let o = st.objects.get_mut(k).ok_or_else(|| bad("anchored.resize", "no such anchored object"))?;
|
||||
let o = Arc::make_mut(o);
|
||||
let it = &mut o.item;
|
||||
if content {
|
||||
super::object::scale_item(it, m, (sx * sy).sqrt(), strokes);
|
||||
} else if matches!(it.content, Content::Group { .. }) {
|
||||
it.xf = m * it.xf;
|
||||
} else {
|
||||
let inner = it.xf.inverse() * m * it.xf;
|
||||
super::object::bake(it, inner);
|
||||
let r = it.inner_bounds();
|
||||
if let Content::Graphic(g) = &mut it.content
|
||||
&& let Some(xf) = g.fitted(r, g.auto_fit)
|
||||
{
|
||||
g.xf = xf;
|
||||
}
|
||||
}
|
||||
// Composition places the object by its top-left: keep that at the origin.
|
||||
let b = it.bounds();
|
||||
it.xf = Affine::translate((-b.x0, -b.y0)) * it.xf;
|
||||
let size = o.size();
|
||||
st.rev = st.rev.wrapping_add(1);
|
||||
Ok(json!({"size": [size.0, size.1]}))
|
||||
})
|
||||
}
|
||||
|
||||
/// Delete a selected anchored object: its mark leaves the text, and the object with it.
|
||||
pub(crate) fn delete(s: &mut Session, a: AnchoredSel) -> Result<Value> {
|
||||
// A locked object keeps its place in the text (Delete does nothing to it, as to a locked item).
|
||||
check_unlocked(s, a.story, a.index, "edit.clear")?;
|
||||
let pos = {
|
||||
let st = s.doc()?.doc.story(a.story).ok_or_else(|| bad("edit.clear", "no such story"))?;
|
||||
st.text.match_indices(OBJECT_MARK).nth(a.index).map(|(i, _)| i).ok_or_else(|| bad("edit.clear", "no such anchored object"))?
|
||||
};
|
||||
s.edit(|d, sel| {
|
||||
let st = d.story_mut(a.story).ok_or(designcraft_doc::DocError::NoStory(a.story))?;
|
||||
st.delete(pos..pos + OBJECT_MARK.len_utf8());
|
||||
*sel = designcraft_doc::Selection::default();
|
||||
Ok(json!({"deleted": 1}))
|
||||
})
|
||||
}
|
||||
|
||||
fn options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (sid, k) = object_ref(s, p, "anchored.options")?;
|
||||
check_unlocked(s, sid, k, "anchored.options")?;
|
||||
let cur = s.doc()?.doc.story(sid).and_then(|st| st.objects.get(k).cloned()).ok_or_else(|| bad("anchored.options", "no such anchored object"))?;
|
||||
let position = position_param(p, &cur.position)?;
|
||||
s.edit(|d, _| {
|
||||
@@ -210,6 +343,7 @@ fn options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (sid, k) = object_ref(s, p, "anchored.release")?;
|
||||
check_unlocked(s, sid, k, "anchored.release")?;
|
||||
let d0 = s.doc()?.doc.clone();
|
||||
let st = d0.story(sid).ok_or_else(|| bad("anchored.release", "no such story"))?;
|
||||
let obj = st.objects.get(k).cloned().ok_or_else(|| bad("anchored.release", "no such anchored object"))?;
|
||||
@@ -259,6 +393,233 @@ fn release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A text frame whose story holds a 24 × 40 inline box: (session, story).
|
||||
fn inline_box() -> (Session, StoryId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Before after and more words."})).unwrap();
|
||||
let sid = s.doc().unwrap().doc.item(ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;
|
||||
let r = s.execute("frame.create", &json!({"rect": [450, 450, 474, 490]})).unwrap();
|
||||
s.execute("anchored.insert", &json!({"ids": [r["id"]], "story": sid.0, "pos": 7})).unwrap();
|
||||
(s, sid)
|
||||
}
|
||||
|
||||
/// Review of #1195: an anchored selection follows its object through edits of the story. An
|
||||
/// object inserted before it moves it along; resizing it keeps it selected; deleting its
|
||||
/// text deletes it from the selection too, so Delete never takes another object.
|
||||
#[test]
|
||||
fn an_anchored_selection_follows_its_object() {
|
||||
let (mut s, sid) = inline_box();
|
||||
let id = |s: &Session, k: usize| s.doc().unwrap().doc.story(sid).unwrap().objects[k].item.id;
|
||||
s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap();
|
||||
let selected = id(&s, 0);
|
||||
// Another object anchored at the start of the story, before the selected one.
|
||||
let r = s.execute("frame.create", &json!({"rect": [450, 300, 470, 320]})).unwrap();
|
||||
s.execute("anchored.insert", &json!({"ids": [r["id"]], "story": sid.0, "pos": 0})).unwrap();
|
||||
// The selected object is now the second.
|
||||
let st = s.doc_mut().unwrap();
|
||||
st.selection = designcraft_doc::Selection { anchored: Some(AnchoredSel { story: sid, index: 1 }), ..Default::default() };
|
||||
assert_eq!(id(&s, 1), selected);
|
||||
// An edit that inserts an object before it: the selection moves with it.
|
||||
s.edit(|d, _| {
|
||||
let st = d.story_mut(sid).unwrap();
|
||||
let first = (*st.objects[0]).clone();
|
||||
let mut copy = first;
|
||||
copy.item.id = ItemId(9_999);
|
||||
st.insert_object(0, copy);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let a = s.doc().unwrap().selection.anchored.unwrap();
|
||||
assert_eq!((a.index, id(&s, a.index)), (2, selected), "follows its object");
|
||||
// Resizing keeps it selected.
|
||||
s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [0, 0, 30, 40]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.anchored.map(|a| a.index), Some(2));
|
||||
// Its text deleted with the object: nothing stays selected, rather than another object.
|
||||
let pos = s.doc().unwrap().doc.story(sid).unwrap().text.match_indices(designcraft_doc::OBJECT_MARK).nth(2).unwrap().0;
|
||||
s.edit(|d, _| {
|
||||
d.story_mut(sid).unwrap().delete(pos..pos + designcraft_doc::OBJECT_MARK.len_utf8());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.anchored, None);
|
||||
let _ = s.execute("edit.clear", &json!({}));
|
||||
assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().objects.len(), 2, "Delete took nothing");
|
||||
}
|
||||
|
||||
/// A locked anchored object, one on a locked layer, or one in a locked frame or a frame on a
|
||||
/// locked layer can't be selected, resized, deleted, changed in Anchored Object Options or
|
||||
/// released: it stays in the text with its marker.
|
||||
#[test]
|
||||
fn locked_anchored_objects_are_left_alone() {
|
||||
type Lock = fn(&mut designcraft_doc::Document, StoryId);
|
||||
let lock_object: Lock = |d, sid| Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).item.locked = true;
|
||||
let lock_object_layer: Lock = |d, sid| {
|
||||
let layer = d.story(sid).unwrap().objects[0].item.layer;
|
||||
d.layers.iter_mut().find(|l| l.id == layer).unwrap().locked = true;
|
||||
};
|
||||
let lock_frame: Lock = |d, sid| {
|
||||
let f = d.story(sid).unwrap().frames[0];
|
||||
d.item_mut(f).unwrap().locked = true;
|
||||
};
|
||||
let lock_frame_layer: Lock = |d, sid| {
|
||||
let f = d.story(sid).unwrap().frames[0];
|
||||
let layer = d.item(f).unwrap().layer;
|
||||
d.layers.iter_mut().find(|l| l.id == layer).unwrap().locked = true;
|
||||
};
|
||||
for (what, lock) in
|
||||
[("object", lock_object), ("its layer", lock_object_layer), ("its frame", lock_frame), ("its frame's layer", lock_frame_layer)]
|
||||
{
|
||||
let (mut s, sid) = inline_box();
|
||||
// Selected before it is locked, so Delete and Resize meet the lock themselves.
|
||||
s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap();
|
||||
s.edit(|d, _| {
|
||||
lock(d, sid);
|
||||
Ok(Value::Null)
|
||||
})
|
||||
.unwrap();
|
||||
assert!(s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).is_err(), "{what}: select");
|
||||
assert!(s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [0, 0, 24, 60]})).is_err(), "{what}: resize");
|
||||
assert!(s.execute("edit.clear", &json!({})).is_err(), "{what}: delete");
|
||||
// Anchored Object Options and Release (on the selected object, as from the menu).
|
||||
assert!(s.execute("anchored.options", &json!({"position": "aboveLine"})).is_err(), "{what}: options");
|
||||
assert!(s.execute("anchored.release", &json!({})).is_err(), "{what}: release");
|
||||
let st = s.doc().unwrap().doc.story(sid).unwrap().clone();
|
||||
assert_eq!(st.objects.len(), 1, "{what}: the object stays");
|
||||
assert_eq!(st.text.matches(OBJECT_MARK).count(), 1, "{what}: and its marker");
|
||||
assert_eq!(st.objects[0].size(), (24.0, 40.0), "{what}: at its size");
|
||||
assert!(matches!(st.objects[0].position, AnchorPosition::Inline { .. }), "{what}: inline still");
|
||||
}
|
||||
}
|
||||
|
||||
/// Placing a graphic selects the new frame alone: a selected anchored object is deselected.
|
||||
#[test]
|
||||
fn placing_a_graphic_deselects_an_anchored_object() {
|
||||
let (mut s, sid) = inline_box();
|
||||
s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap();
|
||||
// A video (any bytes: media is placed by its name) gets a media frame of its own.
|
||||
let b64 = crate::cmd::base64_encode(b"not really a video");
|
||||
let r = s.execute("file.place", &json!({"name": "clip.mp4", "base64": b64, "x": 500, "y": 500})).unwrap();
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
assert_eq!(sel.items, [ItemId(r["id"].as_u64().unwrap())]);
|
||||
assert_eq!(sel.anchored, None, "not both the new frame and the anchored object");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_inline_object_resizes_and_the_line_follows() {
|
||||
let (mut s, sid) = inline_box();
|
||||
s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap();
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
assert_eq!(sel.anchored, Some(AnchoredSel { story: sid, index: 0 }));
|
||||
assert!(sel.items.is_empty() && sel.text.is_none() && !sel.is_empty());
|
||||
// Taller by its bottom handle: the line grows to fit it; its top-left stays at the origin.
|
||||
let r = s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [0, 0, 24, 60]})).unwrap();
|
||||
assert_eq!(r["size"], json!([24.0, 60.0]));
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let b = d.story(sid).unwrap().objects[0].item.bounds();
|
||||
assert!(b.x0.abs() < 1e-9 && b.y0.abs() < 1e-9, "{b:?}");
|
||||
let cs = s.cache.get(&d, sid, None);
|
||||
let o = &cs.frames[0].objects[0];
|
||||
assert!(cs.frames[0].lines[o.line].ascent >= 60.0);
|
||||
// Narrower from its left handle: still at the origin, 10 pt wide.
|
||||
s.execute("anchored.resize", &json!({"from": [0, 0, 24, 60], "to": [14, 0, 24, 60]})).unwrap();
|
||||
let o = s.doc().unwrap().doc.story(sid).unwrap().objects[0].clone();
|
||||
assert_eq!(o.size(), (10.0, 60.0));
|
||||
assert!(o.item.bounds().x0.abs() < 1e-9);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().objects[0].size(), (24.0, 40.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_left_or_top_handle_crops_that_side_of_the_picture() {
|
||||
let (mut s, sid) = inline_box();
|
||||
let graphic = designcraft_doc::Graphic {
|
||||
asset: designcraft_doc::AssetId(1),
|
||||
size: (24.0, 40.0),
|
||||
xf: Affine::IDENTITY,
|
||||
clip: None,
|
||||
auto_fit: Default::default(),
|
||||
fit_align: 4,
|
||||
crop: [0.0; 4],
|
||||
wrap: Default::default(),
|
||||
fill: Default::default(),
|
||||
layer_options: Default::default(),
|
||||
};
|
||||
s.edit(|d, _| {
|
||||
let it = &mut Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).item;
|
||||
// At the frame's top-left, in its inner space.
|
||||
let inner = it.inner_bounds();
|
||||
it.content = Content::Graphic(designcraft_doc::Graphic { xf: Affine::translate((inner.x0, inner.y0)), ..graphic.clone() });
|
||||
Ok(Value::Null)
|
||||
})
|
||||
.unwrap();
|
||||
// The picture's top-left relative to the frame's.
|
||||
let offset = |s: &Session| {
|
||||
let it = s.doc().unwrap().doc.story(sid).unwrap().objects[0].item.clone();
|
||||
let Content::Graphic(g) = &it.content else { panic!() };
|
||||
let b = it.bounds();
|
||||
((it.xf * g.xf) * designcraft_geom::Point::ORIGIN - designcraft_geom::Point::new(b.x0, b.y0), b)
|
||||
};
|
||||
s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap();
|
||||
// The left handle 10 pt right and the top handle 20 pt down: the picture stayed put while
|
||||
// those edges moved, so its left 10 and top 20 points are cropped.
|
||||
s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [10, 20, 24, 40]})).unwrap();
|
||||
let (d, b) = offset(&s);
|
||||
assert!((b.width() - 14.0).abs() < 1e-9 && (b.height() - 20.0).abs() < 1e-9 && b.x0.abs() < 1e-9 && b.y0.abs() < 1e-9, "{b:?}");
|
||||
assert!((d.x + 10.0).abs() < 1e-9 && (d.y + 20.0).abs() < 1e-9, "{d:?}");
|
||||
// The right and bottom handles leave the picture at the frame's top-left.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [0, 0, 30, 50]})).unwrap();
|
||||
let (d, _) = offset(&s);
|
||||
assert!(d.x.abs() < 1e-9 && d.y.abs() < 1e-9, "{d:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_removes_a_selected_anchored_object_from_the_text() {
|
||||
let (mut s, sid) = inline_box();
|
||||
let before = s.doc().unwrap().doc.story(sid).unwrap().text.clone();
|
||||
s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap();
|
||||
assert_eq!(s.execute("edit.clear", &json!({})).unwrap()["deleted"], 1);
|
||||
let st = s.doc().unwrap().doc.story(sid).unwrap().clone();
|
||||
assert!(st.objects.is_empty() && !st.text.contains(OBJECT_MARK));
|
||||
assert!(s.doc().unwrap().selection.is_empty());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, before);
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_and_release_act_on_the_selected_anchored_object() {
|
||||
let (mut s, sid) = inline_box();
|
||||
s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap();
|
||||
s.execute("anchored.options", &json!({"position": "aboveLine"})).unwrap();
|
||||
assert!(matches!(s.doc().unwrap().doc.story(sid).unwrap().objects[0].position, AnchorPosition::AboveLine { .. }));
|
||||
s.execute("anchored.release", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.story(sid).unwrap().objects.is_empty());
|
||||
assert_eq!(s.doc().unwrap().selection.items.len(), 1, "the released item is selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selecting_items_drops_an_anchored_selection_and_bad_input_is_refused() {
|
||||
let (mut s, sid) = inline_box();
|
||||
assert!(s.execute("anchored.select", &json!({"story": sid.0, "index": 5})).is_err());
|
||||
assert!(s.execute("anchored.select", &json!({"story": 999_999, "index": 0})).is_err());
|
||||
s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap();
|
||||
for bad in [
|
||||
json!({"from": [0, 0, 0, 40], "to": [0, 0, 24, 40]}),
|
||||
json!({"from": [0, 0, 24, 40], "to": [0, 0, "wide", 40]}),
|
||||
json!({"to": [0, 0, 1, 1]}),
|
||||
] {
|
||||
assert!(s.execute("anchored.resize", &bad).is_err(), "{bad}");
|
||||
}
|
||||
// Dragged inside out or to nothing: at least a point each way.
|
||||
s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [24, 40, 24, 40]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().objects[0].size(), (1.0, 1.0));
|
||||
s.execute("selection.set", &json!({"ids": []})).unwrap();
|
||||
assert!(s.doc().unwrap().selection.anchored.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_object_flows_with_text_and_releases() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -21,6 +21,10 @@ use crate::EngineError;
|
||||
pub struct Maps {
|
||||
pub items: HashMap<ItemId, ItemId>,
|
||||
pub stories: HashMap<StoryId, StoryId>,
|
||||
/// Each source text frame's place in its story's thread, for the stories copied so far.
|
||||
source_ranks: HashMap<ItemId, usize>,
|
||||
/// The same place, by the id of the frame's copy.
|
||||
frame_ranks: HashMap<ItemId, usize>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -104,6 +108,7 @@ fn renumber_in(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Docum
|
||||
}
|
||||
}
|
||||
designcraft_doc::remap_story_assets(&mut st, &assets);
|
||||
maps.source_ranks.extend(st.frames.iter().enumerate().map(|(i, f)| (*f, i)));
|
||||
st.frames.clear();
|
||||
// Mapped first: the map is the seen-set that stops story recursion.
|
||||
maps.stories.insert(tf.story, n);
|
||||
@@ -112,8 +117,13 @@ fn renumber_in(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Docum
|
||||
n
|
||||
};
|
||||
tf.story = new_sid;
|
||||
// Frames are copied in page and nesting order, which can differ from the thread order:
|
||||
// each copy goes where its source frame is in the source story's thread.
|
||||
let rank = maps.source_ranks.get(&old).copied().unwrap_or(usize::MAX);
|
||||
maps.frame_ranks.insert(new_id, rank);
|
||||
if let Some(st) = dst.story_mut(new_sid) {
|
||||
st.frames.push(new_id);
|
||||
let at = st.frames.partition_point(|f| maps.frame_ranks.get(f).is_some_and(|r| *r <= rank));
|
||||
st.frames.insert(at, new_id);
|
||||
}
|
||||
}
|
||||
Content::Graphic(g) => {
|
||||
@@ -130,16 +140,20 @@ fn renumber_in(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Docum
|
||||
}
|
||||
}
|
||||
|
||||
/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes (#1522).
|
||||
/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes, and
|
||||
/// the cells and notes inside those at any depth (#1522). The texts are walked with a stack, so a deeply
|
||||
/// nested file can't exhaust the call stack.
|
||||
fn renumber_anchored(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Document, st: &mut Story, maps: &mut Maps) {
|
||||
let mut fresh = |t: &mut Story| {
|
||||
for o in &mut t.objects {
|
||||
let mut texts = vec![st];
|
||||
while let Some(t) = texts.pop() {
|
||||
let Story { objects, tables, notes, endnotes, .. } = t;
|
||||
for o in objects.iter_mut() {
|
||||
renumber_in(dst, src, &mut Arc::make_mut(o).item, maps, false);
|
||||
}
|
||||
};
|
||||
st.for_each_text_mut(&mut fresh);
|
||||
for n in &mut st.endnotes {
|
||||
Arc::make_mut(n).text.for_each_text_mut(&mut fresh);
|
||||
for table in tables.values_mut() {
|
||||
texts.extend(Arc::make_mut(table).cells.iter_mut().map(|c| &mut c.text));
|
||||
}
|
||||
texts.extend(notes.iter_mut().chain(endnotes.iter_mut()).map(|n| &mut Arc::make_mut(n).text));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1567,6 +1567,103 @@ fn merged_records_give_anchored_objects_their_own_ids() {
|
||||
designcraft_format::load(&designcraft_format::save(doc).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
/// A record's copy gives the objects anchored in an endnote of a table cell or of a footnote ids of
|
||||
/// their own, and maps them, so placeholders on them follow the copy.
|
||||
#[test]
|
||||
fn record_copies_renumber_objects_anchored_in_nested_endnotes() {
|
||||
use designcraft_doc::{AnchoredObject, ItemId, SpreadRef};
|
||||
use std::sync::Arc;
|
||||
|
||||
let mut s = Session::new();
|
||||
new_doc(&mut s, 1);
|
||||
let made = text_frame(&mut s, [36.0, 36.0, 400.0, 300.0], "Body", None);
|
||||
let (frame, sid) = (ItemId(made["id"].as_u64().unwrap()), StoryId(made["story"].as_u64().unwrap()));
|
||||
let a = exec(&mut s, "frame.create", json!({"rect": [450, 450, 474, 490]}))["id"].as_u64().unwrap();
|
||||
let b = exec(&mut s, "frame.create", json!({"rect": [480, 450, 504, 490]}))["id"].as_u64().unwrap();
|
||||
let mut src = s.doc().unwrap().doc.as_ref().clone();
|
||||
let d = &mut src;
|
||||
let take = |d: &mut designcraft_doc::Document, id: u64| {
|
||||
let it = d.item(ItemId(id)).cloned().unwrap();
|
||||
Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != id);
|
||||
AnchoredObject::new(it, Default::default())
|
||||
};
|
||||
let in_cell = take(d, a);
|
||||
let in_footnote = take(d, b);
|
||||
let mut table = designcraft_doc::Table::new(d.alloc(), 1, 1, 0, 0, 40.0);
|
||||
let cell = &mut table.cells[0].text;
|
||||
cell.insert_endnote(cell.len(), "Cell endnote", Default::default()).unwrap();
|
||||
Arc::make_mut(&mut cell.endnotes[0]).text.insert_object(0, in_cell);
|
||||
let st = d.story_mut(sid).unwrap();
|
||||
st.insert_note(st.len(), "Footnote", Default::default()).unwrap();
|
||||
let note = &mut Arc::make_mut(&mut st.notes[0]).text;
|
||||
note.insert_endnote(note.len(), "Footnote endnote", Default::default()).unwrap();
|
||||
Arc::make_mut(&mut note.endnotes[0]).text.insert_object(0, in_footnote);
|
||||
st.insert_table(0, table);
|
||||
src.check().unwrap();
|
||||
|
||||
let mut dst = src.clone();
|
||||
let it = src.item(frame).cloned().unwrap();
|
||||
let mut maps = super::fill::Maps::default();
|
||||
super::fill::copy_item(&mut dst, &src, &it, SpreadRef::Doc(0), designcraft_geom::Vec2::new(0.0, 0.0), &mut maps).unwrap();
|
||||
let ids: Vec<u64> = dst.anchored_items().into_iter().map(|(_, i)| i.id.0).collect();
|
||||
let unique: std::collections::BTreeSet<_> = ids.iter().collect();
|
||||
assert_eq!((ids.len(), unique.len()), (4, 4), "the copies have ids of their own: {ids:?}");
|
||||
for old in [a, b] {
|
||||
assert!(maps.items.contains_key(&ItemId(old)), "object {old} is mapped to its copy");
|
||||
}
|
||||
dst.check().unwrap();
|
||||
}
|
||||
|
||||
/// A story threaded through anchored text frames in two table cells keeps its thread order in a
|
||||
/// record's copy, so its text flows through the copied frames in the same order, whichever cell
|
||||
/// holds the first frame.
|
||||
#[test]
|
||||
fn record_copies_keep_the_thread_order_of_frames_anchored_in_cells() {
|
||||
for first_in_first_cell in [true, false] {
|
||||
thread_order_of_frames_anchored_in_cells(first_in_first_cell);
|
||||
}
|
||||
}
|
||||
|
||||
fn thread_order_of_frames_anchored_in_cells(first_in_first_cell: bool) {
|
||||
use designcraft_doc::{AnchoredObject, ItemId, SpreadRef};
|
||||
use std::sync::Arc;
|
||||
|
||||
let mut s = Session::new();
|
||||
new_doc(&mut s, 1);
|
||||
let made = text_frame(&mut s, [36.0, 36.0, 400.0, 300.0], "Body", None);
|
||||
let (frame, sid) = (ItemId(made["id"].as_u64().unwrap()), StoryId(made["story"].as_u64().unwrap()));
|
||||
let first = text_frame(&mut s, [450.0, 450.0, 500.0, 490.0], "Threaded text", None);
|
||||
let second = text_frame(&mut s, [450.0, 500.0, 500.0, 540.0], "", None);
|
||||
exec(&mut s, "text.thread", json!({"from": first["id"], "to": second["id"]}));
|
||||
let (a, b) = (first["id"].as_u64().unwrap(), second["id"].as_u64().unwrap());
|
||||
let thread = StoryId(first["story"].as_u64().unwrap());
|
||||
let mut src = s.doc().unwrap().doc.as_ref().clone();
|
||||
assert_eq!(src.story(thread).unwrap().frames, vec![ItemId(a), ItemId(b)]);
|
||||
let d = &mut src;
|
||||
let take = |d: &mut designcraft_doc::Document, id: u64| {
|
||||
let it = d.item(ItemId(id)).cloned().unwrap();
|
||||
Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != id);
|
||||
AnchoredObject::new(it, Default::default())
|
||||
};
|
||||
let in_first = take(d, a);
|
||||
let in_second = take(d, b);
|
||||
let mut table = designcraft_doc::Table::new(d.alloc(), 1, 2, 0, 0, 80.0);
|
||||
let (left, right) = if first_in_first_cell { (in_first, in_second) } else { (in_second, in_first) };
|
||||
table.cells[0].text.insert_object(0, left);
|
||||
table.cells[1].text.insert_object(0, right);
|
||||
d.story_mut(sid).unwrap().insert_table(0, table);
|
||||
src.check().unwrap();
|
||||
|
||||
let mut dst = src.clone();
|
||||
let it = src.item(frame).cloned().unwrap();
|
||||
let mut maps = super::fill::Maps::default();
|
||||
super::fill::copy_item(&mut dst, &src, &it, SpreadRef::Doc(0), designcraft_geom::Vec2::new(0.0, 0.0), &mut maps).unwrap();
|
||||
let copy = maps.stories[&thread];
|
||||
let expected = vec![maps.items[&ItemId(a)], maps.items[&ItemId(b)]];
|
||||
assert_eq!(dst.story(copy).unwrap().frames, expected, "the copy's frames keep the thread order ({first_in_first_cell})");
|
||||
dst.check().unwrap();
|
||||
}
|
||||
|
||||
/// A record previewed into an image placeholder whose frame wraps with an Alpha Channel contour
|
||||
/// gets the image's outline, as an edit would.
|
||||
#[test]
|
||||
|
||||
@@ -277,6 +277,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
st.history.redo.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() });
|
||||
let mut doc = e.doc;
|
||||
super::rulers::keep_zero_point(&st.doc, &mut doc);
|
||||
super::file::keep_title(&st.doc, &mut doc);
|
||||
st.doc = doc;
|
||||
st.selection = e.selection;
|
||||
st.bump_revision();
|
||||
@@ -290,6 +291,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
st.history.undo.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() });
|
||||
let mut doc = e.doc;
|
||||
super::rulers::keep_zero_point(&st.doc, &mut doc);
|
||||
super::file::keep_title(&st.doc, &mut doc);
|
||||
st.doc = doc;
|
||||
st.selection = e.selection;
|
||||
st.bump_revision();
|
||||
@@ -329,6 +331,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
st.selection.text = None;
|
||||
st.selection.cells = None;
|
||||
st.selection.anchored = None;
|
||||
st.bump_revision();
|
||||
ok()
|
||||
}),
|
||||
@@ -337,6 +340,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let st = s.doc_mut()?;
|
||||
st.selection.text = None;
|
||||
st.selection.cells = None;
|
||||
st.selection.anchored = None;
|
||||
if let Some(i) = st.selection.items.iter().position(|x| *x == id) {
|
||||
st.selection.items.remove(i);
|
||||
// Its points go with it: arrow keys and Delete act on the selected points.
|
||||
@@ -406,6 +410,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
if s.doc()?.selection.text.is_some() && p.get("ids").is_none() {
|
||||
return super::text::delete_selection(s);
|
||||
}
|
||||
// A selected anchored object leaves the text.
|
||||
if p.get("ids").is_none()
|
||||
&& let Some(a) = s.doc()?.selection.anchored
|
||||
{
|
||||
return super::anchored::delete(s, a);
|
||||
}
|
||||
if p.get("ids").is_none() && s.doc()?.selection.items.is_empty() && !s.doc()?.selection.guides.is_empty() {
|
||||
return s.execute("guide.delete", &json!({}));
|
||||
}
|
||||
|
||||
@@ -28,24 +28,9 @@ pub(super) fn print_booklet(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// HTML and reflowable EPUB read embedded bytes only: every used linked asset gets its output
|
||||
/// bytes embedded, and EPS its preview. The session's own assets stay as they are.
|
||||
fn eps_previews(d: &designcraft_doc::Document) -> (Cow<'_, designcraft_doc::Document>, Vec<String>) {
|
||||
// Match the exporter's reading order (including Article exclusions), not every asset
|
||||
// in the document: unused or hidden graphics must not prevent an export.
|
||||
let mut used = std::collections::BTreeSet::new();
|
||||
for block in designcraft_epub::reading_order(d) {
|
||||
let designcraft_epub::Block::Image(id) = block else {
|
||||
continue;
|
||||
};
|
||||
let Some(it) = d.item(id) else { continue };
|
||||
let designcraft_doc::Content::Graphic(g) = &it.content else {
|
||||
continue;
|
||||
};
|
||||
used.insert(g.asset);
|
||||
if d.assets.get(&g.asset).is_some_and(|a| designcraft_doc::media_kind(&a.mime).is_some())
|
||||
&& let Some(poster) = it.media.as_ref().and_then(|m| m.poster)
|
||||
{
|
||||
used.insert(poster);
|
||||
}
|
||||
}
|
||||
// Match the exporter's reading order and visible story content (including Article exclusions),
|
||||
// not every asset in the document: unused or hidden graphics must not prevent an export.
|
||||
let used = designcraft_epub::used_assets(d);
|
||||
let mut out = Cow::Borrowed(d);
|
||||
let mut warnings = Vec::new();
|
||||
for id in used {
|
||||
@@ -81,6 +66,10 @@ fn eps_previews(d: &designcraft_doc::Document) -> (Cow<'_, designcraft_doc::Docu
|
||||
let a = Arc::make_mut(a);
|
||||
if eps {
|
||||
a.mime = "image/png".into();
|
||||
} else if got.proxied
|
||||
&& let Some(proxy) = &a.proxy
|
||||
{
|
||||
a.mime = proxy.mime.clone();
|
||||
}
|
||||
a.data = designcraft_doc::AssetData::embedded(data);
|
||||
}
|
||||
|
||||
@@ -168,3 +168,78 @@ fn a_package_copies_a_modified_link_from_disk_with_a_warning() {
|
||||
assert_eq!(std::fs::read(out.join("Links/art.png")).unwrap(), changed);
|
||||
assert!(r.to_string().contains("file on disk"), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn html_and_epub_export_linked_inline_anchored_image_and_report_changes_or_missing() {
|
||||
use std::io::Read;
|
||||
|
||||
let dir = Dir::new("anchored-svg");
|
||||
let svg_path = dir.0.join("dot.svg");
|
||||
let svg = br#"<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12"><circle cx="6" cy="6" r="5"/></svg>"#;
|
||||
std::fs::write(&svg_path, svg).unwrap();
|
||||
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let text_frame = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": " Text"})).unwrap();
|
||||
let story = text_frame["story"].as_u64().unwrap();
|
||||
let graphic_frame = s.execute("frame.create", &json!({"rect": [500, 72, 512, 84], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();
|
||||
let placed = s.execute("file.place", &json!({"path": svg_path.to_string_lossy(), "frame": graphic_frame})).unwrap();
|
||||
let aid = AssetId(placed["asset"].as_u64().unwrap());
|
||||
s.execute("anchored.insert", &json!({"ids": [graphic_frame], "story": story, "pos": 0, "position": "inline"})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.assets[&aid].data.is_linked());
|
||||
|
||||
// Linked inline anchored SVG exports cleanly in HTML and EPUB without mutating the document.
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let html = s.execute("file.exportHtml", &json!({})).unwrap();
|
||||
assert!(html["warnings"].as_array().unwrap().is_empty(), "{}", warnings(&html));
|
||||
let body = html["text"].as_str().unwrap();
|
||||
let encoded = body.split("data:image/svg+xml;base64,").nth(1).expect("inline SVG data URI").split('"').next().unwrap();
|
||||
assert_eq!(crate::cmd::base64_decode(encoded), svg);
|
||||
assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc));
|
||||
|
||||
let epub = s.execute("file.exportEpub", &json!({})).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(crate::cmd::base64_decode(epub["base64"].as_str().unwrap()))).unwrap();
|
||||
let mut xhtml = String::new();
|
||||
z.by_name("OEBPS/content.xhtml").unwrap().read_to_string(&mut xhtml).unwrap();
|
||||
assert!(xhtml.contains("<img"), "anchored linked image in EPUB: {xhtml}");
|
||||
let mut packaged = Vec::new();
|
||||
z.by_name(&format!("OEBPS/images/dot-{}.svg", aid.0)).unwrap().read_to_end(&mut packaged).unwrap();
|
||||
assert_eq!(packaged, svg);
|
||||
|
||||
// Wait for link hash & proxy, then modify the file on disk: HTML exports the new file with a warning.
|
||||
crate::cmd::native_links::wait(&mut s);
|
||||
let updated = br#"<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12"><rect width="12" height="12"/></svg>"#;
|
||||
std::fs::write(&svg_path, updated).unwrap();
|
||||
let html = s.execute("file.exportHtml", &json!({})).unwrap();
|
||||
assert!(warnings(&html).contains("file on disk"), "{}", warnings(&html));
|
||||
let encoded = html["text"].as_str().unwrap().split("data:image/svg+xml;base64,").nth(1).expect("updated SVG data URI").split('"').next().unwrap();
|
||||
assert_eq!(crate::cmd::base64_decode(encoded), updated);
|
||||
|
||||
// Delete the linked file while a proxy exists: exports the proxy with the proxy's MIME type and warns.
|
||||
let proxy_mime = s.doc().unwrap().doc.assets[&aid].proxy.as_ref().expect("proxy built").mime.clone();
|
||||
assert_ne!(proxy_mime, "image/svg+xml");
|
||||
std::fs::remove_file(&svg_path).unwrap();
|
||||
let html = s.execute("file.exportHtml", &json!({})).unwrap();
|
||||
assert!(warnings(&html).contains("preview"), "{}", warnings(&html));
|
||||
let body = html["text"].as_str().unwrap();
|
||||
assert!(body.contains(&format!("data:{proxy_mime};base64,")), "proxy MIME used: {body}");
|
||||
assert!(!body.contains("data:image/svg+xml;base64,"));
|
||||
|
||||
// Without a proxy, the missing linked graphic is omitted with an explicit warning.
|
||||
s.edit(|d, _| {
|
||||
Arc::make_mut(d.assets.get_mut(&aid).unwrap()).proxy = None;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let html = s.execute("file.exportHtml", &json!({})).unwrap();
|
||||
assert!(!html["text"].as_str().unwrap().contains("<img"));
|
||||
assert!(warnings(&html).contains("unavailable"), "{}", warnings(&html));
|
||||
|
||||
// When the anchor's run is hidden by a condition, the missing link must not warn.
|
||||
s.execute("condition.new", &json!({"name": "Hide", "visible": false})).unwrap();
|
||||
s.execute("text.select", &json!({"story": story, "anchor": 0, "focus": designcraft_doc::OBJECT_MARK.len_utf8()})).unwrap();
|
||||
s.execute("condition.apply", &json!({"name": "Hide"})).unwrap();
|
||||
let html = s.execute("file.exportHtml", &json!({})).unwrap();
|
||||
assert!(!html["text"].as_str().unwrap().contains("<img"));
|
||||
assert!(html["warnings"].as_array().unwrap().is_empty(), "hidden anchored graphic must not warn: {}", warnings(&html));
|
||||
}
|
||||
@@ -25,6 +25,7 @@ pub use open::{ReadDocument, read_document};
|
||||
pub use open::{RecentPreview, recent_preview};
|
||||
pub(crate) use place::{crop_pdf, crop_pdf_from, document_of, prepare_placed, read_source, validate_placement};
|
||||
pub use registry::specs;
|
||||
pub(crate) use save::keep_title;
|
||||
pub(crate) use snippets::{snippet_bytes, snippet_place};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -37,6 +37,25 @@ pub(super) fn without_native_extension(name: &str) -> &str {
|
||||
}
|
||||
}
|
||||
|
||||
/// The document title for a saved file at `path`: its file name without a trailing `.designcraft`
|
||||
/// or `.idml` extension (any case). `None` when `path` has no file name.
|
||||
pub(super) fn title_from_path(path: &std::path::Path) -> Option<String> {
|
||||
let name = path.file_name()?.to_string_lossy();
|
||||
let stem = match name.rsplit_once('.') {
|
||||
Some((stem, ext))
|
||||
if !stem.is_empty()
|
||||
&& matches!(
|
||||
craft_file_formats::from_extension(ext),
|
||||
Some(craft_file_formats::Format::DesignCraft | craft_file_formats::Format::Idml)
|
||||
) =>
|
||||
{
|
||||
stem
|
||||
}
|
||||
_ => &name,
|
||||
};
|
||||
(!stem.is_empty()).then(|| stem.to_string())
|
||||
}
|
||||
|
||||
/// Whether `bytes` are a document `file.open` reads: a DesignCraft package or an IDML package.
|
||||
/// The first [`DOCUMENT_SNIFF_BYTES`] of a file are enough for packages that start with their
|
||||
/// `mimetype` entry, as both formats write them.
|
||||
|
||||
@@ -144,6 +144,9 @@ pub fn read_document(path: &str, cancel: &std::sync::atomic::AtomicBool) -> Resu
|
||||
return Err(e);
|
||||
}
|
||||
let file = std::path::Path::new(path);
|
||||
if let Some(title) = file.file_name().map(|n| without_native_extension(&n.to_string_lossy()).to_string()).filter(|t| !t.is_empty()) {
|
||||
d.title = title;
|
||||
}
|
||||
crate::cmd::interchange::resolve_packaged_links(&mut d, Some(file));
|
||||
crate::cmd::datamerge::resolve_sources_on_open(&mut d, Some(file));
|
||||
let links = crate::cmd::native_links::resolve(&mut d, Some(file), true);
|
||||
|
||||
@@ -2,12 +2,19 @@
|
||||
use super::DocState;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::bytes::from_bytes;
|
||||
use super::bytes::{bytes_for_path, with_save_extension};
|
||||
use super::bytes::{bytes_for_path, title_from_path, with_save_extension};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::open::load_document_fonts;
|
||||
#[cfg(test)]
|
||||
use super::place::image_place_tests;
|
||||
use super::{Arc, EngineError, Result, Session, Value, bad, json, str_param};
|
||||
use super::{Arc, Document, EngineError, Result, Session, Value, bad, json, str_param};
|
||||
|
||||
/// Undo and redo swap whole documents; the saved file's title stays as it is now.
|
||||
pub(crate) fn keep_title(now: &Document, to: &mut Arc<Document>) {
|
||||
if to.title != now.title {
|
||||
Arc::make_mut(to).title.clone_from(&now.title);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn file_save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc_mut()?;
|
||||
@@ -24,13 +31,21 @@ pub(super) fn file_save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let linked = crate::cmd::native_links::for_destination(&st.doc, from, destination);
|
||||
let links_changed = linked.is_some();
|
||||
let mut saved = linked.unwrap_or_else(|| (*st.doc).clone());
|
||||
let title_changed = title_from_path(destination).is_some_and(|title| {
|
||||
if saved.title != title {
|
||||
saved.title = title;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
crate::cmd::datamerge::refresh_relative_paths(&mut saved, destination);
|
||||
// Proxies the background job hasn't made yet are made here, on this thread: the save is
|
||||
// synchronous. The document keeps them.
|
||||
let proxied = crate::cmd::native_links::with_proxies(&saved, || false);
|
||||
let proxies_made = proxied.is_some();
|
||||
let saved = proxied.unwrap_or(saved);
|
||||
let changed = links_changed || proxies_made || saved.data_merge != st.doc.data_merge;
|
||||
let changed = links_changed || proxies_made || title_changed || saved.data_merge != st.doc.data_merge;
|
||||
let saved = if changed { Arc::new(saved) } else { st.doc.clone() };
|
||||
let mut warnings = crate::cmd::native_links::web_save_warnings(&saved);
|
||||
let allow_loss = p.get("allowLoss").and_then(Value::as_bool).unwrap_or(false);
|
||||
@@ -72,6 +87,9 @@ pub(super) fn file_save_a_copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let destination = std::path::Path::new(&path);
|
||||
let from = st.path.as_deref().map(std::path::Path::new);
|
||||
let mut copy = crate::cmd::native_links::for_destination(&st.doc, from, destination).unwrap_or_else(|| (*st.doc).clone());
|
||||
if let Some(title) = title_from_path(destination) {
|
||||
copy.title = title;
|
||||
}
|
||||
crate::cmd::datamerge::refresh_relative_paths(&mut copy, destination);
|
||||
if embed {
|
||||
crate::cmd::native_links::embed_linked(&mut copy, "file.saveACopy")?;
|
||||
@@ -139,6 +157,9 @@ pub(super) fn file_revert(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
} else {
|
||||
from_bytes(&bytes)?
|
||||
};
|
||||
if let Some(title) = title_from_path(std::path::Path::new(&path)) {
|
||||
d.title = title;
|
||||
}
|
||||
// As opened again: the fonts beside it now (unchanged files are shared, not read again),
|
||||
// its linked files found again.
|
||||
let (fonts, _, _) = load_document_fonts(&mut d, &path);
|
||||
|
||||
@@ -554,4 +554,38 @@ mod resolution_tests {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(before, s.execute("font.list", &json!({})).unwrap());
|
||||
}
|
||||
|
||||
/// #2618: a face's legacy family name with a style it doesn't have (`Source Serif 4
|
||||
/// Semibold` `Regular`, which the lookup takes to Source Serif 4 Regular) is a substitute,
|
||||
/// not exact; the typographic name and an alternate spelling of it stay exact.
|
||||
#[test]
|
||||
fn a_legacy_family_name_resolving_to_another_face_is_a_style_substitute() {
|
||||
let status = |family: &str, style: &str| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("frame.create", &json!({"rect":[20,20,300,400],"content":"text","text":"Body"})).unwrap();
|
||||
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let sid = *d.stories.keys().next().unwrap();
|
||||
d.story_mut(sid).unwrap().format_chars(0..4, |f| {
|
||||
f.over.font_family = Some(family.into());
|
||||
f.over.font_style = Some(style.into());
|
||||
});
|
||||
let list = s.execute("font.list", &json!({})).unwrap();
|
||||
let font = list.as_array().unwrap().iter().find(|f| f["family"] == family).cloned().unwrap();
|
||||
let preflight = s.execute("preflight.run", &json!({})).unwrap();
|
||||
let flagged = preflight["issues"].as_array().unwrap().iter().any(|i| i["kind"] == "missingFontStyle");
|
||||
(font, flagged)
|
||||
};
|
||||
let (font, flagged) = status("Source Serif 4 Semibold", "Regular");
|
||||
assert_eq!((font["resolvedFamily"].as_str(), font["resolvedStyle"].as_str()), (Some("Source Serif 4"), Some("Regular")), "{font}");
|
||||
assert_eq!(font["matchStatus"], "styleSubstitute", "{font}");
|
||||
assert_eq!(font["styleMissing"], true);
|
||||
assert_eq!(font["missing"], false);
|
||||
assert!(flagged, "preflight reports the substituted style");
|
||||
for (family, style) in [("Source Serif 4", "Semibold"), ("Source Serif 4 (OTF)", "Semibold"), ("Source Serif 4", "Regular")] {
|
||||
let (font, flagged) = status(family, style);
|
||||
assert_eq!(font["matchStatus"], "exact", "{family} {style}: {font}");
|
||||
assert!(!flagged, "{family} {style}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -171,7 +171,7 @@ fn finite_number(p: &Value, key: &str, command: &str) -> Result<Option<f64>> {
|
||||
}
|
||||
|
||||
/// `position` as a guide position: finite and within [`MAX_GUIDE_POSITION`] of the origin.
|
||||
fn guide_position(position: f64, command: &str) -> Result<f64> {
|
||||
pub(crate) fn guide_position(position: f64, command: &str) -> Result<f64> {
|
||||
if !position.is_finite() || position.abs() > MAX_GUIDE_POSITION {
|
||||
return Err(bad(command, format!("a guide position must be between -{MAX_GUIDE_POSITION} and {MAX_GUIDE_POSITION}")));
|
||||
}
|
||||
|
||||
@@ -11,6 +11,30 @@ use super::parents::{
|
||||
use super::sections::{ChapterEdit, SectionEdit, chapter_numbering, start_number};
|
||||
use super::{CommandSpec, LAYER_COLORS, Layer, LayerId, Margins, Result, SpreadId, Value, bad, cmd, has_doc, json, ok, str_param};
|
||||
|
||||
fn numbering_edit(s: &crate::Session, p: &Value) -> Result<(SectionEdit, Option<ChapterEdit>)> {
|
||||
let section = SectionEdit::parse("layout.numberingOptions", s, p)?;
|
||||
let chapter = match p.get("chapter") {
|
||||
Some(c) => Some(ChapterEdit::parse("layout.numberingOptions", c)?),
|
||||
None => None,
|
||||
};
|
||||
Ok((section, chapter))
|
||||
}
|
||||
|
||||
fn numbering_is_unchanged(d: &designcraft_doc::Document, section: &SectionEdit, chapter: Option<&ChapterEdit>) -> bool {
|
||||
section.planned_sections(&d.sections) == d.sections && chapter.is_none_or(|chapter| !chapter.changes(d))
|
||||
}
|
||||
|
||||
fn numbering_result(d: &designcraft_doc::Document) -> Value {
|
||||
json!({"names": (0..d.page_count()).map(|i| d.page_name(i)).collect::<Vec<_>>(), "chapter": d.chapter_label()})
|
||||
}
|
||||
|
||||
/// Pure, validated no-op probe. Errors and real changes MUST use the original execution path.
|
||||
fn numbering_noop(s: &crate::Session, p: &Value) -> Option<Value> {
|
||||
let (section, chapter) = numbering_edit(s, p).ok()?;
|
||||
let d = &s.doc().ok()?.doc;
|
||||
numbering_is_unchanged(d, §ion, chapter.as_ref()).then(|| numbering_result(d))
|
||||
}
|
||||
|
||||
// A group can hold children on other layers, including in inactive states or pasted-into frames.
|
||||
// Only references to removed layers change; surviving layers keep their assignments. Containers
|
||||
// without such a reference stay shared with the undo history (copy-on-write only where one is).
|
||||
@@ -705,24 +729,25 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
),
|
||||
cmd!(
|
||||
"layout.numberingOptions",
|
||||
on_document_change(numbering_noop) "layout.numberingOptions",
|
||||
"Apply Numbering & Section Options",
|
||||
[],
|
||||
None,
|
||||
"{page, …the settings as layout.section, chapter?: {…the settings as layout.chapterNumbering}} — the section and the document's chapter numbering in one undo step; if either is refused nothing changes",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let section = SectionEdit::parse("layout.numberingOptions", s, p)?;
|
||||
let chapter = match p.get("chapter") {
|
||||
Some(c) => Some(ChapterEdit::parse("layout.numberingOptions", c)?),
|
||||
None => None,
|
||||
};
|
||||
// Re-parse after the original lifecycle prelude; never reuse a preflight plan.
|
||||
let (section, chapter) = numbering_edit(s, p)?;
|
||||
let current = &s.doc()?.doc;
|
||||
if numbering_is_unchanged(current, §ion, chapter.as_ref()) {
|
||||
return Ok(numbering_result(current));
|
||||
}
|
||||
s.edit(|d, _| {
|
||||
section.apply(d);
|
||||
if let Some(chapter) = &chapter {
|
||||
chapter.apply(d);
|
||||
}
|
||||
Ok(json!({"names": (0..d.page_count()).map(|i| d.page_name(i)).collect::<Vec<_>>(), "chapter": d.chapter_label()}))
|
||||
Ok(numbering_result(d))
|
||||
})
|
||||
}
|
||||
),
|
||||
|
||||
@@ -59,22 +59,22 @@ impl SectionEdit {
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn apply(&self, d: &mut designcraft_doc::Document) {
|
||||
pub(super) fn planned_sections(&self, current: &[designcraft_doc::Section]) -> Vec<designcraft_doc::Section> {
|
||||
let mut sections = current.to_vec();
|
||||
let start = self.start;
|
||||
// Page 1 always starts a section.
|
||||
if self.remove && start != 0 {
|
||||
// A section that starts an alternate layout stays (the layout needs it); it just
|
||||
// continues the previous section's numbers.
|
||||
if let Some(sec) = d.sections.iter_mut().find(|x| x.start == start && x.layout.is_some()) {
|
||||
if let Some(sec) = sections.iter_mut().find(|x| x.start == start && x.layout.is_some()) {
|
||||
sec.start_number = None;
|
||||
} else {
|
||||
d.sections.retain(|x| x.start != start);
|
||||
sections.retain(|x| x.start != start);
|
||||
}
|
||||
// The pages after it follow the previous section's numbers again.
|
||||
d.repaginate();
|
||||
return;
|
||||
return sections;
|
||||
}
|
||||
let mut sec = d.sections.iter().find(|x| x.start == start).cloned().unwrap_or(designcraft_doc::Section {
|
||||
let mut sec = sections.iter().find(|x| x.start == start).cloned().unwrap_or(designcraft_doc::Section {
|
||||
start,
|
||||
start_number: None,
|
||||
style: Default::default(),
|
||||
@@ -98,10 +98,15 @@ impl SectionEdit {
|
||||
if let Some(marker) = &self.marker {
|
||||
sec.marker = marker.clone();
|
||||
}
|
||||
d.sections.retain(|x| x.start != start);
|
||||
d.sections.push(sec);
|
||||
d.sections.sort_by_key(|x| x.start);
|
||||
// Facing pages take their sides from their numbers: odd on the right.
|
||||
sections.retain(|x| x.start != start);
|
||||
sections.push(sec);
|
||||
sections.sort_by_key(|x| x.start);
|
||||
sections
|
||||
}
|
||||
|
||||
pub(super) fn apply(&self, d: &mut designcraft_doc::Document) {
|
||||
d.sections = self.planned_sections(&d.sections);
|
||||
// Real edits retain the existing reflow, including chapter-only combined edits.
|
||||
d.repaginate();
|
||||
}
|
||||
}
|
||||
@@ -143,6 +148,13 @@ impl ChapterEdit {
|
||||
Ok(ChapterEdit { style, source, start })
|
||||
}
|
||||
|
||||
pub(super) fn changes(&self, d: &designcraft_doc::Document) -> bool {
|
||||
// Stored values matter even when the current mode/labels do not expose them.
|
||||
self.style.is_some_and(|style| style != d.settings.chapter_style)
|
||||
|| self.source.is_some_and(|source| source != d.settings.chapter_source)
|
||||
|| self.start.is_some_and(|start| start != d.settings.chapter_number)
|
||||
}
|
||||
|
||||
pub(super) fn apply(&self, d: &mut designcraft_doc::Document) {
|
||||
if let Some(style) = self.style {
|
||||
d.settings.chapter_style = style;
|
||||
@@ -256,3 +268,471 @@ mod section_side_tests {
|
||||
assert!(sp.iter().all(|p| p.len() == 1 && p[0].1 == 'S'), "{sp:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod numbering_noop_guard_tests {
|
||||
use super::{Value, json};
|
||||
use crate::{DocState, HistoryEntry, Session};
|
||||
use std::sync::Arc;
|
||||
|
||||
type Entries = Vec<(String, Arc<designcraft_doc::Document>, designcraft_doc::Selection)>;
|
||||
fn entries(items: &[HistoryEntry]) -> Entries {
|
||||
items.iter().map(|item| (item.label.clone(), item.doc.clone(), item.selection.clone())).collect()
|
||||
}
|
||||
fn fresh() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"pages": 4, "width": 612, "height": 792, "facingPages": true})).unwrap();
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
s
|
||||
}
|
||||
fn snapshot(s: &Session) -> (DocState, Vec<(String, Value)>) {
|
||||
(s.doc().unwrap().clone(), s.journal.clone())
|
||||
}
|
||||
fn preserved(s: &Session, before: &(DocState, Vec<(String, Value)>), attempt: Option<&Value>) {
|
||||
let now = s.doc().unwrap();
|
||||
let old = &before.0;
|
||||
assert_eq!(now.doc.as_ref(), old.doc.as_ref(), "ALL document fields, IDs, next_id and geometry remain exact");
|
||||
assert!(Arc::ptr_eq(&now.doc, &old.doc), "no-op/refusal cannot replace the live Arc");
|
||||
assert!(Arc::ptr_eq(&now.saved_doc, &old.saved_doc));
|
||||
assert_eq!(now.saved_doc.as_ref(), old.saved_doc.as_ref());
|
||||
assert_eq!(
|
||||
(now.uid, now.identity_epoch, now.revision, now.saved_revision, now.is_dirty()),
|
||||
(old.uid, old.identity_epoch, old.revision, old.saved_revision, old.is_dirty())
|
||||
);
|
||||
assert_eq!(now.selection, old.selection);
|
||||
assert_eq!(entries(&now.history.undo), entries(&old.history.undo));
|
||||
assert_eq!(entries(&now.history.redo), entries(&old.history.redo));
|
||||
assert_eq!(now.history.limit, old.history.limit);
|
||||
assert_eq!(now.path, old.path);
|
||||
assert_eq!(now.preview_record, old.preview_record);
|
||||
assert_eq!(now.preview_stash.as_deref(), old.preview_stash.as_deref());
|
||||
if let (Some(now), Some(old)) = (&now.preview_stash, &old.preview_stash) {
|
||||
assert!(Arc::ptr_eq(now, old));
|
||||
}
|
||||
assert_eq!(now.active_layer, old.active_layer);
|
||||
assert_eq!(now.editing_parents, old.editing_parents);
|
||||
let mut journal = before.1.clone();
|
||||
if let Some(params) = attempt {
|
||||
journal.push(("layout.numberingOptions".into(), params.clone()));
|
||||
}
|
||||
assert_eq!(s.journal, journal, "successful no-ops journal attempts; refused commands do not");
|
||||
}
|
||||
fn one_edit(s: &Session, before: &(DocState, Vec<(String, Value)>), params: &Value) {
|
||||
let now = s.doc().unwrap();
|
||||
let old = &before.0;
|
||||
assert_ne!(now.doc.as_ref(), old.doc.as_ref());
|
||||
assert!(!Arc::ptr_eq(&now.doc, &old.doc));
|
||||
assert_ne!(
|
||||
now.doc.spreads.iter().map(|spread| spread.id).collect::<Vec<_>>(),
|
||||
old.doc.spreads.iter().map(|spread| spread.id).collect::<Vec<_>>(),
|
||||
"real combined edits still run the original repagination, even for chapter-only changes"
|
||||
);
|
||||
assert!(now.revision > old.revision, "a fresh process-global revision, not a guessed +1");
|
||||
assert_eq!((now.uid, now.identity_epoch, now.saved_revision), (old.uid, old.identity_epoch, old.saved_revision));
|
||||
assert!(Arc::ptr_eq(&now.saved_doc, &old.saved_doc));
|
||||
assert!(now.is_dirty());
|
||||
assert_eq!(now.history.undo.len(), old.history.undo.len() + 1);
|
||||
assert!(now.history.redo.is_empty());
|
||||
assert_eq!(entries(&now.history.undo[..old.history.undo.len()]), entries(&old.history.undo));
|
||||
let undo = now.history.undo.last().unwrap();
|
||||
assert_eq!(undo.label, "Apply Numbering & Section Options");
|
||||
assert_eq!(undo.doc.as_ref(), old.doc.as_ref());
|
||||
assert_eq!(undo.selection, old.selection);
|
||||
assert_eq!(now.selection, old.selection);
|
||||
let mut journal = before.1.clone();
|
||||
journal.push(("layout.numberingOptions".into(), params.clone()));
|
||||
assert_eq!(s.journal, journal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_noops_preserve_full_identity_saved_state_and_normal_attempt_journal() {
|
||||
let mut s = fresh();
|
||||
for params in [
|
||||
json!({"page": 1}),
|
||||
json!({"page": 1, "startNumber": 1, "style": "arabic", "prefix": "", "marker": "", "includePrefix": false,
|
||||
"chapter": {"source": "automatic", "style": "arabic", "start": 1}}),
|
||||
json!({"page": 1, "remove": true}),
|
||||
json!({"page": 3, "remove": true}),
|
||||
json!({"page": 1, "chapter": {}}),
|
||||
json!({"page": 1, "chapter": null}),
|
||||
] {
|
||||
let before = snapshot(&s);
|
||||
let result = s.execute("layout.numberingOptions", ¶ms).unwrap();
|
||||
assert_eq!(result, json!({"names": ["1", "2", "3", "4"], "chapter": "1"}));
|
||||
preserved(&s, &before, Some(¶ms));
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dirty_noops_preserve_nonempty_selection_and_complete_undo_and_redo_entries() {
|
||||
let mut s = fresh();
|
||||
let id = s.execute("frame.create", &json!({"rect": [10, 10, 40, 40]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("frame.create", &json!({"rect": [50, 50, 80, 80]})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("selection.set", &json!({"ids": [id]})).unwrap();
|
||||
assert!(s.doc().unwrap().is_dirty());
|
||||
assert!(!s.doc().unwrap().history.undo.is_empty());
|
||||
assert!(!s.doc().unwrap().history.redo.is_empty());
|
||||
assert_eq!(s.doc().unwrap().selection.items, [designcraft_doc::ItemId(id)]);
|
||||
let params = json!({"page": 1, "startNumber": 1, "chapter": {"source": "automatic"}});
|
||||
let before = snapshot(&s);
|
||||
s.execute("layout.numberingOptions", ¶ms).unwrap();
|
||||
preserved(&s, &before, Some(¶ms));
|
||||
// Redo is still the real previously undone frame edit, not a length-only placeholder.
|
||||
let expected = s.doc().unwrap().history.redo.last().unwrap().clone();
|
||||
let revision = s.doc().unwrap().revision;
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.as_ref(), expected.doc.as_ref());
|
||||
assert_eq!(s.doc().unwrap().selection, expected.selection);
|
||||
assert!(s.doc().unwrap().revision > revision);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_values_modes_and_new_section_targets_are_real_edits_even_with_equal_labels() {
|
||||
for params in [
|
||||
json!({"page": 1, "prefix": "A"}), // hidden while includePrefix is false
|
||||
json!({"page": 1, "marker": "bookmark"}),
|
||||
json!({"page": 1, "startNumber": null}), // explicit one -> Automatic
|
||||
json!({"page": 1, "chapter": {"source": "sameAsPrevious"}}),
|
||||
json!({"page": 1, "chapter": {"source": "automatic", "start": 7}}),
|
||||
json!({"page": 1, "chapter": {"style": "upperRoman"}}),
|
||||
json!({"page": 3}), // create a continuing section, though its page labels match
|
||||
json!({"page": 3, "startNumber": 1}),
|
||||
] {
|
||||
let mut s = fresh();
|
||||
let before = snapshot(&s);
|
||||
s.execute("layout.numberingOptions", ¶ms).unwrap();
|
||||
one_edit(&s, &before, ¶ms);
|
||||
let changed = snapshot(&s);
|
||||
// Repeating the exact typed plan must now be a no-op, including latent fields.
|
||||
s.execute("layout.numberingOptions", ¶ms).unwrap();
|
||||
preserved(&s, &changed, Some(¶ms));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.as_ref(), before.0.doc.as_ref());
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.as_ref(), changed.0.doc.as_ref());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refusal_validates_both_parts_before_noop_or_atomic_mutation() {
|
||||
let mut s = fresh();
|
||||
for params in [
|
||||
json!({"page": 1, "chapter": {"start": 100000}}), // otherwise unchanged section
|
||||
json!({"page": 3, "startNumber": 5, "chapter": {"start": 100000}}),
|
||||
json!({"page": 1, "chapter": {"source": "unknown"}}),
|
||||
json!({"page": 1, "chapter": {"style": "symbols"}}),
|
||||
json!({"page": 1, "startNumber": 0, "chapter": {"start": 4}}),
|
||||
json!({"page": 1, "prefix": "A+B", "chapter": {"start": 4}}),
|
||||
json!({"page": 0, "chapter": {"start": 4}}),
|
||||
json!({"page": 5, "chapter": {"start": 4}}),
|
||||
json!({"page": 1, "style": "symbols", "chapter": {"start": 4}}),
|
||||
json!({"page": 3, "remove": true, "chapter": {"start": 0}}),
|
||||
] {
|
||||
let before = snapshot(&s);
|
||||
assert!(s.execute("layout.numberingOptions", ¶ms).is_err(), "{params}");
|
||||
preserved(&s, &before, None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_atomic_edits_keep_repagination_object_page_and_full_undo_redo_checkpoints() {
|
||||
let mut s = fresh();
|
||||
let id = s.execute("frame.create", &json!({"spread": 1, "rect": [700, 100, 800, 200]})).unwrap()["id"].as_u64().unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.page_of_item(designcraft_doc::ItemId(id)), Some(2));
|
||||
assert_eq!(s.doc().unwrap().doc.page(1).unwrap().side, designcraft_doc::PageSide::Left);
|
||||
let before = snapshot(&s);
|
||||
let params = json!({"page": 2, "startNumber": 1, "style": "lowerRoman", "prefix": "A-", "includePrefix": true,
|
||||
"chapter": {"source": "userDefined", "start": 4, "style": "upperRoman"}});
|
||||
let result = s.execute("layout.numberingOptions", ¶ms).unwrap();
|
||||
assert_eq!(result, json!({"names": ["1", "A-i", "A-ii", "A-iii"], "chapter": "IV"}));
|
||||
one_edit(&s, &before, ¶ms);
|
||||
assert_eq!(s.doc().unwrap().doc.page(1).unwrap().side, designcraft_doc::PageSide::Right);
|
||||
assert_eq!(s.doc().unwrap().doc.page_of_item(designcraft_doc::ItemId(id)), Some(2));
|
||||
let changed = snapshot(&s);
|
||||
s.execute("layout.numberingOptions", ¶ms).unwrap();
|
||||
preserved(&s, &changed, Some(¶ms));
|
||||
let revision = s.doc().unwrap().revision;
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.as_ref(), before.0.doc.as_ref());
|
||||
assert_eq!(s.doc().unwrap().selection, before.0.selection);
|
||||
assert!(s.doc().unwrap().revision > revision);
|
||||
assert!(Arc::ptr_eq(&s.doc().unwrap().saved_doc, &before.0.saved_doc));
|
||||
assert_eq!((s.doc().unwrap().history.undo.len(), s.doc().unwrap().history.redo.len()), (before.0.history.undo.len(), 1));
|
||||
let revision = s.doc().unwrap().revision;
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.as_ref(), changed.0.doc.as_ref());
|
||||
assert_eq!(s.doc().unwrap().selection, changed.0.selection);
|
||||
assert!(s.doc().unwrap().revision > revision);
|
||||
assert_eq!(entries(&s.doc().unwrap().history.undo), entries(&changed.0.history.undo));
|
||||
assert_eq!(entries(&s.doc().unwrap().history.redo), entries(&changed.0.history.redo));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removal_plans_keep_alternate_layouts_and_distinguish_missing_and_existing_sections() {
|
||||
let mut s = fresh();
|
||||
s.execute("layout.section", &json!({"page": 3, "startNumber": 9})).unwrap();
|
||||
let params = json!({"page": 3, "remove": true});
|
||||
let before = snapshot(&s);
|
||||
s.execute("layout.numberingOptions", ¶ms).unwrap();
|
||||
one_edit(&s, &before, ¶ms);
|
||||
assert!(!s.doc().unwrap().doc.sections.iter().any(|section| section.start == 2));
|
||||
let missing = snapshot(&s);
|
||||
s.execute("layout.numberingOptions", ¶ms).unwrap();
|
||||
preserved(&s, &missing, Some(¶ms));
|
||||
let result = s.execute("layout.createAlternate", &json!({"name": "Wide", "width": 900, "height": 600})).unwrap();
|
||||
let page = result["firstPage"].as_u64().unwrap();
|
||||
s.execute("layout.section", &json!({"page": page, "startNumber": 7})).unwrap();
|
||||
let params = json!({"page": page, "remove": true});
|
||||
let before = snapshot(&s);
|
||||
s.execute("layout.numberingOptions", ¶ms).unwrap();
|
||||
one_edit(&s, &before, ¶ms);
|
||||
let section = s.doc().unwrap().doc.sections.iter().find(|section| section.start == (page - 1) as usize).unwrap();
|
||||
assert_eq!(section.layout.as_deref(), Some("Wide"));
|
||||
assert_eq!(section.start_number, None);
|
||||
assert_eq!(s.doc().unwrap().doc.layouts().len(), 2);
|
||||
let kept = snapshot(&s);
|
||||
// These validated but ignored section fields must not fool the remove-layout plan.
|
||||
let params = json!({"page": page, "remove": true, "startNumber": 9, "style": "upperRoman", "prefix": "UNUSED", "marker": "ignored", "includePrefix": true});
|
||||
s.execute("layout.numberingOptions", ¶ms).unwrap();
|
||||
preserved(&s, &kept, Some(¶ms));
|
||||
}
|
||||
|
||||
fn pending_primary_story() -> Session {
|
||||
// Same public native document/story fixture seam used by place_text's autoflow tests.
|
||||
// Explicit page breaks make pending flow independent of an incidental line-wrap count.
|
||||
let mut doc = designcraft_doc::Document::new(&designcraft_doc::build::NewDocument {
|
||||
pages: 1,
|
||||
facing_pages: false,
|
||||
primary_text_frame: true,
|
||||
..Default::default()
|
||||
});
|
||||
let story = doc.settings.primary_story.unwrap();
|
||||
doc.story_mut(story).unwrap().insert(0, &format!("First{}Second{}Third", designcraft_doc::PAGE_BREAK, designcraft_doc::PAGE_BREAK));
|
||||
let mut s = Session::new();
|
||||
s.add_document(DocState::new(doc, None));
|
||||
s.execute("prefs.set", &json!({"smartTextReflow": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.page_count(), 1);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
assert!(s.cache.get(&s.doc().unwrap().doc, story, None).overset_at.is_some(), "a legal loaded/pending primary story really needs reflow");
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_primary_story_noop_preserves_identity_but_real_numbering_change_keeps_postpasses() {
|
||||
let mut s = pending_primary_story();
|
||||
let before = snapshot(&s);
|
||||
let params = json!({"page": 1});
|
||||
s.execute("layout.numberingOptions", ¶ms).unwrap();
|
||||
preserved(&s, &before, Some(¶ms));
|
||||
let story = s.doc().unwrap().doc.settings.primary_story.unwrap();
|
||||
assert!(s.cache.get(&s.doc().unwrap().doc, story, None).overset_at.is_some(), "a no-op does not secretly settle the pending story");
|
||||
let real_before = snapshot(&s);
|
||||
let params = json!({"page": 1, "startNumber": 2});
|
||||
s.execute("layout.numberingOptions", ¶ms).unwrap();
|
||||
one_edit(&s, &real_before, ¶ms);
|
||||
assert!(s.doc().unwrap().doc.page_count() > 1, "genuine numbering changes still run ordinary smart reflow");
|
||||
assert!(s.cache.get(&s.doc().unwrap().doc, story, None).overset_at.is_none());
|
||||
let changed = snapshot(&s);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.as_ref(), before.0.doc.as_ref());
|
||||
assert_eq!(s.doc().unwrap().selection, before.0.selection);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.as_ref(), changed.0.doc.as_ref());
|
||||
assert_eq!(s.doc().unwrap().selection, changed.0.selection);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_unchanged_commands_retain_their_existing_edit_and_postpass_policy() {
|
||||
for (id, params) in [
|
||||
("layout.chapterNumbering", json!({"source": "automatic"})),
|
||||
// Its empty-object handler does NOT edit or replace the document Arc.
|
||||
// Default success passes must still run, unlike the numbering opt-in.
|
||||
("document.preferences", json!({})),
|
||||
] {
|
||||
let mut s = pending_primary_story();
|
||||
let before = snapshot(&s);
|
||||
s.execute(id, ¶ms).unwrap();
|
||||
assert!(s.doc().unwrap().doc.page_count() > 1);
|
||||
assert!(!Arc::ptr_eq(&s.doc().unwrap().doc, &before.0.doc));
|
||||
assert!(s.doc().unwrap().revision > before.0.revision);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.0.history.undo.len() + 1);
|
||||
assert_eq!(s.journal.len(), before.1.len() + 1);
|
||||
assert_eq!(s.journal.last().unwrap(), &(id.to_owned(), params));
|
||||
assert!(Arc::ptr_eq(&s.doc().unwrap().saved_doc, &before.0.saved_doc));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.as_ref(), before.0.doc.as_ref());
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_caption() -> (Session, designcraft_doc::ItemId, designcraft_doc::StoryId) {
|
||||
let mut source = Session::new();
|
||||
source.execute("file.new", &json!({"pages": 1})).unwrap();
|
||||
let item = source.execute("frame.create", &json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap();
|
||||
source.execute("object.altText", &json!({"text": "First", "ids": [item]})).unwrap();
|
||||
let caption =
|
||||
source.execute("object.caption", &json!({"ids": [item], "text": "Photo: {altText}", "live": true})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let caption = designcraft_doc::ItemId(caption);
|
||||
let mut loaded = (*source.doc().unwrap().doc).clone();
|
||||
// A legal persisted/native model with stale dependent text, not a synthetic engine flag.
|
||||
// Native opening/add_document leaves the stored geometry/text intact until an edit.
|
||||
loaded.item_mut(designcraft_doc::ItemId(item)).unwrap().alt_text = "Second\nThird\nFourth\nFifth\nSixth".into();
|
||||
let frame = loaded.item_mut(caption).unwrap().text_frame_mut().unwrap();
|
||||
frame.options.auto_size = designcraft_doc::AutoSize::HeightOnly;
|
||||
let story = frame.story;
|
||||
loaded.check().unwrap();
|
||||
let mut s = Session::new();
|
||||
s.add_document(DocState::new(loaded, None));
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
assert_eq!(s.doc().unwrap().doc.story(story).unwrap().text, "Photo: First");
|
||||
(s, caption, story)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legal_pending_caption_and_dependent_autosize_are_quiet_only_for_numbering_noops() {
|
||||
for (id, params) in [
|
||||
("layout.numberingOptions", json!({"page": 1, "startNumber": 2})),
|
||||
("layout.chapterNumbering", json!({"source": "automatic"})),
|
||||
("document.preferences", json!({})),
|
||||
] {
|
||||
let genuine = id == "layout.numberingOptions";
|
||||
let (mut s, caption, story) = pending_caption();
|
||||
let before = snapshot(&s);
|
||||
let noop = json!({"page": 1});
|
||||
s.execute("layout.numberingOptions", &noop).unwrap();
|
||||
preserved(&s, &before, Some(&noop));
|
||||
assert_eq!(s.doc().unwrap().doc.item(caption).unwrap().bounds(), before.0.doc.item(caption).unwrap().bounds());
|
||||
let before_real = snapshot(&s);
|
||||
s.execute(id, ¶ms).unwrap();
|
||||
if genuine {
|
||||
one_edit(&s, &before_real, ¶ms);
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc.story(story).unwrap().text, "Photo: Second\nThird\nFourth\nFifth\nSixth");
|
||||
assert!(
|
||||
s.doc().unwrap().doc.item(caption).unwrap().bounds().height() > before_real.0.doc.item(caption).unwrap().bounds().height(),
|
||||
"the original caption->autosize ordering remains effective"
|
||||
);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before_real.0.history.undo.len() + 1);
|
||||
assert_eq!(s.journal.last().unwrap(), &(id.to_owned(), params));
|
||||
assert_eq!(s.journal.len(), before_real.1.len() + 1);
|
||||
assert!(Arc::ptr_eq(&s.doc().unwrap().saved_doc, &before_real.0.saved_doc));
|
||||
assert!(s.doc().unwrap().is_dirty());
|
||||
let accepted = snapshot(&s);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.as_ref(), before_real.0.doc.as_ref());
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.as_ref(), accepted.0.doc.as_ref());
|
||||
}
|
||||
}
|
||||
|
||||
fn preview_fixture() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"pages": 1})).unwrap();
|
||||
s.execute("data.source.select", &json!({"bytes": crate::cmd::base64_encode(b"Name\nAda\nGrace\nKatherine\n"), "name": "people.csv"}))
|
||||
.unwrap();
|
||||
s.execute("data.preview", &json!({"record": 2})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().preview_record, Some(2));
|
||||
assert!(s.doc().unwrap().preview_stash.is_some());
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legal_preview_noop_is_quiet_while_real_default_and_invalid_attempts_keep_legacy_prelude() {
|
||||
let mut s = preview_fixture();
|
||||
let before = snapshot(&s);
|
||||
let template = before.0.preview_stash.as_ref().unwrap().clone();
|
||||
let params = json!({"page": 1});
|
||||
s.execute("layout.numberingOptions", ¶ms).unwrap();
|
||||
preserved(&s, &before, Some(¶ms));
|
||||
assert_eq!(s.doc().unwrap().preview_record, before.0.preview_record);
|
||||
assert!(Arc::ptr_eq(s.doc().unwrap().preview_stash.as_ref().unwrap(), &template));
|
||||
for (id, params, refused) in [
|
||||
("layout.numberingOptions", json!({"page": 1, "startNumber": 2}), false),
|
||||
("layout.chapterNumbering", json!({"source": "automatic"}), false),
|
||||
("layout.numberingOptions", json!({"page": 1, "chapter": {"source": "invalid"}}), true),
|
||||
] {
|
||||
let mut s = preview_fixture();
|
||||
let before = snapshot(&s);
|
||||
let template = before.0.preview_stash.as_ref().unwrap().clone();
|
||||
let result = s.execute(id, ¶ms);
|
||||
assert_eq!(result.is_err(), refused);
|
||||
assert!(s.doc().unwrap().preview_stash.is_none());
|
||||
assert_eq!(s.doc().unwrap().preview_record, None);
|
||||
assert!(s.doc().unwrap().revision > before.0.revision);
|
||||
assert!(Arc::ptr_eq(&s.doc().unwrap().saved_doc, &before.0.saved_doc));
|
||||
if refused {
|
||||
assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &template));
|
||||
assert_eq!(s.doc().unwrap().selection, before.0.selection);
|
||||
assert_eq!(entries(&s.doc().unwrap().history.undo), entries(&before.0.history.undo));
|
||||
assert_eq!(entries(&s.doc().unwrap().history.redo), entries(&before.0.history.redo));
|
||||
assert_eq!(s.doc().unwrap().history.limit, before.0.history.limit);
|
||||
assert_eq!(s.journal, before.1);
|
||||
} else {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.0.history.undo.len() + 1);
|
||||
assert_eq!(s.journal.len(), before.1.len() + 1);
|
||||
assert_eq!(s.journal.last().unwrap(), &(id.to_owned(), params));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.as_ref(), template.as_ref(), "the undo target is the template, never a preview");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn composing_fixture() -> (Session, designcraft_doc::StoryId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"pages": 1})).unwrap();
|
||||
let story = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap()["story"].as_u64().unwrap();
|
||||
s.set_tool("type");
|
||||
s.tool_preedit("Marked", Some(0..6), crate::ViewInfo::default()).unwrap();
|
||||
assert!(s.tool_composing());
|
||||
(s, designcraft_doc::StoryId(story))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legal_composition_noop_is_quiet_while_real_default_and_invalid_attempts_keep_legacy_prelude() {
|
||||
let (mut s, story) = composing_fixture();
|
||||
let before = snapshot(&s);
|
||||
let params = json!({"page": 1});
|
||||
s.execute("layout.numberingOptions", ¶ms).unwrap();
|
||||
preserved(&s, &before, Some(¶ms));
|
||||
assert!(s.tool_composing());
|
||||
assert!(s.doc().unwrap().interaction.is_some());
|
||||
assert_eq!(s.doc().unwrap().doc.story(story).unwrap().text, "Marked");
|
||||
s.tool_ime_commit("Committed", crate::ViewInfo::default()).unwrap();
|
||||
assert!(!s.tool_composing());
|
||||
assert_eq!(s.doc().unwrap().doc.story(story).unwrap().text, "Committed");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.0.history.undo.len() + 1);
|
||||
assert_eq!(s.journal.len(), before.1.len() + 2, "one numbering attempt plus the later independent IME commit");
|
||||
for (id, params, refused) in [
|
||||
("layout.numberingOptions", json!({"page": 1, "startNumber": 2}), false),
|
||||
("layout.chapterNumbering", json!({"source": "automatic"}), false),
|
||||
("layout.numberingOptions", json!({"page": 1, "chapter": {"source": "invalid"}}), true),
|
||||
] {
|
||||
let (mut s, story) = composing_fixture();
|
||||
let before = snapshot(&s);
|
||||
let result = s.execute(id, ¶ms);
|
||||
assert_eq!(result.is_err(), refused);
|
||||
assert!(!s.tool_composing(), "non-noop and invalid attempts retain the original composition commit prelude");
|
||||
assert!(s.doc().unwrap().interaction.is_none());
|
||||
assert_eq!(s.doc().unwrap().doc.story(story).unwrap().text, "Marked");
|
||||
assert!(Arc::ptr_eq(&s.doc().unwrap().saved_doc, &before.0.saved_doc));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.0.history.undo.len() + if refused { 1 } else { 2 });
|
||||
assert_eq!(s.journal.len(), before.1.len() + if refused { 1 } else { 2 });
|
||||
assert_eq!(s.journal[before.1.len()], ("text.insert".to_owned(), json!({"text": "Marked"})));
|
||||
if !refused {
|
||||
assert_eq!(s.journal.last().unwrap(), &(id.to_owned(), params));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
s.doc().unwrap().doc.story(story).unwrap().text,
|
||||
"Marked",
|
||||
"numbering is one atomic step after the separate prelude commit"
|
||||
);
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.story(story).unwrap().text, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,8 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = it.id;
|
||||
d.insert_item(spread, it, None)?;
|
||||
sel.items = vec![id];
|
||||
sel.text = None;
|
||||
sel.anchored = None;
|
||||
Ok(json!({"id": id.0}))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -72,6 +72,7 @@ pub(crate) fn place_media(s: &mut Session, p: &Value, asset: Asset) -> Result<Va
|
||||
};
|
||||
sel.items = vec![id];
|
||||
sel.text = None;
|
||||
sel.anchored = None;
|
||||
Ok(json!({"id": id.0, "asset": aid.0, "media": true}))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6,13 +6,16 @@ use std::sync::Arc;
|
||||
|
||||
use designcraft_color::BlendMode;
|
||||
use designcraft_doc::{
|
||||
AssetId, Content, Document, Effects, Fill, Item, ItemId, ItemLoc, ParaFormat, Selection, Shape, SpreadRef, Story, StoryId, Stroke, TextFrame,
|
||||
TextFrameOptions, TextSel,
|
||||
AssetId, Content, Document, Effects, Fill, Guide, GuideSel, Item, ItemId, ItemLoc, Orientation, ParaFormat, Selection, Shape, SpreadRef, Story,
|
||||
StoryId, Stroke, TextFrame, TextFrameOptions, TextSel,
|
||||
};
|
||||
use designcraft_geom::{Affine, Point, Rect, Vec2, shapes};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, bad, bool_or, cmd, f64_or, has_doc, has_selection, ok, point_param, rect_param, spread_param, str_param, targets};
|
||||
use super::{
|
||||
CommandSpec, bad, bool_or, cmd, f64_or, has_doc, has_selection, has_selection_or_guides, ok, point_param, rect_param, spread_param, str_param,
|
||||
targets,
|
||||
};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// `name` must be a swatch of the document: an unknown name would paint nothing. The error names
|
||||
@@ -736,8 +739,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Step and Repeat…",
|
||||
["Edit"],
|
||||
Some("Cmd+Alt+U"),
|
||||
"{count?: 1..1000, dx?, dy?, rows?, columns?, ids?} — copies of the selection (or ids) offset by (dx, dy); with rows/columns, a grid of at most 1000 cells, and at most 1000 item copies including group contents → {created, ids: the copies}",
|
||||
has_selection,
|
||||
"{count?: 1..1000, dx?, dy?, rows?, columns?, ids?} — copies of the selection (or ids) offset by (dx, dy); a selected ruler guide is copied by `dx` when vertical and by `dy` when horizontal (the other offset is ignored, each distance once so a grid never stacks two copies on one spot, copies stay within 1000000 pt of the spread origin) → {created, guides: [{spread: {kind, index}, page, index}]}; with rows/columns, a grid of at most 1000 cells, and at most 1000 item copies including group contents → {created, ids: the copies}",
|
||||
has_selection_or_guides,
|
||||
step_and_repeat
|
||||
),
|
||||
cmd!("path.create", "Create Path", [], None, "{spread?, anchors: [{p:[x,y], in?:[x,y], out?:[x,y]}], closed?: bool}", has_doc, path_create),
|
||||
@@ -4253,6 +4256,63 @@ fn checked_step_offset(dx: f64, dy: f64, x: u64, y: u64) -> Result<Vec2> {
|
||||
Ok(Vec2::new(x, y))
|
||||
}
|
||||
|
||||
/// Copies the selected ruler guides by `offsets`, moving a vertical guide by the offsets' x and a
|
||||
/// horizontal one by their y, ignoring the other. A shift already made for a guide is not made again,
|
||||
/// so grid cells never stack copies. `None` when nothing is selected but objects, so the object path
|
||||
/// reports it.
|
||||
fn step_and_repeat_guides(s: &mut Session, offsets: &[Vec2]) -> Result<Option<Value>> {
|
||||
let picked = s.doc()?.selection.guides.clone();
|
||||
if picked.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
picked
|
||||
.len()
|
||||
.checked_mul(offsets.len())
|
||||
.filter(|work| *work <= MAX_STEP_REPEAT_WORK)
|
||||
.ok_or_else(|| bad("edit.stepAndRepeat", format!("a single command may create at most {MAX_STEP_REPEAT_WORK} guides")))?;
|
||||
let src = s.doc()?.doc.clone();
|
||||
let mut plan = Vec::with_capacity(picked.len());
|
||||
for g in &picked {
|
||||
let page = src.spread(g.spread).and_then(|sp| sp.pages.get(g.page)).ok_or_else(|| bad("edit.stepAndRepeat", "a selected guide is gone"))?;
|
||||
let guide = page.guides.get(g.index).ok_or_else(|| bad("edit.stepAndRepeat", "a selected guide is gone"))?.clone();
|
||||
plan.push((*g, guide));
|
||||
}
|
||||
s.edit(|d, sel| {
|
||||
let mut made = Vec::new();
|
||||
for (at, guide) in &plan {
|
||||
let sp = d.spread_mut(at.spread).ok_or_else(|| bad("edit.stepAndRepeat", "no such spread"))?;
|
||||
let pg = sp.pages.get_mut(at.page).ok_or_else(|| bad("edit.stepAndRepeat", "no such page"))?;
|
||||
let mut shifts: Vec<f64> = Vec::new();
|
||||
for off in offsets {
|
||||
let shift = match guide.orientation {
|
||||
Orientation::Horizontal => off.y,
|
||||
Orientation::Vertical => off.x,
|
||||
};
|
||||
if shift == 0.0 || shifts.contains(&shift) {
|
||||
continue;
|
||||
}
|
||||
shifts.push(shift);
|
||||
let index = pg.guides.len();
|
||||
let position = super::guides::guide_position(guide.position + shift, "edit.stepAndRepeat")?;
|
||||
pg.guides.push(Guide { position, ..guide.clone() });
|
||||
made.push(GuideSel { spread: at.spread, page: at.page, index });
|
||||
}
|
||||
}
|
||||
if made.is_empty() {
|
||||
return Err(bad(
|
||||
"edit.stepAndRepeat",
|
||||
"the offsets do not move the guide along its own axis: a horizontal guide takes `dy`, a vertical one `dx`",
|
||||
));
|
||||
}
|
||||
let mut all = picked.clone();
|
||||
all.extend(made.iter().copied());
|
||||
*sel = Selection { guides: all, ..Default::default() };
|
||||
let out: Vec<Value> = made.iter().map(|g| json!({"spread": g.spread, "page": g.page, "index": g.index})).collect();
|
||||
Ok(json!({"created": out.len(), "guides": out}))
|
||||
})
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
fn step_repeat_offsets(p: &Value) -> Result<Vec<Vec2>> {
|
||||
let (dx, dy) = (step_repeat_delta(p, "dx", 12.0)?, step_repeat_delta(p, "dy", 12.0)?);
|
||||
match (p.get("rows"), p.get("columns")) {
|
||||
@@ -4329,6 +4389,15 @@ fn checked_step_repeat_targets(d: &Document, ids: &[ItemId], copies: usize, max_
|
||||
fn step_and_repeat(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = targets(s, p)?;
|
||||
let offsets = step_repeat_offsets(p)?;
|
||||
// No object was named and none is selected: a ruler guide may be, and it repeats across
|
||||
// its own line — a horizontal guide only takes `dy`, a vertical one only `dx`.
|
||||
if ids.is_empty()
|
||||
&& p.get("id").is_none()
|
||||
&& p.get("ids").is_none()
|
||||
&& let Some(out) = step_and_repeat_guides(s, &offsets)?
|
||||
{
|
||||
return Ok(out);
|
||||
}
|
||||
let ids = checked_step_repeat_targets(&s.doc()?.doc, &ids, offsets.len(), MAX_STEP_REPEAT_WORK)?;
|
||||
s.edit(|d, sel| {
|
||||
let src = d.clone();
|
||||
@@ -4834,6 +4903,55 @@ mod step_repeat_tests {
|
||||
assert!(s.execute("object.swapFillStroke", &json!({})).is_err(), "nothing unlocked to change");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_guide_repeats_along_its_own_axis() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let positions = |s: &Session, o: Orientation| -> Vec<f64> {
|
||||
s.doc().unwrap().doc.spreads[0].pages[0].guides.iter().filter(|g| g.orientation == o).map(|g| g.position).collect()
|
||||
};
|
||||
s.execute("guide.add", &json!({"orientation": "vertical", "position": 100.0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.guides.len(), 1, "a new guide is selected, as in InDesign");
|
||||
let r = s.execute("edit.stepAndRepeat", &json!({"count": 2, "dx": 30.0, "dy": 999.0})).unwrap();
|
||||
assert_eq!(r["created"], 2);
|
||||
assert_eq!(
|
||||
r["guides"][0],
|
||||
json!({"spread": {"kind": "doc", "index": 0}, "page": 0, "index": 1}),
|
||||
"a copy says which spread, page and index it went into"
|
||||
);
|
||||
assert_eq!(positions(&s, Orientation::Vertical), vec![100.0, 130.0, 160.0], "a vertical guide takes `dx` and ignores `dy`");
|
||||
assert_eq!(s.doc().unwrap().selection.guides.len(), 3, "the guide and its copies stay selected");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(positions(&s, Orientation::Vertical), vec![100.0], "one undo step");
|
||||
|
||||
s.execute("guide.add", &json!({"orientation": "horizontal", "position": 50.0})).unwrap();
|
||||
let r = s.execute("edit.stepAndRepeat", &json!({"rows": 2, "columns": 2, "dx": 99.0, "dy": 25.0})).unwrap();
|
||||
assert_eq!(r["created"], 1, "cells that only move across the guide, or repeat a shift already made, are skipped");
|
||||
assert_eq!(positions(&s, Orientation::Horizontal), vec![50.0, 75.0], "a horizontal guide takes `dy`, each distance once");
|
||||
|
||||
// An offset that does not move the guide at all is refused rather than stacking a copy on it.
|
||||
s.execute("guide.add", &json!({"orientation": "vertical", "position": 7.0})).unwrap();
|
||||
assert!(s.execute("edit.stepAndRepeat", &json!({"count": 3, "dx": 0.0, "dy": 10.0})).is_err());
|
||||
assert_eq!(positions(&s, Orientation::Vertical), vec![100.0, 7.0]);
|
||||
|
||||
// A copy of a spread guide stays a spread guide.
|
||||
s.execute("guide.add", &json!({"orientation": "vertical", "position": 5.0, "spreadGuide": true})).unwrap();
|
||||
s.execute("edit.stepAndRepeat", &json!({"count": 1, "dx": 5.0})).unwrap();
|
||||
let copies: Vec<bool> =
|
||||
s.doc().unwrap().doc.spreads[0].pages[0].guides.iter().filter(|g| g.position == 5.0 || g.position == 10.0).map(|g| g.spread).collect();
|
||||
assert_eq!(copies, vec![true, true]);
|
||||
|
||||
// Naming objects keeps the object path: a guide selected beside them is left where it is.
|
||||
let frame = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap();
|
||||
let before = s.doc().unwrap().doc.spreads[0].pages[0].guides.len();
|
||||
assert_eq!(s.execute("edit.stepAndRepeat", &json!({"ids": [frame], "count": 1, "dx": 20.0})).unwrap()["created"], 1);
|
||||
assert_eq!(s.doc().unwrap().doc.spreads[0].pages[0].guides.len(), before, "the selected guide is untouched");
|
||||
s.execute("guide.add", &json!({"orientation": "vertical", "position": 999_990.0})).unwrap();
|
||||
let antes = positions(&s, Orientation::Vertical);
|
||||
assert!(s.execute("edit.stepAndRepeat", &json!({"count": 2, "dx": 10.0})).is_err(), "a copy past the guide range is refused");
|
||||
assert_eq!(positions(&s, Orientation::Vertical), antes, "the first copy fitted and the second did not: neither is left behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn step_repeat_validates_counts_and_offsets() {
|
||||
assert_eq!(step_repeat_offsets(&json!({"count": MAX_STEP_REPEAT_COPIES})).unwrap().len(), MAX_STEP_REPEAT_COPIES as usize);
|
||||
|
||||
@@ -590,6 +590,8 @@ fn CharProps_to_attrs(p: &designcraft_doc::CharProps) -> CharAttrs {
|
||||
designcraft_doc::CharProps::common([p])
|
||||
}
|
||||
|
||||
/// `style.paragraph.edit`: change a paragraph style's attributes, based-on, next style or name;
|
||||
/// a rename follows the style into every use.
|
||||
pub(super) fn edit_para(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_param(p, "name").ok_or_else(|| bad("style.paragraph.edit", "missing name"))?.to_string();
|
||||
let chars: CharAttrs = attrs("style.paragraph.edit", "chars", p, |a: &mut CharAttrs, k, v| a.set_json(k, v))?;
|
||||
@@ -661,7 +663,7 @@ pub(super) fn edit_para(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => {}
|
||||
}
|
||||
if let Some(n) = rename.clone() {
|
||||
// Every use: other styles, stories, table cells, footnotes, object styles.
|
||||
// Every use: other styles, stories, table cells, footnotes, object styles, running headers.
|
||||
rename_style(d, true, &name, &n);
|
||||
}
|
||||
ok()
|
||||
@@ -779,14 +781,30 @@ fn redirect_style_refs(d: &mut designcraft_doc::Document, para: bool, from: &str
|
||||
st.rev = st.rev.wrapping_add(1);
|
||||
});
|
||||
}
|
||||
rename_running_headers(d, para, from, to);
|
||||
}
|
||||
|
||||
/// Point the nested, nested line and GREP styles, and the drop cap style, of paragraph
|
||||
/// attributes at a renamed (or deleted, pointed at its replacement) character style.
|
||||
/// Point the Running Header variables that pick up paragraph (`para`) or character style `from`
|
||||
/// at `to`. A variable of the other kind keeps its style, even under the same name.
|
||||
fn rename_running_headers(d: &mut designcraft_doc::Document, para: bool, from: &str, to: &str) {
|
||||
for v in &mut d.text_variables {
|
||||
if let designcraft_doc::vars::VarKind::RunningHeader { style, character, .. } = &mut v.kind
|
||||
&& *character != para
|
||||
&& style == from
|
||||
{
|
||||
*style = to.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Point the nested, nested line and GREP styles, the drop cap style, and the bullet and number
|
||||
/// character styles, of paragraph attributes at a renamed (or deleted, pointed at its
|
||||
/// replacement) character style.
|
||||
fn rename_char_refs(p: &mut ParaAttrs, from: &str, to: &str) {
|
||||
let names = p.nested_styles.iter_mut().flatten().map(|n| &mut n.style);
|
||||
let names = names.chain(p.nested_line_styles.iter_mut().flatten().map(|n| &mut n.style));
|
||||
let names = names.chain(p.drop_cap_style.iter_mut());
|
||||
let names = names.chain(p.bullet_char_style.iter_mut().chain(p.number_char_style.iter_mut()));
|
||||
for n in names.chain(p.grep_styles.iter_mut().flatten().map(|g| &mut g.style)) {
|
||||
if n == from {
|
||||
*n = to.to_string();
|
||||
@@ -885,7 +903,7 @@ fn delete_style(s: &mut Session, p: &Value, para: bool) -> Result<Value> {
|
||||
}
|
||||
// The replacement keeps its own Export Tagging.
|
||||
st.export_tags.remove(&export_tag_key(para, &name));
|
||||
// Every other use: styles, stories, table cells, nested and GREP styles, notes, defaults.
|
||||
// Every other use: styles, stories, table cells, nested and GREP styles, notes, defaults, list labels, running headers.
|
||||
redirect_style_refs(d, para, &name, &repl);
|
||||
ok()
|
||||
})
|
||||
@@ -927,6 +945,8 @@ pub(super) fn create_char(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// `style.character.edit`: change a character style's attributes, based-on or name; a rename
|
||||
/// follows the style into every use.
|
||||
pub(super) fn edit_char(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_param(p, "name").ok_or_else(|| bad("style.character.edit", "missing name"))?.to_string();
|
||||
if name == designcraft_doc::NO_CHAR_STYLE {
|
||||
@@ -974,7 +994,7 @@ pub(super) fn edit_char(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.based_on = b;
|
||||
}
|
||||
if let Some(n) = &rename {
|
||||
// Every use: other styles, stories, table cells, nested and GREP styles, footnotes.
|
||||
// Every use: other styles, stories, table cells, nested and GREP styles, list labels, footnotes, running headers.
|
||||
rename_style(d, false, &name, n);
|
||||
}
|
||||
ok()
|
||||
@@ -1162,6 +1182,7 @@ mod cjk_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod delete_tests {
|
||||
use designcraft_doc::vars::{TextVariable, VarKind};
|
||||
use designcraft_doc::{CellStyle, ObjectStyle, StoryId, Toc, TocEntry};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -1172,6 +1193,26 @@ mod delete_tests {
|
||||
serde_json::to_string(&*s.doc().unwrap().doc).unwrap().contains(&format!("\"{name}\""))
|
||||
}
|
||||
|
||||
/// The style the Running Header variable `name` picks up, and whether it's a character style.
|
||||
fn header(s: &Session, name: &str) -> (String, bool) {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
match &d.text_variables[d.variable(name).unwrap()].kind {
|
||||
VarKind::RunningHeader { style, character, .. } => (style.clone(), *character),
|
||||
k => panic!("`{name}` is {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the Running Header variable `name` shows on the first page.
|
||||
fn header_text(s: &Session, name: &str) -> String {
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let values = designcraft_compose::vars::values(&d, Some(0), Some(&s.cache.running_index(&d)));
|
||||
values[d.variable(name).unwrap()].clone()
|
||||
}
|
||||
|
||||
/// A document whose character style `Emphasis` is used everywhere one can be: as a based-on
|
||||
/// parent, on text, in a paragraph style's and a paragraph's nested, nested line, GREP, drop
|
||||
/// cap, bullet and number styles, as the footnote reference style, the default character
|
||||
/// style and a character Running Header. Returns the session and the text's story.
|
||||
fn char_doc() -> (Session, u64) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
@@ -1183,9 +1224,11 @@ mod delete_tests {
|
||||
"nestedStyles": [{"style": "Emphasis", "through": true, "count": 1, "until": {"kind": "words"}}],
|
||||
"grepStyles": [{"style": "Emphasis", "pattern": "\\d+"}],
|
||||
"nestedLineStyles": [{"style": "Emphasis", "lines": 1}],
|
||||
"dropCapLines": 2, "dropCapChars": 1, "dropCapStyle": "Emphasis"});
|
||||
"dropCapLines": 2, "dropCapChars": 1, "dropCapStyle": "Emphasis",
|
||||
"listType": "bullets", "bulletCharStyle": "Emphasis", "numberCharStyle": "Emphasis"});
|
||||
s.execute("style.paragraph.create", &json!({"name": "Lead", "para": refs})).unwrap();
|
||||
s.execute("footnote.options", &json!({"refCharStyle": "Emphasis"})).unwrap();
|
||||
s.execute("variables.define", &json!({"name": "Term", "type": "runningHeader", "style": "Emphasis", "character": true})).unwrap();
|
||||
let sid = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hi there"})).unwrap()["story"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
@@ -1216,6 +1259,10 @@ mod delete_tests {
|
||||
assert_eq!(lead.grep_styles.as_ref().unwrap()[0].style, "Strong");
|
||||
assert_eq!(lead.nested_line_styles.as_ref().unwrap()[0].style, "Strong");
|
||||
assert_eq!(lead.drop_cap_style.as_deref(), Some("Strong"));
|
||||
assert_eq!((lead.bullet_char_style.as_deref(), lead.number_char_style.as_deref()), (Some("Strong"), Some("Strong")));
|
||||
let local = &d.story(StoryId(sid)).unwrap().paras[0].para;
|
||||
assert_eq!((local.bullet_char_style.as_deref(), local.number_char_style.as_deref()), (Some("Strong"), Some("Strong")));
|
||||
assert_eq!(header(&s, "Term"), ("Strong".into(), true));
|
||||
assert_eq!(d.footnote_options.ref_char_style, "Strong");
|
||||
assert_eq!(d.styles.default_character, "Strong");
|
||||
// One undo step brings the style and every use back.
|
||||
@@ -1223,16 +1270,29 @@ mod delete_tests {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.styles.char_style("Emphasis").is_some());
|
||||
assert_eq!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().chars[0].format.style, "Emphasis");
|
||||
assert_eq!(header(&s, "Term"), ("Emphasis".into(), true));
|
||||
assert_eq!(s.doc().unwrap().doc.styles.para("Lead").unwrap().para.bullet_char_style.as_deref(), Some("Emphasis"));
|
||||
}
|
||||
|
||||
/// Deleting with no replacement points every use at `[None]`, a character Running Header too,
|
||||
/// as InDesign does. Such a header then picks up text with no character style, as one defined
|
||||
/// with `[None]` does in InDesign: a Last on Page header that showed the styled `Hi` now shows
|
||||
/// the unstyled `there` after it.
|
||||
#[test]
|
||||
fn deleting_a_character_style_for_none_unsets_based_on() {
|
||||
let (mut s, _) = char_doc();
|
||||
let last = json!({"name": "Last", "type": "runningHeader", "style": "Emphasis", "character": true, "use": "lastOnPage"});
|
||||
s.execute("variables.define", &last).unwrap();
|
||||
assert_eq!((header_text(&s, "Term"), header_text(&s, "Last")), ("Hi".into(), "Hi".into()));
|
||||
s.execute("style.character.delete", &json!({"name": "Emphasis"})).unwrap();
|
||||
assert_eq!(header_text(&s, "Last"), "there", "the header shows the last unstyled text on the page");
|
||||
assert!(!named(&s, "Emphasis"), "no dangling reference");
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
assert_eq!(d.styles.char_style("Child").unwrap().based_on, None);
|
||||
assert_eq!(d.footnote_options.ref_char_style, designcraft_doc::NO_CHAR_STYLE);
|
||||
let lead = &d.styles.para("Lead").unwrap().para;
|
||||
assert_eq!(lead.bullet_char_style.as_deref(), Some(designcraft_doc::NO_CHAR_STYLE));
|
||||
assert_eq!(header(&s, "Term"), (designcraft_doc::NO_CHAR_STYLE.into(), true));
|
||||
}
|
||||
|
||||
/// Replacing a style with its own descendant rebases the deleted style's children on its
|
||||
@@ -1290,6 +1350,8 @@ mod delete_tests {
|
||||
d.endnote_options.para_style = "Table Body".into();
|
||||
d.endnote_options.heading_style = "Table Body".into();
|
||||
d.settings.epub_split = designcraft_doc::EpubSplit::Style("Table Body".into());
|
||||
let kind = VarKind::RunningHeader { style: "Table Body".into(), use_: Default::default(), character: false };
|
||||
d.text_variables.push(TextVariable::new("Section", kind));
|
||||
d.toc = Some(Toc {
|
||||
story,
|
||||
title: "Contents".into(),
|
||||
@@ -1310,9 +1372,71 @@ mod delete_tests {
|
||||
assert_eq!(d.styles.default_paragraph, "Body");
|
||||
assert_eq!(d.endnote_options.heading_style, "Body");
|
||||
assert_eq!(d.settings.epub_split, designcraft_doc::EpubSplit::Style("Body".into()), "EPUB Split Document follows the replacement");
|
||||
assert_eq!(header(&s, "Section"), ("Body".into(), false));
|
||||
let after = s.execute("preflight.run", &json!({})).unwrap();
|
||||
assert!(!after.to_string().contains("Table Body"), "{after}");
|
||||
}
|
||||
|
||||
/// #1794: a rename moves the Running Headers of the style's kind (only those: a paragraph and a
|
||||
/// character style can share a name) and the bullet and number character styles, of styles
|
||||
/// and of local paragraph formatting. The headers still show their text on the page and the
|
||||
/// labels keep their style's size; one undo each puts the old names back.
|
||||
#[test]
|
||||
fn renaming_a_style_moves_running_headers_and_list_label_styles() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("style.paragraph.create", &json!({"name": "Chapter"})).unwrap();
|
||||
s.execute("style.character.create", &json!({"name": "Dot", "chars": {"size": 30}})).unwrap();
|
||||
s.execute("style.paragraph.create", &json!({"name": "Item", "para": {"listType": "bullets", "bulletCharStyle": "Dot"}})).unwrap();
|
||||
let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Origins\nFirst\nSecond"})).unwrap();
|
||||
let sid = r["story"].as_u64().unwrap();
|
||||
let select = |s: &mut Session, anchor: usize, focus: usize| {
|
||||
s.execute("text.select", &json!({"story": sid, "anchor": anchor, "focus": focus})).unwrap();
|
||||
};
|
||||
select(&mut s, 0, 0);
|
||||
s.execute("style.paragraph.apply", &json!({"name": "Chapter"})).unwrap();
|
||||
select(&mut s, 8, 8);
|
||||
s.execute("style.paragraph.apply", &json!({"name": "Item"})).unwrap();
|
||||
select(&mut s, 14, 14);
|
||||
s.execute("type.para", &json!({"attrs": {"listType": "numbers", "numberCharStyle": "Dot"}})).unwrap();
|
||||
select(&mut s, 14, 17);
|
||||
s.execute("style.character.apply", &json!({"name": "Dot"})).unwrap();
|
||||
let vars = [("Chapter Head", "Chapter", false), ("Dot Head", "Dot", true), ("Para Dot", "Dot", false), ("Char Chapter", "Chapter", true)];
|
||||
for (name, style, character) in vars {
|
||||
s.execute("variables.define", &json!({"name": name, "type": "runningHeader", "style": style, "character": character})).unwrap();
|
||||
}
|
||||
// What the four headers show on page 1, and the list labels' (character, size).
|
||||
let shown = |s: &Session| {
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let values = designcraft_compose::vars::values(&d, Some(0), Some(&s.cache.running_index(&d)));
|
||||
let values: Vec<String> = vars.iter().map(|(name, ..)| values[d.variable(name).unwrap()].clone()).collect();
|
||||
let cs = s.cache.get(&d, StoryId(sid), Some(0));
|
||||
let glyphs = cs.frames.iter().flat_map(|f| &f.lines).flat_map(|l| &l.glyphs);
|
||||
let labels = glyphs.filter(|g| g.generated_text.is_some() && g.rendered_char != '\t');
|
||||
let labels: Vec<(char, f64)> = labels.map(|g| (g.rendered_char, cs.styles[g.style as usize].size)).collect();
|
||||
(values, labels)
|
||||
};
|
||||
let before = shown(&s);
|
||||
assert_eq!(before.0, ["Origins", "Sec", "", ""]);
|
||||
assert_eq!(before.1, [('\u{2022}', 30.0), ('1', 30.0), ('.', 30.0)], "the labels are set in Dot");
|
||||
|
||||
s.execute("style.paragraph.edit", &json!({"name": "Chapter", "rename": "Title"})).unwrap();
|
||||
s.execute("style.character.edit", &json!({"name": "Dot", "rename": "Marker"})).unwrap();
|
||||
let headers: Vec<_> = vars.iter().map(|(name, ..)| header(&s, name)).collect();
|
||||
let expect = [("Title", false), ("Marker", true), ("Dot", false), ("Chapter", true)];
|
||||
assert_eq!(headers, expect.map(|(n, c)| (n.to_string(), c)));
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
assert_eq!(d.styles.para("Item").unwrap().para.bullet_char_style.as_deref(), Some("Marker"));
|
||||
assert_eq!(d.story(StoryId(sid)).unwrap().paras[2].para.number_char_style.as_deref(), Some("Marker"));
|
||||
assert_eq!(shown(&s), before, "the headers and labels look as they did");
|
||||
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let headers: Vec<_> = vars.iter().map(|(name, ..)| header(&s, name)).collect();
|
||||
assert_eq!(headers, vars.map(|(_, style, c)| (style.to_string(), c)));
|
||||
assert_eq!(s.doc().unwrap().doc.styles.para("Item").unwrap().para.bullet_char_style.as_deref(), Some("Dot"));
|
||||
assert_eq!(shown(&s), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -131,7 +131,7 @@ fn unit_at(s: &Session, sid: StoryId, cell: Option<CellAddr>, b: usize, unit: &s
|
||||
"word" => word_or_spaces_at(text, b),
|
||||
"line" => {
|
||||
let cs = s.cache.get(&st.doc, sid, None);
|
||||
line_at(&text_composition(cs, cell), b).unwrap_or((b, b))
|
||||
line_at(&text_composition(cs, cell), text, b).unwrap_or((b, b))
|
||||
}
|
||||
// The paragraph with its return (the last paragraph has none).
|
||||
"paragraph" => story.para_ranges().get(story.para_at(b)).map_or((b, b), |r| (r.start, (r.end + 1).min(text.len()))),
|
||||
@@ -141,8 +141,9 @@ fn unit_at(s: &Session, sid: StoryId, cell: Option<CellAddr>, b: usize, unit: &s
|
||||
}
|
||||
|
||||
/// The word at byte `i`; on spaces the run of spaces; on anything else that one character
|
||||
/// (grapheme cluster). At the end of a paragraph, what ends it. Grapheme clusters are never split:
|
||||
/// combining marks, viramas, variation selectors and emoji ZWJ sequences stay with their base.
|
||||
/// (grapheme cluster). At the end of a paragraph, what ends it; on an empty paragraph, its
|
||||
/// return if it has one. Grapheme clusters are never split: combining marks, viramas, variation
|
||||
/// selectors and emoji ZWJ sequences stay with their base.
|
||||
fn word_or_spaces_at(s: &str, i: usize) -> (usize, usize) {
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
let i = floor_char_boundary(s, i.min(s.len()));
|
||||
@@ -150,7 +151,10 @@ fn word_or_spaces_at(s: &str, i: usize) -> (usize, usize) {
|
||||
let ps = s[..i].rfind('\n').map_or(0, |k| k + 1);
|
||||
let pe = s[i..].find('\n').map_or(s.len(), |k| i + k);
|
||||
let g: Vec<(usize, &str)> = s[ps..pe].grapheme_indices(true).collect();
|
||||
let Some(k) = g.iter().rposition(|(o, _)| ps + o <= i) else { return (i, i) };
|
||||
let Some(k) = g.iter().rposition(|(o, _)| ps + o <= i) else {
|
||||
// An empty paragraph has only its return; select it so double-clicking selects the line.
|
||||
return if s.as_bytes().get(i) == Some(&b'\n') { (i, i + 1) } else { (i, i) };
|
||||
};
|
||||
let kind = |c: &str| match c.chars().next() {
|
||||
Some(c) if is_word(c) => 1,
|
||||
Some(c) if c.is_whitespace() => 2,
|
||||
@@ -181,10 +185,11 @@ fn text_composition(cs: std::sync::Arc<compose::ComposedStory>, cell: Option<Cel
|
||||
}
|
||||
}
|
||||
|
||||
/// The composed line holding the character at byte `pos`.
|
||||
fn line_at(cs: &compose::ComposedStory, pos: usize) -> Option<(usize, usize)> {
|
||||
/// The composed line holding the character at byte `pos`, or an empty line's return if it has one.
|
||||
fn line_at(cs: &compose::ComposedStory, text: &str, pos: usize) -> Option<(usize, usize)> {
|
||||
let lines = || cs.frames.iter().flat_map(|f| f.lines.iter());
|
||||
lines().find(|l| l.range.contains(&pos)).map(|l| (l.range.start, l.range.end)).or_else(|| line_of(cs, pos))
|
||||
let (a, e) = lines().find(|l| l.range.contains(&pos)).map(|l| (l.range.start, l.range.end)).or_else(|| line_of(cs, pos))?;
|
||||
Some(if a == e && text.as_bytes().get(e) == Some(&b'\n') { (a, e + 1) } else { (a, e) })
|
||||
}
|
||||
|
||||
pub(super) fn place(s: &mut Session, p: &Value, extend: bool) -> Result<Value> {
|
||||
@@ -545,8 +550,10 @@ mod multi_click_tests {
|
||||
assert_eq!(word(s, 2), e);
|
||||
assert_eq!(word(s, 6), e, "on the joiner");
|
||||
assert_eq!(word(s, s.len() - 1), (s.len() - 6, s.len()), "at the end: the last character whole");
|
||||
// Empty paragraphs select nothing.
|
||||
assert_eq!(word("a\n\nb", 2), (2, 2));
|
||||
// Empty paragraphs select their return when one is present, otherwise nothing.
|
||||
assert_eq!(word("a\n\nb", 2), (2, 3));
|
||||
assert_eq!(word("a\n", 2), (2, 2));
|
||||
assert_eq!(word("", 0), (0, 0));
|
||||
}
|
||||
|
||||
/// Issue #981: holding the button after a double, triple or quadruple click and moving extends
|
||||
@@ -638,6 +645,94 @@ mod multi_click_tests {
|
||||
assert!(s.execute("text.selectAt", &json!({"frame": fid, "point": p, "unit": "sentence"})).is_err());
|
||||
assert!(s.execute("text.selectAt", &json!({"frame": fid, "unit": "word"})).is_err(), "no point");
|
||||
}
|
||||
|
||||
/// Issue #3321: double- or triple-clicking an empty line selects its paragraph return so the
|
||||
/// selection is visible and character formatting such as leading applies to that line.
|
||||
#[test]
|
||||
fn double_and_triple_clicking_an_empty_line_selects_its_return_and_applies_leading() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let text = "First\n\nSecond";
|
||||
let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 300], "content": "text", "text": text})).unwrap();
|
||||
let (fid, sid) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap());
|
||||
let line_pt = |s: &Session, idx: usize| {
|
||||
let cs = s.cache.get(&s.doc().unwrap().doc, designcraft_doc::StoryId(sid), None);
|
||||
let l = &cs.frames[0].lines[idx];
|
||||
json!([l.x0 + 4.0, l.baseline - l.ascent * 0.5])
|
||||
};
|
||||
let sel = |s: &Session| s.doc().unwrap().selection.text.map(|t| (t.anchor, t.focus)).unwrap();
|
||||
let baselines = |s: &Session| -> Vec<f64> {
|
||||
let cs = s.cache.get(&s.doc().unwrap().doc, designcraft_doc::StoryId(sid), None);
|
||||
cs.frames[0].lines.iter().map(|l| l.baseline).collect()
|
||||
};
|
||||
|
||||
let base = baselines(&s);
|
||||
assert_eq!(base.len(), 3);
|
||||
let default_gap = base[2] - base[0];
|
||||
|
||||
// Double-click ("word"), triple-click ("line") and text.selectWord on the empty middle
|
||||
// line all select its paragraph return (byte 6..7).
|
||||
let empty_pt = line_pt(&s, 1);
|
||||
for unit in ["word", "line"] {
|
||||
s.execute("text.selectAt", &json!({"frame": fid, "point": empty_pt, "unit": unit})).unwrap();
|
||||
assert_eq!(sel(&s), (6, 7), "unit={unit}");
|
||||
}
|
||||
s.execute("text.selectWord", &json!({"frame": fid, "point": empty_pt})).unwrap();
|
||||
assert_eq!(sel(&s), (6, 7));
|
||||
|
||||
// The selected paragraph return produces a visible highlight quad on the empty line.
|
||||
{
|
||||
let cs = s.cache.get(&s.doc().unwrap().doc, designcraft_doc::StoryId(sid), None);
|
||||
let l = &cs.frames[0].lines[1];
|
||||
let range = s.doc().unwrap().selection.text.unwrap().range();
|
||||
let (a, e) = (range.start.max(l.range.start), range.end.min(l.range.end));
|
||||
let past = e == l.range.end && range.end > l.range.end;
|
||||
assert!(past);
|
||||
let quads = crate::compose::highlight_quads(l, a, e, past);
|
||||
assert_eq!(quads.len(), 1);
|
||||
assert!(quads[0][1].x > quads[0][0].x && quads[0][2].y > quads[0][0].y);
|
||||
}
|
||||
|
||||
// Dragging after double- or triple-clicking an empty line extends across it in both directions.
|
||||
for unit in ["word", "line"] {
|
||||
s.execute("text.selectAt", &json!({"frame": fid, "point": line_pt(&s, 1), "unit": unit})).unwrap();
|
||||
s.execute("text.extendTo", &json!({"frame": fid, "point": line_pt(&s, 2), "unit": unit})).unwrap();
|
||||
assert_eq!(sel(&s), (6, text.len()), "extend forward unit={unit}");
|
||||
s.execute("text.extendTo", &json!({"frame": fid, "point": line_pt(&s, 0), "unit": unit})).unwrap();
|
||||
assert_eq!(sel(&s), (7, 0), "extend backward unit={unit}");
|
||||
}
|
||||
|
||||
// Changing leading with the empty line selected updates the empty line's height.
|
||||
s.execute("text.selectAt", &json!({"frame": fid, "point": empty_pt, "unit": "word"})).unwrap();
|
||||
assert_eq!(sel(&s), (6, 7));
|
||||
s.execute("type.char", &json!({"attrs": {"leading": {"kind": "points", "value": 30.0}}})).unwrap();
|
||||
let wider = baselines(&s);
|
||||
assert!(wider[2] - wider[0] > default_gap, "wider leading must expand the gap: {wider:?} vs {base:?}");
|
||||
assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["leading"], json!({"kind": "points", "value": 30.0}));
|
||||
|
||||
s.execute("type.char", &json!({"attrs": {"leading": {"kind": "points", "value": 6.0}}})).unwrap();
|
||||
let tighter = baselines(&s);
|
||||
assert!(tighter[2] - tighter[0] < default_gap, "tighter leading must shrink the gap: {tighter:?} vs {base:?}");
|
||||
|
||||
// Empty first line, consecutive empty lines, trailing empty line, and empty story bounds.
|
||||
s.execute("story.setText", &json!({"story": sid, "text": "\n\nTail\n"})).unwrap();
|
||||
for unit in ["word", "line"] {
|
||||
s.execute("text.selectAt", &json!({"frame": fid, "point": line_pt(&s, 0), "unit": unit})).unwrap();
|
||||
assert_eq!(sel(&s), (0, 1), "leading empty line unit={unit}");
|
||||
s.execute("text.selectAt", &json!({"frame": fid, "point": line_pt(&s, 1), "unit": unit})).unwrap();
|
||||
assert_eq!(sel(&s), (1, 2), "second empty line unit={unit}");
|
||||
// Trailing empty paragraph has no return after it: stays safely collapsed at story end.
|
||||
s.execute("text.selectAt", &json!({"frame": fid, "point": line_pt(&s, 3), "unit": unit})).unwrap();
|
||||
assert_eq!(sel(&s), (7, 7), "trailing empty line unit={unit}");
|
||||
}
|
||||
|
||||
// Empty story: stays safely collapsed at byte 0.
|
||||
s.execute("story.setText", &json!({"story": sid, "text": ""})).unwrap();
|
||||
for unit in ["word", "line"] {
|
||||
s.execute("text.selectAt", &json!({"frame": fid, "point": [80, 80], "unit": unit})).unwrap();
|
||||
assert_eq!(sel(&s), (0, 0), "empty story unit={unit}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -2,21 +2,6 @@ use super::caret::story_of;
|
||||
use super::format::{Target, effective_char_format, format_targets};
|
||||
use super::{ItemId, Result, Session, StoryId, Value, bad, bool_or, json};
|
||||
|
||||
/// The stories of the text selection, the selected cells and the selected text frames.
|
||||
fn selected_stories(s: &Session) -> Result<Vec<StoryId>> {
|
||||
let st = s.doc()?;
|
||||
let mut stories: Vec<StoryId> = st.selection.text.map(|t| t.story).into_iter().chain(st.selection.cells.map(|c| c.story)).collect();
|
||||
stories.dedup();
|
||||
for id in &st.selection.items {
|
||||
if let Some(tf) = st.doc.item(*id).and_then(|i| i.text_frame())
|
||||
&& !stories.contains(&tf.story)
|
||||
{
|
||||
stories.push(tf.story);
|
||||
}
|
||||
}
|
||||
Ok(stories)
|
||||
}
|
||||
|
||||
/// Type ▸ Story: the story-wide options (Optical Margin Alignment and its size).
|
||||
pub(super) fn story_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "story.options";
|
||||
@@ -55,7 +40,7 @@ pub(super) fn story_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
vec![story_of(s, p).ok_or_else(|| bad(CMD, "no such story"))?]
|
||||
} else {
|
||||
selected_stories(s)?
|
||||
s.doc()?.selected_story_ids()
|
||||
};
|
||||
if stories.is_empty() {
|
||||
return Err(bad(CMD, "no story: select text or a text frame, or give story or frame"));
|
||||
@@ -78,7 +63,7 @@ pub(super) fn story_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Type ▸ Story Direction.
|
||||
pub(super) fn story_direction(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let vertical = p.get("vertical").and_then(Value::as_bool).ok_or_else(|| bad("type.storyDirection", "missing vertical"))?;
|
||||
let stories = selected_stories(s)?;
|
||||
let stories = s.doc()?.selected_story_ids();
|
||||
s.edit(|d, _| {
|
||||
set_story_direction(d, &stories, vertical);
|
||||
Ok(json!({"stories": stories.len()}))
|
||||
@@ -134,7 +119,7 @@ pub(super) fn selection_attrs(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"paraOverrides": style_para.delta(&pp).count() + style_chars.delta(&base).count(),
|
||||
"charOverrides": char_delta.count(), "characterStyleOverrides": character_style_overrides,
|
||||
"selectedText": selected.trim()});
|
||||
let mut stories = selected_stories(s)?;
|
||||
let mut stories = s.doc()?.selected_story_ids();
|
||||
if stories.is_empty() {
|
||||
stories.push(sid);
|
||||
}
|
||||
|
||||
@@ -485,3 +485,84 @@ fn a_custom_variable_defined_with_a_number_shows_its_digits() {
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
assert_eq!(shown_on_parent(&s, &d, sid), 4, "2026 shows");
|
||||
}
|
||||
|
||||
/// #3258: saving under a new name updates the `File Name` text variable (and its cached
|
||||
/// composition) on both document pages and parent pages, keeps it across undo, leaves it alone
|
||||
/// when Save As fails, and picks up a renamed file on open.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn file_name_variable_updates_on_save_as_including_parent_pages() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.title, "Untitled-1");
|
||||
|
||||
let parent_frame = s
|
||||
.execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 30, 500, 60], "content": "text", "text": ""}))
|
||||
.unwrap();
|
||||
let parent_sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(parent_frame["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;
|
||||
s.execute("text.select", &json!({"story": parent_sid.0, "anchor": 0, "focus": 0})).unwrap();
|
||||
s.execute("variables.insert", &json!({"name": "File Name"})).unwrap();
|
||||
|
||||
let doc_frame = s.execute("frame.create", &json!({"rect": [72, 100, 500, 140], "content": "text", "text": ""})).unwrap();
|
||||
let doc_sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(doc_frame["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;
|
||||
s.execute("text.select", &json!({"story": doc_sid.0, "anchor": 0, "focus": 0})).unwrap();
|
||||
s.execute("variables.insert", &json!({"name": "File Name"})).unwrap();
|
||||
|
||||
let visible_glyphs = |s: &Session, sid, page: Option<usize>| -> usize {
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let cs = s.cache.get(&d, sid, page);
|
||||
cs.frames.iter().flat_map(|f| f.lines.iter()).map(|l| l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).count()).sum()
|
||||
};
|
||||
let listed = |s: &mut Session| -> String {
|
||||
let list = s.execute("variables.list", &json!({})).unwrap();
|
||||
list.as_array().unwrap().iter().find(|v| v["name"] == "File Name").unwrap()["value"].as_str().unwrap().to_string()
|
||||
};
|
||||
|
||||
// Warm the composition cache before Save As on document, parent-on-page, and parent spread.
|
||||
assert_eq!(listed(&mut s), "Untitled-1");
|
||||
assert_eq!(visible_glyphs(&s, doc_sid, None), "Untitled-1".len());
|
||||
assert_eq!(visible_glyphs(&s, parent_sid, Some(0)), "Untitled-1".len());
|
||||
assert_eq!(visible_glyphs(&s, parent_sid, None), "Untitled-1".len());
|
||||
|
||||
// Save As updates the title, bumps revision, and invalidates cached compositions.
|
||||
let rev_before = s.doc().unwrap().revision;
|
||||
let saved_path = dir.path().join("CatalogEdition.designcraft");
|
||||
s.execute("file.saveAs", &json!({"path": saved_path.to_string_lossy()})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.title, "CatalogEdition");
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
assert_ne!(s.doc().unwrap().revision, rev_before, "canvas and thumbnails must redraw");
|
||||
assert_eq!(listed(&mut s), "CatalogEdition");
|
||||
assert_eq!(visible_glyphs(&s, doc_sid, None), "CatalogEdition".len());
|
||||
assert_eq!(visible_glyphs(&s, parent_sid, Some(0)), "CatalogEdition".len());
|
||||
assert_eq!(visible_glyphs(&s, parent_sid, None), "CatalogEdition".len());
|
||||
|
||||
// A failed Save As leaves the current title and File Name variable intact.
|
||||
let missing = dir.path().join("missing/Other.designcraft");
|
||||
assert!(s.execute("file.saveAs", &json!({"path": missing.to_string_lossy()})).is_err());
|
||||
assert_eq!(s.doc().unwrap().doc.title, "CatalogEdition");
|
||||
assert_eq!(listed(&mut s), "CatalogEdition");
|
||||
|
||||
// Save As under another name (including .idml) updates it again.
|
||||
let idml_path = dir.path().join("Issue.idml");
|
||||
s.execute("file.saveAs", &json!({"path": idml_path.to_string_lossy()})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.title, "Issue");
|
||||
assert_eq!(listed(&mut s), "Issue");
|
||||
assert_eq!(visible_glyphs(&s, doc_sid, None), "Issue".len());
|
||||
assert_eq!(visible_glyphs(&s, parent_sid, Some(0)), "Issue".len());
|
||||
|
||||
// Undoing an edit made before Save As keeps the saved file name instead of reverting to Untitled-1.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.title, "Issue");
|
||||
assert_eq!(listed(&mut s), "Issue");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.title, "Issue");
|
||||
|
||||
// Reopening a file renamed on disk reflects its current file name.
|
||||
let renamed = dir.path().join("RenamedBook.designcraft");
|
||||
std::fs::rename(&saved_path, &renamed).unwrap();
|
||||
let mut reopened = Session::new();
|
||||
reopened.execute("file.open", &json!({"path": renamed.to_string_lossy()})).unwrap();
|
||||
assert_eq!(reopened.doc().unwrap().doc.title, "RenamedBook");
|
||||
assert_eq!(listed(&mut reopened), "RenamedBook");
|
||||
}
|
||||
+111
-30
@@ -27,7 +27,7 @@ mod tooling;
|
||||
use std::sync::Arc;
|
||||
|
||||
use designcraft_compose::Cache;
|
||||
use designcraft_doc::{Document, LayerId, Selection};
|
||||
use designcraft_doc::{Document, LayerId, Selection, StoryId};
|
||||
use serde_json::Value;
|
||||
|
||||
pub use cmd::params::{check_keys, check_params};
|
||||
@@ -84,6 +84,8 @@ pub struct Interaction {
|
||||
pub preview: Option<(String, Value)>,
|
||||
/// The document's revision when the gesture began: a cancel puts it back.
|
||||
pub revision: u64,
|
||||
/// A tool's gesture opened it, not a dialog's preview.
|
||||
pub tool: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -176,6 +178,20 @@ impl DocState {
|
||||
links: Default::default(),
|
||||
}
|
||||
}
|
||||
/// The stories of the text selection, selected cells, and selected text frames, in target order without duplicates.
|
||||
pub fn selected_story_ids(&self) -> Vec<StoryId> {
|
||||
let mut stories: Vec<StoryId> = self.selection.text.map(|t| t.story).into_iter().chain(self.selection.cells.map(|c| c.story)).collect();
|
||||
stories.dedup();
|
||||
for id in &self.selection.items {
|
||||
if let Some(tf) = self.doc.item(*id).and_then(|i| i.text_frame())
|
||||
&& !stories.contains(&tf.story)
|
||||
{
|
||||
stories.push(tf.story);
|
||||
}
|
||||
}
|
||||
stories
|
||||
}
|
||||
|
||||
/// The document changed: it gets a revision no document state had before. A cancelled
|
||||
/// gesture puts back the revision it began at, so the numbers its previews used are never
|
||||
/// handed out again (a cache entry for one would show the cancelled preview).
|
||||
@@ -444,6 +460,9 @@ pub struct Session {
|
||||
/// The selection tool a Cmd-held press borrows for one gesture while another tool stays
|
||||
/// chosen (#919). Dropped on release.
|
||||
pub(crate) temp_tool: Option<Box<dyn designcraft_tools::Tool>>,
|
||||
/// The tool's gesture began while another interaction (a dialog's preview) was open, so its
|
||||
/// Begin was refused: its previews, commit and cancel are dropped until it ends.
|
||||
pub(crate) refused_gesture: bool,
|
||||
/// The selection tool (`selection` or `directSelection`) chosen last: the one Cmd borrows.
|
||||
pub(crate) last_selection_tool: &'static str,
|
||||
pub journal: Vec<(String, Value)>,
|
||||
@@ -523,6 +542,7 @@ impl Session {
|
||||
cache: Arc::new(Cache::new()),
|
||||
tool: designcraft_tools::create("selection"),
|
||||
temp_tool: None,
|
||||
refused_gesture: false,
|
||||
last_selection_tool: "selection",
|
||||
journal: vec![],
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -679,17 +699,45 @@ impl Session {
|
||||
/// Run command `id`. A panic inside it becomes [`EngineError::Internal`] and leaves the
|
||||
/// document as it was (see [`guard`]).
|
||||
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
|
||||
let spec = find_command(id);
|
||||
if let Some(spec) = spec
|
||||
&& let cmd::SuccessPasses::IfDocumentChanged(unchanged) = spec.success_passes
|
||||
{
|
||||
let mut result = None;
|
||||
// Only this opt-in's pure probe runs before generic lifecycle work. Keep the
|
||||
// ordinary panic boundary. Failed admission/validation and false probes fall
|
||||
// through unchanged; they do not return an early error or retain a stale plan.
|
||||
self.guarded(id, |s| {
|
||||
#[cfg(test)]
|
||||
let valid_params = check_params(id, params).is_ok();
|
||||
#[cfg(not(test))]
|
||||
let valid_params = true;
|
||||
if valid_params && s.check_enabled(spec, id, params).is_ok() {
|
||||
result = unchanged(s, params);
|
||||
if result.is_some() {
|
||||
if spec.journal {
|
||||
s.journal.push((id.to_string(), params.clone()));
|
||||
}
|
||||
s.discard_stale_find_scope();
|
||||
}
|
||||
}
|
||||
Ok(Value::Null)
|
||||
})?;
|
||||
if let Some(result) = result {
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
// A command from outside the IME ends its composition first, keeping the marked text as
|
||||
// typed: Undo then takes back that typing, and nothing runs on top of the preview the
|
||||
// composition would drop. Queries and recovery saves leave it alone.
|
||||
if self.tool.composing() && id != "file.recovery.save" && find_command(id).is_some_and(|c| c.journal || c.undoable) {
|
||||
if self.tool.composing() && id != "file.recovery.save" && spec.is_some_and(|c| c.journal || c.undoable) {
|
||||
self.end_composition()?;
|
||||
}
|
||||
self.guarded(id, |s| s.execute_unguarded(id, params))
|
||||
self.guarded(id, |s| s.execute_unguarded(id, params, spec))
|
||||
}
|
||||
|
||||
fn execute_unguarded(&mut self, id: &str, params: &Value) -> Result<Value> {
|
||||
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
|
||||
fn execute_unguarded(&mut self, id: &str, params: &Value, spec: Option<&CommandSpec>) -> Result<Value> {
|
||||
let spec = spec.ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
|
||||
// The crate's own tests are the audit of the params descriptions (#776): a key a test
|
||||
// passes that its command's description doesn't name fails the test.
|
||||
#[cfg(test)]
|
||||
@@ -718,33 +766,44 @@ impl Session {
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
// Undo, redo or deleting layers can take the active layer away: new objects would land on
|
||||
// a layer that isn't there (invisible, not exported). Fall back to the top layer.
|
||||
if let Some(st) = self.active_mut()
|
||||
&& st.doc.layer(st.active_layer).is_none()
|
||||
{
|
||||
st.active_layer = st.doc.working_layer();
|
||||
}
|
||||
self.record_transform(id, params);
|
||||
if self.prefs.smart_text_reflow && spec.undoable {
|
||||
self.smart_reflow();
|
||||
}
|
||||
// Live captions follow their sources.
|
||||
if spec.undoable
|
||||
&& let Some(st) = self.active_mut()
|
||||
&& st.interaction.is_none()
|
||||
&& cmd::captions::has_live(&st.doc)
|
||||
{
|
||||
let mut d = (*st.doc).clone();
|
||||
if cmd::captions::refresh_live(&mut d) {
|
||||
cmd::captions::clamp_text_selection(&d, &mut st.selection);
|
||||
st.doc = Arc::new(d);
|
||||
st.bump_revision();
|
||||
// Most commands retain all existing success passes. The typed opt-in is used only
|
||||
// by combined numbering: a genuine handler edit still runs EVERY pass in order,
|
||||
// while a true no-op cannot accidentally settle unrelated pending document work.
|
||||
let run_success_passes = match spec.success_passes {
|
||||
cmd::SuccessPasses::Always => true,
|
||||
cmd::SuccessPasses::IfDocumentChanged(_) => {
|
||||
!before.as_ref().is_some_and(|(uid, doc, _)| self.active().is_some_and(|st| st.uid == *uid && Arc::ptr_eq(doc, &st.doc)))
|
||||
}
|
||||
};
|
||||
if run_success_passes {
|
||||
// Undo, redo or deleting layers can take the active layer away: new objects would land on
|
||||
// a layer that isn't there (invisible, not exported). Fall back to the top layer.
|
||||
if let Some(st) = self.active_mut()
|
||||
&& st.doc.layer(st.active_layer).is_none()
|
||||
{
|
||||
st.active_layer = st.doc.working_layer();
|
||||
}
|
||||
self.record_transform(id, params);
|
||||
if self.prefs.smart_text_reflow && spec.undoable {
|
||||
self.smart_reflow();
|
||||
}
|
||||
// Live captions follow their sources.
|
||||
if spec.undoable
|
||||
&& let Some(st) = self.active_mut()
|
||||
&& st.interaction.is_none()
|
||||
&& cmd::captions::has_live(&st.doc)
|
||||
{
|
||||
let mut d = (*st.doc).clone();
|
||||
if cmd::captions::refresh_live(&mut d) {
|
||||
cmd::captions::clamp_text_selection(&d, &mut st.selection);
|
||||
st.doc = Arc::new(d);
|
||||
st.bump_revision();
|
||||
}
|
||||
}
|
||||
self.autosize_changed(spec, before.as_ref());
|
||||
self.keep_guide_selection_valid(before.as_ref(), id);
|
||||
self.record_undo_step(spec, before, nested);
|
||||
}
|
||||
self.autosize_changed(spec, before.as_ref());
|
||||
self.keep_guide_selection_valid(before.as_ref(), id);
|
||||
self.record_undo_step(spec, before, nested);
|
||||
if spec.journal {
|
||||
self.journal.push((id.to_string(), params.clone()));
|
||||
}
|
||||
@@ -907,7 +966,17 @@ impl Session {
|
||||
let st = self.doc_mut()?;
|
||||
let mut doc = (*st.doc).clone();
|
||||
let mut sel = st.selection.clone();
|
||||
let anchored = sel.anchored;
|
||||
let anchored_id = anchored.and_then(|a| doc.story(a.story)?.objects.get(a.index)).map(|o| o.item.id);
|
||||
let r = f(&mut doc, &mut sel)?;
|
||||
// An anchored selection names its object by place in the story: an edit that inserts or
|
||||
// removes objects before it would leave it naming another. Follow the object instead (a
|
||||
// command that chose a new selection keeps its choice).
|
||||
if sel.anchored == anchored
|
||||
&& let Some(a) = anchored
|
||||
{
|
||||
sel.anchored = anchored_id.and_then(|id| follow_anchored(&doc, a, id));
|
||||
}
|
||||
crate::cmd::sync_placeholders(&mut doc);
|
||||
crate::cmd::flex::sync(&mut doc);
|
||||
crate::cmd::alpha_wrap::sync(&mut doc);
|
||||
@@ -927,6 +996,18 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the anchored object `a` named before an edit is now: the object of its story with item
|
||||
/// `id`, the one nearest its old place when copies share the id (pasted text); `None` when it is
|
||||
/// gone.
|
||||
fn follow_anchored(doc: &Document, a: designcraft_doc::AnchoredSel, id: designcraft_doc::ItemId) -> Option<designcraft_doc::AnchoredSel> {
|
||||
let objects = &doc.story(a.story)?.objects;
|
||||
if objects.get(a.index).is_some_and(|o| o.item.id == id) {
|
||||
return Some(a);
|
||||
}
|
||||
let index = objects.iter().enumerate().filter(|(_, o)| o.item.id == id).map(|(k, _)| k).min_by_key(|k| k.abs_diff(a.index))?;
|
||||
Some(designcraft_doc::AnchoredSel { index, ..a })
|
||||
}
|
||||
|
||||
fn push_undo(st: &mut DocState, e: HistoryEntry) {
|
||||
st.history.undo.push(e);
|
||||
st.history.redo.clear();
|
||||
|
||||
@@ -160,6 +160,95 @@ fn tool_gesture_creates_one_undo_step() {
|
||||
assert!((it.visible_bounds().x0 - 36.0).abs() < 1e-6, "visible {:?} path {:?}", it.visible_bounds(), it.bounds());
|
||||
}
|
||||
|
||||
/// A tool's drag while a dialog's preview is open is refused: the preview stays for the dialog to
|
||||
/// keep or cancel, and the drag leaves no change without an undo step.
|
||||
#[test]
|
||||
fn a_tool_drag_leaves_a_dialogs_preview_alone() {
|
||||
use designcraft_tools::{PointerEvent, PointerKind};
|
||||
let mut s = session();
|
||||
let v = ViewInfo::at_zoom(1.0);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
s.begin_interaction("Create Guides").unwrap();
|
||||
s.preview("layout.createGuides", json!({"rows": 2, "columns": 2})).unwrap();
|
||||
let previewed = s.doc().unwrap().doc.clone();
|
||||
assert_ne!(previewed, before, "previewed");
|
||||
s.set_tool("rectangle");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
|
||||
let err = s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap_err().to_string();
|
||||
assert!(err.contains("Create Guides is in progress"), "{err}");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 200.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 200.0), v).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.interaction.as_ref().map(|it| it.label.as_str()), Some("Create Guides"));
|
||||
assert_eq!(st.doc, previewed, "the drag drew nothing");
|
||||
assert!(st.history.undo.is_empty());
|
||||
s.cancel_interaction();
|
||||
assert_eq!(s.doc().unwrap().doc, before, "Cancel takes the guides away");
|
||||
// With the preview gone, the next drag draws as before.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.doc.spreads[0].items.len(), 1);
|
||||
assert_eq!(st.history.undo.len(), 1);
|
||||
}
|
||||
|
||||
/// A dialog's preview does not start while a tool's drag is open, and a drag whose release never
|
||||
/// came is kept as its own undo step when the tool's next one begins.
|
||||
#[test]
|
||||
fn an_open_tool_drag_is_not_replaced() {
|
||||
use designcraft_tools::{PointerEvent, PointerKind};
|
||||
let mut s = session();
|
||||
let v = ViewInfo::at_zoom(1.0);
|
||||
s.set_tool("rectangle");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 100.0, 55.0), v).unwrap();
|
||||
let label = s.doc().unwrap().interaction.as_ref().map(|it| it.label.clone()).expect("the drag is open");
|
||||
let err = s.begin_interaction("Create Guides").unwrap_err().to_string();
|
||||
assert_eq!(err, format!("{label} is in progress"));
|
||||
assert_eq!(s.doc().unwrap().interaction.as_ref().map(|it| it.label.clone()), Some(label));
|
||||
// No release: the next press starts another drag.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 300.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
assert!(st.interaction.is_none());
|
||||
assert_eq!(st.doc.spreads[0].items.len(), 2);
|
||||
assert_eq!(st.history.undo.len(), 2, "one undo step for each drag");
|
||||
}
|
||||
|
||||
/// A drag left open in one document stays that document's: a finished drag in another document
|
||||
/// does not take it over, and the next drag back in the first one keeps it as its own undo step.
|
||||
#[test]
|
||||
fn an_open_tool_drag_stays_with_its_document() {
|
||||
use designcraft_tools::{PointerEvent, PointerKind};
|
||||
let mut s = session();
|
||||
let v = ViewInfo::at_zoom(1.0);
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.set_active(0);
|
||||
s.set_tool("rectangle");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 100.0, 55.0), v).unwrap();
|
||||
// No release: the other document's drag begins and ends.
|
||||
s.set_active(1);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 100.0, 55.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 100.0, 55.0), v).unwrap();
|
||||
s.set_active(0);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 300.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
assert!(st.interaction.is_none());
|
||||
assert_eq!(st.doc.spreads[0].items.len(), 2);
|
||||
assert_eq!(st.history.undo.len(), 2, "one undo step for each drag");
|
||||
s.set_active(1);
|
||||
let st = s.doc().unwrap();
|
||||
assert!(st.interaction.is_none());
|
||||
assert_eq!(st.doc.spreads[0].items.len(), 1);
|
||||
assert_eq!(st.history.undo.len(), 1);
|
||||
}
|
||||
|
||||
/// A command that runs another one (Cut runs Clear) recorded an undo step for each, so the
|
||||
/// second Undo did nothing. One command is one step, whatever it runs inside.
|
||||
#[test]
|
||||
@@ -2317,6 +2406,39 @@ fn direct_selection_pulls_one_corner_of_an_unselected_frame() {
|
||||
assert!(corners(&s).iter().zip(&before).all(|(p, q)| (p.y - q.y - 50.0).abs() < 1e-6), "{:?}", corners(&s));
|
||||
}
|
||||
|
||||
/// Issue #2564: with Direct Selection, pressing a point of a path that isn't selected selects
|
||||
/// that point (drawn solid), whether the press is a click or a drag.
|
||||
#[test]
|
||||
fn direct_selection_press_on_an_unselected_path_selects_the_point() {
|
||||
use designcraft_tools::{PointerEvent, PointerKind, SnapView};
|
||||
let mut s = session();
|
||||
let id = s.execute("path.create", &json!({"anchors": [{"p": [100, 300]}, {"p": [300, 400]}]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.set_tool("directSelection");
|
||||
let v = ViewInfo { snap: SnapView::OFF, ..ViewInfo::at_zoom(1.0) };
|
||||
let layout = s.layout();
|
||||
let at = |x: f64, y: f64| layout.to_canvas(designcraft_doc::SpreadRef::Doc(0), designcraft_geom::Point::new(x, y));
|
||||
let item = designcraft_doc::ItemId(id);
|
||||
// A click on the end point.
|
||||
s.execute("edit.deselectAll", &json!({})).unwrap();
|
||||
let p = at(300.0, 400.0);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, p.x, p.y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, p.x, p.y), v).unwrap();
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
assert_eq!(sel.items, [item]);
|
||||
assert_eq!(sel.anchors, [(item, 0, 1)], "the clicked point is selected");
|
||||
// A drag from the start point: it moves and stays selected.
|
||||
s.execute("edit.deselectAll", &json!({})).unwrap();
|
||||
let (a, b) = (at(100.0, 300.0), at(100.0, 250.0));
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, a.x, a.y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, a.x, a.y - 20.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, b.x, b.y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, b.x, b.y), v).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let it = st.doc.item(item).unwrap();
|
||||
assert!((it.xf * it.path.subpaths[0].anchors[0].p - designcraft_geom::Point::new(100.0, 250.0)).hypot() < 1e-6);
|
||||
assert_eq!(st.selection.anchors, [(item, 0, 0)], "the dragged point is selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_selection_on_a_selected_frame_deletes_only_its_image() {
|
||||
use designcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
@@ -2719,6 +2841,23 @@ fn deleting_the_active_layer_moves_to_a_usable_layer() {
|
||||
assert_eq!(s.doc().unwrap().active_layer, artwork);
|
||||
}
|
||||
|
||||
/// A preview that fails leaves the gesture's starting document with the revision it began at,
|
||||
/// so a cache keyed by revision does not show the previous preview's contents.
|
||||
#[test]
|
||||
fn a_failed_preview_puts_back_the_revision_the_gesture_began_at() {
|
||||
let mut s = session();
|
||||
let id = s.execute("frame.create", &json!({"rect": [36, 36, 100, 100]})).unwrap()["id"].as_u64().unwrap();
|
||||
let (start, before) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().revision);
|
||||
s.begin_interaction("Move").unwrap();
|
||||
s.preview("transform.move", json!({"ids": [id], "dx": 30, "dy": 0})).unwrap();
|
||||
let moved = s.doc().unwrap().revision;
|
||||
assert_ne!(moved, before);
|
||||
assert!(s.preview("transform.move", json!({"ids": [9999], "dx": 60, "dy": 0})).is_err());
|
||||
let st = s.doc().unwrap();
|
||||
assert!(Arc::ptr_eq(&st.doc, &start), "the document is the one the gesture began with");
|
||||
assert_eq!(st.revision, before, "not {moved}, the revision of the previous preview");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_a_frame_across_its_spread_renumbers_continuing_lists() {
|
||||
// Regression: the composition cache keyed list numbering by spread address, and each preview of
|
||||
@@ -2832,3 +2971,53 @@ fn selection_tool_drag_and_double_click_at_top_keeps_bottom_aligned_text_in_plac
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.item(id).unwrap().bounds(), original);
|
||||
}
|
||||
|
||||
/// Choosing the Eyedropper while text is selected keeps the text selection active so clicking
|
||||
/// another text frame copies its formatting onto the selected text (#3264).
|
||||
#[test]
|
||||
fn switching_to_eyedropper_keeps_text_selection_and_copies_formatting() {
|
||||
use designcraft_doc::{ItemId, SpreadRef};
|
||||
use designcraft_geom::Point;
|
||||
use designcraft_tools::{PointerEvent, PointerKind};
|
||||
|
||||
let mut s = session();
|
||||
let head = s.execute("frame.create", &json!({"rect": [36, 36, 400, 100], "content": "text", "text": "Heading"})).unwrap();
|
||||
s.execute("text.select", &json!({"story": head["story"], "anchor": 0, "focus": 7})).unwrap();
|
||||
s.execute("type.char", &json!({"attrs": {"fontStyle": "Bold", "size": 18}})).unwrap();
|
||||
s.execute("type.para", &json!({"attrs": {"align": "center"}})).unwrap();
|
||||
|
||||
let body = s.execute("frame.create", &json!({"rect": [36, 200, 400, 300], "content": "text", "text": "Body copy"})).unwrap();
|
||||
let body_id = ItemId(body["id"].as_u64().unwrap());
|
||||
s.set_tool("type");
|
||||
s.execute("text.select", &json!({"story": body["story"], "anchor": 0, "focus": 4})).unwrap();
|
||||
assert!(s.wants_text());
|
||||
|
||||
// Switching to the Eyedropper keeps the text selection active without capturing typing keys.
|
||||
s.execute("tool.select", &json!({"tool": "eyedropper"})).unwrap();
|
||||
let sel = s.doc().unwrap().selection.text;
|
||||
assert_eq!(sel.map(|t| (t.story.0, t.anchor, t.focus)), Some((body["story"].as_u64().unwrap(), 0, 4)));
|
||||
assert!(!s.wants_text());
|
||||
|
||||
// Clicking the header frame copies its character and paragraph formatting to the selected text.
|
||||
let pt = s.layout().to_canvas(SpreadRef::Doc(0), Point::new(80.0, 50.0));
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, pt.x, pt.y), ViewInfo::at_zoom(1.0)).unwrap();
|
||||
let a = s.execute("type.selectionAttrs", &json!({})).unwrap();
|
||||
assert_eq!((&a["chars"]["fontStyle"], &a["chars"]["size"], &a["para"]["align"]), (&json!("Bold"), &json!(18.0), &json!("center")), "{a}");
|
||||
assert_eq!(s.doc().unwrap().selection.text, sel);
|
||||
|
||||
// Unselected characters in the body frame keep their original size.
|
||||
s.execute("text.select", &json!({"story": body["story"], "anchor": 5, "focus": 9})).unwrap();
|
||||
assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["size"], json!(12.0));
|
||||
|
||||
// Switching between Type, Vertical Type and Eyedropper keeps the text selection; leaving for
|
||||
// Selection exits text selection and selects the text frame.
|
||||
s.set_tool("type");
|
||||
assert!(s.doc().unwrap().selection.text.is_some());
|
||||
s.set_tool("verticalType");
|
||||
assert!(s.doc().unwrap().selection.text.is_some());
|
||||
s.set_tool("eyedropper");
|
||||
assert!(s.doc().unwrap().selection.text.is_some());
|
||||
s.set_tool("selection");
|
||||
assert!(s.doc().unwrap().selection.text.is_none());
|
||||
assert_eq!(s.doc().unwrap().selection.items, vec![body_id]);
|
||||
}
|
||||
@@ -222,3 +222,19 @@ fn a_cancelled_gesture_puts_back_the_revision_and_leaves_a_saved_document_saved(
|
||||
assert!(!seen.contains(&after), "{after} in {seen:?}");
|
||||
assert!(s.doc().unwrap().is_dirty());
|
||||
}
|
||||
|
||||
/// A dialog's preview that opens during a composition keeps the marked text as typed first, as
|
||||
/// one undo step, and then opens on that document.
|
||||
#[test]
|
||||
fn a_dialog_preview_ends_the_composition_first() {
|
||||
let mut s = session();
|
||||
let sid = typing_into(&mut s, "a");
|
||||
s.tool_preedit("が", None, ViewInfo::default()).unwrap();
|
||||
let before = steps(&s);
|
||||
s.begin_interaction("Hyphenation").unwrap();
|
||||
assert!(!s.tool_composing());
|
||||
assert_eq!(s.doc().unwrap().interaction.as_ref().map(|it| it.label.as_str()), Some("Hyphenation"));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
s.cancel_interaction();
|
||||
assert_eq!(text(&mut s, sid), "aが");
|
||||
}
|
||||
@@ -68,6 +68,7 @@ impl Session {
|
||||
}
|
||||
self.tool = designcraft_tools::create(id);
|
||||
self.temp_tool = None;
|
||||
self.refused_gesture = false;
|
||||
if matches!(self.tool.id(), "selection" | "directSelection") {
|
||||
self.last_selection_tool = self.tool.id();
|
||||
}
|
||||
@@ -76,8 +77,9 @@ impl Session {
|
||||
self.loaded = None;
|
||||
self.loaded_queue.clear();
|
||||
}
|
||||
// Leaving the Type tool keeps the text frame selected.
|
||||
if id != "type"
|
||||
// Leaving a Type tool keeps the text frame selected; the Eyedropper keeps the text
|
||||
// selection so clicking text or an image applies formatting or colour to it.
|
||||
if !matches!(self.tool.id(), "type" | "verticalType" | "eyedropper")
|
||||
&& let Some(st) = self.active_mut()
|
||||
&& let Some(t) = st.selection.text.take()
|
||||
&& let Some(f) = t.frame.or_else(|| st.doc.story(t.story).and_then(|s| s.frames.first().copied()))
|
||||
@@ -270,10 +272,19 @@ impl Session {
|
||||
self.with_ctx(view, |s, cx| s.tool.ime_caret(cx)).flatten()
|
||||
}
|
||||
|
||||
/// The caret line (canvas space) at the moving end of the text selection, whatever the tool: what
|
||||
/// the view keeps in sight as the caret moves. `None` with no text selection or an overset caret.
|
||||
pub fn text_caret(&mut self, view: ViewInfo) -> Option<(designcraft_geom::Point, designcraft_geom::Point)> {
|
||||
self.with_ctx(view, |_, cx| designcraft_tools::text_caret(cx)).flatten()
|
||||
}
|
||||
|
||||
pub fn run_actions(&mut self, actions: Vec<Action>) -> Result<()> {
|
||||
for a in actions {
|
||||
match a {
|
||||
Action::Begin(label) => self.begin_interaction(&label)?,
|
||||
Action::Begin(label) => self.begin_gesture(&label)?,
|
||||
// A refused gesture leaves the open interaction alone until it ends.
|
||||
Action::Preview(..) if self.refused_gesture => {}
|
||||
Action::Commit | Action::Cancel if self.refused_gesture => self.refused_gesture = false,
|
||||
Action::Preview(cmd, p) => self.preview(&cmd, p)?,
|
||||
Action::Commit => self.commit_interaction()?,
|
||||
Action::Cancel => self.cancel_interaction(),
|
||||
@@ -289,10 +300,40 @@ impl Session {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Open an interaction (a dialog's preview) on the active document. Marked text of an IME
|
||||
/// composition is kept as typed first. Fails while another interaction is open.
|
||||
pub fn begin_interaction(&mut self, label: &str) -> Result<()> {
|
||||
self.end_composition()?;
|
||||
self.open_interaction(label, false)
|
||||
}
|
||||
|
||||
/// A tool's Begin. The tool's own gesture on this document that never got its end (a release
|
||||
/// lost to a tool or document switch) is kept as its own undo step first. While another
|
||||
/// interaction is open (a dialog's preview) the gesture is refused, and its previews, commit and
|
||||
/// cancel are dropped.
|
||||
fn begin_gesture(&mut self, label: &str) -> Result<()> {
|
||||
if self.active().is_some_and(|st| st.interaction.as_ref().is_some_and(|it| it.tool)) {
|
||||
self.commit_interaction()?;
|
||||
}
|
||||
let r = self.open_interaction(label, true);
|
||||
self.refused_gesture = r.is_err();
|
||||
r
|
||||
}
|
||||
|
||||
fn open_interaction(&mut self, label: &str, tool: bool) -> Result<()> {
|
||||
let st = self.doc_mut()?;
|
||||
st.interaction =
|
||||
Some(Interaction { label: label.into(), doc: st.doc.clone(), selection: st.selection.clone(), preview: None, revision: st.revision });
|
||||
// Replacing an open interaction would leave its preview in the document with no undo step.
|
||||
if let Some(open) = &st.interaction {
|
||||
return Err(EngineError::Other(format!("{} is in progress", open.label)));
|
||||
}
|
||||
st.interaction = Some(Interaction {
|
||||
label: label.into(),
|
||||
doc: st.doc.clone(),
|
||||
selection: st.selection.clone(),
|
||||
preview: None,
|
||||
revision: st.revision,
|
||||
tool,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -302,9 +343,12 @@ impl Session {
|
||||
let Some(it) = st.interaction.clone() else { return Err(EngineError::Other("no interaction".into())) };
|
||||
st.doc = it.doc.clone();
|
||||
st.selection = it.selection.clone();
|
||||
// A preview that fails or changes nothing shows the snapshot under the snapshot's
|
||||
// revision, not under the revision of the preview before it.
|
||||
st.revision = it.revision;
|
||||
// Not through `execute`: a preview is part of the gesture (an IME composition included),
|
||||
// not a command that ends it.
|
||||
let r = self.guarded(cmd, |s| s.execute_unguarded(cmd, ¶ms));
|
||||
let r = self.guarded(cmd, |s| s.execute_unguarded(cmd, ¶ms, crate::find_command(cmd)));
|
||||
if let Some(st) = self.active_mut()
|
||||
&& let Some(i) = st.interaction.as_mut()
|
||||
{
|
||||
|
||||
+41
-10
@@ -162,6 +162,21 @@ pub(crate) struct Body<'a> {
|
||||
no_alt: Vec<String>,
|
||||
}
|
||||
|
||||
/// Pre-order index of items on all spreads, built only when `order` contains top-level images.
|
||||
fn item_index<'a>(doc: &'a Document, order: &[Block]) -> std::collections::HashMap<ItemId, &'a Item> {
|
||||
let mut items = std::collections::HashMap::new();
|
||||
if order.iter().any(|b| matches!(b, Block::Image(_))) {
|
||||
for sp in doc.spreads.iter().map(|s| &**s).chain(doc.parents.iter().map(|s| &**s)) {
|
||||
for it in &sp.items {
|
||||
it.walk(&mut |i| {
|
||||
items.entry(i.id).or_insert(i);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
/// The content in reading order as HTML sections and figures; `img_src` names each image
|
||||
/// (a package path, or a data URI for single-file HTML).
|
||||
pub(crate) fn body_html<'a>(doc: &'a Document, epub: bool, split: Option<&EpubSplit>, img_src: &dyn Fn(&str, &str, &[u8]) -> String) -> Body<'a> {
|
||||
@@ -173,16 +188,7 @@ pub(crate) fn body_html<'a>(doc: &'a Document, epub: bool, split: Option<&EpubSp
|
||||
let mut body = String::new();
|
||||
let mut toc = toc_entries(doc, &order);
|
||||
// `Document::item` searches every spread: one pre-order index for all the placed graphics.
|
||||
let mut items: std::collections::HashMap<ItemId, &Item> = std::collections::HashMap::new();
|
||||
if order.iter().any(|b| matches!(b, Block::Image(_))) {
|
||||
for sp in doc.spreads.iter().map(|s| &**s).chain(doc.parents.iter().map(|s| &**s)) {
|
||||
for it in &sp.items {
|
||||
it.walk(&mut |i| {
|
||||
items.entry(i.id).or_insert(i);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let items = item_index(doc, &order);
|
||||
for (k, b) in order.iter().enumerate() {
|
||||
match b {
|
||||
// The endnote frame's text is generated from the endnotes, which end the body as a
|
||||
@@ -224,6 +230,31 @@ pub(crate) fn body_html<'a>(doc: &'a Document, epub: bool, split: Option<&EpubSp
|
||||
Body { html: body, images: writer.images, toc, no_alt: writer.no_alt }
|
||||
}
|
||||
|
||||
/// Assets that HTML and reflowable EPUB export will read: placed graphics in reading order,
|
||||
/// anchored graphics in exported stories (including visible tables, footnotes and endnotes),
|
||||
/// and their media posters.
|
||||
pub fn used_assets(doc: &Document) -> std::collections::BTreeSet<designcraft_doc::AssetId> {
|
||||
let order = reading_order(doc);
|
||||
let items = item_index(doc, &order);
|
||||
let mut out = std::collections::BTreeSet::new();
|
||||
for b in &order {
|
||||
match b {
|
||||
Block::Story(sid) if doc.endnote_story == Some(*sid) => {}
|
||||
Block::Story(sid) => {
|
||||
if let Some(st) = doc.story(*sid) {
|
||||
super::story_writer::collect_story_assets(doc, st, 0, &mut out);
|
||||
}
|
||||
}
|
||||
Block::Image(iid) => {
|
||||
if let Some(&it) = items.get(iid) {
|
||||
super::story_writer::collect_graphic_assets(doc, it, &mut out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Placed and anchored images (not video or sound) without alt text, by asset name: they are exported as
|
||||
/// decorative (`alt=""`), which an export can report.
|
||||
pub fn images_without_alt(doc: &Document) -> Vec<String> {
|
||||
|
||||
@@ -36,7 +36,7 @@ pub use fonts::{EmbeddedFont, stylesheet_fonts};
|
||||
use fonts::{css_weight_style, generic_family};
|
||||
#[cfg(test)]
|
||||
use html::base64;
|
||||
pub use html::{Block, HtmlOptions, export_html, images_without_alt, reading_order};
|
||||
pub use html::{Block, HtmlOptions, export_html, images_without_alt, reading_order, used_assets};
|
||||
pub use markup::{EpubError, slug};
|
||||
pub use package::{FixedPage, contents_title, export_epub, export_fixed_epub};
|
||||
pub use story_writer::story_html;
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use designcraft_doc::AssetId;
|
||||
|
||||
use super::chapters::{CHAPTER_MARK, heading_level, starts_chapter};
|
||||
use super::css::{char_classes, export_mapping, override_css, para_classes};
|
||||
use super::html::asset_path;
|
||||
@@ -23,6 +27,20 @@ fn close_blocks(list: &mut Option<&str>, pre: &mut Option<(String, bool)>, out:
|
||||
/// nested or cyclic document can't recurse without bound.
|
||||
const MAX_DEPTH: usize = 8;
|
||||
|
||||
/// The table anchored in `pf` if its anchor run is visible (neither hidden nor deleted).
|
||||
fn visible_table<'a>(
|
||||
doc: &Document,
|
||||
st: &'a Story,
|
||||
pf: &story::ParaFormat,
|
||||
base: &CharProps,
|
||||
r: &std::ops::Range<usize>,
|
||||
text: &str,
|
||||
) -> Option<&'a Table> {
|
||||
pf.table
|
||||
.and_then(|id| st.tables.get(&id).map(std::sync::Arc::as_ref))
|
||||
.filter(|_| text.find(story::TABLE_ANCHOR).is_some_and(|at| !doc.hides_run(base, st.char_format_of(r.start + at))))
|
||||
}
|
||||
|
||||
/// Writes stories with their tables and notes, numbering notes across the stories of one export.
|
||||
pub(crate) struct StoryWriter<'a, 'f> {
|
||||
doc: &'a Document,
|
||||
@@ -128,10 +146,7 @@ impl<'a, 'f> StoryWriter<'a, 'f> {
|
||||
let Some(text) = st.text.get(r.clone()) else { continue };
|
||||
let base = doc.styles.resolve_para(pf).1;
|
||||
// A table whose anchor is hidden or deleted is off the page, so it stays out.
|
||||
let table = pf
|
||||
.table
|
||||
.and_then(|id| st.tables.get(&id))
|
||||
.filter(|_| text.find(story::TABLE_ANCHOR).is_some_and(|at| !doc.hides_run(&base, st.char_format_of(r.start + at))));
|
||||
let table = visible_table(doc, st, pf, &base, &r, text);
|
||||
let only_table = table.is_some() && text.chars().all(|c| c == story::TABLE_ANCHOR || c.is_whitespace());
|
||||
if !only_table || !lead.is_empty() {
|
||||
// Export Tagging: the style's element and class.
|
||||
@@ -494,3 +509,101 @@ fn run_text(doc: &Document, raw: &str, left: &mut usize) -> String {
|
||||
pub fn story_html(doc: &Document, sid: StoryId) -> String {
|
||||
StoryWriter::new(doc, true, None).story(sid, None)
|
||||
}
|
||||
|
||||
/// Assets [`StoryWriter::graphic`] reads for `it`: its graphic asset and a media frame's poster.
|
||||
pub(crate) fn collect_graphic_assets(doc: &Document, it: &Item, out: &mut BTreeSet<AssetId>) {
|
||||
let Content::Graphic(g) = &it.content else { return };
|
||||
let Some(a) = doc.assets.get(&g.asset) else { return };
|
||||
out.insert(g.asset);
|
||||
if designcraft_doc::media_kind(safe_mime(&a.mime)).is_some()
|
||||
&& let Some(poster) = it.media.as_ref().and_then(|m| m.poster)
|
||||
&& doc.assets.contains_key(&poster)
|
||||
{
|
||||
out.insert(poster);
|
||||
}
|
||||
}
|
||||
|
||||
/// Assets a story's exported content reads: visible anchored objects, and recursively its visible
|
||||
/// tables, footnotes and endnotes up to [`MAX_DEPTH`].
|
||||
pub(crate) fn collect_story_assets(doc: &Document, st: &Story, depth: usize, out: &mut BTreeSet<AssetId>) {
|
||||
if st.objects.is_empty() && st.tables.is_empty() && st.notes.is_empty() && st.endnotes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let marks = |c: char| -> Vec<usize> { st.text.match_indices(c).map(|(i, _)| i).collect() };
|
||||
let obj_marks = if st.objects.is_empty() { Vec::new() } else { marks(OBJECT_MARK) };
|
||||
let foot_refs = if depth < MAX_DEPTH && !st.notes.is_empty() { marks(FOOTNOTE_REF) } else { Vec::new() };
|
||||
let end_refs = if depth < MAX_DEPTH && !st.endnotes.is_empty() { marks(ENDNOTE_REF) } else { Vec::new() };
|
||||
let runs: Vec<(std::ops::Range<usize>, &story::CharFormat)> =
|
||||
if !obj_marks.is_empty() || !foot_refs.is_empty() || !end_refs.is_empty() { st.runs().collect() } else { Vec::new() };
|
||||
for (r, pf) in st.para_ranges().into_iter().zip(&st.paras) {
|
||||
let Some(text) = st.text.get(r.clone()) else { continue };
|
||||
let base = doc.styles.resolve_para(pf).1;
|
||||
let table = visible_table(doc, st, pf, &base, &r, text);
|
||||
let only_table = table.is_some() && text.chars().all(|c| c == story::TABLE_ANCHOR || c.is_whitespace());
|
||||
if !only_table && !runs.is_empty() {
|
||||
let first = runs.partition_point(|(rr, _)| rr.end <= r.start);
|
||||
for (rr, f) in runs.iter().skip(first).take_while(|(rr, _)| rr.start < r.end) {
|
||||
let a = rr.start.max(r.start);
|
||||
let b = rr.end.min(r.end);
|
||||
if a >= b || doc.hides_run(&base, f) {
|
||||
continue;
|
||||
}
|
||||
let Some(raw) = st.text.get(a..b) else { continue };
|
||||
for (i, c) in raw.char_indices() {
|
||||
if c == OBJECT_MARK {
|
||||
let k = obj_marks.partition_point(|&p| p < a + i);
|
||||
if let Some(o) = st.objects.get(k) {
|
||||
o.item.walk(&mut |it| collect_graphic_assets(doc, it, out));
|
||||
}
|
||||
} else if depth < MAX_DEPTH && c == FOOTNOTE_REF {
|
||||
let k = foot_refs.partition_point(|&p| p < a + i);
|
||||
if let Some(note) = st.notes.get(k) {
|
||||
collect_story_assets(doc, ¬e.text, depth + 1, out);
|
||||
}
|
||||
} else if depth < MAX_DEPTH && c == ENDNOTE_REF {
|
||||
let k = end_refs.partition_point(|&p| p < a + i);
|
||||
if let Some(note) = st.endnotes.get(k) {
|
||||
collect_story_assets(doc, ¬e.text, depth + 1, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(t) = table
|
||||
&& depth < MAX_DEPTH
|
||||
{
|
||||
collect_table_assets(doc, t, depth + 1, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_table_assets(doc: &Document, t: &Table, depth: usize, out: &mut BTreeSet<AssetId>) {
|
||||
let (nr, nc) = (t.nrows(), t.ncols());
|
||||
if nr.checked_mul(nc) != Some(t.cells.len()) {
|
||||
return;
|
||||
}
|
||||
let (h, f) = (t.header_rows(), t.footer_rows());
|
||||
let body_end = nr.saturating_sub(f).max(h);
|
||||
let mut covered = vec![false; t.cells.len()];
|
||||
for rows in [0..h, h..body_end, body_end..nr] {
|
||||
for r in rows.clone() {
|
||||
for c in 0..nc {
|
||||
let i = r * nc + c;
|
||||
if covered.get(i).copied().unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
let Some(cell) = t.cells.get(i) else { continue };
|
||||
let rs = (cell.row_span.max(1) as usize).min(rows.end.saturating_sub(r));
|
||||
let cs = (cell.col_span.max(1) as usize).min(nc.saturating_sub(c));
|
||||
for rr in r..r.saturating_add(rs) {
|
||||
for cc in c..c.saturating_add(cs) {
|
||||
if let Some(slot) = covered.get_mut(rr * nc + cc) {
|
||||
*slot = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
collect_story_assets(doc, &cell.text, depth, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1084,3 +1084,105 @@ fn shared_base64_keeps_binary_padding_and_long_data_uris_on_one_line() {
|
||||
assert_eq!(base64(&[0xff, 0xff]), "//8=");
|
||||
assert_eq!(base64(&[0; 60]), "A".repeat(80));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn used_assets_finds_anchored_graphics_and_skips_hidden_ones() {
|
||||
use designcraft_doc::{AnchorPosition, AnchoredObject, ChangeMark, CharAttrs, Condition, Graphic, MediaOptions};
|
||||
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
let lid = d.default_layer();
|
||||
d.conditions.push(Condition { name: "Secret".into(), color: [0, 0, 0], visible: false });
|
||||
|
||||
let add_asset = |d: &mut Document, name: &str, mime: &str| {
|
||||
let id = AssetId(d.alloc());
|
||||
d.assets.insert(id, Arc::new(Asset { id, name: name.into(), mime: mime.into(), data: AssetData::default(), ..Default::default() }));
|
||||
id
|
||||
};
|
||||
let a_inline = add_asset(&mut d, "inline.svg", "image/svg+xml");
|
||||
let a_group = add_asset(&mut d, "group.png", "image/png");
|
||||
let a_media = add_asset(&mut d, "clip.mp4", "video/mp4");
|
||||
let a_poster = add_asset(&mut d, "poster.png", "image/png");
|
||||
let a_table = add_asset(&mut d, "cell.png", "image/png");
|
||||
let a_note = add_asset(&mut d, "note.png", "image/png");
|
||||
let a_endnote = add_asset(&mut d, "endnote.png", "image/png");
|
||||
let a_hidden = add_asset(&mut d, "hidden.png", "image/png");
|
||||
let a_deleted = add_asset(&mut d, "deleted.png", "image/png");
|
||||
let a_unused = add_asset(&mut d, "unused.png", "image/png");
|
||||
|
||||
let graphic_item = |d: &mut Document, asset: AssetId, poster: Option<AssetId>| {
|
||||
let mut item = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)));
|
||||
item.content = Content::Graphic(Graphic {
|
||||
layer_options: None,
|
||||
asset,
|
||||
size: (10.0, 10.0),
|
||||
xf: Affine::IDENTITY,
|
||||
auto_fit: Default::default(),
|
||||
fit_align: 4,
|
||||
crop: [0.0; 4],
|
||||
clip: None,
|
||||
wrap: Default::default(),
|
||||
fill: Default::default(),
|
||||
});
|
||||
if poster.is_some() {
|
||||
item.media = Some(MediaOptions { poster, ..Default::default() });
|
||||
}
|
||||
item
|
||||
};
|
||||
let anchor = |item: Item| AnchoredObject::new(item, AnchorPosition::Inline { y_offset: 0.0 });
|
||||
|
||||
let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 200.0), lid, "Body\n", ParaFormat::default()).unwrap();
|
||||
|
||||
// 1. Inline anchored graphic
|
||||
let it = graphic_item(&mut d, a_inline, None);
|
||||
d.story_mut(sid).unwrap().insert_object(0, anchor(it));
|
||||
|
||||
// 2. Grouped anchored graphic + media with poster
|
||||
let child_img = Arc::new(graphic_item(&mut d, a_group, None));
|
||||
let child_media = Arc::new(graphic_item(&mut d, a_media, Some(a_poster)));
|
||||
let mut group = Item::new(ItemId(d.alloc()), lid, Shape::Group, Default::default());
|
||||
group.content = Content::Group { items: vec![child_img, child_media] };
|
||||
let pos = d.story(sid).unwrap().len();
|
||||
d.story_mut(sid).unwrap().insert_object(pos, anchor(group));
|
||||
|
||||
// 3. Anchored graphic inside a footnote and inside an endnote
|
||||
let note_it = graphic_item(&mut d, a_note, None);
|
||||
let endnote_it = graphic_item(&mut d, a_endnote, None);
|
||||
let note_pos = d.story(sid).unwrap().len();
|
||||
d.story_mut(sid).unwrap().insert_note(note_pos, "note", ParaFormat::default());
|
||||
Arc::make_mut(&mut d.story_mut(sid).unwrap().notes[0]).text.insert_object(0, anchor(note_it));
|
||||
let endnote_pos = d.story(sid).unwrap().len();
|
||||
d.story_mut(sid).unwrap().insert_endnote(endnote_pos, "endnote", ParaFormat::default());
|
||||
Arc::make_mut(&mut d.story_mut(sid).unwrap().endnotes[0]).text.insert_object(0, anchor(endnote_it));
|
||||
|
||||
// 4. Anchored graphic inside a visible table cell
|
||||
let cell_it = graphic_item(&mut d, a_table, None);
|
||||
let mut tbl = Table::new(d.alloc(), 1, 1, 0, 0, 100.0);
|
||||
tbl.cell_mut(0, 0).unwrap().text = Story::with_text(StoryId(0), "cell", ParaFormat::default());
|
||||
tbl.cell_mut(0, 0).unwrap().text.insert_object(0, anchor(cell_it));
|
||||
let tpos = d.story(sid).unwrap().len();
|
||||
d.story_mut(sid).unwrap().insert_table(tpos, tbl);
|
||||
|
||||
// 5. Anchored graphic in a hidden condition run (must be skipped)
|
||||
let hidden_pos = d.story(sid).unwrap().len();
|
||||
let hidden_it = graphic_item(&mut d, a_hidden, None);
|
||||
d.story_mut(sid).unwrap().insert_object(hidden_pos, anchor(hidden_it));
|
||||
d.story_mut(sid).unwrap().format_chars(hidden_pos..hidden_pos + OBJECT_MARK.len_utf8(), |f| {
|
||||
f.over = CharAttrs { conditions: Some(vec!["Secret".into()]), ..Default::default() }
|
||||
});
|
||||
|
||||
// 6. Anchored graphic in a deleted run (must be skipped)
|
||||
let del_pos = d.story(sid).unwrap().len();
|
||||
let del_it = graphic_item(&mut d, a_deleted, None);
|
||||
d.story_mut(sid).unwrap().insert_object(del_pos, anchor(del_it));
|
||||
d.story_mut(sid)
|
||||
.unwrap()
|
||||
.format_chars(del_pos..del_pos + OBJECT_MARK.len_utf8(), |f| f.over = CharAttrs { change: Some(ChangeMark::Deleted), ..Default::default() });
|
||||
|
||||
let used = used_assets(&d);
|
||||
for expected in [a_inline, a_group, a_media, a_poster, a_table, a_note, a_endnote] {
|
||||
assert!(used.contains(&expected), "missing expected asset {expected:?} in {used:?}");
|
||||
}
|
||||
for excluded in [a_hidden, a_deleted, a_unused] {
|
||||
assert!(!used.contains(&excluded), "unexpected excluded asset {excluded:?} in {used:?}");
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,11 @@ pub struct FontDb {
|
||||
/// when it was read: [`FontDb::reload_fonts`] reads again the files that changed since.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
installed_files: Mutex<HashMap<std::path::PathBuf, FileStamp>>,
|
||||
/// The (family, style) pairs, lowercased, looked for in the catalog because the loaded faces
|
||||
/// lack that style: each is looked for once per scan of the font folders (see
|
||||
/// [`FontDb::load_cataloged_style`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
styles_tried: Mutex<std::collections::HashSet<(String, String)>>,
|
||||
/// 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>,
|
||||
@@ -150,21 +155,40 @@ use system::unix_font_dirs;
|
||||
use system::{CatalogEntry, FileStamp};
|
||||
pub use system::{ReloadedFonts, system_font_dirs};
|
||||
|
||||
impl FlipPen {
|
||||
/// Room for one more path element. A glyph that expands past [`outline::MAX_OUTLINE_ELEMENTS`]
|
||||
/// (a variable-font composite repeating a complex base) stops growing here, and
|
||||
/// [`outline::font_outline`] then returns no outline rather than a truncated one.
|
||||
fn has_room(&self) -> bool {
|
||||
self.0.elements().len() < outline::MAX_OUTLINE_ELEMENTS
|
||||
}
|
||||
}
|
||||
|
||||
impl OutlinePen for FlipPen {
|
||||
fn move_to(&mut self, x: f32, y: f32) {
|
||||
self.0.move_to((x as f64, -y as f64));
|
||||
if self.has_room() {
|
||||
self.0.move_to((x as f64, -y as f64));
|
||||
}
|
||||
}
|
||||
fn line_to(&mut self, x: f32, y: f32) {
|
||||
self.0.line_to((x as f64, -y as f64));
|
||||
if self.has_room() {
|
||||
self.0.line_to((x as f64, -y as f64));
|
||||
}
|
||||
}
|
||||
fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
|
||||
self.0.quad_to((cx0 as f64, -cy0 as f64), (x as f64, -y as f64));
|
||||
if self.has_room() {
|
||||
self.0.quad_to((cx0 as f64, -cy0 as f64), (x as f64, -y as f64));
|
||||
}
|
||||
}
|
||||
fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
|
||||
self.0.curve_to((cx0 as f64, -cy0 as f64), (cx1 as f64, -cy1 as f64), (x as f64, -y as f64));
|
||||
if self.has_room() {
|
||||
self.0.curve_to((cx0 as f64, -cy0 as f64), (cx1 as f64, -cy1 as f64), (x as f64, -y as f64));
|
||||
}
|
||||
}
|
||||
fn close(&mut self) {
|
||||
self.0.close_path();
|
||||
if self.has_room() {
|
||||
self.0.close_path();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,8 @@ impl FontDb {
|
||||
catalog: RwLock::new(Vec::new()),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
installed_files: Mutex::new(HashMap::new()),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
styles_tried: Mutex::new(std::collections::HashSet::new()),
|
||||
font_dirs,
|
||||
font_files: Vec::new,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -207,6 +209,10 @@ impl FontDb {
|
||||
/// The box drawn for `face`'s missing glyph (.notdef) when the font's own has no outline, in
|
||||
/// font units, y-down: a hollow rectangle across the glyph's advance, cap height tall. `None`
|
||||
/// when the font draws its own.
|
||||
///
|
||||
/// Contract: `Some` means exactly that the font's .notdef (glyph 0) has an empty outline, so
|
||||
/// callers may test `missing_box(face).is_some()` for "this font's .notdef is empty" (PDF export
|
||||
/// prints such a glyph as nothing, while [`FontDb::outline`] and the screen show this box).
|
||||
pub fn missing_box(&self, face: &FontFace) -> Option<BezPath> {
|
||||
if !font_outline(face, 0).elements().is_empty() {
|
||||
return None;
|
||||
|
||||
@@ -68,7 +68,12 @@ pub(super) fn has_serifs(face: &FontFace) -> Option<bool> {
|
||||
Some(foot > stem * 1.6)
|
||||
}
|
||||
|
||||
/// Glyph `gid`'s outline as the font draws it, in font units, y-down (flipped).
|
||||
/// Most path elements one glyph's outline may hold: ten times what the largest real glyphs use,
|
||||
/// so only a font that repeats a complex base component past all reason reaches it.
|
||||
pub(super) const MAX_OUTLINE_ELEMENTS: usize = 1 << 18;
|
||||
|
||||
/// Glyph `gid`'s outline as the font draws it, in font units, y-down (flipped). A glyph past
|
||||
/// [`MAX_OUTLINE_ELEMENTS`] has no outline (a truncated one would be a wrong glyph).
|
||||
pub(super) fn font_outline(face: &FontFace, gid: u32) -> BezPath {
|
||||
let mut pen = FlipPen(BezPath::new());
|
||||
if let Some(f) = face.skrifa()
|
||||
@@ -76,6 +81,10 @@ pub(super) fn font_outline(face: &FontFace, gid: u32) -> BezPath {
|
||||
{
|
||||
let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen);
|
||||
}
|
||||
if !pen.has_room() {
|
||||
log::warn!("glyph {gid} has more than {MAX_OUTLINE_ELEMENTS} path elements: drawn empty");
|
||||
return BezPath::new();
|
||||
}
|
||||
pen.0
|
||||
}
|
||||
|
||||
|
||||
@@ -62,10 +62,26 @@ impl ScopedFonts<'_> {
|
||||
return false;
|
||||
}
|
||||
let face = self.face(family, style);
|
||||
// The face found must be one `family` names. `face` takes a face's legacy family name
|
||||
// (`Source Serif 4 Semibold`, name ID 1) to its typographic family and looks the style up
|
||||
// there, so `Source Serif 4 Semibold` `Regular` finds Source Serif 4 Regular: another
|
||||
// face, which Find Font and preflight called exact (#2618).
|
||||
let names = |f: &str| f.eq_ignore_ascii_case(&face.family) || face.family_aliases.iter().any(|alias| alias.eq_ignore_ascii_case(f));
|
||||
// A style with axis settings (`Regular {wght:650}`) matches by its base name only on a
|
||||
// face those settings apply to (an instance); a static face draws without them.
|
||||
let axes_apply = !style.contains('{') || !face.coords.is_empty();
|
||||
let wws_named = |w: &(String, String)| {
|
||||
std::iter::once(family).chain(alternate_names(family)).any(|f| w.0.eq_ignore_ascii_case(f))
|
||||
&& norm(&w.1) == norm(base_style(style))
|
||||
&& axes_apply
|
||||
};
|
||||
if !std::iter::once(family).chain(alternate_names(family)).any(names) {
|
||||
return face.wws.as_ref().is_some_and(wws_named);
|
||||
}
|
||||
norm(&face.style) == norm(style)
|
||||
|| (face.coords.is_empty() && face.style_aliases.iter().any(|alias| norm(alias) == norm(style)))
|
||||
// An optical-size face asked for by its WWS names.
|
||||
|| face.wws.as_ref().is_some_and(|w| w.0.eq_ignore_ascii_case(family) && norm(&w.1) == norm(style))
|
||||
|| face.wws.as_ref().is_some_and(wws_named)
|
||||
}
|
||||
|
||||
/// Prefer known metric-compatible substitutes, then an appropriate script family. This
|
||||
@@ -258,6 +274,12 @@ impl ScopedFonts<'_> {
|
||||
|
||||
fn find_or_load(&self, family: &str, style: &str) -> Option<Arc<FontFace>> {
|
||||
if let Some(f) = self.find(family, style) {
|
||||
// Only another style of the family is loaded: the asked one may have been installed
|
||||
// since the family was loaded (#2617).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if !style.contains('{') && !Self::is_style(&f, family, style) && self.db.load_cataloged_style(family, style) {
|
||||
return self.find(family, style);
|
||||
}
|
||||
return Some(f);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -267,6 +289,16 @@ impl ScopedFonts<'_> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Is `face`, found for `family`, the `style` asked for (by its own, a localized or its WWS
|
||||
/// style name), not the closest of another style?
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn is_style(face: &FontFace, family: &str, style: &str) -> bool {
|
||||
let ns = norm(style);
|
||||
norm(&face.style) == ns
|
||||
|| (face.coords.is_empty() && face.style_aliases.iter().any(|alias| norm(alias) == ns))
|
||||
|| face.wws.as_ref().is_some_and(|w| w.0.eq_ignore_ascii_case(family) && norm(&w.1) == ns)
|
||||
}
|
||||
|
||||
/// The family and style of the face whose PostScript name is `name`, ignoring case (the
|
||||
/// document's, loaded, or installed on the system, not loading it). SVGs exported from
|
||||
/// Illustrator name fonts this way (`font-family="'MyriadPro-Regular'"`).
|
||||
|
||||
@@ -328,6 +328,9 @@ impl FontDb {
|
||||
sys.chain_tried.clear();
|
||||
sys.coverage.clear();
|
||||
sys.coverage_ranges = 0;
|
||||
drop(sys);
|
||||
// Styles installed since their family was loaded can now be found (#2617).
|
||||
self.styles_tried.lock().unwrap_or_else(PoisonError::into_inner).clear();
|
||||
count
|
||||
}
|
||||
|
||||
@@ -461,6 +464,38 @@ impl FontDb {
|
||||
self.insert_faces(faces) > 0
|
||||
}
|
||||
|
||||
/// Load the installed files that hold `style` of `family` (by its typographic or WWS names),
|
||||
/// for a family loaded before that style was installed (#2617). Each family and style is
|
||||
/// looked for once per scan of the font folders, so a style that isn't installed costs one
|
||||
/// catalog search. Returns whether any face was added.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn load_cataloged_style(&self, family: &str, style: &str) -> bool {
|
||||
let ns = norm(style);
|
||||
let paths: Vec<std::path::PathBuf> = {
|
||||
// Held while the catalog is read: a rescan clears it only after its catalog is in.
|
||||
let mut tried = self.styles_tried.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if !tried.insert((family.to_lowercase(), ns.clone())) {
|
||||
return false;
|
||||
}
|
||||
let cat = self.read_catalog();
|
||||
let named = |c: &CatalogEntry| {
|
||||
(c.family.eq_ignore_ascii_case(family) && norm(&c.style) == ns)
|
||||
|| c.wws.as_ref().is_some_and(|w| w.0.eq_ignore_ascii_case(family) && norm(&w.1) == ns)
|
||||
};
|
||||
let mut p: Vec<_> = cat.iter().filter(|c| named(c)).map(|c| c.path.clone()).collect();
|
||||
p.sort();
|
||||
p.dedup();
|
||||
p
|
||||
};
|
||||
let mut faces = Vec::new();
|
||||
for p in paths {
|
||||
if let Some(data) = self.read_installed(&p) {
|
||||
faces.extend(self.new_faces(data, FontSource::Installed(p)));
|
||||
}
|
||||
}
|
||||
self.insert_faces(faces) > 0
|
||||
}
|
||||
|
||||
/// Load the font files (.ttf, .otf, .ttc, .otc; not in subfolders) of a document's `Document
|
||||
/// Fonts` folder under a new scope, for that document alone: looked up through
|
||||
/// [`FontDb::scoped`], they come before the shared faces of the same family and style, until
|
||||
|
||||
@@ -8,3 +8,18 @@ mod fallback;
|
||||
mod docfonts;
|
||||
|
||||
mod vertical;
|
||||
|
||||
/// A glyph that keeps drawing past the element cap stops growing the path, and says so.
|
||||
#[test]
|
||||
fn the_outline_pen_stops_at_the_element_cap() {
|
||||
use super::outline::MAX_OUTLINE_ELEMENTS;
|
||||
use super::{BezPath, FlipPen, OutlinePen};
|
||||
let mut pen = FlipPen(BezPath::new());
|
||||
pen.move_to(0.0, 0.0);
|
||||
for i in 0..MAX_OUTLINE_ELEMENTS + 10 {
|
||||
pen.line_to(i as f32, 0.0);
|
||||
}
|
||||
pen.close();
|
||||
assert_eq!(pen.0.elements().len(), MAX_OUTLINE_ELEMENTS);
|
||||
assert!(!pen.has_room());
|
||||
}
|
||||
@@ -227,6 +227,8 @@ fn a_wws_family_that_is_also_the_legacy_family_finds_the_optical_size_face() {
|
||||
assert_eq!(fonts.face("DocFont Kepler Display", "Light").style, "Light Display", "the display face, not the text size");
|
||||
assert_eq!(fonts.styles("DocFont Kepler Display"), ["Light"]);
|
||||
assert!(fonts.has_style("DocFont Kepler Display", "Light"));
|
||||
// Axis settings on a static face aren't applied, so that style isn't there (#2672 review).
|
||||
assert!(!fonts.has_style("DocFont Kepler Display", "Light {wght:650}"));
|
||||
assert_eq!(fonts.face("DocFont Kepler", "Light").style, "Light");
|
||||
let _ = std::fs::remove_dir_all(&folder);
|
||||
}
|
||||
@@ -165,6 +165,27 @@ fn rescanning_finds_fonts_installed_since() {
|
||||
assert!(db.has_family(FAMILY) && has(&db.families(), FAMILY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reloading_finds_a_style_installed_since_its_family_was_loaded() {
|
||||
// #2617: the family's Regular is in use; its Bold is installed while the app runs.
|
||||
let dir = font_dir("new-style");
|
||||
let later = dir.join("Later");
|
||||
std::fs::create_dir_all(&later).unwrap();
|
||||
std::fs::copy(dir.join("Sysfont-Regular.ttf"), later.join("Sysfont-Regular.ttf")).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![later.clone()]);
|
||||
assert_eq!(db.face(FAMILY, "Regular").style, "Regular");
|
||||
assert!(db.is_loaded(FAMILY));
|
||||
assert!(!db.scoped(0).has_style(FAMILY, "Bold"));
|
||||
std::fs::copy(dir.join("Sub/Sysfont-Bold.TTF"), later.join("Sysfont-Bold.ttf")).unwrap();
|
||||
assert_eq!(db.reload_fonts().cataloged, 2);
|
||||
assert_eq!(db.face(FAMILY, "Bold").style, "Bold");
|
||||
assert!(db.scoped(0).has_style(FAMILY, "Bold"));
|
||||
assert_eq!(db.face(FAMILY, "Regular").style, "Regular");
|
||||
// A style still missing is the closest one, as before.
|
||||
assert_eq!(db.face(FAMILY, "Light").style, "Regular");
|
||||
assert!(!db.scoped(0).has_style(FAMILY, "Light"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_background_scan_serves_the_first_lookup() {
|
||||
let dir = font_dir("background");
|
||||
|
||||
@@ -184,6 +184,9 @@ struct Importer<'r> {
|
||||
para_els: HashMap<String, El>,
|
||||
layers: Vec<Layer>,
|
||||
layer_ids: HashMap<String, LayerId>,
|
||||
/// The layer of the group (or frame) whose children are being read: IDML gives children no
|
||||
/// ItemLayer of their own, they sit on their parent's layer.
|
||||
parent_layer: Option<LayerId>,
|
||||
stories: BTreeMap<StoryId, Story>,
|
||||
story_ids: HashMap<String, StoryId>,
|
||||
parents: Vec<Spread>,
|
||||
@@ -290,6 +293,7 @@ impl<'r> Importer<'r> {
|
||||
para_els: HashMap::new(),
|
||||
layers: Vec::new(),
|
||||
layer_ids: HashMap::new(),
|
||||
parent_layer: None,
|
||||
stories: BTreeMap::new(),
|
||||
story_ids: HashMap::new(),
|
||||
parents: Vec::new(),
|
||||
|
||||
@@ -61,7 +61,7 @@ impl<'r> Importer<'r> {
|
||||
if let Some(s) = model_item.self_id() {
|
||||
self.item_ids.insert(s.to_string(), id);
|
||||
}
|
||||
let layer = model_item.item_layer().and_then(|l| self.layer_ids.get(l)).copied().unwrap_or_else(|| self.layers[0].id);
|
||||
let layer = model_item.item_layer().and_then(|l| self.layer_ids.get(l)).copied().or(self.parent_layer).unwrap_or_else(|| self.layers[0].id);
|
||||
let path = path_from_model(model_item.geometry());
|
||||
let mut it = Item::new(id, layer, shape, path);
|
||||
it.xf = parent * Affine::new(model_item.item_transform());
|
||||
@@ -184,19 +184,47 @@ impl<'r> Importer<'r> {
|
||||
}
|
||||
}
|
||||
self.read_content(e, &model_item, tag, id, &mut it);
|
||||
// A text frame drawn as a slightly slanted rectangle carries the slant in its transform:
|
||||
// its text is set in the rectangle and slants with the frame, instead of being cut by
|
||||
// the sloped edges as in a shaped frame (#2615).
|
||||
if tag == "TextFrame"
|
||||
&& let Some((rect, slant)) = unslant_text_frame_path(&it.path)
|
||||
{
|
||||
let back = slant.inverse();
|
||||
it.path = rect;
|
||||
it.xf *= slant;
|
||||
if let Some(p) = &mut it.wrap.path {
|
||||
p.transform(back);
|
||||
}
|
||||
// Explicit gradient vectors are in the inner space too, so they move with the path. A
|
||||
// linear gradient's colour is its parameter along the axis, which the slant changes
|
||||
// for points off the axis, so its axis is compensated; a radial vector is a centre
|
||||
// and a radius point, so both just move back.
|
||||
let linear = |name: &str| {
|
||||
designcraft_color::swatch::resolve_gradient(&self.swatches, name).is_some_and(|g| g.kind == designcraft_color::GradientKind::Linear)
|
||||
};
|
||||
if let Some(v) = it.fill.gradient_vector {
|
||||
it.fill.gradient_vector = Some(unslant_gradient_vector(v, back, linear(&it.fill.swatch)));
|
||||
}
|
||||
if let Some(v) = it.stroke.gradient_vector {
|
||||
it.stroke.gradient_vector = Some(unslant_gradient_vector(v, back, linear(&it.stroke.swatch)));
|
||||
}
|
||||
}
|
||||
Some(it)
|
||||
}
|
||||
|
||||
fn read_content(&mut self, e: &El, model_item: &craft_idml::model::PageItem, tag: &str, id: ItemId, item: &mut Item) {
|
||||
match tag {
|
||||
"TextFrame" => {
|
||||
let story_self = model_item.parent_story().unwrap_or("n").to_string();
|
||||
let mut story_self = model_item.parent_story().unwrap_or("n").to_string();
|
||||
let story = match self.story_ids.get(&story_self) {
|
||||
Some(s) => *s,
|
||||
None => {
|
||||
let sid = StoryId(self.alloc());
|
||||
self.stories.insert(sid, Story::new(sid));
|
||||
self.story_ids.insert(format!("#orphan{}", sid.0), sid);
|
||||
// Threaded by this key (an anchored frame isn't on a spread to find it by).
|
||||
story_self = format!("#orphan{}", sid.0);
|
||||
self.story_ids.insert(story_self.clone(), sid);
|
||||
sid
|
||||
}
|
||||
};
|
||||
@@ -233,12 +261,14 @@ impl<'r> Importer<'r> {
|
||||
}
|
||||
"Group" => {
|
||||
let mut kids = Vec::new();
|
||||
let outer = self.parent_layer.replace(item.layer);
|
||||
for child in model_item.items() {
|
||||
let child = crate::xml::from_craft(child.to_el());
|
||||
if let Some(k) = self.item(&child, Affine::IDENTITY) {
|
||||
kids.push(Arc::new(k));
|
||||
}
|
||||
}
|
||||
self.parent_layer = outer;
|
||||
item.content = Content::Group { items: kids };
|
||||
item.fill = Fill::none();
|
||||
item.stroke = Stroke::none();
|
||||
@@ -265,12 +295,14 @@ impl<'r> Importer<'r> {
|
||||
}
|
||||
} else {
|
||||
// Page items pasted into this frame (Paste Into).
|
||||
let outer = self.parent_layer.replace(item.layer);
|
||||
let kids: Vec<Arc<Item>> = e
|
||||
.elements()
|
||||
.filter(|c| matches!(c.local(), "Rectangle" | "Oval" | "Polygon" | "GraphicLine" | "Group" | "TextFrame"))
|
||||
.filter_map(|c| self.item(c, Affine::IDENTITY))
|
||||
.map(Arc::new)
|
||||
.collect();
|
||||
self.parent_layer = outer;
|
||||
if !kids.is_empty() {
|
||||
item.content = Content::Group { items: kids };
|
||||
}
|
||||
@@ -416,6 +448,71 @@ fn clipping_path(g: &El, to_graphic: Affine) -> Option<Arc<designcraft_doc::Clip
|
||||
Some(Arc::new(c))
|
||||
}
|
||||
|
||||
/// Largest slope (1 in 20, about 3°) of a slanted rectangle's edges that [`unslant_text_frame_path`]
|
||||
/// moves into the transform; a frame slanted more stays a shaped frame.
|
||||
const MAX_FRAME_SLANT: f64 = 0.05;
|
||||
|
||||
/// For a text frame path that is one closed parallelogram of four corner points, each edge within
|
||||
/// [`MAX_FRAME_SLANT`] of horizontal or vertical but not all axis-aligned: the axis-aligned
|
||||
/// rectangle with the same centre, width and height (anchors in the same order), and the slant
|
||||
/// that maps it onto the path. None for any other path.
|
||||
fn unslant_text_frame_path(path: &PathData) -> Option<(PathData, Affine)> {
|
||||
let [sp] = path.subpaths.as_slice() else { return None };
|
||||
let [p0, p1, p2, p3] = sp.anchors.as_slice() else { return None };
|
||||
let pts = [p0, p1, p2, p3];
|
||||
if !sp.closed || pts.iter().any(|a| a.h_in != a.p || a.h_out != a.p || !(a.p.x.is_finite() && a.p.y.is_finite())) {
|
||||
return None;
|
||||
}
|
||||
let (e1, e2) = (p1.p - p0.p, p3.p - p0.p);
|
||||
// A parallelogram: the fourth corner is where the two edges from the first one lead.
|
||||
let size = e1.hypot().max(e2.hypot());
|
||||
if !size.is_finite() || ((p0.p + e1 + e2) - p2.p).hypot() > size * 1e-9 {
|
||||
return None;
|
||||
}
|
||||
let (h, v) = if e1.x.abs() >= e1.y.abs() { (e1, e2) } else { (e2, e1) };
|
||||
// Edge directions with positive width and height.
|
||||
let h = if h.x < 0.0 { -h } else { h };
|
||||
let v = if v.y < 0.0 { -v } else { v };
|
||||
let (w, ht) = (h.x, v.y);
|
||||
let (sy, sx) = (h.y / w, v.x / ht);
|
||||
if !(w > 0.0 && ht > 0.0 && sy.abs() <= MAX_FRAME_SLANT && sx.abs() <= MAX_FRAME_SLANT) || (sy == 0.0 && sx == 0.0) {
|
||||
return None;
|
||||
}
|
||||
let c = p0.p.midpoint(p2.p).to_vec2();
|
||||
let slant = Affine::translate(c) * Affine::new([1.0, sy, sx, 1.0, 0.0, 0.0]) * Affine::translate(-c);
|
||||
// Unslanted corners, snapped to the rectangle's edges so it is exactly axis-aligned.
|
||||
let mut rect = path.transformed(slant.inverse());
|
||||
for sp in &mut rect.subpaths {
|
||||
for a in &mut sp.anchors {
|
||||
let x = if a.p.x < c.x { c.x - w / 2.0 } else { c.x + w / 2.0 };
|
||||
let y = if a.p.y < c.y { c.y - ht / 2.0 } else { c.y + ht / 2.0 };
|
||||
a.p = Point::new(x, y);
|
||||
(a.h_in, a.h_out) = (a.p, a.p);
|
||||
}
|
||||
}
|
||||
Some((rect, slant))
|
||||
}
|
||||
|
||||
/// A gradient vector in a text frame's inner space, moved into the unslanted space that `back`
|
||||
/// maps the path back to. A radial vector is a centre and a radius point, so both move back. A
|
||||
/// linear gradient's colour is its parameter along the axis, and the slant changes that parameter
|
||||
/// for points off the axis, so its axis takes the shear's inverse transpose, scaled to span the
|
||||
/// same parameter range: every point then keeps the colour it had in the original space.
|
||||
fn unslant_gradient_vector([x0, y0, x1, y1]: [f64; 4], back: Affine, linear: bool) -> [f64; 4] {
|
||||
let (a, b) = (back * Point::new(x0, y0), back * Point::new(x1, y1));
|
||||
let [m11, m12, m21, m22, _, _] = back.as_coeffs();
|
||||
let det = m11 * m22 - m12 * m21;
|
||||
let (dx, dy) = (x1 - x0, y1 - y0);
|
||||
// The axis's image under the shear's inverse transpose, and the factor that keeps the
|
||||
// parameter the one it had in the original space.
|
||||
let (ex, ey) = ((m22 * dx - m12 * dy) / det, (m11 * dy - m21 * dx) / det);
|
||||
let k = (dx * dx + dy * dy) / (ex * ex + ey * ey);
|
||||
if !linear || !(k.is_finite() && k > 0.0) {
|
||||
return [a.x, a.y, b.x, b.y];
|
||||
}
|
||||
[a.x, a.y, a.x + k * ex, a.y + k * ey]
|
||||
}
|
||||
|
||||
fn path_from_model(geometry: craft_idml::model::PathGeometry) -> PathData {
|
||||
let subpaths = geometry
|
||||
.paths
|
||||
|
||||
@@ -120,11 +120,18 @@ impl<'r> Importer<'r> {
|
||||
}
|
||||
|
||||
pub(super) fn stroke_from(&mut self, e: &El, item: Option<&El>) -> Stroke {
|
||||
let model_elements = if item.is_some() {
|
||||
std::iter::once(e).chain(self.object_style_chain(e).iter()).map(crate::xml::to_craft).collect::<Vec<_>>()
|
||||
if item.is_some() {
|
||||
let chain = self.object_style_chain(e);
|
||||
let levels: Vec<&El> = std::iter::once(e).chain(chain.iter()).collect();
|
||||
self.stroke_in(&levels)
|
||||
} else {
|
||||
vec![crate::xml::to_craft(e)]
|
||||
};
|
||||
self.stroke_in(&[e])
|
||||
}
|
||||
}
|
||||
|
||||
/// The stroke that `levels` give, nearest first: each setting from the first level that has it.
|
||||
pub(super) fn stroke_in(&mut self, levels: &[&El]) -> Stroke {
|
||||
let model_elements: Vec<_> = levels.iter().map(|l| crate::xml::to_craft(l)).collect();
|
||||
let model_refs: Vec<_> = model_elements.iter().collect();
|
||||
let model = craft_idml::model::StrokeValues::from_elements(&model_refs);
|
||||
let mut s = Stroke::none();
|
||||
|
||||
@@ -184,26 +184,31 @@ impl<'r> Importer<'r> {
|
||||
.unwrap_or_else(|| names::style_name_in(OBJECT_BUILTINS, &unescape_id(b.trim_start_matches("ObjectStyle/"))))
|
||||
});
|
||||
let based_on = based_on.filter(|b| *b != designcraft_doc::NO_OBJECT_STYLE && *b != name);
|
||||
let fill = values.fill_enabled.then(|| {
|
||||
let sw = values.fill_color.as_deref().map(|r| self.swatch_ref(r)).unwrap_or_else(|| swatch::NONE.into());
|
||||
Fill { swatch: sw, tint: tint(values.fill_tint).unwrap_or(1.0), ..Fill::none() }
|
||||
});
|
||||
let stroke = values.stroke_enabled.then(|| self.stroke_from(e, None));
|
||||
let paragraph_style = values.paragraph_style_enabled.then(|| values.paragraph_style.as_deref().map(|r| self.para_style_ref(r))).flatten();
|
||||
let levels = based_on_levels(e, &objects_by_self);
|
||||
// Fill, stroke and paragraph style: each category as the nearest style that gives its
|
||||
// flag (or, without one, its value) sets it, and each value from the nearest style that
|
||||
// gives it, up to the first style that turns the category off.
|
||||
let fill = category_on(&levels, "EnableFill", |l| l.get("FillColor").is_some()).then(|| {
|
||||
let on = category_levels(&levels, "EnableFill");
|
||||
let sw = on.iter().find_map(|l| l.get("FillColor")).map(|r| self.swatch_ref(r)).unwrap_or_else(|| swatch::NONE.into());
|
||||
Fill { swatch: sw, tint: tint(on.iter().find_map(|l| l.num("FillTint"))).unwrap_or(1.0), ..Fill::none() }
|
||||
});
|
||||
let stroke = category_on(&levels, "EnableStroke", |l| l.get("StrokeColor").is_some())
|
||||
.then(|| self.stroke_in(&category_levels(&levels, "EnableStroke")));
|
||||
let para_levels = category_levels(&levels, "EnableParagraphStyle");
|
||||
let paragraph_style = category_on(&levels, "EnableParagraphStyle", |l| l.get("AppliedParagraphStyle").is_some())
|
||||
.then(|| para_levels.iter().find_map(|l| l.get("AppliedParagraphStyle")).map(|r| self.para_style_ref(r)))
|
||||
.flatten();
|
||||
let text_frame = if category_on(&levels, "EnableTextFrameGeneralOptions", |_| false) {
|
||||
let prefs: Vec<&El> = levels
|
||||
.iter()
|
||||
.filter(|l| l.get("EnableTextFrameGeneralOptions") != Some("false"))
|
||||
.filter_map(|l| l.find("TextFramePreference"))
|
||||
.collect();
|
||||
let prefs: Vec<&El> =
|
||||
category_levels(&levels, "EnableTextFrameGeneralOptions").into_iter().filter_map(|l| l.find("TextFramePreference")).collect();
|
||||
(!prefs.is_empty()).then(|| self.frame_options(&prefs))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let effects = self.style_effects(e);
|
||||
let corners = style_corners(&levels);
|
||||
let apply_next_style = paragraph_style.is_some() && e.get("ApplyNextParagraphStyle") == Some("true");
|
||||
let apply_next_style = paragraph_style.is_some() && para_levels.iter().find_map(|l| l.get("ApplyNextParagraphStyle")) == Some("true");
|
||||
let s = ObjectStyle { name: name.clone(), based_on, fill, stroke, paragraph_style, apply_next_style, text_frame, effects, corners };
|
||||
match self.styles.object.iter_mut().find(|o| o.name == name) {
|
||||
Some(slot) => *slot = s,
|
||||
@@ -224,8 +229,12 @@ impl<'r> Importer<'r> {
|
||||
}
|
||||
|
||||
fn based_on(&self, e: &El, para: bool) -> Option<String> {
|
||||
let b = e.prop("BasedOn")?;
|
||||
let b = b.trim();
|
||||
let raw = e.prop("BasedOn")?;
|
||||
// Style names may end in a space: use the reference as written, or without the line
|
||||
// breaks and indentation an indented file puts around it, when that names a style; only
|
||||
// otherwise trim it.
|
||||
let names = if para { &self.para_names } else { &self.char_names };
|
||||
let b = [raw.as_str(), unindented(&raw)].into_iter().find(|r| names.contains_key(*r)).unwrap_or_else(|| raw.trim());
|
||||
if para {
|
||||
if let Some(n) = self.para_names.get(b) {
|
||||
return Some(n.clone());
|
||||
@@ -327,7 +336,11 @@ impl<'r> Importer<'r> {
|
||||
if let Some(v) = e.prop(k) {
|
||||
return Some(v);
|
||||
}
|
||||
let style_ref = |r: String| if r.starts_with("ParagraphStyle/") { r } else { format!("ParagraphStyle/{}", names::escape_id(&r)) };
|
||||
// As `based_on` reads it: the reference as written, or without the line breaks and
|
||||
// indentation an indented file puts around it, when that names a style; else trimmed.
|
||||
let id = |r: &str| if r.starts_with("ParagraphStyle/") { r.to_string() } else { format!("ParagraphStyle/{}", names::escape_id(r)) };
|
||||
let style_ref =
|
||||
|r: String| [r.as_str(), unindented(&r)].into_iter().map(id).find(|i| self.para_els.contains_key(i)).unwrap_or_else(|| id(r.trim()));
|
||||
let mut next =
|
||||
if e.local() == "ParagraphStyle" { e.prop("BasedOn") } else { e.get("AppliedParagraphStyle").map(str::to_string) }.map(style_ref);
|
||||
for _ in 0..16 {
|
||||
@@ -405,25 +418,35 @@ impl<'r> Importer<'r> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `r` without the whitespace an indented file puts around an element's text: all of it before
|
||||
/// (a style reference never starts with a space), and after it from the first line break on (a
|
||||
/// name's own trailing spaces come before that).
|
||||
fn unindented(r: &str) -> &str {
|
||||
let r = r.trim_start();
|
||||
let text = r.trim_end().len();
|
||||
match r.get(text..).and_then(|tail| tail.find(['\n', '\r'])) {
|
||||
Some(i) => r.get(..text + i).unwrap_or(r),
|
||||
None => r,
|
||||
}
|
||||
}
|
||||
|
||||
/// The corner options (Stroke & Corner Options) of the object style that starts `levels` (the
|
||||
/// style, then the styles it is based on), by name, when it sets them. A style that sets some
|
||||
/// corners, or turns the category on (itself or through the style it is based on), takes the
|
||||
/// others from the styles in `levels` that don't turn the category off.
|
||||
/// others from the styles in `levels` before the first one that turns the category off.
|
||||
fn style_corners(levels: &[&El]) -> Option<CornerOptions> {
|
||||
if !category_on(levels, "EnableStrokeAndCornerOptions", |l| corners(l, "").is_some()) {
|
||||
return None;
|
||||
}
|
||||
let on: Vec<&El> = levels.iter().copied().filter(|l| l.get("EnableStrokeAndCornerOptions") != Some("false")).collect();
|
||||
corners_in(&on, "").map(|c| CornerOptions { corners: c })
|
||||
corners_in(&category_levels(levels, "EnableStrokeAndCornerOptions"), "").map(|c| CornerOptions { corners: c })
|
||||
}
|
||||
|
||||
/// Whether the style chain `levels` (a style, then the styles it is based on) turns the category
|
||||
/// whose flag is `flag` on. The nearest style that gives the flag decides; a style without it
|
||||
/// turns the category on when `own` finds settings of its own. A `[None]` after the first style
|
||||
/// ends the chain, as a `BasedOn` of `[None]` names no style.
|
||||
/// ends the chain ([`chain`]).
|
||||
fn category_on(levels: &[&El], flag: &str, own: impl Fn(&El) -> bool) -> bool {
|
||||
let none = |l: &&El| l.get("Self") == Some("ObjectStyle/$ID/[None]");
|
||||
for l in levels.iter().take(1).chain(levels.iter().skip(1).take_while(|l| !none(l))) {
|
||||
for l in chain(levels) {
|
||||
match l.get(flag) {
|
||||
Some(v) => return v == "true",
|
||||
None if own(l) => return true,
|
||||
@@ -433,6 +456,19 @@ fn category_on(levels: &[&El], flag: &str, own: impl Fn(&El) -> bool) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The styles in `levels` (a style, then the styles it is based on) that give the values of the
|
||||
/// category whose flag is `flag`, nearest first: those before the first one that turns it off, and
|
||||
/// before a `[None]` after the first style.
|
||||
fn category_levels<'e>(levels: &[&'e El], flag: &str) -> Vec<&'e El> {
|
||||
chain(levels).take_while(|l| l.get(flag) != Some("false")).collect()
|
||||
}
|
||||
|
||||
/// `levels` up to a `[None]` after the first style, as a `BasedOn` of `[None]` names no style.
|
||||
fn chain<'a, 'e>(levels: &'a [&'e El]) -> impl Iterator<Item = &'e El> + 'a {
|
||||
let more = levels.iter().skip(1).take_while(|l| l.get("Self") != Some("ObjectStyle/$ID/[None]"));
|
||||
levels.iter().take(1).chain(more).copied()
|
||||
}
|
||||
|
||||
/// Object style `e`, then the styles it is based on, nearest first (cycle-safe, at most 16). A
|
||||
/// `BasedOn` may name a style by its `Self` id or by its bare name.
|
||||
fn based_on_levels<'e>(e: &'e El, objects_by_self: &HashMap<&str, &'e El>) -> Vec<&'e El> {
|
||||
|
||||
@@ -660,6 +660,102 @@ fn absent_item_and_document_attributes_take_indesign_defaults() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #2615: a text frame whose path is a slightly slanted rectangle (here its top and bottom drop
|
||||
/// 2.09 pt across 207.75 pt) is imported as a rectangle with the slant in its transform. Its text
|
||||
/// starts at the column edge and a heading that fits stays on one line, instead of the sloped top
|
||||
/// edge cutting the first lines as in a shaped frame.
|
||||
#[test]
|
||||
fn slightly_slanted_text_frame_sets_its_text_in_the_rectangle() {
|
||||
let corners = [(-136.5, -74.69600535168195), (-136.5, 93.6875), (71.24999999999999, 91.6022553516819), (71.24999999999999, -76.78125000000001)];
|
||||
let pts: String =
|
||||
corners.iter().map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#)).collect();
|
||||
let body = "Body text follows the heading and fills a few more lines of the frame so that the story has more than one paragraph.";
|
||||
let designmap = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0" Self="d">
|
||||
<Story Self="s1"><ParagraphStyleRange><CharacterStyleRange><Content>Results at a glance</Content><Br/><Content>{body}</Content></CharacterStyleRange></ParagraphStyleRange></Story>
|
||||
<Spread Self="sp1"><Page Self="p1"/>
|
||||
<TextFrame Self="tf" ParentStory="s1" ItemTransform="1 0 0 1 300 300" GradientFillLength="100" GradientFillStart="-100 0"><Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties></TextFrame>
|
||||
</Spread>
|
||||
</Document>"#
|
||||
);
|
||||
let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap)]), &|_| None).unwrap();
|
||||
let it = &d.spreads[0].items[0];
|
||||
// The frame is where InDesign drew it: its corners on the spread are unchanged.
|
||||
let anchors = &it.path.subpaths[0].anchors;
|
||||
for (a, &(x, y)) in anchors.iter().zip(&corners) {
|
||||
let p = it.xf * a.p;
|
||||
assert!((p.x - (x + 300.0)).abs() < 1e-9 && (p.y - (y + 300.0)).abs() < 1e-9, "{p:?} vs {x} {y}");
|
||||
}
|
||||
// An explicit gradient vector moves with the path: it is still where InDesign put it.
|
||||
let [x0, y0, x1, y1] = it.fill.gradient_vector.expect("gradient vector");
|
||||
for ((x, y), (ex, ey)) in [(x0, y0), (x1, y1)].into_iter().zip([(-100.0, 0.0), (0.0, 0.0)]) {
|
||||
let p = it.xf * designcraft_geom::Point::new(x, y);
|
||||
assert!((p.x - (ex + 300.0)).abs() < 1e-9 && (p.y - (ey + 300.0)).abs() < 1e-9, "{p:?} vs {ex} {ey}");
|
||||
}
|
||||
let sid = it.text_frame().unwrap().story;
|
||||
let cs = designcraft_compose::compose_story(&d, sid, &Default::default());
|
||||
let lines: Vec<_> = cs.frames[0].lines.iter().collect();
|
||||
assert!(lines.len() >= 3, "{} lines", lines.len());
|
||||
let area = it.text_area();
|
||||
assert!((lines[0].x0 - area.x0).abs() < 1e-9 && (lines[0].x1 - area.x1).abs() < 1e-9, "first line {}..{} in {area:?}", lines[0].x0, lines[0].x1);
|
||||
assert_eq!(lines.iter().filter(|l| l.para == 0).count(), 1, "the heading fits on one line");
|
||||
assert!(lines.iter().all(|l| (l.x0 - area.x0).abs() < 1e-9), "every line starts at the column edge");
|
||||
}
|
||||
|
||||
/// #2615: a linear gradient (fill and stroke) on a slanted text frame keeps the colour it had in
|
||||
/// the frame's original space at points off its axis. Mapping only the vector's endpoints back
|
||||
/// would tilt the parameter field: here the frame's sides lean 8 pt over its 300 pt height, and
|
||||
/// the spread point (300, 300) is half-way along the gradient.
|
||||
#[test]
|
||||
fn a_slanted_text_frames_gradient_keeps_its_parameter_off_the_axis() {
|
||||
let corners = [(246.0, 0.0), (254.0, 300.0), (354.0, 300.0), (346.0, 0.0)];
|
||||
let pts: String =
|
||||
corners.iter().map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#)).collect();
|
||||
let graphic = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<idPkg:Graphic xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
|
||||
<Color Self="Color/From" Model="Process" Space="CMYK" ColorValue="0 0 0 0" Name="From"/>
|
||||
<Color Self="Color/To" Model="Process" Space="CMYK" ColorValue="0 0 0 100" Name="To"/>
|
||||
<Gradient Self="Gradient/Ramp" Type="Linear" Name="Ramp">
|
||||
<GradientStop Self="g0" StopColor="Color/From" Location="0"/>
|
||||
<GradientStop Self="g1" StopColor="Color/To" Location="100"/>
|
||||
</Gradient>
|
||||
</idPkg:Graphic>"#;
|
||||
let designmap = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0" Self="d">
|
||||
<idPkg:Graphic src="Resources/Graphic.xml"/>
|
||||
<Spread Self="sp1"><Page Self="p1"/>
|
||||
<TextFrame Self="tf" ItemTransform="1 0 0 1 0 0" FillColor="Gradient/Ramp" StrokeColor="Gradient/Ramp" StrokeWeight="2" GradientFillStart="250 150" GradientFillLength="100" GradientStrokeStart="250 150" GradientStrokeLength="100"><Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties></TextFrame>
|
||||
</Spread>
|
||||
</Document>"#
|
||||
);
|
||||
let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap), ("Resources/Graphic.xml", graphic)]), &|_| None).unwrap();
|
||||
let it = &d.spreads[0].items[0];
|
||||
// The frame is unslanted: its path is the rectangle, the slant is in its transform, and its
|
||||
// corners on the spread are where InDesign drew them.
|
||||
let rect = [(250.0, 0.0), (250.0, 300.0), (350.0, 300.0), (350.0, 0.0)];
|
||||
for (a, (&(x, y), &(ex, ey))) in it.path.subpaths[0].anchors.iter().zip(rect.iter().zip(&corners)) {
|
||||
assert!((a.p.x - x).abs() < 1e-9 && (a.p.y - y).abs() < 1e-9, "path {:?} vs {x} {y}", a.p);
|
||||
let p = it.xf * a.p;
|
||||
assert!((p.x - ex).abs() < 1e-9 && (p.y - ey).abs() < 1e-9, "corner {p:?} vs {ex} {ey}");
|
||||
}
|
||||
// The parameter along each gradient at an off-axis spread point is the one it had before the
|
||||
// frame was unslanted: (250, 150) to (350, 150), so x = 275 is a quarter and x = 300 a half.
|
||||
let param = |v: [f64; 4], p: designcraft_geom::Point| {
|
||||
let d = designcraft_geom::Point::new(v[2], v[3]) - designcraft_geom::Point::new(v[0], v[1]);
|
||||
(p - designcraft_geom::Point::new(v[0], v[1])).dot(d) / d.hypot2()
|
||||
};
|
||||
for (x, want) in [(275.0, 0.25), (300.0, 0.5)] {
|
||||
let p = it.xf.inverse() * designcraft_geom::Point::new(x, 300.0);
|
||||
for (what, v) in [("fill", it.fill.gradient_vector), ("stroke", it.stroke.gradient_vector)] {
|
||||
let v = v.unwrap_or_else(|| panic!("{what} gradient vector"));
|
||||
let got = param(v, p);
|
||||
assert!((got - want).abs() < 1e-9, "{what} at x = {x}: {got} instead of {want}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// InDesign: a break character ends its paragraph (`<Br/>` with a ParagraphBreakType closes the
|
||||
/// range); the text after it is a paragraph with its own style, set on the next page of the
|
||||
/// break's parity.
|
||||
@@ -2688,6 +2784,72 @@ fn layers_import_and_export_in_stacking_order() {
|
||||
assert_eq!(back.spreads[0].items[0].layer, back.layers[1].id);
|
||||
}
|
||||
|
||||
/// A character style based on one whose name ends in a space ("arabic purple ") inherits from
|
||||
/// it: the reference was trimmed, the base went missing and its font and colour with it.
|
||||
#[test]
|
||||
fn based_on_a_style_name_ending_in_a_space() {
|
||||
let styles = STYLES.replace(
|
||||
r#"<CharacterStyle Self="CharacterStyle/Strong" Name="Strong" FontStyle="Bold">"#,
|
||||
r#"<CharacterStyle Self="CharacterStyle/purple " Name="purple " FillColor="Color/Brand">
|
||||
<Properties><AppliedFont type="string">Source Sans 3</AppliedFont></Properties>
|
||||
</CharacterStyle>
|
||||
<CharacterStyle Self="CharacterStyle/purple 23 pt " Name="purple 23 pt " PointSize="23">
|
||||
<Properties><BasedOn type="object">CharacterStyle/purple </BasedOn></Properties>
|
||||
</CharacterStyle>
|
||||
<CharacterStyle Self="CharacterStyle/Strong" Name="Strong" FontStyle="Bold">"#,
|
||||
);
|
||||
let story = STORY.replace("CharacterStyle/Strong", "CharacterStyle/purple 23 pt ");
|
||||
let pkg = zip_files(&[
|
||||
("designmap.xml", DESIGNMAP),
|
||||
("Resources/Graphic.xml", GRAPHIC),
|
||||
("Resources/Styles.xml", &styles),
|
||||
("Resources/Preferences.xml", PREFS),
|
||||
("MasterSpreads/MasterSpread_m1.xml", MASTER),
|
||||
("Spreads/Spread_sp1.xml", SPREAD),
|
||||
("Stories/Story_s1.xml", &story),
|
||||
]);
|
||||
let d = import_idml(&pkg).unwrap();
|
||||
let st = d.styles.character.iter().find(|c| c.name == "purple 23 pt ").expect("the derived style");
|
||||
assert_eq!(st.based_on.as_deref(), Some("purple "));
|
||||
let sid = *d.stories.keys().next().unwrap();
|
||||
let story = d.story(sid).unwrap();
|
||||
let at = story.text.find("bold").unwrap();
|
||||
let (_, base) = d.styles.resolve_para(&story.paras[0]);
|
||||
let props = d.styles.resolve_char(&base, story.char_format_at(at + 1));
|
||||
assert_eq!(props.font_family, "Source Sans 3");
|
||||
let fill = d.styles.char_style_attrs("purple ").fill.expect("the base style's colour");
|
||||
assert_eq!(props.fill, fill);
|
||||
}
|
||||
|
||||
/// A BasedOn on lines of its own (an indented file) that names a style whose name ends in a
|
||||
/// space: only the line breaks and indentation around the reference go, not the name's space.
|
||||
#[test]
|
||||
fn based_on_on_lines_of_its_own_keeps_a_trailing_space() {
|
||||
let styles = STYLES.replace(
|
||||
r#"<CharacterStyle Self="CharacterStyle/Strong" Name="Strong" FontStyle="Bold">"#,
|
||||
&[
|
||||
r#"<CharacterStyle Self="CharacterStyle/purple " Name="purple " FillColor="Color/Brand"/>"#,
|
||||
r#"<CharacterStyle Self="CharacterStyle/purple 23 pt " Name="purple 23 pt " PointSize="23">"#,
|
||||
"<Properties><BasedOn type=\"object\">\n CharacterStyle/purple \n </BasedOn></Properties>",
|
||||
r#"</CharacterStyle><CharacterStyle Self="CharacterStyle/Strong" Name="Strong" FontStyle="Bold">"#,
|
||||
]
|
||||
.concat(),
|
||||
);
|
||||
let pkg = zip_files(&[
|
||||
("designmap.xml", DESIGNMAP),
|
||||
("Resources/Graphic.xml", GRAPHIC),
|
||||
("Resources/Styles.xml", &styles),
|
||||
("Resources/Preferences.xml", PREFS),
|
||||
("MasterSpreads/MasterSpread_m1.xml", MASTER),
|
||||
("Spreads/Spread_sp1.xml", SPREAD),
|
||||
("Stories/Story_s1.xml", STORY),
|
||||
]);
|
||||
let d = import_idml(&pkg).unwrap();
|
||||
let st = d.styles.character.iter().find(|c| c.name == "purple 23 pt ").expect("the derived style");
|
||||
assert_eq!(st.based_on.as_deref(), Some("purple "));
|
||||
assert!(d.styles.char_style_attrs("purple 23 pt ").fill.is_some(), "the base style's colour");
|
||||
}
|
||||
|
||||
/// Layer Options › Lock Guides is IDML's `LockGuides`: read, and written back (it was always
|
||||
/// written as false).
|
||||
#[test]
|
||||
@@ -3409,6 +3571,46 @@ fn list_numbering_format_expression_and_bullet_import_and_round_trip() {
|
||||
check(&import_idml(&export_idml(&d)).unwrap());
|
||||
}
|
||||
|
||||
/// The items of a group, and those pasted into a frame, carry no ItemLayer in IDML: they sit on
|
||||
/// the group's or the frame's layer, not on the front layer (which may be hidden or locked and
|
||||
/// took their wrap and editing with it).
|
||||
#[test]
|
||||
fn group_children_sit_on_the_groups_layer() {
|
||||
let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">
|
||||
<Layer Self="L1" Name="Background"/>
|
||||
<Layer Self="L2" Name="Hidden" Visible="false" Locked="true"/>
|
||||
<idPkg:Spread src="Spreads/Spread_s.xml"/>
|
||||
</Document>"#;
|
||||
let rect = |me: &str| {
|
||||
format!(
|
||||
r#"<Rectangle Self="{me}"><Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>
|
||||
<PathPointType Anchor="0 0"/><PathPointType Anchor="0 10"/><PathPointType Anchor="10 10"/><PathPointType Anchor="10 0"/>
|
||||
</PathPointArray></GeometryPathType></PathGeometry></Properties></Rectangle>"#
|
||||
)
|
||||
};
|
||||
let spread = format!(
|
||||
r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Spread Self="s">
|
||||
<Page Self="p" GeometricBounds="0 0 100 100" ItemTransform="1 0 0 1 0 0"/>
|
||||
<Group Self="g" ItemLayer="L1" ItemTransform="1 0 0 1 0 0">{}<Group Self="g2" ItemTransform="1 0 0 1 0 0">{}</Group></Group>
|
||||
{}
|
||||
</Spread></idPkg:Spread>"#,
|
||||
rect("a"),
|
||||
rect("b"),
|
||||
// A frame with an item pasted into it.
|
||||
rect("f").replace(r#"Self="f""#, r#"Self="f" ItemLayer="L1""#).replace("</Rectangle>", &format!("{}</Rectangle>", rect("c")))
|
||||
);
|
||||
let d = import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", &spread)])).unwrap();
|
||||
let background = d.layers.iter().find(|l| l.name == "Background").unwrap().id;
|
||||
let items = &d.spreads[0].items;
|
||||
assert!(items.len() == 2 && items[1].shape == Shape::Rectangle && items[1].has_nested_items(), "{items:?}");
|
||||
let mut layers = Vec::new();
|
||||
for it in items {
|
||||
it.walk(&mut |i| layers.push(i.layer));
|
||||
}
|
||||
assert_eq!(layers.len(), 6);
|
||||
assert!(layers.iter().all(|l| *l == background), "{layers:?}");
|
||||
}
|
||||
|
||||
/// InDesign can write `AppliedFont` with its `$ID/` prefix (`$ID/Source Serif 4`). The text is
|
||||
/// set in that family instead of counting as a missing font drawn in the fallback.
|
||||
#[test]
|
||||
@@ -4505,6 +4707,36 @@ fn style_names_ending_in_a_space_and_partial_rule_overrides_import() {
|
||||
assert_ne!(black.color, white.color, "only the colour is overridden");
|
||||
}
|
||||
|
||||
/// A paragraph style whose `BasedOn` sits on lines of its own (an indented file) takes the
|
||||
/// rule settings it doesn't set from the style it is based on.
|
||||
#[test]
|
||||
fn a_rule_inherits_through_a_based_on_on_lines_of_its_own() {
|
||||
let styles = STYLES.replace(
|
||||
r#" </RootParagraphStyleGroup>"#,
|
||||
" <ParagraphStyle Self=\"ParagraphStyle/Base\" Name=\"Base\" RuleAbove=\"true\" RuleAboveLineWeight=\"16\" RuleAboveOffset=\"-3\">
|
||||
<Properties><BasedOn type=\"string\">$ID/[No paragraph style]</BasedOn></Properties>
|
||||
</ParagraphStyle>
|
||||
<ParagraphStyle Self=\"ParagraphStyle/Derived\" Name=\"Derived\">
|
||||
<Properties><BasedOn type=\"object\">
|
||||
ParagraphStyle/Base
|
||||
</BasedOn><RuleAboveColor type=\"object\">Color/Black</RuleAboveColor></Properties>
|
||||
</ParagraphStyle>
|
||||
<ParagraphStyle Self=\"ParagraphStyle/Spaced\" Name=\"Spaced\">
|
||||
<Properties><BasedOn type=\"object\">
|
||||
ParagraphStyle/Base
|
||||
</BasedOn><RuleAboveColor type=\"object\">Color/Black</RuleAboveColor></Properties>
|
||||
</ParagraphStyle>
|
||||
</RootParagraphStyleGroup>",
|
||||
);
|
||||
let d = import_idml(&fixture_with_table_styles(&styles, STORY)).unwrap();
|
||||
// "Spaced" has a space before the line break, and no style is named with that space.
|
||||
for name in ["Derived", "Spaced"] {
|
||||
let rule = d.styles.paragraph.iter().find(|s| s.name == name).unwrap().para.rule_above.clone().unwrap();
|
||||
assert!(rule.on, "{name}: the rule stays on");
|
||||
assert_eq!((rule.weight, rule.offset), (16.0, -3.0), "{name}: weight and offset come from the base style");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_style_setting_only_a_rules_type_gap_or_keep_in_frame_overrides_it() {
|
||||
let styles = STYLES.replace(
|
||||
@@ -5577,3 +5809,44 @@ fn only_exactly_generated_cross_reference_text_is_regenerated() {
|
||||
let got: Vec<Option<&str>> = s.xrefs.iter().map(|x| x.text.as_deref()).collect();
|
||||
assert_eq!(got, [Some("Page <pageNum />, revised"), None, Some("Seite <pageNum />")]);
|
||||
}
|
||||
|
||||
/// A story part holding `before`, then the anchored text frame `a1` (120 × 40 pt) with
|
||||
/// attributes `attrs` (its story reference), then `after`.
|
||||
fn story_with_anchored_text_frame(before: &str, attrs: &str, after: &str) -> String {
|
||||
format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
|
||||
<Story Self="s1">
|
||||
<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Text%3aBody">
|
||||
<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]">
|
||||
<Content>{before}</Content>
|
||||
<TextFrame Self="a1" {attrs} PreviousTextFrame="n" NextTextFrame="n" ItemTransform="1 0 0 1 10 5">
|
||||
<Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>
|
||||
<PathPointType Anchor="-10 -45"/><PathPointType Anchor="-10 -5"/><PathPointType Anchor="110 -5"/><PathPointType Anchor="110 -45"/>
|
||||
</PathPointArray></GeometryPathType></PathGeometry></Properties>
|
||||
<AnchoredObjectSetting AnchoredPosition="InlinePosition"/>
|
||||
</TextFrame>
|
||||
<Content>{after}</Content>
|
||||
</CharacterStyleRange>
|
||||
</ParagraphStyleRange>
|
||||
</Story>
|
||||
</idPkg:Story>"#
|
||||
)
|
||||
}
|
||||
|
||||
/// An anchored text frame whose ParentStory is unknown or missing gets an empty story threaded to
|
||||
/// it. The empty story was registered under one key and looked up under another when threading,
|
||||
/// so the frame was left out of its thread and the import failed ("embedded text frame … not in
|
||||
/// its story's thread").
|
||||
#[test]
|
||||
fn anchored_text_frames_with_unknown_stories_import_with_empty_ones() {
|
||||
for attrs in [r#"ParentStory="nope""#, ""] {
|
||||
let d = import_idml_with(&fixture_with_story(&story_with_anchored_text_frame("Before ", attrs, " after")), &|_| None).unwrap();
|
||||
d.check().unwrap();
|
||||
let host = d.stories.values().find(|s| s.text.starts_with("Before")).unwrap();
|
||||
let frame = &host.objects[0].item;
|
||||
let shown = d.story(frame.text_frame().unwrap().story).unwrap();
|
||||
assert!(shown.text.is_empty(), "{attrs}");
|
||||
assert_eq!(shown.frames, vec![frame.id], "{attrs}");
|
||||
}
|
||||
}
|
||||
@@ -414,6 +414,93 @@ fn a_style_without_category_flags_takes_them_from_its_based_on_style() {
|
||||
assert!(style(designcraft_doc::NO_OBJECT_STYLE).corners.is_some(), "[None] keeps the corners it sets itself");
|
||||
}
|
||||
|
||||
/// A style without a Fill, Stroke or Paragraph Styles flag or value of its own takes each category
|
||||
/// from the style it is based on, and a style turning a category on takes the values it leaves out
|
||||
/// from there; a based-on style that turns a category off gives nothing.
|
||||
#[test]
|
||||
fn fill_stroke_and_paragraph_style_categories_come_through_the_based_on_chain() {
|
||||
let styles = r#"<ObjectStyle Self="ObjectStyle/Brand" Name="Brand" EnableFill="true" FillColor="Color/Black" FillTint="40"
|
||||
EnableStroke="true" StrokeColor="Color/Black" StrokeWeight="3" EnableParagraphStyle="true"
|
||||
AppliedParagraphStyle="ParagraphStyle/Opener" ApplyNextParagraphStyle="true">
|
||||
<Properties><BasedOn type="string">$ID/[None]</BasedOn></Properties>
|
||||
</ObjectStyle>
|
||||
<ObjectStyle Self="ObjectStyle/Kid" Name="Kid">
|
||||
<Properties><BasedOn type="object">ObjectStyle/Brand</BasedOn></Properties>
|
||||
</ObjectStyle>
|
||||
<ObjectStyle Self="ObjectStyle/Tint" Name="Tint" EnableFill="true" FillTint="70" EnableStroke="true" StrokeWeight="5">
|
||||
<Properties><BasedOn type="object">ObjectStyle/Brand</BasedOn></Properties>
|
||||
</ObjectStyle>
|
||||
<ObjectStyle Self="ObjectStyle/Off" Name="Off" EnableFill="false" EnableStroke="false" EnableParagraphStyle="false">
|
||||
<Properties><BasedOn type="object">ObjectStyle/Brand</BasedOn></Properties>
|
||||
</ObjectStyle>
|
||||
<ObjectStyle Self="ObjectStyle/OffKid" Name="OffKid">
|
||||
<Properties><BasedOn type="object">ObjectStyle/Off</BasedOn></Properties>
|
||||
</ObjectStyle>"#;
|
||||
let d = fixture(styles, &[]);
|
||||
let style = |n: &str| d.styles.object_style(n).cloned().unwrap();
|
||||
let brand = style("Brand");
|
||||
let (brand_fill, brand_stroke) = (brand.fill.clone().expect("Brand sets a fill"), brand.stroke.clone().expect("Brand sets a stroke"));
|
||||
let kid = style("Kid");
|
||||
assert_eq!((kid.fill.as_ref(), kid.stroke.as_ref()), (Some(&brand_fill), Some(&brand_stroke)), "Kid inherits Brand's fill and stroke");
|
||||
assert_eq!((kid.paragraph_style.as_deref(), kid.apply_next_style), (Some("Opener"), true), "Kid inherits Brand's paragraph style");
|
||||
let t = style("Tint");
|
||||
let (fill, stroke) = (t.fill.expect("Tint sets a fill"), t.stroke.expect("Tint sets a stroke"));
|
||||
assert_eq!(fill.swatch, brand_fill.swatch, "Tint takes Brand's fill color");
|
||||
assert!((fill.tint - 0.7).abs() < 1e-6 && (brand_fill.tint - 0.4).abs() < 1e-6, "{fill:?} {brand_fill:?}");
|
||||
assert_eq!((stroke.swatch, stroke.weight), (brand_stroke.swatch.clone(), 5.0), "Tint takes Brand's stroke color");
|
||||
for n in ["Off", "OffKid"] {
|
||||
let s = style(n);
|
||||
assert!(s.fill.is_none() && s.stroke.is_none() && s.paragraph_style.is_none(), "{n}: {s:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A style that turns a category on takes none of its values from beyond a based-on style that
|
||||
/// turns the category off.
|
||||
#[test]
|
||||
fn category_values_stop_at_a_based_on_style_that_turns_the_category_off() {
|
||||
let styles = r#"<ObjectStyle Self="ObjectStyle/Full" Name="Full" EnableFill="true" FillColor="Color/Black"
|
||||
EnableTextFrameGeneralOptions="true" EnableStrokeAndCornerOptions="true" TopLeftCornerOption="RoundedCorner" TopLeftCornerRadius="17">
|
||||
<Properties><BasedOn type="string">$ID/[None]</BasedOn></Properties>
|
||||
<TextFramePreference TextColumnCount="3"/>
|
||||
</ObjectStyle>
|
||||
<ObjectStyle Self="ObjectStyle/Off" Name="Off" EnableFill="false" EnableTextFrameGeneralOptions="false" EnableStrokeAndCornerOptions="false">
|
||||
<Properties><BasedOn type="object">ObjectStyle/Full</BasedOn></Properties>
|
||||
</ObjectStyle>
|
||||
<ObjectStyle Self="ObjectStyle/Gap" Name="Gap" EnableFill="true" EnableTextFrameGeneralOptions="true" EnableStrokeAndCornerOptions="true">
|
||||
<Properties><BasedOn type="object">ObjectStyle/Off</BasedOn></Properties>
|
||||
</ObjectStyle>"#;
|
||||
let d = fixture(styles, &[]);
|
||||
let gap = d.styles.object_style("Gap").cloned().unwrap();
|
||||
assert_eq!(gap.fill.as_ref().map(|f| f.swatch.as_str()), Some(designcraft_color::swatch::NONE), "{:?}", gap.fill);
|
||||
assert_ne!(gap.text_frame.as_ref().map(|t| t.columns), Some(3), "{:?}", gap.text_frame);
|
||||
assert!(gap.corners.is_none(), "{:?}", gap.corners);
|
||||
}
|
||||
|
||||
/// A style based on `[None]` that turns a category on takes none of that category's values from
|
||||
/// `[None]`, which keeps its own.
|
||||
#[test]
|
||||
fn category_values_stop_at_none() {
|
||||
let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">
|
||||
<RootObjectStyleGroup Self="ro">
|
||||
<ObjectStyle Self="ObjectStyle/$ID/[None]" Name="$ID/[None]" EnableFill="true" FillColor="Color/Black" EnableStroke="true"
|
||||
StrokeColor="Color/Black" StrokeWeight="0"/>
|
||||
<ObjectStyle Self="ObjectStyle/Plain" Name="Plain" EnableFill="true" FillTint="70" EnableStroke="true" StrokeColor="Color/Black">
|
||||
<Properties><BasedOn type="string">$ID/[None]</BasedOn></Properties>
|
||||
</ObjectStyle>
|
||||
</RootObjectStyleGroup>
|
||||
<idPkg:Spread src="Spreads/Spread_s.xml"/>
|
||||
</Document>"#;
|
||||
let spread = r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">
|
||||
<Spread Self="s"><Page Self="p" GeometricBounds="0 0 200 200" ItemTransform="1 0 0 1 0 0"/></Spread>
|
||||
</idPkg:Spread>"#;
|
||||
let d = import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", spread)])).unwrap();
|
||||
let plain = d.styles.object_style("Plain").cloned().unwrap();
|
||||
assert_eq!(plain.fill.as_ref().map(|f| f.swatch.as_str()), Some(designcraft_color::swatch::NONE), "{:?}", plain.fill);
|
||||
assert_eq!(plain.stroke.as_ref().map(|s| s.weight), Some(designcraft_doc::Stroke::none().weight), "{:?}", plain.stroke);
|
||||
let none = d.styles.object_style(designcraft_doc::NO_OBJECT_STYLE).cloned().unwrap();
|
||||
assert_eq!(none.stroke.map(|s| s.weight), Some(0.0), "[None] keeps its own stroke weight");
|
||||
}
|
||||
|
||||
/// An object style giving its corners only with the legacy all-corners `CornerOption` and
|
||||
/// `CornerRadius` keeps them, so applying it to another frame rounds it.
|
||||
#[test]
|
||||
|
||||
@@ -68,7 +68,7 @@ pub fn to_display_rgba(px: Pixels, embedded_icc: Option<&[u8]>, display: &Displa
|
||||
if let Some(x) = own(ColorSpace::Rgb)
|
||||
&& !keeps_rgb(&x)
|
||||
{
|
||||
in_place(&mut img, &x);
|
||||
let _ = in_place(&mut img, &x);
|
||||
}
|
||||
Some(img)
|
||||
}
|
||||
@@ -76,7 +76,7 @@ pub fn to_display_rgba(px: Pixels, embedded_icc: Option<&[u8]>, display: &Displa
|
||||
if let Some(x) = own(ColorSpace::Gray)
|
||||
&& !keeps_gray(&x)
|
||||
{
|
||||
in_place(&mut img, &x);
|
||||
let _ = in_place(&mut img, &x);
|
||||
}
|
||||
Some(img)
|
||||
}
|
||||
@@ -87,6 +87,18 @@ pub fn to_display_rgba(px: Pixels, embedded_icc: Option<&[u8]>, display: &Displa
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert straight RGBA8 pixels from `embedded_icc` into sRGB, returning `None` if the profile
|
||||
/// cannot be parsed as RGB, yields no usable RGB → sRGB transform, or fails during pixel
|
||||
/// conversion. Unlike [`to_display_rgba`], never falls back to unconverted pixels.
|
||||
pub fn convert_rgb_to_srgb(mut img: RgbaImage, embedded_icc: &[u8], display: &DisplayColour) -> Option<RgbaImage> {
|
||||
let profile = parse(embedded_icc, ColorSpace::Rgb)?;
|
||||
let x = to_srgb(&profile, display.options)?;
|
||||
if !keeps_rgb(&x) && !in_place(&mut img, &x) {
|
||||
return None;
|
||||
}
|
||||
Some(img)
|
||||
}
|
||||
|
||||
fn parse(icc: &[u8], pixels: ColorSpace) -> Option<Profile> {
|
||||
if icc.len() > MAX_ICC_BYTES {
|
||||
log::warn!("embedded ICC profile of {} bytes is too large: ignored", icc.len());
|
||||
@@ -149,16 +161,17 @@ fn keeps_gray(x: &Transform) -> bool {
|
||||
}
|
||||
|
||||
/// Convert RGBA pixels whose first channels (RGB, or grey for a grey transform) hold the source
|
||||
/// values; alpha is kept.
|
||||
fn in_place(img: &mut RgbaImage, x: &Transform) {
|
||||
/// values; alpha is kept. Returns `false` if any chunk fails to convert.
|
||||
fn in_place(img: &mut RgbaImage, x: &Transform) -> bool {
|
||||
let mut src = Vec::with_capacity(CHUNK * 4);
|
||||
for chunk in img.chunks_mut(CHUNK * 4) {
|
||||
src.clear();
|
||||
src.extend_from_slice(chunk);
|
||||
if !convert(x, &src, 4, chunk, 4) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// CMYK inks → RGBA through `x`, or the profile-free formula without one.
|
||||
|
||||
@@ -16,7 +16,7 @@ mod tiff_reduced;
|
||||
mod tone;
|
||||
pub use craft_ps::read::is_eps;
|
||||
pub use eps::{bounding_box as eps_bounding_box, eps_pixel_size, eps_png, eps_proxy, eps_size};
|
||||
pub use tone::{Tone, tone};
|
||||
pub use tone::{Tone, is_bitmap, tone};
|
||||
|
||||
/// CSS pixels (SVG user units) → points.
|
||||
pub const PT_PER_PX: f64 = 0.75;
|
||||
@@ -413,6 +413,19 @@ pub fn decode_rgba(bytes: &[u8]) -> Option<image::RgbaImage> {
|
||||
to_display_rgba(px, Some(icc), &DisplayColour::active())
|
||||
}
|
||||
|
||||
/// Straight RGBA8 of an RGB raster decoded under the normal RGBA budget and strictly converted
|
||||
/// from `icc` to sRGB. Returns `None` if decoding fails, the image exceeds the decode budget, or
|
||||
/// `icc` yields no usable RGB → sRGB conversion (unlike [`decode_rgba`], never falls back to
|
||||
/// unconverted RGB).
|
||||
pub fn decode_rgb_to_srgb(bytes: &[u8], icc: &[u8]) -> Option<image::RgbaImage> {
|
||||
if too_large_to_decode(bytes) {
|
||||
return None;
|
||||
}
|
||||
let decoded = craft_image_codecs::decode_with(bytes, &decode_options()).ok()?;
|
||||
let rgba = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8())?;
|
||||
colour::convert_rgb_to_srgb(rgba, icc, &colour::DisplayColour::active())
|
||||
}
|
||||
|
||||
/// About how many bytes a pixel [`decode_rgba`] of `bytes` holds at once, with a premultiplied
|
||||
/// copy of its result. A decode holds the samples as decoded beside the 8-bit RGBA (or, for
|
||||
/// CMYK, the 8-bit CMYKA copy and its ink and alpha planes) they are converted to, or two copies
|
||||
|
||||
@@ -11,6 +11,15 @@ pub enum Tone {
|
||||
Bitmap,
|
||||
}
|
||||
|
||||
/// Whether `bytes` is a 1-bit (bitmap mode) raster: TIFF, PNG, PSD or BMP with one channel and
|
||||
/// one bit per sample. Header-only (never decodes pixels).
|
||||
pub fn is_bitmap(bytes: &[u8]) -> bool {
|
||||
craft_image_codecs::inspect_raster(bytes)
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some_and(|info| info.channels == 1 && info.color_type == craft_image_codecs::RasterColorType::Bitmap)
|
||||
}
|
||||
|
||||
/// The [`Tone`] of an image file, `None` when a swatch doesn't colour it.
|
||||
pub fn tone(bytes: &[u8]) -> Option<Tone> {
|
||||
if let Some(info) = craft_image_codecs::inspect_raster(bytes).ok().flatten()
|
||||
@@ -79,17 +88,21 @@ mod tests {
|
||||
png
|
||||
}
|
||||
|
||||
/// A 1-bit TIFF (BlackIsZero), one row of 8 pixels, uncompressed.
|
||||
/// A 1-bit TIFF (`photometric`: 0 = WhiteIsZero, 1 = BlackIsZero), one row of 8 pixels, uncompressed.
|
||||
fn tiff_1bit(bits: u8) -> Vec<u8> {
|
||||
tiff_1bit_with(bits, 1)
|
||||
}
|
||||
|
||||
fn tiff_1bit_with(bits: u8, photometric: u32) -> Vec<u8> {
|
||||
let entries: [(u16, u16, u32); 8] = [
|
||||
(256, 3, 8), // width
|
||||
(257, 3, 1), // height
|
||||
(258, 3, 1), // bits per sample
|
||||
(259, 3, 1), // no compression
|
||||
(262, 3, 1), // BlackIsZero
|
||||
(273, 4, 8), // strip offset
|
||||
(278, 3, 1), // rows per strip
|
||||
(279, 4, 1), // strip byte count
|
||||
(256, 3, 8), // width
|
||||
(257, 3, 1), // height
|
||||
(258, 3, 1), // bits per sample
|
||||
(259, 3, 1), // no compression
|
||||
(262, 3, photometric), // PhotometricInterpretation
|
||||
(273, 4, 8), // strip offset
|
||||
(278, 3, 1), // rows per strip
|
||||
(279, 4, 1), // strip byte count
|
||||
];
|
||||
let mut t = b"II*\0".to_vec();
|
||||
t.extend(10u32.to_le_bytes());
|
||||
@@ -134,6 +147,7 @@ mod tests {
|
||||
assert_eq!(tone(&encode(&wide, 2, 2, ExtendedColorType::L16, Png)), Some(Tone::Gray));
|
||||
assert_eq!(tone(&png_1bit(8, 0b1010_0000)), Some(Tone::Bitmap));
|
||||
assert_eq!(tone(&tiff_1bit(0b1100_0000)), Some(Tone::Bitmap));
|
||||
assert_eq!(tone(&tiff_1bit_with(0b1100_0000, 0)), Some(Tone::Bitmap));
|
||||
assert_eq!(tone(&psd_header(1, 1)), Some(Tone::Gray));
|
||||
assert_eq!(tone(&psd_header(1, 0)), Some(Tone::Bitmap));
|
||||
|
||||
@@ -145,6 +159,25 @@ mod tests {
|
||||
assert_eq!(tone(&encode(&greys, 2, 2, ExtendedColorType::Rgba8, Gif)), Some(Tone::Gray));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_bitmap_matches_one_bit_rasters_only() {
|
||||
use image::ImageFormat::{Gif, Jpeg, Png, Tiff};
|
||||
assert!(is_bitmap(&tiff_1bit_with(0b1010_0000, 0)));
|
||||
assert!(is_bitmap(&tiff_1bit_with(0b1010_0000, 1)));
|
||||
assert!(is_bitmap(&png_1bit(8, 0b1010_0000)));
|
||||
assert!(is_bitmap(&psd_header(1, 0)));
|
||||
|
||||
let grey = [0u8, 128, 255, 64];
|
||||
assert!(!is_bitmap(&encode(&grey, 2, 2, ExtendedColorType::L8, Tiff)));
|
||||
assert!(!is_bitmap(&encode(&grey, 2, 2, ExtendedColorType::L8, Png)));
|
||||
assert!(!is_bitmap(&encode(&grey, 2, 2, ExtendedColorType::L8, Jpeg)));
|
||||
assert!(!is_bitmap(&psd_header(1, 1)));
|
||||
assert!(!is_bitmap(&psd_header(2, 0)));
|
||||
let bw_gif = [[0u8, 0, 0, 255], [255, 255, 255, 255], [0, 0, 0, 255], [255, 255, 255, 255]].concat();
|
||||
assert!(!is_bitmap(&encode(&bw_gif, 2, 2, ExtendedColorType::Rgba8, Gif)));
|
||||
assert!(!is_bitmap(b""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_and_alpha_files_keep_their_colours() {
|
||||
use image::ImageFormat::{Gif, Png};
|
||||
|
||||
@@ -45,6 +45,8 @@ use images::ConstantImageHasher;
|
||||
pub(crate) use images::SRGB_ICC;
|
||||
use images::{CmykImage, GreyImage, ImageContentCache, RasterMode, SrgbImage, embedded_icc, is_grey, is_grey_icc};
|
||||
pub(crate) use metadata::civil;
|
||||
#[cfg(test)]
|
||||
pub(crate) use pipeline::export_pdf_with_cms;
|
||||
pub(crate) use pipeline::{MARK_LEN, Sheet, exported_items, mark_start};
|
||||
pub use pipeline::{
|
||||
drawn_children, export_pdf, export_pdf_with_report, item_exported, layer_exported, print_color, sheet_spreads, shown_parent_items,
|
||||
@@ -99,6 +101,8 @@ pub(crate) struct Exporter<'a> {
|
||||
pub reverse_cmaps: HashMap<u32, Arc<HashMap<u32, char>>>,
|
||||
/// Convert CMYK to RGB (PDF/A: krilla needs a CMYK output profile we don't ship yet).
|
||||
pub rgb_only: bool,
|
||||
/// PDF/X-1a: RGB process colours converted here with black point compensation.
|
||||
pub(crate) x1a_process: Option<crate::pdfx1a::ProcessConversion>,
|
||||
/// Tagged PDF: the structure in reading order (stories gather their frames' content).
|
||||
tags: Vec<TagEntry>,
|
||||
story_tags: HashMap<designcraft_doc::StoryId, Vec<Identifier>>,
|
||||
|
||||
@@ -120,6 +120,7 @@ fn export_booklet_inner(doc: &Document, cache: &Cache, opts: &BookletOptions) ->
|
||||
fonts: HashMap::new(),
|
||||
reverse_cmaps: HashMap::new(),
|
||||
rgb_only: false,
|
||||
x1a_process: None,
|
||||
tags: Vec::new(),
|
||||
story_tags: HashMap::new(),
|
||||
tag_story: None,
|
||||
|
||||
@@ -153,7 +153,7 @@ impl Exporter<'_> {
|
||||
self.doc.swatch(ink).filter(|w| matches!(w.value, SwatchValue::Color { color_type: ColorType::Spot, .. })).unwrap_or(sw);
|
||||
let SwatchValue::Color { color, .. } = &target.value else { break };
|
||||
if process {
|
||||
return Some(device(&designcraft_color::swatch::apply_tint(*color, t), self.rgb_only));
|
||||
return Some(self.process(&designcraft_color::swatch::apply_tint(*color, t)));
|
||||
}
|
||||
let space = SeparationSpace::new(SeparationColorant::Custom(target.name.clone()), regular(color, self.rgb_only));
|
||||
return Some(SepColor::new(q(t), space).into());
|
||||
@@ -161,6 +161,17 @@ impl Exporter<'_> {
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
self.doc.resolve_color(name, tint).map(|c| device(&c, self.rgb_only))
|
||||
self.doc.resolve_color(name, tint).map(|c| self.process(&c))
|
||||
}
|
||||
|
||||
/// A process colour in its own device space, except RGB in PDF/X-1a with black point
|
||||
/// compensation: converted here into CMYK with it, as the flattener would convert it without.
|
||||
fn process(&self, c: &Color) -> krilla::color::Color {
|
||||
if let (Some(conversion), Color::Rgb { r, g, b }) = (&self.x1a_process, *c)
|
||||
&& let Some([c, m, y, k]) = conversion.cmyk([q(r), q(g), q(b)])
|
||||
{
|
||||
return device(&Color::cmyk(c, m, y, k), self.rgb_only);
|
||||
}
|
||||
device(c, self.rgb_only)
|
||||
}
|
||||
}
|
||||
@@ -341,18 +341,31 @@ impl Exporter<'_> {
|
||||
true
|
||||
}
|
||||
|
||||
/// A greyscale or bitmap image coloured by the swatch applied to it (#1094): the swatch is
|
||||
/// painted through the image's ink coverage (its darkness), over 0% ink for a greyscale
|
||||
/// image, whose white is opaque. `false`, drawing nothing, when the image keeps its own
|
||||
/// colours: no swatch, one that no longer exists, a colour image. With `compress_images` the
|
||||
/// coverage is a grey JPEG, as the image itself would be.
|
||||
/// A greyscale or bitmap image coloured by the swatch applied to it (#1094), or a 1-bit
|
||||
/// (bitmap mode) image with no swatch applied (default `[Black]`): the swatch is painted
|
||||
/// through the image's ink coverage (its darkness), over 0% ink for a greyscale image, whose
|
||||
/// white is opaque, and with transparent white for a bitmap image. `false`, drawing nothing,
|
||||
/// when the image keeps its own colours: a colour image, an uncoloured greyscale image, or
|
||||
/// one with a missing swatch. With `compress_images` the coverage is a grey JPEG for
|
||||
/// greyscale images, as the image itself would be.
|
||||
fn colorized(&mut self, s: &mut Surface, g: &designcraft_doc::Graphic) -> bool {
|
||||
if g.fill.is_none() {
|
||||
return false;
|
||||
}
|
||||
let Some((bytes, _)) = self.asset_bytes(g.asset) else { return false };
|
||||
let Some(tone) = designcraft_images::tone(&bytes) else { return false };
|
||||
let Some(paint) = self.swatch_color(&g.fill.swatch, g.fill.tint) else { return false };
|
||||
let default_black =
|
||||
|| self.swatch_color(designcraft_color::swatch::BLACK, 1.0).unwrap_or_else(|| device(&Color::cmyk(0.0, 0.0, 0.0, 1.0), self.rgb_only));
|
||||
let (tone, paint) = if g.fill.is_none() {
|
||||
if !designcraft_images::is_bitmap(&bytes) {
|
||||
return false;
|
||||
}
|
||||
(designcraft_images::Tone::Bitmap, default_black())
|
||||
} else {
|
||||
let Some(tone) = designcraft_images::tone(&bytes) else { return false };
|
||||
let paint = match self.swatch_color(&g.fill.swatch, g.fill.tint) {
|
||||
Some(paint) => paint,
|
||||
None if tone == designcraft_images::Tone::Bitmap && designcraft_images::is_bitmap(&bytes) => default_black(),
|
||||
None => return false,
|
||||
};
|
||||
(tone, paint)
|
||||
};
|
||||
let Some(coverage) = designcraft_images::decode_rgba(&bytes).and_then(|img| CoverageImage::new(&img)) else { return false };
|
||||
let interpolate = RasterMode::for_standard(self.opts.standard).interpolate;
|
||||
let mask = if self.opts.compress_images && tone == designcraft_images::Tone::Gray { coverage.jpeg(interpolate) } else { None };
|
||||
|
||||
+135
-27
@@ -58,6 +58,34 @@ pub(super) fn is_grey_icc(icc: &[u8]) -> bool {
|
||||
icc.get(16..20) == Some(b"GRAY".as_slice())
|
||||
}
|
||||
|
||||
/// Whether an ICC profile describes CMYK.
|
||||
fn is_cmyk_icc(icc: &[u8]) -> bool {
|
||||
icc.get(16..20) == Some(b"CMYK".as_slice())
|
||||
}
|
||||
|
||||
/// Whether krilla embeds `icc` as `/ICCBased` in a PDF 1.6 (PDF/X-4) file.
|
||||
///
|
||||
/// krilla's `PdfVersion::Pdf16::supports_icc` checks `major <= 4 && minor <= 1`, so ICC v2.2–2.4
|
||||
/// and v4.2+ profiles (such as LittleCMS/Pillow sRGB v4.4 or sRGB2014 v2.4) are dropped to
|
||||
/// `/DeviceRGB` if passed through unchanged.
|
||||
fn pdf16_accepts_icc(icc: &[u8]) -> bool {
|
||||
icc.get(8).is_some_and(|&major| major <= 4) && icc.get(9).is_some_and(|&minor| (minor >> 4) <= 1)
|
||||
}
|
||||
|
||||
/// Whether krilla embeds `icc` as an RGB `/ICCBased` space in PDF 1.6.
|
||||
fn pdf16_accepts_rgb_icc(icc: &[u8]) -> bool {
|
||||
is_rgb_icc(icc) && pdf16_accepts_icc(icc)
|
||||
}
|
||||
|
||||
/// Whether `icc` is a readable RGB profile whose colours differ from sRGB (e.g. Display P3 or
|
||||
/// Adobe RGB), so tagging raw pixels with `SRGB_ICC` without converting them would shift colour.
|
||||
fn needs_srgb_conversion(icc: &[u8]) -> bool {
|
||||
is_rgb_icc(icc)
|
||||
&& icc.len() <= designcraft_images::colour::MAX_ICC_BYTES
|
||||
&& craft_cms::Profile::parse(icc)
|
||||
.is_ok_and(|p| p.color_space == craft_cms::ColorSpace::Rgb && !p.same_colors(craft_cms::Builtin::Srgb.profile()))
|
||||
}
|
||||
|
||||
/// Whether `data` decodes to grey (with or without alpha), read from its header.
|
||||
pub(super) fn is_grey(data: &[u8]) -> bool {
|
||||
craft_image_codecs::inspect_raster(data).ok().flatten().is_some_and(|info| {
|
||||
@@ -68,39 +96,57 @@ pub(super) fn is_grey(data: &[u8]) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// A JPEG, passed through. With `tag_rgb`, a JPEG keeps its own profile, and one without gets
|
||||
/// sRGB. krilla uses a profile only when its channels match the JPEG's, so a grey or CMYK JPEG
|
||||
/// without a profile stays DeviceGray or DeviceCMYK.
|
||||
/// A JPEG, passed through. With `tag_rgb`, a JPEG keeps its own profile when PDF 1.6 accepts it
|
||||
/// and its colour space matches the JPEG's channels; an RGB JPEG whose profile PDF 1.6 drops is
|
||||
/// tagged with sRGB (after converting pixels to sRGB if the profile isn't sRGB), and an untagged
|
||||
/// RGB JPEG gets sRGB. Grey and CMYK JPEGs without an accepted matching profile stay DeviceGray
|
||||
/// or DeviceCMYK.
|
||||
pub(super) fn jpeg(data: krilla::Data, icc: impl FnOnce() -> Option<Vec<u8>>, mode: RasterMode) -> Option<Image> {
|
||||
if !mode.tag_rgb {
|
||||
return Image::from_jpeg(data, mode.interpolate).ok();
|
||||
}
|
||||
let icc: krilla::Data = match icc() {
|
||||
Some(own) => own.into(),
|
||||
None => SRGB_ICC.into(),
|
||||
};
|
||||
Image::from_jpeg_with_icc(data, Some(icc), mode.interpolate).ok()
|
||||
}
|
||||
|
||||
/// Whether krilla would write this PNG, GIF or WebP as untagged RGB: not grey, and no profile of
|
||||
/// its own. The header inspection doesn't read WebP, which has no grey form, so a file it can't
|
||||
/// read counts as colour.
|
||||
fn untagged_rgb(data: &[u8]) -> bool {
|
||||
!is_grey(data) && embedded_icc(data).is_none()
|
||||
let color = craft_image_codecs::inspect_raster(data.as_ref()).ok().flatten().map(|info| info.color_type);
|
||||
let own = icc();
|
||||
let keep_own = own.as_deref().is_some_and(|p| {
|
||||
pdf16_accepts_icc(p)
|
||||
&& match color {
|
||||
Some(craft_image_codecs::RasterColorType::Gray | craft_image_codecs::RasterColorType::Bitmap) => is_grey_icc(p),
|
||||
Some(craft_image_codecs::RasterColorType::Cmyk) => is_cmyk_icc(p),
|
||||
_ => is_rgb_icc(p),
|
||||
}
|
||||
});
|
||||
if keep_own {
|
||||
return Image::from_jpeg_with_icc(data, own.map(Into::into), mode.interpolate).ok();
|
||||
}
|
||||
let is_rgb = !matches!(
|
||||
color,
|
||||
Some(craft_image_codecs::RasterColorType::Gray | craft_image_codecs::RasterColorType::Bitmap | craft_image_codecs::RasterColorType::Cmyk)
|
||||
);
|
||||
if is_rgb && let Some(p) = own.as_deref().filter(|p| needs_srgb_conversion(p)) {
|
||||
let rgba = designcraft_images::decode_rgb_to_srgb(data.as_ref(), p)?;
|
||||
return SrgbImage::new(rgba).and_then(|img| Image::from_custom(img, mode.interpolate).ok());
|
||||
}
|
||||
Image::from_jpeg_with_icc(data, Some(SRGB_ICC.into()), mode.interpolate).ok()
|
||||
}
|
||||
|
||||
pub(super) fn lossless(data: &Arc<Vec<u8>>, fmt: Option<craft_image_codecs::Format>, mode: RasterMode) -> Option<Image> {
|
||||
if designcraft_images::too_large_to_decode(data) {
|
||||
return None;
|
||||
}
|
||||
let i = mode.interpolate;
|
||||
let direct_format = matches!(fmt, Some(craft_image_codecs::Format::Png | craft_image_codecs::Format::Gif | craft_image_codecs::Format::WebP));
|
||||
let own_icc = if mode.tag_rgb { embedded_icc(data) } else { None };
|
||||
let will_tag_srgb = mode.tag_rgb && !is_grey(data) && !(direct_format && own_icc.as_deref().is_some_and(pdf16_accepts_rgb_icc));
|
||||
// krilla reads PNG, GIF and WebP lazily: a damaged file is accepted here and fails the whole
|
||||
// export when the PDF is written. Decoding it first means it is skipped, like any other
|
||||
// image that can't be decoded.
|
||||
let rgba = designcraft_images::decode_rgba(data)?;
|
||||
let i = mode.interpolate;
|
||||
let rgba = if will_tag_srgb && let Some(icc) = own_icc.as_deref().filter(|p| needs_srgb_conversion(p)) {
|
||||
designcraft_images::decode_rgb_to_srgb(data, icc)?
|
||||
} else {
|
||||
designcraft_images::decode_rgba(data)?
|
||||
};
|
||||
let direct = match fmt {
|
||||
Some(craft_image_codecs::Format::Png | craft_image_codecs::Format::Gif | craft_image_codecs::Format::WebP)
|
||||
if mode.tag_rgb && untagged_rgb(data) =>
|
||||
{
|
||||
None
|
||||
}
|
||||
Some(craft_image_codecs::Format::Png | craft_image_codecs::Format::Gif | craft_image_codecs::Format::WebP) if will_tag_srgb => None,
|
||||
Some(craft_image_codecs::Format::Png) => Image::from_png(data.clone().into(), i).ok(),
|
||||
Some(craft_image_codecs::Format::Gif) => Image::from_gif(data.clone().into(), i).ok(),
|
||||
Some(craft_image_codecs::Format::WebP) => Image::from_webp(data.clone().into(), i).ok(),
|
||||
@@ -113,6 +159,11 @@ pub(super) fn lossless(data: &Arc<Vec<u8>>, fmt: Option<craft_image_codecs::Form
|
||||
}
|
||||
// TIFF, BMP, PSD composites… and, with `tag_rgb`, untagged RGB.
|
||||
if mode.tag_rgb {
|
||||
let rgba = if !will_tag_srgb && let Some(icc) = own_icc.as_deref().filter(|p| needs_srgb_conversion(p)) {
|
||||
designcraft_images::decode_rgb_to_srgb(data, icc)?
|
||||
} else {
|
||||
rgba
|
||||
};
|
||||
return SrgbImage::new(rgba).and_then(|img| Image::from_custom(img, i).ok());
|
||||
}
|
||||
let (w, h) = rgba.dimensions();
|
||||
@@ -165,7 +216,8 @@ thread_local! {
|
||||
}
|
||||
|
||||
/// Opaque raster → JPEG (quality 90). `None` when the image has transparency, is too large or
|
||||
/// can't be decoded. With `tag_rgb`, the JPEG keeps the source's RGB profile, or gets sRGB.
|
||||
/// can't be decoded. With `tag_rgb`, the JPEG keeps the source's profile when PDF 1.6 accepts it,
|
||||
/// or converts/tags to sRGB.
|
||||
pub(super) fn recompress(data: &[u8], mode: RasterMode) -> Option<Image> {
|
||||
if designcraft_images::too_large_to_decode(data) {
|
||||
return None;
|
||||
@@ -181,14 +233,40 @@ pub(super) fn recompress(data: &[u8], mode: RasterMode) -> Option<Image> {
|
||||
}
|
||||
// A grey image stays a grey JPEG (#1426).
|
||||
let grey = img.layout().is_gray();
|
||||
let jpeg_image = if grey {
|
||||
img.convert(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8)
|
||||
let icc = img.icc.as_deref();
|
||||
let (jpeg_image, out_icc) = if grey {
|
||||
(
|
||||
img.convert(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8),
|
||||
mode.tag_rgb.then(|| icc.filter(|p| is_grey_icc(p) && pdf16_accepts_icc(p)).map(<[u8]>::to_vec)).flatten(),
|
||||
)
|
||||
} else if mode.tag_rgb
|
||||
&& let Some(icc) = icc.filter(|p| !pdf16_accepts_rgb_icc(p) && needs_srgb_conversion(p))
|
||||
{
|
||||
let rgba_img = image::RgbaImage::from_raw(img.width(), img.height(), rgba)?;
|
||||
let converted = designcraft_images::colour::convert_rgb_to_srgb(rgba_img, icc, &designcraft_images::colour::DisplayColour::active())?;
|
||||
let pixels = usize::try_from(converted.width()).ok()?.checked_mul(usize::try_from(converted.height()).ok()?)?;
|
||||
let mut rgb = Vec::with_capacity(pixels.checked_mul(3)?);
|
||||
for p in converted.pixels() {
|
||||
rgb.extend_from_slice(&p.0[..3]);
|
||||
}
|
||||
let converted_img = craft_image_codecs::Image::from_raw(
|
||||
converted.width(),
|
||||
converted.height(),
|
||||
craft_image_codecs::ChannelLayout::Rgb,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
rgb,
|
||||
)
|
||||
.ok()?;
|
||||
(converted_img, None)
|
||||
} else {
|
||||
img.convert(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8)
|
||||
(
|
||||
img.convert(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8),
|
||||
mode.tag_rgb.then(|| icc.filter(|p| is_rgb_icc(p) && pdf16_accepts_icc(p)).map(<[u8]>::to_vec)).flatten(),
|
||||
)
|
||||
};
|
||||
let options = craft_image_codecs::EncodeOptions { jpeg_quality: 90, ..Default::default() };
|
||||
let buf = craft_image_codecs::encode(&jpeg_image, craft_image_codecs::Format::Jpeg, &options).ok()?;
|
||||
jpeg(buf.into(), || embedded_icc(data).filter(|p| if grey { is_grey_icc(p) } else { is_rgb_icc(p) }), mode)
|
||||
jpeg(buf.into(), || out_icc, mode)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -241,6 +319,7 @@ mod image_content_cache_tests {
|
||||
fonts: HashMap::new(),
|
||||
reverse_cmaps: HashMap::new(),
|
||||
rgb_only: false,
|
||||
x1a_process: None,
|
||||
tags: Vec::new(),
|
||||
story_tags: HashMap::new(),
|
||||
tag_story: None,
|
||||
@@ -563,4 +642,33 @@ mod recompress_tests {
|
||||
assert!(recompress(&crate::tests::blank_png(9), mode).is_some());
|
||||
assert_eq!(decodes(), start + 1);
|
||||
}
|
||||
|
||||
/// A wide-gamut RGB JPEG whose embedded profile PDF 1.6 drops cannot be silently tagged as
|
||||
/// sRGB when `decode_rgba` fails; an sRGB-equivalent JPEG still passes through without decoding.
|
||||
#[test]
|
||||
fn wide_gamut_jpeg_conversion_failure_does_not_fall_back_to_srgb_passthrough() {
|
||||
let img = craft_image_codecs::Image::from_raw(
|
||||
4,
|
||||
2,
|
||||
craft_image_codecs::ChannelLayout::Rgb,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
[60, 200, 60].repeat(8),
|
||||
)
|
||||
.unwrap();
|
||||
let mut bad_scan = craft_image_codecs::encode(&img, craft_image_codecs::Format::Jpeg, &Default::default()).unwrap();
|
||||
// Truncate right after the SOS header so header-only parsers succeed while full decode fails.
|
||||
let sos = bad_scan.windows(2).position(|w| w == [0xFF, 0xDA]).unwrap();
|
||||
let sos_len = usize::from(u16::from_be_bytes([bad_scan[sos + 2], bad_scan[sos + 3]]));
|
||||
bad_scan.truncate(sos + 2 + sos_len);
|
||||
assert!(designcraft_images::decode_rgba(&bad_scan).is_none());
|
||||
|
||||
let mode = RasterMode { interpolate: false, tag_rgb: true };
|
||||
let p3 = craft_cms::Builtin::DisplayP3.profile().clone().with_encoded_bytes().to_bytes().to_vec();
|
||||
assert!(jpeg(bad_scan.clone().into(), || Some(p3), mode).is_none());
|
||||
|
||||
let mut srgb_v44 = craft_cms::Builtin::Srgb.profile().clone().with_encoded_bytes().to_bytes().to_vec();
|
||||
srgb_v44[8] = 4;
|
||||
srgb_v44[9] = 0x40;
|
||||
assert!(jpeg(bad_scan.into(), || Some(srgb_v44), mode).is_some());
|
||||
}
|
||||
}
|
||||
@@ -164,13 +164,13 @@ impl Exporter<'_> {
|
||||
// Viewers expand dashes too: a degenerate pattern draws solid, as on screen.
|
||||
let length = designcraft_doc::path_length_bound(bp);
|
||||
let dash = match &kind {
|
||||
StrokeType::Dashed { pattern } if StrokeType::expandable_dashes(pattern, length) => {
|
||||
StrokeType::Dashed { .. } => kind.dashes(st.weight).filter(|p| StrokeType::expandable_dashes(p, length)).map(|pattern| {
|
||||
let mut pat: Vec<f32> = pattern.iter().map(|v| v.max(0.0) as f32).collect();
|
||||
if pat.len() % 2 == 1 {
|
||||
pat.extend(pat.clone());
|
||||
}
|
||||
Some(StrokeDash { array: pat, offset: 0.0 })
|
||||
}
|
||||
StrokeDash { array: pat, offset: 0.0 }
|
||||
}),
|
||||
StrokeType::Dotted if StrokeType::expandable_dashes(&[0.0, st.weight * 2.0], length) => {
|
||||
cap = krilla::paint::LineCap::Round;
|
||||
Some(StrokeDash { array: vec![0.0, (st.weight * 2.0) as f32], offset: 0.0 })
|
||||
|
||||
@@ -153,7 +153,14 @@ pub fn print_color(doc: &Document, opts: &PdfOptions) -> bool {
|
||||
|
||||
/// Like [`export_pdf`], also returning warnings about approximated or dropped features.
|
||||
pub fn export_pdf_with_report(doc: &Document, cache: &Cache, opts: &PdfOptions) -> Result<ExportReport> {
|
||||
write::guard(|| export_pdf_with_report_inner(doc, cache, opts))
|
||||
write::guard(|| export_pdf_with_report_inner(doc, cache, opts, &designcraft_color::cms::active()))
|
||||
}
|
||||
|
||||
/// [`export_pdf_with_report`] with the colour settings of `cms` for the print output, rather than
|
||||
/// the process-wide ones other tests share.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn export_pdf_with_cms(doc: &Document, cache: &Cache, opts: &PdfOptions, cms: &designcraft_color::cms::Cms) -> Result<ExportReport> {
|
||||
write::guard(|| export_pdf_with_report_inner(doc, cache, opts, cms))
|
||||
}
|
||||
|
||||
/// Form fields (Buttons and Forms) and, for interactive PDF, video and sound; not in PDF/X
|
||||
@@ -176,7 +183,7 @@ fn add_form_fields(bytes: &mut Vec<u8>, warnings: &mut Vec<String>, doc: &Docume
|
||||
}
|
||||
}
|
||||
|
||||
fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions) -> Result<ExportReport> {
|
||||
fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions, cms: &designcraft_color::cms::Cms) -> Result<ExportReport> {
|
||||
let sheets = sheets(doc, opts)?;
|
||||
let (version, archival) = match opts.standard {
|
||||
Standard::None => (PdfVersion::Pdf17, None),
|
||||
@@ -186,9 +193,14 @@ fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions
|
||||
};
|
||||
let configuration = write::configuration(version, archival)?;
|
||||
let mut warnings = Vec::new();
|
||||
let mut x1a_process = None;
|
||||
let (base, cmyk_icc) = if print_color(doc, opts) {
|
||||
// An output intent only for PDF/X, as in InDesign.
|
||||
let (settings, icc, warning) = crate::pdfx::print_settings_and_profile(opts.standard.is_pdfx())?;
|
||||
let (settings, icc, warning) = crate::pdfx::print_settings_and_profile_with(cms, opts.standard.is_pdfx())?;
|
||||
if opts.standard == Standard::PdfX1a {
|
||||
let profile = crate::pdfx::output_profile(cms, warning.is_some());
|
||||
x1a_process = crate::pdfx1a::ProcessConversion::new(&profile, cms.settings().bpc);
|
||||
}
|
||||
warnings.extend(warning);
|
||||
let pdfx_version = (opts.standard == Standard::PdfX4).then(|| "PDF/X-4".to_string());
|
||||
(krilla::SerializeSettings { pdfx_version, ..settings }, Some(icc))
|
||||
@@ -228,6 +240,7 @@ fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions
|
||||
fonts: HashMap::new(),
|
||||
reverse_cmaps: HashMap::new(),
|
||||
rgb_only: archival.is_some(),
|
||||
x1a_process,
|
||||
tags: Vec::new(),
|
||||
story_tags: HashMap::new(),
|
||||
tag_story: None,
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
//! Appearance of Black says so) as `/op` and `/OP` with `/OPM 1`; left out of PDF/A.
|
||||
//! - **Images:** clipped to their frame; JPEG data is passed through, PNG/GIF/WebP are embedded
|
||||
//! losslessly (or re-encoded as JPEG with [`PdfOptions::compress_images`]). PDF/X-4 and PDF/A
|
||||
//! images are written without interpolation. In PDF/X-4 an RGB image without a profile of its own
|
||||
//! carries sRGB (`assets/icc/sRGB-v2-magic.icc`).
|
||||
//! images are written without interpolation. In PDF/X-4 an RGB image without a PDF 1.6-compatible
|
||||
//! profile of its own carries sRGB (`assets/icc/sRGB-v2-magic.icc`).
|
||||
//! - **Text as real text:** the composed glyph runs are emitted with embedded, subsetted fonts and a
|
||||
//! Unicode mapping taken from the story text (ligatures, page numbers and inserted hyphens get the
|
||||
//! right characters), so text is selectable and searchable.
|
||||
|
||||
@@ -66,6 +66,16 @@ pub(crate) fn print_settings_and_profile_with(
|
||||
}
|
||||
}
|
||||
|
||||
/// The CMYK profile [`print_settings_with`] writes as the output intent for `cms`: the working
|
||||
/// space's, else Coated FOGRA39 (also when `replaced`: its warning said the working space's
|
||||
/// profile couldn't be written).
|
||||
pub(crate) fn output_profile(cms: &designcraft_color::cms::Cms, replaced: bool) -> std::borrow::Cow<'static, [u8]> {
|
||||
match cms.output_intent() {
|
||||
Ok(space) if !replaced => space.icc,
|
||||
_ => std::borrow::Cow::Borrowed(craft_cms::builtin::COATED_FOGRA39_ICC),
|
||||
}
|
||||
}
|
||||
|
||||
/// Finish krilla's PDF/X-4 output with the XMP entries PDF/X-4 requires and krilla doesn't write:
|
||||
/// `xmp:MetadataDate` and `xmpMM:VersionID`, as an incremental update. `date` (Unix seconds, UTC)
|
||||
/// is the metadata date; `None` (no clock, as on wasm) writes the epoch. `None` back when the
|
||||
|
||||
@@ -407,9 +407,161 @@ fn own_profiles_and_grey_stay() {
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
place(&mut d, "grey.png", png(true, None), (4.0, 2.0), (72.0, 72.0));
|
||||
place(&mut d, "tagged.png", png(false, Some(rgb_icc())), (4.0, 2.0), (72.0, 172.0));
|
||||
place(&mut d, "tagged.jpg", encode_with_icc(craft_image_codecs::Format::Jpeg, false, [0, 128, 255, 255], rgb_icc()), (4.0, 2.0), (72.0, 272.0));
|
||||
let r = x4(&d);
|
||||
assert_eq!(image_spaces(&r.bytes), ["DeviceGray", "[ICCBased"]);
|
||||
assert_eq!(image_profiles(&r.bytes), [rgb_icc()]);
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
assert_eq!(image_spaces(&r.bytes), ["DeviceGray", "[ICCBased", "[ICCBased"]);
|
||||
assert_eq!(image_profiles(&r.bytes), [rgb_icc(), rgb_icc()]);
|
||||
}
|
||||
|
||||
/// Encode a 4 × 2 RGB or RGBA image with `icc` embedded in `format`.
|
||||
fn encode_with_icc(format: craft_image_codecs::Format, rgba: bool, color: [u8; 4], icc: Vec<u8>) -> Vec<u8> {
|
||||
let (layout, pixels) = if rgba {
|
||||
(craft_image_codecs::ChannelLayout::Rgba, color.repeat(8))
|
||||
} else {
|
||||
(craft_image_codecs::ChannelLayout::Rgb, [color[0], color[1], color[2]].repeat(8))
|
||||
};
|
||||
let img = craft_image_codecs::Image::from_raw(4, 2, layout, craft_image_codecs::SampleType::U8, pixels).unwrap().with_icc(Some(icc));
|
||||
let opts = craft_image_codecs::EncodeOptions { embed_icc: true, ..Default::default() };
|
||||
craft_image_codecs::encode(&img, format, &opts).unwrap()
|
||||
}
|
||||
|
||||
/// Placed RGB/RGBA images with an embedded sRGB profile whose ICC version PDF 1.6 / krilla drops
|
||||
/// (v2.4, v4.2, v4.3, v4.4) or a mismatched profile must still be written as `/ICCBased` in
|
||||
/// PDF/X-4 rather than falling back to `/DeviceRGB` (#3341).
|
||||
#[test]
|
||||
fn embedded_srgb_icc_past_pdf16_stays_iccbased_in_pdfx4() {
|
||||
let srgb_v44 = {
|
||||
let mut p = craft_cms::Builtin::Srgb.profile().clone().with_encoded_bytes().to_bytes().to_vec();
|
||||
p[8] = 4;
|
||||
p[9] = 0x40;
|
||||
p
|
||||
};
|
||||
let srgb_v24 = {
|
||||
let mut p = crate::export::SRGB_ICC.to_vec();
|
||||
p[8] = 2;
|
||||
p[9] = 0x40;
|
||||
p
|
||||
};
|
||||
let mut wrong_space = rgb_icc();
|
||||
wrong_space[16..20].copy_from_slice(b"GRAY");
|
||||
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
let cases = [
|
||||
("srgb-v44.jpg", encode_with_icc(craft_image_codecs::Format::Jpeg, false, [200, 40, 20, 255], srgb_v44.clone())),
|
||||
("srgb-v24.jpg", encode_with_icc(craft_image_codecs::Format::Jpeg, false, [20, 200, 40, 255], srgb_v24.clone())),
|
||||
("srgb-v44.png", encode_with_icc(craft_image_codecs::Format::Png, false, [40, 20, 200, 255], srgb_v44.clone())),
|
||||
("srgb-v44-alpha.png", encode_with_icc(craft_image_codecs::Format::Png, true, [200, 180, 20, 128], srgb_v44.clone())),
|
||||
("srgb-v44.webp", encode_with_icc(craft_image_codecs::Format::WebP, false, [20, 180, 200, 255], srgb_v44)),
|
||||
("wrong-icc.jpg", encode_with_icc(craft_image_codecs::Format::Jpeg, false, [180, 20, 180, 255], wrong_space.clone())),
|
||||
("wrong-icc.png", encode_with_icc(craft_image_codecs::Format::Png, false, [120, 90, 60, 255], wrong_space)),
|
||||
];
|
||||
for (i, (name, data)) in cases.into_iter().enumerate() {
|
||||
place(&mut d, name, data, (4.0, 2.0), (72.0, 72.0 + 40.0 * i as f64));
|
||||
}
|
||||
|
||||
for compress_images in [false, true] {
|
||||
let opts = PdfOptions { standard: Standard::PdfX4, compress_images, ..Default::default() };
|
||||
let r = export_pdf_with_report(&d, &Cache::new(), &opts).unwrap();
|
||||
assert!(r.warnings.is_empty(), "compress_images {compress_images}: {:?}", r.warnings);
|
||||
assert!(check_pdfx4(&r.bytes).is_empty(), "compress_images {compress_images}: {:?}", check_pdfx4(&r.bytes));
|
||||
// 7 colour images (all ICCBased) + 1 DeviceGray SMask for the RGBA PNG.
|
||||
let mut expected = vec!["DeviceGray".to_string()];
|
||||
expected.extend(std::iter::repeat_n("[ICCBased".to_string(), 7));
|
||||
expected.sort();
|
||||
assert_eq!(image_spaces(&r.bytes), expected, "compress_images {compress_images}");
|
||||
let profiles = image_profiles(&r.bytes);
|
||||
assert_eq!(profiles.len(), 7, "compress_images {compress_images}");
|
||||
assert!(profiles.iter().all(|p| p == crate::export::SRGB_ICC), "fallback profile is sRGB v2.1");
|
||||
}
|
||||
|
||||
// sRGB v4.4 JPEG keeps DCTDecode passthrough without re-encoding.
|
||||
let mut single = Document::new(&NewDocument::default());
|
||||
let jpg = encode_with_icc(craft_image_codecs::Format::Jpeg, false, [200, 40, 20, 255], srgb_v24);
|
||||
place(&mut single, "srgb-v24.jpg", jpg, (4.0, 2.0), (72.0, 72.0));
|
||||
let r = x4(&single);
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
assert!(String::from_utf8_lossy(&r.bytes).contains("/DCTDecode"), "sRGB JPEG keeps DCTDecode passthrough");
|
||||
}
|
||||
|
||||
/// A wide-gamut RGB image whose embedded ICC version PDF 1.6 / krilla drops (e.g. Display P3 v4.3)
|
||||
/// is converted to sRGB pixels before being tagged with sRGB v2.1, so colours are not shifted.
|
||||
#[test]
|
||||
fn embedded_wide_gamut_icc_past_pdf16_converts_to_srgb_in_pdfx4() {
|
||||
let p3 = craft_cms::Builtin::DisplayP3.profile().clone().with_encoded_bytes().to_bytes().to_vec();
|
||||
let src_color = [60, 200, 60, 255];
|
||||
let p3_png = encode_with_icc(craft_image_codecs::Format::Png, false, src_color, p3.clone());
|
||||
let p3_jpg = encode_with_icc(craft_image_codecs::Format::Jpeg, false, src_color, p3);
|
||||
let expected_srgb = designcraft_images::decode_rgba(&p3_png).unwrap().get_pixel(0, 0).0;
|
||||
// Sanity: Display P3 green shifts noticeably when converted to sRGB.
|
||||
assert!(expected_srgb[0].abs_diff(src_color[0]) > 10 || expected_srgb[1].abs_diff(src_color[1]) > 5);
|
||||
|
||||
for (name, bytes) in [("p3.png", p3_png), ("p3.jpg", p3_jpg)] {
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
place(&mut d, name, bytes, (4.0, 2.0), (72.0, 72.0));
|
||||
for compress_images in [false, true] {
|
||||
let opts = PdfOptions { standard: Standard::PdfX4, compress_images, ..Default::default() };
|
||||
let r = export_pdf_with_report(&d, &Cache::new(), &opts).unwrap();
|
||||
assert!(r.warnings.is_empty(), "{name} compress={compress_images}: {:?}", r.warnings);
|
||||
assert_eq!(image_spaces(&r.bytes), ["[ICCBased"], "{name} compress={compress_images}");
|
||||
assert_eq!(image_profiles(&r.bytes), [crate::export::SRGB_ICC], "{name} compress={compress_images}");
|
||||
// Decode the written image stream (either raw RGB8 or JPEG) and verify sRGB conversion.
|
||||
let pdf = craft_pdf::syntax::Pdf::new(r.bytes).unwrap();
|
||||
let stream = pdf
|
||||
.objects()
|
||||
.into_iter()
|
||||
.filter_map(|o| o.into_stream())
|
||||
.find(|s| s.dict().get::<Name>(b"Subtype").is_some_and(|n| n.as_str() == "Image"))
|
||||
.unwrap();
|
||||
let px = if stream.dict().get::<Name>(b"Filter").is_some_and(|f| f.as_str() == "DCTDecode") {
|
||||
let raw_jpg = stream.raw_data();
|
||||
let dec = craft_image_codecs::decode(&raw_jpg).unwrap().to_rgba8();
|
||||
[dec[0], dec[1], dec[2]]
|
||||
} else {
|
||||
let raw = stream.decoded().unwrap();
|
||||
[raw[0], raw[1], raw[2]]
|
||||
};
|
||||
for ch in 0..3 {
|
||||
assert!(
|
||||
px[ch].abs_diff(expected_srgb[ch]) <= 4,
|
||||
"{name} compress={compress_images} channel {ch}: got {px:?}, expected ~{:?} (unconverted {src_color:?})",
|
||||
&expected_srgb[..3]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An RGB profile that parses as RGB but lacks a usable source transform (no matrix/TRC or AToB
|
||||
/// tags) keeps display preview's best-effort fallback, but PDF/X-4 export must not tag its
|
||||
/// unconverted samples as sRGB on JPEG, lossless PNG, or recompressed PNG.
|
||||
#[test]
|
||||
fn embedded_unconvertible_rgb_icc_is_not_tagged_as_srgb_in_pdfx4() {
|
||||
let mut unconvertible_v43 = rgb_icc();
|
||||
unconvertible_v43[8] = 4;
|
||||
unconvertible_v43[9] = 0x30;
|
||||
let parsed = craft_cms::Profile::parse(&unconvertible_v43).unwrap();
|
||||
assert_eq!(parsed.color_space, craft_cms::ColorSpace::Rgb);
|
||||
assert!(parsed.device_to_pcs(craft_cms::Intent::RelativeColorimetric).is_err());
|
||||
|
||||
let src_color = [60, 200, 60, 255];
|
||||
let jpg = encode_with_icc(craft_image_codecs::Format::Jpeg, false, src_color, unconvertible_v43.clone());
|
||||
let png_bytes = encode_with_icc(craft_image_codecs::Format::Png, false, src_color, unconvertible_v43);
|
||||
// Display preview retains best-effort fallback when conversion is unavailable.
|
||||
assert_eq!(designcraft_images::decode_rgba(&png_bytes).unwrap().get_pixel(0, 0).0, src_color);
|
||||
assert!(designcraft_images::decode_rgba(&jpg).is_some());
|
||||
|
||||
for (name, bytes) in [("no-lut.jpg", jpg), ("no-lut.png", png_bytes)] {
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
place(&mut d, name, bytes, (4.0, 2.0), (72.0, 72.0));
|
||||
for compress_images in [false, true] {
|
||||
let opts = PdfOptions { standard: Standard::PdfX4, compress_images, ..Default::default() };
|
||||
let r = export_pdf_with_report(&d, &Cache::new(), &opts).unwrap();
|
||||
assert!(image_spaces(&r.bytes).is_empty(), "{name} compress={compress_images}: unconverted image was emitted");
|
||||
assert!(r.warnings.iter().any(|w| w.contains(name)), "{name} compress={compress_images}: expected skip warning, got {:?}", r.warnings);
|
||||
assert!(check_pdfx4(&r.bytes).is_empty(), "{name} compress={compress_images}: {:?}", check_pdfx4(&r.bytes));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every image constructor asked for interpolation, which PDF/X-4 and PDF/A forbid: PDF/A
|
||||
|
||||
@@ -7,6 +7,37 @@ use crate::PdfError;
|
||||
|
||||
pub(crate) use craft_prepress::pdfx1a::PageGraphics;
|
||||
|
||||
/// RGB process colour into the output intent's CMYK with black point compensation, for PDF/X-1a
|
||||
/// when the colour settings ask for it. The flattener converts the RGB left in the print file
|
||||
/// without black point compensation, so this is made only when it is on: otherwise the export
|
||||
/// stays the flattener's. Relative colorimetric, as the flattener converts.
|
||||
pub(crate) struct ProcessConversion(std::sync::Arc<craft_cms::Transform>);
|
||||
|
||||
impl ProcessConversion {
|
||||
/// Into CMYK profile `icc` with black point compensation `bpc`; `None` without it, or when
|
||||
/// the profile isn't a CMYK profile craft-cms converts into (the flattener then converts).
|
||||
pub(crate) fn new(icc: &[u8], bpc: bool) -> Option<Self> {
|
||||
if !bpc {
|
||||
return None;
|
||||
}
|
||||
let profile = craft_cms::Profile::parse(icc).ok()?;
|
||||
if profile.color_space != craft_cms::ColorSpace::Cmyk {
|
||||
return None;
|
||||
}
|
||||
let opts = craft_cms::TransformOptions { intent: craft_cms::Intent::RelativeColorimetric, bpc, precise_float: false };
|
||||
craft_cms::cached(craft_cms::builtin::srgb(), &profile, opts).ok().map(Self)
|
||||
}
|
||||
|
||||
/// The CMYK of 8-bit sRGB `rgb` (as the flattener reads DeviceRGB); `None` when it can't
|
||||
/// convert.
|
||||
pub(crate) fn cmyk(&self, rgb: [u8; 3]) -> Option<[f32; 4]> {
|
||||
let src = rgb.map(|v| f32::from(v) / 255.0);
|
||||
let mut out = [0.0f32; 4];
|
||||
self.0.convert_f32(&src, 3, &mut out, 4, false).ok()?;
|
||||
Some(out.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn flatten_x1a(pdf: &[u8], dpi: f32, pages: &[PageGraphics], warnings: &mut Vec<String>) -> crate::Result<Vec<u8>> {
|
||||
let (bytes, findings) = craft_prepress::pdfx1a::flatten_x1a(pdf, dpi, pages).map_err(PdfError::Write)?;
|
||||
warnings.extend(findings);
|
||||
|
||||
+97
-11
@@ -249,6 +249,35 @@ fn table_gradient_fill_exports_a_shading() {
|
||||
assert!(pdf.contains("/ShadingType 2") || pdf.contains("/ShadingType2"), "table fill must export a linear gradient");
|
||||
}
|
||||
|
||||
/// A table edge's dashed stroke carries no dash array of its own, so matching the raw pattern
|
||||
/// exported it solid while the renderer dashed it -- the PDF disagreed with the screen (#1467,
|
||||
/// noted in review). The edge goes through `StrokeType::dashes` like every other stroke.
|
||||
#[test]
|
||||
fn a_dashed_table_edge_exports_dashed() {
|
||||
let table = |kind: designcraft_doc::StrokeType| {
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
let lid = d.default_layer();
|
||||
let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 336.0, 300.0), lid, "", ParaFormat::default()).unwrap();
|
||||
let mut t = designcraft_doc::Table::new(1, 1, 2, 0, 0, 200.0);
|
||||
t.rows[0].height = 40.0;
|
||||
t.rows[0].mode = designcraft_doc::RowHeightMode::Exactly;
|
||||
t.options.border.weight = 2.0;
|
||||
t.options.border.kind = kind;
|
||||
d.story_mut(sid).unwrap().insert_table(0, t);
|
||||
uncompressed(&d, PdfOptions::default())
|
||||
};
|
||||
// `d` is the PDF dash operator; krilla writes it `[a b]0 d`, with no space before the phase.
|
||||
let ops = |pdf: &str| pdf.replace("]0 d", "] 0 d");
|
||||
|
||||
// Dashed with no pattern of its own: three weights on, two off, as the renderer draws it.
|
||||
let dashed = ops(&table(designcraft_doc::StrokeType::Dashed { pattern: vec![] }));
|
||||
assert!(dashed.contains("] 0 d"), "a dashed edge exports a dash array");
|
||||
assert!(dashed.contains("[6 4] 0 d"), "three weights on, two off at weight 2");
|
||||
|
||||
// A solid edge still writes no dash array, so the check above means something.
|
||||
assert!(!ops(&table(designcraft_doc::StrokeType::Solid)).contains("] 0 d"), "a solid edge exports none");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tables_export_cell_text() {
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
@@ -522,7 +551,7 @@ fn archival_exports_keep_placed_images_without_interpolation() {
|
||||
}
|
||||
|
||||
/// What a page draws: each glyph (its text and outline bounds) and each filled path's bounds.
|
||||
fn drawn(bytes: &[u8]) -> (Vec<(String, kurbo::Rect)>, Vec<kurbo::Rect>) {
|
||||
fn drawn(bytes: &[u8]) -> (Vec<(String, kurbo::Point)>, Vec<kurbo::Rect>) {
|
||||
use hayro_interpret::font::Glyph;
|
||||
use hayro_interpret::{
|
||||
BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask,
|
||||
@@ -530,7 +559,7 @@ fn drawn(bytes: &[u8]) -> (Vec<(String, kurbo::Rect)>, Vec<kurbo::Rect>) {
|
||||
};
|
||||
use kurbo::Shape as _;
|
||||
#[derive(Default)]
|
||||
struct Rec(Vec<(String, kurbo::Rect)>, Vec<kurbo::Rect>);
|
||||
struct Rec(Vec<(String, kurbo::Point)>, Vec<kurbo::Rect>);
|
||||
impl Device<'_> for Rec {
|
||||
fn set_soft_mask(&mut self, _: Option<SoftMask<'_>>) {}
|
||||
fn set_blend_mode(&mut self, _: BlendMode) {}
|
||||
@@ -539,17 +568,13 @@ fn drawn(bytes: &[u8]) -> (Vec<(String, kurbo::Rect)>, Vec<kurbo::Rect>) {
|
||||
}
|
||||
fn push_clip_path(&mut self, _: &ClipPath) {}
|
||||
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {}
|
||||
fn draw_glyph(&mut self, g: &Glyph<'_>, _: kurbo::Affine, _: kurbo::Affine, _: &Paint<'_>, _: &GlyphDrawMode) {
|
||||
fn draw_glyph(&mut self, g: &Glyph<'_>, xf: kurbo::Affine, glyph_xf: kurbo::Affine, _: &Paint<'_>, _: &GlyphDrawMode) {
|
||||
let text = match g.as_unicode() {
|
||||
Some(hayro_cmap::BfString::Char(c)) => c.to_string(),
|
||||
Some(hayro_cmap::BfString::String(s)) => s,
|
||||
None => String::new(),
|
||||
};
|
||||
let bounds = match g {
|
||||
Glyph::Outline(o) => o.outline().bounding_box(),
|
||||
Glyph::Type3(_) => kurbo::Rect::ZERO,
|
||||
};
|
||||
self.0.push((text, bounds));
|
||||
self.0.push((text, xf * glyph_xf * kurbo::Point::ORIGIN));
|
||||
}
|
||||
fn draw_image(&mut self, _: Image<'_, '_>, _: kurbo::Affine) {}
|
||||
fn pop_clip_path(&mut self) {}
|
||||
@@ -667,7 +692,7 @@ fn pdfa_leaves_out_form_fields_added_after_validation() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_glyphs_print_as_boxes() {
|
||||
fn missing_glyphs_print_as_the_fonts_notdef() {
|
||||
// Source Serif 4 lacks 語: its .notdef box is drawn as a path, not as a .notdef glyph
|
||||
// (which PDF/A and PDF/UA forbid).
|
||||
let boxes = |paths: &[kurbo::Rect]| paths.iter().filter(|r| r.width() > 1.0 && r.width() < 12.0 && r.height() > 3.0 && r.height() < 12.0).count();
|
||||
@@ -678,7 +703,7 @@ fn missing_glyphs_print_as_boxes() {
|
||||
assert_eq!(boxes(&paths), 1, "{paths:?}");
|
||||
let a = export_pdf_with_report(&d, &Cache::new(), &PdfOptions { standard: Standard::PdfA2b, ..Default::default() });
|
||||
assert!(a.is_ok(), "PDF/A takes the box: {:?}", a.err());
|
||||
// A font whose .notdef is empty: the box DesignCraft draws for it.
|
||||
// A font whose .notdef is empty prints nothing there, as InDesign exports it.
|
||||
const FAMILY: &str = "DC Test PDF Empty Notdef";
|
||||
let font = designcraft_fonts::testing::font_mapping(FAMILY, &[('a', 'a'), ('b', 'b')]).unwrap();
|
||||
designcraft_fonts::FontDb::global().add_font(designcraft_fonts::testing::with_empty_notdef(font).unwrap());
|
||||
@@ -687,7 +712,15 @@ fn missing_glyphs_print_as_boxes() {
|
||||
d.story_mut(sid).unwrap().format_chars(0.."a語b".len(), |f| f.over.font_family = Some(FAMILY.into()));
|
||||
let (glyphs, paths) = drawn(&export_pdf(&d, &Cache::new(), &PdfOptions::default()).unwrap());
|
||||
assert_eq!(glyphs.iter().map(|g| g.0.as_str()).collect::<Vec<_>>(), ["a", "b"], "{glyphs:?}");
|
||||
assert_eq!(boxes(&paths), 1, "{paths:?}");
|
||||
assert_eq!(boxes(&paths), 0, "{paths:?}");
|
||||
// The empty .notdef still takes its advance: `b` stays where the layout puts it.
|
||||
let cs = designcraft_compose::compose_story(&d, sid, &designcraft_compose::ComposeOptions::default());
|
||||
let line = &cs.frames[0].lines[0];
|
||||
let x = |c: char| line.glyphs.iter().find(|g| g.rendered_char == c).unwrap().x;
|
||||
let notdef = line.glyphs.iter().find(|g| g.gid == 0).unwrap();
|
||||
assert!(notdef.adv > 0.0 && x('b') - x('a') > notdef.adv, "the .notdef has an advance");
|
||||
let pdf_gap = glyphs[1].1.x - glyphs[0].1.x;
|
||||
assert!((pdf_gap - (x('b') - x('a'))).abs() < 0.01, "pdf {pdf_gap}, layout {}", x('b') - x('a'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1069,6 +1102,59 @@ fn a_swatch_colours_a_greyscale_image() {
|
||||
assert!(!s.contains("PANTONE#20Test"), "a colour image keeps its colours");
|
||||
}
|
||||
|
||||
/// A 1-bit (bitmap mode) TIFF with no colour applied (`Fill::none()`) exports with transparent
|
||||
/// white pixels and black ink, not as an opaque white image or JPEG (#3379).
|
||||
#[test]
|
||||
fn uncoloured_one_bit_tiff_exports_with_transparent_white() {
|
||||
// 1-bit WhiteIsZero TIFF, 8×1: first 4 pixels white (0), last 4 pixels black (1).
|
||||
let entries: [(u16, u16, u32); 8] = [(256, 3, 8), (257, 3, 1), (258, 3, 1), (259, 3, 1), (262, 3, 0), (273, 4, 8), (278, 3, 1), (279, 4, 1)];
|
||||
let mut tiff = b"II*\0".to_vec();
|
||||
tiff.extend(10u32.to_le_bytes());
|
||||
tiff.extend([0b0000_1111u8, 0]);
|
||||
tiff.extend(u16::try_from(entries.len()).unwrap().to_le_bytes());
|
||||
for (tag, kind, value) in entries {
|
||||
tiff.extend(tag.to_le_bytes());
|
||||
tiff.extend(kind.to_le_bytes());
|
||||
tiff.extend(1u32.to_le_bytes());
|
||||
if kind == 3 {
|
||||
tiff.extend(u16::try_from(value).unwrap().to_le_bytes());
|
||||
tiff.extend([0, 0]);
|
||||
} else {
|
||||
tiff.extend(value.to_le_bytes());
|
||||
}
|
||||
}
|
||||
tiff.extend(0u32.to_le_bytes());
|
||||
|
||||
let mut d = doc_with_text("underneath");
|
||||
place(&mut d, tiff, (8, 1));
|
||||
let expected_mask = vec![0, 0, 0, 0, 255, 255, 255, 255];
|
||||
|
||||
for (standard, compress_images) in [(Standard::None, false), (Standard::None, true), (Standard::PdfX4, false), (Standard::PdfA2b, false)] {
|
||||
let opts = PdfOptions { standard, compress_images, compress: false, created: Some(1_700_000_000), ..Default::default() };
|
||||
let r = export_pdf_with_report(&d, &Cache::new(), &opts).unwrap_or_else(|e| panic!("{standard:?} compress={compress_images}: {e}"));
|
||||
if standard != Standard::PdfA2b {
|
||||
assert!(r.warnings.is_empty(), "{standard:?} compress={compress_images}: {:?}", r.warnings);
|
||||
}
|
||||
let s = String::from_utf8_lossy(&r.bytes);
|
||||
assert!(s.contains("/SMask"), "{standard:?} compress={compress_images}: white pixels must be masked transparent");
|
||||
assert!(!s.contains("/DCTDecode"), "{standard:?} compress={compress_images}: 1-bit bitmap must not become opaque JPEG");
|
||||
let xobjects = image_xobjects(&r.bytes);
|
||||
assert_eq!(xobjects.len(), 1, "{standard:?} compress={compress_images}: {xobjects:?}");
|
||||
if standard != Standard::PdfA2b {
|
||||
assert_eq!(xobjects[0].0, "DeviceGray", "{standard:?} compress={compress_images}");
|
||||
}
|
||||
assert_eq!(xobjects[0].1, expected_mask, "{standard:?} compress={compress_images}: coverage mask has 0 for white and 255 for black");
|
||||
}
|
||||
// PDF/X-1a flattens the 1-bit bitmap's transparency cleanly with no transparency left.
|
||||
let x1a = export_pdf_with_report(
|
||||
&d,
|
||||
&Cache::new(),
|
||||
&PdfOptions { standard: Standard::PdfX1a, compress: false, created: Some(1_700_000_000), ..Default::default() },
|
||||
)
|
||||
.expect("PDF/X-1a export succeeds");
|
||||
assert!(!String::from_utf8_lossy(&x1a.bytes).contains("/SMask"), "PDF/X-1a flattens soft masks");
|
||||
}
|
||||
|
||||
/// An inline object is painted under its frame's text, as InDesign draws it: a picture whose
|
||||
/// frame reaches down into the next line (a negative Y offset) doesn't hide that line.
|
||||
#[test]
|
||||
|
||||
+25
-10
@@ -433,18 +433,24 @@ impl Exporter<'_> {
|
||||
s.set_fill(None);
|
||||
return;
|
||||
}
|
||||
let (cap, dash) = match &kind {
|
||||
designcraft_doc::StrokeType::Dashed { pattern } if designcraft_doc::StrokeType::expandable_dashes(pattern, seg.a.distance(seg.b)) => {
|
||||
let mut pat: Vec<f32> = pattern.iter().map(|v| v.max(0.0) as f32).collect();
|
||||
if pat.len() % 2 == 1 {
|
||||
pat.extend(pat.clone());
|
||||
}
|
||||
(krilla::paint::LineCap::Butt, Some(krilla::paint::StrokeDash { array: pat, offset: 0.0 }))
|
||||
let len = seg.a.distance(seg.b);
|
||||
let expandable = |p: &[f64]| designcraft_doc::StrokeType::expandable_dashes(p, len);
|
||||
// Through the resolved pattern, so a `Dashed` with none of its own dashes by its
|
||||
// weight here as well. Matching the raw pattern left a table edge exporting solid
|
||||
// while the renderer and the item stroke dashed it (noted in review).
|
||||
let dashed = kind.dashes(st.weight).filter(|p| expandable(p)).map(|pattern| {
|
||||
let mut pat: Vec<f32> = pattern.iter().map(|v| v.max(0.0) as f32).collect();
|
||||
if pat.len() % 2 == 1 {
|
||||
pat.extend(pat.clone());
|
||||
}
|
||||
designcraft_doc::StrokeType::Dotted if designcraft_doc::StrokeType::expandable_dashes(&[0.0, st.weight * 2.0], seg.a.distance(seg.b)) => {
|
||||
(krilla::paint::LineCap::Butt, krilla::paint::StrokeDash { array: pat, offset: 0.0 })
|
||||
});
|
||||
let (cap, dash) = match dashed {
|
||||
Some((cap, d)) => (cap, Some(d)),
|
||||
None if matches!(kind, designcraft_doc::StrokeType::Dotted) && expandable(&[0.0, st.weight * 2.0]) => {
|
||||
(krilla::paint::LineCap::Round, Some(krilla::paint::StrokeDash { array: vec![0.0, (st.weight * 2.0) as f32], offset: 0.0 }))
|
||||
}
|
||||
_ => (krilla::paint::LineCap::Square, None),
|
||||
None => (krilla::paint::LineCap::Square, None),
|
||||
};
|
||||
s.set_fill(None);
|
||||
s.set_stroke(Some(Stroke { paint: col.into(), width: st.weight as f32, line_cap: cap, dash, ..Default::default() }));
|
||||
@@ -562,7 +568,8 @@ impl Exporter<'_> {
|
||||
} else {
|
||||
stroke
|
||||
};
|
||||
// A missing glyph is drawn as its box: PDF/A and PDF/UA forbid showing .notdef as text.
|
||||
// A missing glyph is drawn as the font's .notdef outline: PDF/A and PDF/UA forbid showing
|
||||
// .notdef as text.
|
||||
if g0.gid == 0 {
|
||||
self.paint_outlines(s, &glyph_outlines(glyphs, size, tan), origin, fill, stroke, weight);
|
||||
} else if let Some(font) = self.font(&face) {
|
||||
@@ -691,6 +698,14 @@ fn glyph_outlines(glyphs: &[PlacedGlyph], size: f64, tan: f64) -> BezPath {
|
||||
let Some(g0) = glyphs.first() else { return bp };
|
||||
let k = size / g0.face.upem;
|
||||
for g in glyphs {
|
||||
// A .notdef the font leaves empty prints as nothing, as InDesign exports it (the screen
|
||||
// shows a box, and Preflight lists the character). `missing_box` is `Some` exactly when
|
||||
// the font's .notdef is empty. Only PDF text painting calls this function: outline
|
||||
// conversion and the screen still get the box from `FontDb::outline`. The glyphs after it
|
||||
// keep their places: each is placed from its own position.
|
||||
if g.gid == 0 && db.missing_box(&g.face).is_some() {
|
||||
continue;
|
||||
}
|
||||
let dy = g.y - g0.y;
|
||||
let a = Affine::translate(((g.x - g0.x + tan * dy) / (g0.sx / g0.sy), dy)) * Affine::scale(k);
|
||||
let mut o = (*db.outline(&g.face, g.gid)).clone();
|
||||
|
||||
@@ -319,6 +319,49 @@ fn x1a_dropped_inks_warning_says_they_wont_print() {
|
||||
assert!(warnings.iter().all(|w| !w.contains("converted to process")), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// The `k` (DeviceCMYK fill) operands of the first page's content, in order.
|
||||
fn cmyk_fills(bytes: &[u8]) -> Vec<Vec<f32>> {
|
||||
let pdf = Pdf::new(bytes.to_vec()).unwrap();
|
||||
let pages = pdf.pages();
|
||||
let content = pages.iter().next().unwrap().page_stream().unwrap().to_vec();
|
||||
let text = String::from_utf8_lossy(&content);
|
||||
let tokens: Vec<&str> = text.split_whitespace().collect();
|
||||
tokens
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, t)| **t == "k" && *i >= 4)
|
||||
.map(|(i, _)| tokens[i - 4..i].iter().map(|s| s.parse().unwrap()).collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// An RGB fill converts into the output intent's CMYK with black point compensation when the
|
||||
/// colour settings ask for it (#2570): the issue's blue and a dark grey print with less ink than
|
||||
/// without it.
|
||||
#[test]
|
||||
fn x1a_converts_rgb_fills_with_black_point_compensation() {
|
||||
use designcraft_color::cms::{Cms, ColorSettings};
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
d.swatches.push(Swatch::color("Blue", Color::rgb(40.0 / 255.0, 60.0 / 255.0, 180.0 / 255.0)));
|
||||
d.swatches.push(Swatch::color("Shadow", Color::rgb(30.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0)));
|
||||
add(&mut d, Rect::new(72.0, 72.0, 172.0, 172.0), "Blue", |_| {});
|
||||
add(&mut d, Rect::new(272.0, 72.0, 372.0, 172.0), "Shadow", |_| {});
|
||||
let opts = PdfOptions { standard: Standard::PdfX1a, ..PdfOptions::default() };
|
||||
let fills = |bpc: bool| {
|
||||
let cms = Cms::new(&ColorSettings { bpc, ..ColorSettings::default() }).unwrap();
|
||||
let r = crate::export::export_pdf_with_cms(&d, &Cache::new(), &opts, &cms).unwrap();
|
||||
assert_eq!(check_pdfx1a(&r.bytes), Vec::<String>::new(), "bpc {bpc}");
|
||||
let fills = cmyk_fills(&r.bytes);
|
||||
assert_eq!(fills.len(), 2, "bpc {bpc}: {fills:?}");
|
||||
fills
|
||||
};
|
||||
let (with, without) = (fills(true), fills(false));
|
||||
for (with, without) in with.iter().zip(&without) {
|
||||
assert_ne!(with, without, "black point compensation changed nothing");
|
||||
let ink = |c: &Vec<f32>| c.iter().sum::<f32>();
|
||||
assert!(ink(with) < ink(without), "with {with:?}, without {without:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The output intent and the identification are read as objects: whitespace between tokens (as
|
||||
/// qpdf and Ghostscript write them) doesn't hide them.
|
||||
#[test]
|
||||
|
||||
+13
-14
@@ -452,21 +452,20 @@ impl<'a> Exporter<'a> {
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
match &stroke.kind {
|
||||
StrokeType::Dashed { pattern } if pattern.iter().any(|length| *length > 0.0) => {
|
||||
let mut pattern = pattern.iter().map(|length| length.max(0.0)).collect::<Vec<_>>();
|
||||
if pattern.len() % 2 == 1 {
|
||||
pattern.extend(pattern.clone());
|
||||
}
|
||||
let pairs = pattern
|
||||
.chunks(2)
|
||||
.filter_map(|pair| pair.first().zip(pair.get(1)))
|
||||
.map(|(dash, gap)| (*dash / stroke.weight, *gap / stroke.weight))
|
||||
.collect();
|
||||
line.dash = Some(craft_pptx::style::Dash::Custom { pattern: pairs });
|
||||
// Resolve empty Dashed patterns through StrokeType::dashes so a named dashed
|
||||
// style with no array of its own still exports dashed (#1467).
|
||||
if let Some(mut pattern) = stroke.kind.dashes(stroke.weight).filter(|p| stroke.weight > 0.0 && p.len() <= designcraft_doc::MAX_DASH_ENTRIES) {
|
||||
if pattern.len() % 2 == 1 {
|
||||
pattern.extend(pattern.clone());
|
||||
}
|
||||
StrokeType::Dotted => line.dash = Some(craft_pptx::style::Dash::Preset { name: "sysDot".into() }),
|
||||
_ => {}
|
||||
let pairs = pattern
|
||||
.chunks(2)
|
||||
.filter_map(|pair| pair.first().zip(pair.get(1)))
|
||||
.map(|(dash, gap)| (*dash / stroke.weight, *gap / stroke.weight))
|
||||
.collect();
|
||||
line.dash = Some(craft_pptx::style::Dash::Custom { pattern: pairs });
|
||||
} else if matches!(stroke.kind, StrokeType::Dotted) {
|
||||
line.dash = Some(craft_pptx::style::Dash::Preset { name: "sysDot".into() });
|
||||
}
|
||||
let end = |arrow: Arrowhead| {
|
||||
match arrow {
|
||||
|
||||
@@ -87,10 +87,19 @@ fn model_border(ex: &Exporter, s: Option<&StrokeSeg>, k: f64, opacity: f32) -> c
|
||||
let Some(color) = ex.model_color(&stroke.stroke.color, stroke.stroke.tint, opacity) else { return craft_pptx::Line::none() };
|
||||
let mut line = craft_pptx::Line::solid(color, stroke.stroke.weight * k);
|
||||
line.cap = Some(craft_pptx::style::LineCap::Flat);
|
||||
line.dash = match stroke.stroke.kind {
|
||||
StrokeType::Dashed { .. } => Some(craft_pptx::style::Dash::Preset { name: "dash".into() }),
|
||||
StrokeType::Dotted => Some(craft_pptx::style::Dash::Preset { name: "sysDot".into() }),
|
||||
_ => None,
|
||||
// The pattern items use, not the fixed `dash` preset, so a dashed edge matches the PDF.
|
||||
let st = &stroke.stroke;
|
||||
line.dash = if let Some(mut pattern) = st.kind.dashes(st.weight).filter(|p| st.weight > 0.0 && p.len() <= designcraft_doc::MAX_DASH_ENTRIES) {
|
||||
if pattern.len() % 2 == 1 {
|
||||
pattern.extend(pattern.clone());
|
||||
}
|
||||
let pairs =
|
||||
pattern.chunks(2).filter_map(|pair| pair.first().zip(pair.get(1))).map(|(dash, gap)| (*dash / st.weight, *gap / st.weight)).collect();
|
||||
Some(craft_pptx::style::Dash::Custom { pattern: pairs })
|
||||
} else if matches!(st.kind, StrokeType::Dotted) {
|
||||
Some(craft_pptx::style::Dash::Preset { name: "sysDot".into() })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
line
|
||||
}
|
||||
|
||||
@@ -123,6 +123,27 @@ fn shapes_keep_geometry_fill_stroke_and_effects() {
|
||||
assert!(s.contains("rot=\"1800000\""), "{s}");
|
||||
}
|
||||
|
||||
/// A dashed table edge with no pattern of its own is written with the pattern a dashed frame
|
||||
/// gets (three weights on, two off), not PowerPoint's fixed `dash` preset, so it matches the
|
||||
/// PDF and the screen.
|
||||
#[test]
|
||||
fn a_dashed_table_edge_keeps_the_dash_pattern() {
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
let lid = d.default_layer();
|
||||
let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 336.0, 300.0), lid, "", ParaFormat::default()).unwrap();
|
||||
let mut t = designcraft_doc::Table::new(1, 1, 2, 0, 0, 200.0);
|
||||
t.rows[0].height = 40.0;
|
||||
t.rows[0].mode = designcraft_doc::RowHeightMode::Exactly;
|
||||
t.options.border.weight = 2.0;
|
||||
t.options.border.kind = StrokeType::Dashed { pattern: vec![] };
|
||||
d.story_mut(sid).unwrap().insert_table(0, t);
|
||||
let mut z = export(&d, &PptxOptions::default());
|
||||
let s = part(&mut z, "ppt/slides/slide1.xml");
|
||||
assert!(s.contains("<a:tbl>"), "the table is exported as a table: {s}");
|
||||
assert!(s.contains("<a:custDash><a:ds d=\"300000\" sp=\"200000\"/></a:custDash>"), "6 on, 4 off for a 2 pt edge: {s}");
|
||||
assert!(!s.contains("<a:prstDash val=\"dash\"/>"), "{s}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composed_lines_become_line_breaks_with_the_story_text() {
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
|
||||
@@ -64,10 +64,19 @@ fn tone_of(data: &AssetData, wait: bool) -> Prepared<Option<Tone>> {
|
||||
}
|
||||
|
||||
/// `pm` (decoded from `data`) coloured by `fill`, cached per image and on-screen colour; `None`
|
||||
/// when the image keeps its own colours: no swatch, one that no longer exists, a colour image,
|
||||
/// or one whose file can't be had. Without `wait`, an image whose tone isn't known yet is
|
||||
/// [`Prepared::Pending`] while it is found in the background.
|
||||
pub(crate) fn colorized(doc: &Document, fill: &Fill, data: &AssetData, pm: &Arc<Pixmap>, wait: bool) -> Prepared<Option<Arc<Pixmap>>> {
|
||||
/// when the image keeps its own colours: a colour image, an uncoloured greyscale image, or one
|
||||
/// whose file can't be had. A 1-bit (bitmap mode) raster always has transparent white pixels and
|
||||
/// draws its black pixels in `[Black]` when no swatch applies. Without `wait`, a coloured image
|
||||
/// whose tone isn't known yet is [`Prepared::Pending`] while it is found in the background.
|
||||
pub(crate) fn colorized(doc: &Document, fill: &Fill, data: &AssetData, pm: &Arc<Pixmap>, bitmap: bool, wait: bool) -> Prepared<Option<Arc<Pixmap>>> {
|
||||
if bitmap {
|
||||
let color = (!fill.is_none())
|
||||
.then(|| doc.resolve_color(&fill.swatch, fill.tint))
|
||||
.flatten()
|
||||
.or_else(|| doc.resolve_color(designcraft_color::swatch::BLACK, 1.0))
|
||||
.unwrap_or_else(|| designcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0));
|
||||
return Prepared::Ready(Some(coloured(color, Tone::Bitmap, pm)));
|
||||
}
|
||||
if fill.is_none() {
|
||||
return Prepared::Ready(None);
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ pub fn damage_with(old: &Document, new: &Document, cache: Option<&designcraft_co
|
||||
|| old.layers != new.layers
|
||||
|| old.settings != new.settings
|
||||
|| old.sections != new.sections
|
||||
|| old.title != new.title
|
||||
|| old.text_variables != new.text_variables
|
||||
|| old.footnote_options != new.footnote_options
|
||||
|| old.xref_formats != new.xref_formats
|
||||
@@ -582,4 +583,16 @@ mod tests {
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// #3258: saving under a new name changes `doc.title` without touching spreads or stories;
|
||||
/// damage reports a full repaint so File Name variables on document and parent pages redraw.
|
||||
#[test]
|
||||
fn renaming_document_damages_canvas() {
|
||||
let mut d = Document::new(&NewDocument { pages: 1, title: "Untitled-1".into(), ..Default::default() });
|
||||
let old = d.clone();
|
||||
let cache = designcraft_compose::Cache::new();
|
||||
d.title = "CatalogEdition".into();
|
||||
assert!(damage(&old, &d).is_none());
|
||||
assert!(damage_with(&old, &d, Some(&cache)).is_none());
|
||||
}
|
||||
}
|
||||
+84
-53
@@ -49,6 +49,7 @@ const MAX_KEPT_FULL: usize = 2;
|
||||
struct Entry {
|
||||
pm: Arc<Pixmap>,
|
||||
stamp: u64,
|
||||
bitmap: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -115,17 +116,21 @@ fn with<R>(f: impl FnOnce(&mut Cache) -> R) -> R {
|
||||
f(c)
|
||||
}
|
||||
|
||||
fn lookup(key: (SourceKey, u32, u8)) -> Option<Arc<Pixmap>> {
|
||||
fn lookup_entry(key: (SourceKey, u32, u8)) -> Option<(Arc<Pixmap>, bool)> {
|
||||
with(|c| {
|
||||
c.clock += 1;
|
||||
let clock = c.clock;
|
||||
c.map.get_mut(&key).map(|e| {
|
||||
e.stamp = clock;
|
||||
e.pm.clone()
|
||||
(e.pm.clone(), e.bitmap)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn lookup(key: (SourceKey, u32, u8)) -> Option<Arc<Pixmap>> {
|
||||
lookup_entry(key).map(|(pm, _)| pm)
|
||||
}
|
||||
|
||||
/// Whether any level of the bytes `id` names is cached.
|
||||
pub(crate) fn has_decodes(id: SourceKey) -> bool {
|
||||
with(|c| c.map.keys().any(|k| k.0 == id))
|
||||
@@ -177,11 +182,11 @@ pub(crate) fn load_bytes(data: &AssetData, gate: bool) -> Option<Arc<Vec<u8>>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Cache `pm` as `level` of the bytes `id` names. `colour` is the
|
||||
/// [`designcraft_color::cms::generation`] read before the pixels were looked up or decoded:
|
||||
/// pixels converted under settings changed since are not kept (the next request decodes them
|
||||
/// again).
|
||||
fn store(id: SourceKey, page: u32, level: u8, pm: Arc<Pixmap>, colour: u64) {
|
||||
/// Cache `pm` as `level` of the bytes `id` names, together with whether the source is a 1-bit
|
||||
/// bitmap raster (`bitmap`). `colour` is the [`designcraft_color::cms::generation`] read before
|
||||
/// the pixels were looked up or decoded: pixels converted under settings changed since are not
|
||||
/// kept (the next request decodes them again).
|
||||
fn store(id: SourceKey, page: u32, level: u8, pm: Arc<Pixmap>, colour: u64, bitmap: bool) {
|
||||
with(|c| {
|
||||
if c.colour != colour {
|
||||
return;
|
||||
@@ -189,7 +194,7 @@ fn store(id: SourceKey, page: u32, level: u8, pm: Arc<Pixmap>, colour: u64) {
|
||||
c.clock += 1;
|
||||
let key = (id, page, level);
|
||||
let n = size_of(&pm);
|
||||
if let Some(old) = c.map.insert(key, Entry { pm, stamp: c.clock }) {
|
||||
if let Some(old) = c.map.insert(key, Entry { pm, stamp: c.clock, bitmap }) {
|
||||
c.bytes -= size_of(&old.pm);
|
||||
}
|
||||
c.bytes += n;
|
||||
@@ -268,15 +273,16 @@ fn dims_now(data: &AssetData, page: u32) -> Option<(u32, u32)> {
|
||||
}
|
||||
|
||||
/// Decode `bytes` (named by `id`) at full resolution without caching the pixels (its size is
|
||||
/// remembered); a failure marks it bad.
|
||||
fn decode_full(id: SourceKey, bytes: &[u8], page: u32) -> Option<Arc<Pixmap>> {
|
||||
/// remembered), together with whether `bytes` is a 1-bit bitmap raster; a failure marks it bad.
|
||||
fn decode_full(id: SourceKey, bytes: &[u8], page: u32) -> Option<(Arc<Pixmap>, bool)> {
|
||||
// Decode outside the lock: other threads keep drawing cached images meanwhile.
|
||||
let pm = decode_pixmap_page(bytes, page);
|
||||
log_decode(id);
|
||||
match pm {
|
||||
Some(pm) => {
|
||||
let bitmap = page == 0 && designcraft_images::is_bitmap(bytes);
|
||||
set_dims(id, page, (u32::from(pm.width()), u32::from(pm.height())), true);
|
||||
Some(Arc::new(pm))
|
||||
Some((Arc::new(pm), bitmap))
|
||||
}
|
||||
None => {
|
||||
with(|c| c.mark_bad((id, page)));
|
||||
@@ -319,8 +325,8 @@ pub fn decoded(data: &AssetData, page: u32) -> Option<Arc<Pixmap>> {
|
||||
return None;
|
||||
}
|
||||
let bytes = load_bytes(data, false)?;
|
||||
let pm = decode_full(id, &bytes, page)?;
|
||||
store(id, page, 0, pm.clone(), colour);
|
||||
let (pm, bitmap) = decode_full(id, &bytes, page)?;
|
||||
store(id, page, 0, pm.clone(), colour, bitmap);
|
||||
Some(pm)
|
||||
}
|
||||
|
||||
@@ -375,32 +381,37 @@ fn halve_to(mut pm: Arc<Pixmap>, from: u8, to: u8) -> Arc<Pixmap> {
|
||||
}
|
||||
|
||||
/// Level `level` of the bytes `id` names from the cache: that level, or one built from the
|
||||
/// nearest finer cached level (no decode).
|
||||
fn cached_level(id: SourceKey, page: u32, level: u8, colour: u64) -> Option<Arc<Pixmap>> {
|
||||
if let Some(pm) = lookup((id, page, level)) {
|
||||
return Some(pm);
|
||||
/// nearest finer cached level (no decode), together with its 1-bit bitmap flag.
|
||||
fn cached_level(id: SourceKey, page: u32, level: u8, colour: u64) -> Option<(Arc<Pixmap>, bool)> {
|
||||
if let Some(entry) = lookup_entry((id, page, level)) {
|
||||
return Some(entry);
|
||||
}
|
||||
let (from, finer) = (0..level).rev().find_map(|l| lookup((id, page, l)).map(|pm| (l, pm)))?;
|
||||
let (from, (finer, bitmap)) = (0..level).rev().find_map(|l| lookup_entry((id, page, l)).map(|e| (l, e)))?;
|
||||
let pm = halve_to(finer, from, level);
|
||||
store(id, page, level, pm.clone(), colour);
|
||||
Some(pm)
|
||||
store(id, page, level, pm.clone(), colour, bitmap);
|
||||
Some((pm, bitmap))
|
||||
}
|
||||
|
||||
/// The mip level of `data` closest above `on_screen` device pixels per point for a graphic
|
||||
/// `width_pt` points wide. Only that level is cached, not the full decode it is built from,
|
||||
/// except while an image is zoomed into (see [`KEEP_FULL`]).
|
||||
pub fn mip(data: &AssetData, page: u32, width_pt: f64, on_screen: f64) -> Option<Arc<Pixmap>> {
|
||||
mip_with_bitmap(data, page, width_pt, on_screen).map(|(pm, _)| pm)
|
||||
}
|
||||
|
||||
/// [`mip`], together with whether `data` is a 1-bit (bitmap mode) raster.
|
||||
pub(crate) fn mip_with_bitmap(data: &AssetData, page: u32, width_pt: f64, on_screen: f64) -> Option<(Arc<Pixmap>, bool)> {
|
||||
mip_gated(data, page, width_pt, on_screen, false)
|
||||
}
|
||||
|
||||
/// [`mip`]; with `gate`, a decode first waits at [`GATE`] for its peak bytes ([`reserve`]),
|
||||
/// counted for the decode path it takes.
|
||||
/// [`mip_with_bitmap`]; with `gate`, a decode first waits at [`GATE`] for its peak bytes
|
||||
/// ([`reserve`]), counted for the decode path it takes.
|
||||
///
|
||||
/// The bytes are loaded only when the level isn't cached (nor a finer one to halve). Gated, a
|
||||
/// load of linked bytes waits at [`GATE`] for their size first, and the decode counts them too
|
||||
/// when the store didn't keep them (two reservations one after the other, never one inside the
|
||||
/// other: a decode holding one while waiting for another could wait for itself).
|
||||
fn mip_gated(data: &AssetData, page: u32, width_pt: f64, on_screen: f64, gate: bool) -> Option<Arc<Pixmap>> {
|
||||
fn mip_gated(data: &AssetData, page: u32, width_pt: f64, on_screen: f64, gate: bool) -> Option<(Arc<Pixmap>, bool)> {
|
||||
let id = data.key();
|
||||
if is_bad(id, page) || unavailable_now(id).is_some() {
|
||||
return None;
|
||||
@@ -408,44 +419,44 @@ fn mip_gated(data: &AssetData, page: u32, width_pt: f64, on_screen: f64, gate: b
|
||||
let colour = designcraft_color::cms::generation();
|
||||
let cached = |size: (u32, u32)| {
|
||||
let level = level_for(size, width_pt, on_screen);
|
||||
let pm = cached_level(id, page, level, colour)?;
|
||||
let entry = cached_level(id, page, level, colour)?;
|
||||
if level == 0 {
|
||||
drawn_full((id, page));
|
||||
}
|
||||
Some(pm)
|
||||
Some(entry)
|
||||
};
|
||||
if let Some(pm) = known_dims(id, page).and_then(cached) {
|
||||
return Some(pm);
|
||||
if let Some(entry) = known_dims(id, page).and_then(cached) {
|
||||
return Some(entry);
|
||||
}
|
||||
let bytes = load_bytes(data, gate)?;
|
||||
// Encoded bytes this decode alone holds.
|
||||
let held = if gate && data.is_linked() && data.resident().is_none() { bytes.len() } else { 0 };
|
||||
let mut zoom_in = false;
|
||||
if let Some(size) = dims_from(id, &bytes, page) {
|
||||
if let Some(pm) = cached(size) {
|
||||
return Some(pm);
|
||||
if let Some(entry) = cached(size) {
|
||||
return Some(entry);
|
||||
}
|
||||
let level = level_for(size, width_pt, on_screen);
|
||||
if let Some(pm) = reduced(id, &bytes, page, level, gate.then_some(held), colour) {
|
||||
return Some(pm);
|
||||
if let Some(entry) = reduced(id, &bytes, page, level, gate.then_some(held), colour) {
|
||||
return Some(entry);
|
||||
}
|
||||
zoom_in = (level + 1..=MAX_LEVEL).any(|l| is_cached((id, page, l)));
|
||||
}
|
||||
let _reserved = gate.then(|| reserve((decode_sizes(&bytes, page).1.saturating_mul(3) / 2).saturating_add(held), id, None));
|
||||
let full = decode_full(id, &bytes, page)?;
|
||||
let (full, bitmap) = decode_full(id, &bytes, page)?;
|
||||
let level = level_for((u32::from(full.width()), u32::from(full.height())), width_pt, on_screen);
|
||||
if level == 0 {
|
||||
store(id, page, 0, full.clone(), colour);
|
||||
store(id, page, 0, full.clone(), colour, bitmap);
|
||||
drawn_full((id, page));
|
||||
} else if zoom_in && size_of(&full) <= KEEP_FULL {
|
||||
store(id, page, 0, full.clone(), colour);
|
||||
store(id, page, 0, full.clone(), colour, bitmap);
|
||||
keep_full((id, page));
|
||||
}
|
||||
let pm = halve_to(full, 0, level);
|
||||
if level > 0 {
|
||||
store(id, page, level, pm.clone(), colour);
|
||||
store(id, page, level, pm.clone(), colour, bitmap);
|
||||
}
|
||||
Some(pm)
|
||||
Some((pm, bitmap))
|
||||
}
|
||||
|
||||
/// The full decode of `key` is drawn, not kept for a zoom-in: another image's zoom-in doesn't
|
||||
@@ -480,32 +491,51 @@ pub enum Mip {
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// [`Mip`] with the cached entry's 1-bit bitmap flag carried alongside the pixels.
|
||||
pub(crate) enum MipEntry {
|
||||
Ready(Arc<Pixmap>, bool),
|
||||
Pending(Option<(Arc<Pixmap>, bool)>),
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// [`mip`] without waiting: a level that isn't cached is decoded on a background thread and
|
||||
/// [`generation`] advances when it is ready (the [`set_waker`] callback runs too). On wasm it
|
||||
/// decodes in place.
|
||||
pub fn mip_now(data: &AssetData, page: u32, width_pt: f64, on_screen: f64) -> Mip {
|
||||
match mip_now_entry(data, page, width_pt, on_screen) {
|
||||
MipEntry::Ready(pm, _) => Mip::Ready(pm),
|
||||
MipEntry::Pending(stand_in) => Mip::Pending(stand_in.map(|(pm, _)| pm)),
|
||||
MipEntry::Failed => Mip::Failed,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`mip_now`], returning the 1-bit bitmap flag recorded with the cached pixels.
|
||||
pub(crate) fn mip_now_entry(data: &AssetData, page: u32, width_pt: f64, on_screen: f64) -> MipEntry {
|
||||
let id = data.key();
|
||||
if is_bad(id, page) || unavailable_now(id).is_some() {
|
||||
return Mip::Failed;
|
||||
return MipEntry::Failed;
|
||||
}
|
||||
// Linked bytes not in memory are left to the decode thread to load.
|
||||
let level = dims_now(data, page).map(|size| level_for(size, width_pt, on_screen));
|
||||
// Only the exact level: building it from a finer one is left to the decode thread too.
|
||||
if let Some((l, pm)) = level.and_then(|l| lookup((id, page, l)).map(|pm| (l, pm))) {
|
||||
if let Some((l, (pm, bitmap))) = level.and_then(|l| lookup_entry((id, page, l)).map(|e| (l, e))) {
|
||||
if l == 0 {
|
||||
drawn_full((id, page));
|
||||
}
|
||||
return Mip::Ready(pm);
|
||||
return MipEntry::Ready(pm, bitmap);
|
||||
}
|
||||
let want = Want { bytes: data.clone(), page, width_pt, on_screen };
|
||||
match background::queue(want, level) {
|
||||
background::Queued::Yes | background::Queued::Recent => {}
|
||||
background::Queued::InPlace => return mip(data, page, width_pt, on_screen).map_or(Mip::Failed, Mip::Ready),
|
||||
background::Queued::InPlace => {
|
||||
return mip_with_bitmap(data, page, width_pt, on_screen).map_or(MipEntry::Failed, |(pm, bitmap)| MipEntry::Ready(pm, bitmap));
|
||||
}
|
||||
}
|
||||
DEFERRED.with(|d| d.set(true));
|
||||
let stand_in =
|
||||
level.and_then(|l| (l + 1..=MAX_LEVEL).find_map(|c| lookup((id, page, c))).or_else(|| (0..l).rev().find_map(|f| lookup((id, page, f)))));
|
||||
Mip::Pending(stand_in)
|
||||
let stand_in = level.and_then(|l| {
|
||||
(l + 1..=MAX_LEVEL).find_map(|c| lookup_entry((id, page, c))).or_else(|| (0..l).rev().find_map(|f| lookup_entry((id, page, f))))
|
||||
});
|
||||
MipEntry::Pending(stand_in)
|
||||
}
|
||||
|
||||
/// What is cached of the bytes `id` names, page `page`, drawn `width_pt` points wide at
|
||||
@@ -1212,7 +1242,7 @@ fn waited(id: SourceKey) {
|
||||
/// and for variants only a full decode reads (CMYK JPEGs, non-CMYK separated TIFFs).
|
||||
///
|
||||
/// `gate`: wait at [`GATE`] for the decode's peak bytes, plus the encoded bytes it holds.
|
||||
fn reduced(id: SourceKey, bytes: &[u8], page: u32, level: u8, gate: Option<usize>, colour: u64) -> Option<Arc<Pixmap>> {
|
||||
fn reduced(id: SourceKey, bytes: &[u8], page: u32, level: u8, gate: Option<usize>, colour: u64) -> Option<(Arc<Pixmap>, bool)> {
|
||||
if level == 0 || page != 0 {
|
||||
return None;
|
||||
}
|
||||
@@ -1220,8 +1250,8 @@ fn reduced(id: SourceKey, bytes: &[u8], page: u32, level: u8, gate: Option<usize
|
||||
return None;
|
||||
}
|
||||
let shrink = level.min(designcraft_images::MAX_REDUCED_SHRINK);
|
||||
let mut pm = match lookup((id, page, shrink)) {
|
||||
Some(p) => p,
|
||||
let (mut pm, bitmap) = match lookup_entry((id, page, shrink)) {
|
||||
Some(entry) => entry,
|
||||
None => {
|
||||
// Cut to `halve`'s size (it rounds down, the decoder up), as the level a full
|
||||
// decode makes.
|
||||
@@ -1235,10 +1265,11 @@ fn reduced(id: SourceKey, bytes: &[u8], page: u32, level: u8, gate: Option<usize
|
||||
None => None,
|
||||
};
|
||||
let p = decode_pixmap_reduced(bytes, shrink)?;
|
||||
let bitmap = designcraft_images::is_bitmap(bytes);
|
||||
log_decode(id);
|
||||
let p = Arc::new(crop(p, sw, sh)?);
|
||||
store(id, page, shrink, p.clone(), colour);
|
||||
p
|
||||
store(id, page, shrink, p.clone(), colour, bitmap);
|
||||
(p, bitmap)
|
||||
}
|
||||
};
|
||||
for l in shrink + 1..=level {
|
||||
@@ -1246,12 +1277,12 @@ fn reduced(id: SourceKey, bytes: &[u8], page: u32, level: u8, gate: Option<usize
|
||||
Some(p) => p,
|
||||
None => {
|
||||
let half = Arc::new(halve(&pm));
|
||||
store(id, page, l, half.clone(), colour);
|
||||
store(id, page, l, half.clone(), colour, bitmap);
|
||||
half
|
||||
}
|
||||
};
|
||||
}
|
||||
Some(pm)
|
||||
Some((pm, bitmap))
|
||||
}
|
||||
|
||||
/// The top-left `w` × `h` of `pm`; `None` when `pm` is smaller.
|
||||
@@ -1479,7 +1510,7 @@ pub(crate) mod tests {
|
||||
let put = |c: &mut Cache, key: (SourceKey, u32, u8), side: u16| {
|
||||
let pm = Arc::new(Pixmap::new(side, side));
|
||||
c.bytes += size_of(&pm);
|
||||
c.map.insert(key, Entry { pm, stamp: 0 });
|
||||
c.map.insert(key, Entry { pm, stamp: 0, bitmap: false });
|
||||
};
|
||||
put(&mut c, (id, 0, 4), 16);
|
||||
put(&mut c, (id, 0, 6), 4);
|
||||
@@ -1898,9 +1929,9 @@ pub(crate) mod tests {
|
||||
let id = bytes.key();
|
||||
let pm = Arc::new(Pixmap::new(64, 64));
|
||||
let old = designcraft_color::cms::generation().wrapping_sub(1);
|
||||
store(bytes.key(), 0, 0, pm.clone(), old);
|
||||
store(bytes.key(), 0, 0, pm.clone(), old, false);
|
||||
assert!(!is_cached((id, 0, 0)), "converted before the settings changed");
|
||||
store(bytes.key(), 0, 0, pm, designcraft_color::cms::generation());
|
||||
store(bytes.key(), 0, 0, pm, designcraft_color::cms::generation(), false);
|
||||
assert!(is_cached((id, 0, 0)));
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 284 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user