Compare commits

..
206 changed files with 1979 additions and 11475 deletions
@@ -0,0 +1,60 @@
function Remove-CaptureLocalPort {
param([Parameter(Mandatory)][string]$Name)
if ($Name -notmatch '^[A-Za-z]:\\') {
throw 'A capture port must have an absolute local file path as its name.'
}
# Remove-PrinterPort interprets backslashes as part of a printer/server name.
# Pass the full path as data to the local monitor instead.
if (-not ('CraftCaptureLocalPort' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
public static class CraftCaptureLocalPort
{
[StructLayout(LayoutKind.Sequential)]
private struct PrinterDefaults
{
public IntPtr DataType;
public IntPtr DevMode;
public uint DesiredAccess;
}
[DllImport("winspool.drv", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool OpenPrinter(string name, out IntPtr printer, ref PrinterDefaults defaults);
[DllImport("winspool.drv", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool XcvData(IntPtr printer, string command, byte[] input, uint inputBytes,
IntPtr output, uint outputBytes, out uint bytesNeeded, out uint status);
[DllImport("winspool.drv")]
private static extern bool ClosePrinter(IntPtr printer);
public static void Remove(string name)
{
const uint ServerAccessAdminister = 1;
var defaults = new PrinterDefaults { DesiredAccess = ServerAccessAdminister };
if (!OpenPrinter(",XcvMonitor Local Port", out var printer, ref defaults))
throw new Win32Exception(Marshal.GetLastWin32Error());
try
{
byte[] input = Encoding.Unicode.GetBytes(name + "\0");
if (!XcvData(printer, "DeletePort", input, (uint)input.Length, IntPtr.Zero, 0, out _, out uint status))
throw new Win32Exception(Marshal.GetLastWin32Error());
if (status != 0)
throw new Win32Exception((int)status);
}
finally
{
ClosePrinter(printer);
}
}
}
'@
}
[CraftCaptureLocalPort]::Remove($Name)
}
@@ -0,0 +1,35 @@
$ErrorActionPreference = 'Stop'
. ./.github/print-probe/windows-local-port.ps1
Start-Service Spooler
$driver = 'Microsoft Print To PDF'
if (!(Get-PrinterDriver -Name $driver -ErrorAction SilentlyContinue)) { Add-PrinterDriver -Name $driver }
$out = New-Item -ItemType Directory -Path queue-paper-evidence
$port = Join-Path $out.FullName 'incoming.pdf'
$queue = "WordCraft QA file $env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT"
$binary = Join-Path $env:CARGO_TARGET_DIR 'debug/examples/queue_paper_qa.exe'
Add-PrinterPort -Name $port
try {
Add-Printer -Name $queue -DriverName $driver -PortName $port
try {
Set-PrintConfiguration -PrinterName $queue -PaperSize Letter
foreach ($case in 'no-scaling','a4-form') {
& $binary $queue $case | Tee-Object -FilePath (Join-Path $out.FullName "$case.json")
if ($LASTEXITCODE) { throw "WordCraft print command failed for $case" }
$deadline = [DateTime]::UtcNow.AddSeconds(50)
$complete = $false
while ([DateTime]::UtcNow -lt $deadline) {
try {
$bytes = [IO.File]::ReadAllBytes($port)
$n = [Math]::Min(40, $bytes.Length)
if ($n -gt 0 -and [Text.Encoding]::ASCII.GetString($bytes, $bytes.Length - $n, $n).TrimEnd().EndsWith('%%EOF')) {
Move-Item -LiteralPath $port -Destination (Join-Path $out.FullName "$case.pdf")
$complete = $true
break
}
} catch [IO.IOException] {}
Start-Sleep -Milliseconds 250
}
if (!$complete) { throw "No complete PDF was captured for $case" }
}
} finally { Remove-Printer -Name $queue }
} finally { Remove-CaptureLocalPort -Name $port }
@@ -0,0 +1,38 @@
ZGlmZiAtLWdpdCBhL2NyYXRlcy91aS1jb250cmFjdC9zcmMvcnVudGltZS93aW5kb3dzL2hvc3Qu
cnMgYi9jcmF0ZXMvdWktY29udHJhY3Qvc3JjL3J1bnRpbWUvd2luZG93cy9ob3N0LnJzCmluZGV4
IGYwMDg2OTU4Mi4uNjU0YjQzMTE5IDEwMDY0NAotLS0gYS9jcmF0ZXMvdWktY29udHJhY3Qvc3Jj
L3J1bnRpbWUvd2luZG93cy9ob3N0LnJzCisrKyBiL2NyYXRlcy91aS1jb250cmFjdC9zcmMvcnVu
dGltZS93aW5kb3dzL2hvc3QucnMKQEAgLTM1NCw2ICszNTQsMTggQEAgaW1wbCBXaW5kb3dIb3N0
IHsKICAgICAgICAgUGVyVmlld3BvcnQ6OjxSZWNvcmQ+Ojp3aXRoKCZzZWxmLmN0eCwgVmlld3Bv
cnRJZDo6Uk9PVCwgfHJlY29yZHwgcmVjb3JkLm5hdGl2ZS5jbG9uZSgpKT8ucmF3X2hhbmRsZSgp
CiAgICAgfQogCisgICAgLy8vIFRoZSBXaW4zMiBIV05EIG9mIHRoZSBnaXZlbiB2aWV3cG9ydCdz
IHdpbmRvdywgZm9yIG93bmluZyBhIG5hdGl2ZSBkaWFsb2cuIFJldHVybnMKKyAgICAvLy8gYE5v
bmVgIGlmIHRoZSB2aWV3cG9ydCBoYXMgbm8gbmF0aXZlIHdpbmRvdyBoYW5kbGUuCisgICAgcHVi
IGZuIG5hdGl2ZV93aW5kb3dfaGFuZGxlKCZzZWxmLCB2aWV3cG9ydDogVmlld3BvcnRJZCkgLT4g
T3B0aW9uPHN0ZDo6bnVtOjpOb25aZXJvSXNpemU+IHsKKyAgICAgICAgaWYgdmlld3BvcnQgPT0g
Vmlld3BvcnRJZDo6Uk9PVCB7CisgICAgICAgICAgICByZXR1cm4gc2VsZi5tYWluX3dpbmRvd19o
YW5kbGUoKTsKKyAgICAgICAgfQorICAgICAgICBpZiAhc2VsZi5pc19vcGVuKHZpZXdwb3J0KSB7
CisgICAgICAgICAgICByZXR1cm4gTm9uZTsKKyAgICAgICAgfQorICAgICAgICBzdXBlcjo6bmF0
aXZlOjpuYXRpdmVfb2YoJnNlbGYuY3R4LCB2aWV3cG9ydCk/LnJhd19oYW5kbGUoKQorICAgIH0K
KwogICAgIC8vLyBNb3ZlcyB0aGUgc3lzdGVtIHBvaW50ZXIgdG8gYHRvYCBpbiBkZXNrdG9wIHBv
aW50czsgZmFsc2Ugd2hlcmUgdGhlIHBsYXRmb3JtIGNhbm5vdC4KICAgICBwdWIgZm4gd2FycF9w
b2ludGVyKCZzZWxmLCB0bzogUG9zMikgLT4gYm9vbCB7CiAgICAgICAgIGxldCBzeXN0ZW0gPSBz
aGFyZWQoJnNlbGYuY3R4LCB8c2hhcmVkfCBzaGFyZWQuc3lzdGVtLmNsb25lKCkpOwpkaWZmIC0t
Z2l0IGEvY3JhdGVzL3VpLWNvbnRyYWN0L3NyYy9ydW50aW1lL3dpbmRvd3MvbmF0aXZlLnJzIGIv
Y3JhdGVzL3VpLWNvbnRyYWN0L3NyYy9ydW50aW1lL3dpbmRvd3MvbmF0aXZlLnJzCmluZGV4IDkz
MTM2ODE2OS4uNWVlZmQyNDgzIDEwMDY0NAotLS0gYS9jcmF0ZXMvdWktY29udHJhY3Qvc3JjL3J1
bnRpbWUvd2luZG93cy9uYXRpdmUucnMKKysrIGIvY3JhdGVzL3VpLWNvbnRyYWN0L3NyYy9ydW50
aW1lL3dpbmRvd3MvbmF0aXZlLnJzCkBAIC0yMTUsNyArMjE1LDcgQEAgZm4gc2V0X29wYWNpdHko
Y3R4OiAmQ29udGV4dCwgdmlld3BvcnQ6IFZpZXdwb3J0SWQsIG9wYWNpdHk6IGYzMikgLT4gYm9v
bCB7CiAvLy8gVGhlIE9TIHdpbmRvdyBvZiBgdmlld3BvcnRgLCBmb3VuZCBvbmNlIGl0cyB3aW5k
b3cgZXhpc3RzOiBieSBpdHMgdGl0bGUgYW1vbmcgdGhlIHRocmVhZCdzIHdpbmRvd3MsIHdoZW4g
ZXhhY3RseQogLy8vIG9uZSBzdGFydHMgYXQgdGhlIHJlcG9ydGVkIGNsaWVudCBvcmlnaW4uIEEg
ZmFpbGVkIHNlYXJjaCByZXBlYXRzIGV2ZXJ5IGBTRUFSQ0hfRVZFUllgIHBhc3Nlcy4gVGhlIHJv
b3Qgd2luZG93J3MgaXMKIC8vLyBzZXQgYnkgW2Byb3V0ZV9yb290YF0uCi1mbiBuYXRpdmVfb2Yo
Y3R4OiAmQ29udGV4dCwgdmlld3BvcnQ6IFZpZXdwb3J0SWQpIC0+IE9wdGlvbjxOYXRpdmVXaW5k
b3c+IHsKK3B1YihzdXBlcikgZm4gbmF0aXZlX29mKGN0eDogJkNvbnRleHQsIHZpZXdwb3J0OiBW
aWV3cG9ydElkKSAtPiBPcHRpb248TmF0aXZlV2luZG93PiB7CiAgICAgbGV0IHBhc3MgPSBwYXNz
OjpwYXNzX25yKGN0eCwgdmlld3BvcnQpOwogICAgIGxldCAoa25vd24sIHRpdGxlLCBzZWFyY2hl
ZCwgZmFjdHMpID0KICAgICAgICAgUGVyVmlld3BvcnQ6OjxSZWNvcmQ+Ojp3aXRoKGN0eCwgdmll
d3BvcnQsIHxyZWNvcmR8IChyZWNvcmQubmF0aXZlLmNsb25lKCksIHJlY29yZC50aXRsZS5jbG9u
ZSgpLCByZWNvcmQuc2VhcmNoZWQsIHJlY29yZC5mYWN0cykpOwo=
File diff suppressed because one or more lines are too long
+108
View File
@@ -0,0 +1,108 @@
name: Verify WordCraft queue-specific paper
on:
push:
branches: [verify/wordcraft-queue-paper-4859]
permissions:
contents: read
env:
CARGO_PROFILE_DEV_DEBUG: '0'
CARGO_PROFILE_TEST_DEBUG: '0'
CARGO_INCREMENTAL: '0'
WORDCRAFT_FRAMEWORK: d73e274a01408ef433a291a667e6014937d72165
jobs:
paper:
strategy:
fail-fast: false
matrix:
os: ${{ contains(github.event.head_commit.message, '[same-size-linux]') && fromJSON('["ubuntu-24.04"]') || fromJSON('["windows-2025","ubuntu-24.04"]') }}
runs-on: ${{ matrix.os }}
timeout-minutes: 90
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/install-apt-packages@58848078cd09e3ca182891a8b76ee979f1eb6e1c
if: runner.os == 'Linux'
with:
packages: pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
- name: Choose an isolated build directory on Windows
if: runner.os == 'Windows'
shell: pwsh
run: |
$disk = Get-PSDrive -PSProvider FileSystem | Where-Object { $_.Free -gt 0 -and $_.Root -match '^[A-Za-z]:\\$' } | Sort-Object -Descending Free | Select-Object -First 1
"CARGO_TARGET_DIR=$(Join-Path $disk.Root "wordcraft-paper-$env:GITHUB_RUN_ID")" >> $env:GITHUB_ENV
- name: Apply native window ownership and paper catalogs to the locked library revision
id: overlay
shell: python
run: |
import base64, json, os, pathlib, subprocess
host = next(line[6:] for line in subprocess.check_output(['rustc', '-vV'], text=True).splitlines() if line.startswith('host: '))
os.environ['CARGO_HOME'] = str(pathlib.Path(os.environ['RUNNER_TEMP']) / 'wordcraft-paper-cargo')
graph = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--format-version', '1', '--filter-platform', host]))
package, = (p for p in graph['packages'] if p['name'] == 'craft-print')
crate = pathlib.Path(package['manifest_path']).parent
framework = pathlib.Path(subprocess.check_output(['git', 'rev-parse', '--show-toplevel'], cwd=crate, text=True).strip())
head = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=framework, text=True).strip()
assert head == os.environ['WORDCRAFT_FRAMEWORK'], head
for file in sorted(pathlib.Path('.github/qa').glob('*.patch.b64')):
patch = base64.b64decode(file.read_bytes())
subprocess.run(['git', 'apply', '--check'], cwd=framework, input=patch, check=True)
subprocess.run(['git', 'apply'], cwd=framework, input=patch, check=True)
subprocess.run(['git', 'diff', '--exit-code', '--', 'Cargo.toml', 'Cargo.lock'], check=True)
with open(os.environ['GITHUB_ENV'], 'a', encoding='utf-8') as env:
print('CARGO_HOME=' + os.environ['CARGO_HOME'], file=env)
- name: Capture the no-scaling and discovered A4 form jobs
if: runner.os == 'Windows'
shell: pwsh
run: |
cargo build --locked -p wordcraft-ui-egui --example queue_paper_qa
if ($LASTEXITCODE) { exit $LASTEXITCODE }
./.github/print-probe/wordcraft-paper-capture.ps1
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
if: always() && runner.os == 'Windows'
with:
name: wordcraft-queue-paper
path: queue-paper-evidence/
if-no-files-found: warn
retention-days: 14
- name: Run document geometry and native print integration tests
if: "!cancelled() && steps.overlay.outcome == 'success' && !contains(github.event.head_commit.message, '[same-size-linux]')"
shell: bash
run: |
set -euo pipefail
cargo test --locked -p wordcraft-engine --lib print::
cargo test --locked -p wordcraft-ui-egui --test it native_print::
cargo test --locked -p wordcraft-ui-egui --lib printer_properties_
- name: Verify that same-size CUPS forms preserve different keys
if: contains(github.event.head_commit.message, '[same-size-linux]')
run: cargo test --locked -p wordcraft-ui-egui --test it queue_form_keeps_its_media_with_the_job_and_clears_on_queue_change
- name: Compile the real host and native window ownership
if: "!cancelled() && steps.overlay.outcome == 'success' && runner.os == 'Windows'"
run: cargo check --locked -p wordcraft
inspect:
needs: paper
if: "!cancelled() && !contains(github.event.head_commit.message, '[same-size-linux]')"
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0
with:
name: wordcraft-queue-paper
path: queue-paper-evidence
- uses: storytold/craft-common-actions/actions/install-apt-packages@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
packages: poppler-utils
- name: Inspect the PDF dimensions and identify the submitted sheet
run: |
set -euo pipefail
pdfinfo queue-paper-evidence/no-scaling.pdf | tee "$RUNNER_TEMP/no-scaling.info"
pdfinfo queue-paper-evidence/a4-form.pdf | tee "$RUNNER_TEMP/a4.info"
grep -Eq '^Page size: +612 x 792 pts' "$RUNNER_TEMP/no-scaling.info"
grep -Eq '^Page size: +595\.2[0-9]+ x 841\.8[0-9]+ pts' "$RUNNER_TEMP/a4.info"
for case in no-scaling a4-form; do
pdftoppm -r 72 -singlefile "queue-paper-evidence/$case.pdf" "$RUNNER_TEMP/$case"
python3 -c 'from pathlib import Path; import sys; raw=Path(sys.argv[1]).read_bytes().split(b"\n", 3); assert raw[0] == b"P6" and raw[-1].count(0) > 250, "page must contain visible ink"' "$RUNNER_TEMP/$case.ppm"
done
Generated
+126 -112
View File
@@ -1173,7 +1173,7 @@ dependencies = [
[[package]]
name = "craft"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-automation",
"craft-behavior",
@@ -1214,7 +1214,7 @@ dependencies = [
[[package]]
name = "craft-appkit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"block2 0.6.2",
"objc2 0.6.5",
@@ -1226,7 +1226,7 @@ dependencies = [
[[package]]
name = "craft-atomic"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"rustix 1.1.6",
]
@@ -1234,7 +1234,7 @@ dependencies = [
[[package]]
name = "craft-automation"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"base64 0.23.1",
"craft-behavior",
@@ -1259,7 +1259,7 @@ dependencies = [
[[package]]
name = "craft-behavior"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"accesskit",
"bitflags 2.13.2",
@@ -1277,7 +1277,7 @@ dependencies = [
[[package]]
name = "craft-browse"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-docpath",
@@ -1295,12 +1295,12 @@ dependencies = [
[[package]]
name = "craft-cfb"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
[[package]]
name = "craft-cloud-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"egui",
]
@@ -1308,7 +1308,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"md-5",
"rayon",
@@ -1317,12 +1317,12 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
[[package]]
name = "craft-color"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"serde",
]
@@ -1330,7 +1330,7 @@ dependencies = [
[[package]]
name = "craft-color-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-cms",
@@ -1350,7 +1350,7 @@ dependencies = [
[[package]]
name = "craft-control"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-control-protocol",
"craft-platform",
@@ -1361,7 +1361,7 @@ dependencies = [
[[package]]
name = "craft-control-protocol"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"getrandom 0.3.4",
"serde_json",
@@ -1371,7 +1371,7 @@ dependencies = [
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"rayon",
]
@@ -1379,7 +1379,7 @@ dependencies = [
[[package]]
name = "craft-dialogs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"block2 0.6.2",
"craft-appkit",
@@ -1405,24 +1405,24 @@ dependencies = [
[[package]]
name = "craft-doc-binary"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"chrono",
"craft-cfb",
"craft-codepage",
"craft-offcrypto",
"craft-wordmodel",
"image",
"log",
"md4",
"miniz_oxide 0.9.1",
"sha1 0.11.0",
"thiserror 2.0.21",
]
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"serde",
]
@@ -1430,7 +1430,7 @@ dependencies = [
[[package]]
name = "craft-docx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"base64 0.23.1",
"chrono",
@@ -1450,7 +1450,7 @@ dependencies = [
[[package]]
name = "craft-draw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1469,7 +1469,7 @@ dependencies = [
[[package]]
name = "craft-drawingml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"chrono",
"craft-xml",
@@ -1481,7 +1481,7 @@ dependencies = [
[[package]]
name = "craft-flow"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-wordmodel",
"image",
@@ -1491,7 +1491,7 @@ dependencies = [
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"fontique",
"harfrust 0.13.3",
@@ -1506,7 +1506,7 @@ dependencies = [
[[package]]
name = "craft-font-manager"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-font-catalog",
@@ -1525,7 +1525,7 @@ dependencies = [
[[package]]
name = "craft-font-os-windows"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"windows-registry",
"windows-sys 0.61.2",
@@ -1534,7 +1534,7 @@ dependencies = [
[[package]]
name = "craft-font-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"cap-primitives",
"craft-atomic",
@@ -1557,7 +1557,7 @@ dependencies = [
[[package]]
name = "craft-font-subset"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"brotli 9.1.3",
"harfbuzz-subset-sys",
@@ -1570,7 +1570,7 @@ dependencies = [
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-font-subset",
]
@@ -1578,7 +1578,7 @@ dependencies = [
[[package]]
name = "craft-gpu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"egui-wgpu",
"log",
@@ -1590,7 +1590,7 @@ dependencies = [
[[package]]
name = "craft-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"bitflags 2.13.2",
"craft-i18n",
@@ -1603,7 +1603,7 @@ dependencies = [
[[package]]
name = "craft-html"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-codepage",
"craft-flow",
@@ -1616,7 +1616,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"brotli 9.1.3",
"brotli-decompressor 6.3.1",
@@ -1646,7 +1646,7 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-dds",
"craft-jpeg",
@@ -1673,7 +1673,7 @@ dependencies = [
[[package]]
name = "craft-imaging"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1691,7 +1691,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"thiserror 2.0.21",
]
@@ -1699,7 +1699,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-host",
"craft-i18n",
@@ -1714,7 +1714,7 @@ dependencies = [
[[package]]
name = "craft-latex"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-flow",
"craft-math",
@@ -1725,7 +1725,7 @@ dependencies = [
[[package]]
name = "craft-markdown"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-flow",
"craft-html",
@@ -1735,7 +1735,7 @@ dependencies = [
[[package]]
name = "craft-math"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-xml",
"roxmltree",
@@ -1745,7 +1745,7 @@ dependencies = [
[[package]]
name = "craft-mcp-server"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"serde_json",
]
@@ -1753,7 +1753,7 @@ dependencies = [
[[package]]
name = "craft-menu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1771,7 +1771,7 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"brotli-decompressor 6.3.1",
"chrono",
@@ -1783,7 +1783,7 @@ dependencies = [
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"encoding_rs",
"image",
@@ -1794,7 +1794,7 @@ dependencies = [
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"chardetng",
"chrono",
@@ -1805,7 +1805,7 @@ dependencies = [
[[package]]
name = "craft-nightly"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"uds_windows",
"winsafe",
@@ -1814,7 +1814,7 @@ dependencies = [
[[package]]
name = "craft-odf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"aes",
"base64 0.23.1",
@@ -1840,7 +1840,7 @@ dependencies = [
[[package]]
name = "craft-ods"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-odf",
"craft-sheet",
@@ -1851,7 +1851,7 @@ dependencies = [
[[package]]
name = "craft-offcrypto"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"aes",
"base64 0.23.1",
@@ -1868,7 +1868,7 @@ dependencies = [
[[package]]
name = "craft-opc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-xml",
"craft-zip",
@@ -1879,7 +1879,7 @@ dependencies = [
[[package]]
name = "craft-pages"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -1895,7 +1895,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"krilla",
"serde",
@@ -1905,7 +1905,7 @@ dependencies = [
[[package]]
name = "craft-platform"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"arboard",
"async-channel",
@@ -1943,7 +1943,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1967,7 +1967,7 @@ dependencies = [
[[package]]
name = "craft-proof"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"log",
"miniz_oxide 0.9.1",
@@ -1978,7 +1978,7 @@ dependencies = [
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"dispatch2",
"egui",
@@ -1991,7 +1991,7 @@ dependencies = [
[[package]]
name = "craft-review"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"base64 0.23.1",
"craft-behavior",
@@ -2010,7 +2010,7 @@ dependencies = [
[[package]]
name = "craft-rtf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-codepage",
"craft-flow",
@@ -2023,7 +2023,7 @@ dependencies = [
[[package]]
name = "craft-settings"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-atomic",
"craft-host",
@@ -2040,17 +2040,17 @@ dependencies = [
[[package]]
name = "craft-sheet"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
[[package]]
name = "craft-ssip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-xml",
"flate2",
@@ -2067,7 +2067,7 @@ dependencies = [
[[package]]
name = "craft-table"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2079,7 +2079,7 @@ dependencies = [
[[package]]
name = "craft-text"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2103,7 +2103,7 @@ dependencies = [
[[package]]
name = "craft-theme"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"bitflags 2.13.2",
"craft-tracked",
@@ -2118,7 +2118,7 @@ dependencies = [
[[package]]
name = "craft-theme-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-atomic",
"craft-behavior",
@@ -2133,7 +2133,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -2143,7 +2143,7 @@ dependencies = [
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -2152,7 +2152,7 @@ dependencies = [
[[package]]
name = "craft-timeline"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2167,12 +2167,12 @@ dependencies = [
[[package]]
name = "craft-tracked"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-cloud-ui",
"craft-ui-canvas",
@@ -2186,7 +2186,7 @@ dependencies = [
[[package]]
name = "craft-ui-canvas"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-font-catalog",
@@ -2203,7 +2203,7 @@ dependencies = [
[[package]]
name = "craft-ui-contract"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"accesskit",
"craft-behavior",
@@ -2241,7 +2241,7 @@ dependencies = [
[[package]]
name = "craft-ui-macros"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2252,7 +2252,7 @@ dependencies = [
[[package]]
name = "craft-ui-panels"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2270,7 +2270,7 @@ dependencies = [
[[package]]
name = "craft-ui-patterns"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2291,7 +2291,7 @@ dependencies = [
[[package]]
name = "craft-ui-shell"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2312,7 +2312,7 @@ dependencies = [
[[package]]
name = "craft-ui-test-kit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2323,7 +2323,7 @@ dependencies = [
[[package]]
name = "craft-ui-widgets"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2342,7 +2342,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -2374,7 +2374,7 @@ dependencies = [
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"js-sys",
"serde_json",
@@ -2385,7 +2385,7 @@ dependencies = [
[[package]]
name = "craft-web-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-host",
"craft-platform",
@@ -2397,7 +2397,7 @@ dependencies = [
[[package]]
name = "craft-win32"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"winsafe",
]
@@ -2405,7 +2405,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-appkit",
"craft-atomic",
@@ -2437,7 +2437,7 @@ dependencies = [
[[package]]
name = "craft-wordmodel"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"base64 0.23.1",
"craft-math",
@@ -2451,7 +2451,7 @@ dependencies = [
[[package]]
name = "craft-xls"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-cfb",
"craft-sheet",
@@ -2464,7 +2464,7 @@ dependencies = [
[[package]]
name = "craft-xlsx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"craft-drawingml",
"craft-opc",
@@ -2476,7 +2476,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -2486,7 +2486,7 @@ dependencies = [
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -2842,7 +2842,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
[[package]]
name = "ecolor"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
dependencies = [
"bytemuck",
"emath",
@@ -2875,7 +2875,7 @@ dependencies = [
[[package]]
name = "eframe"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
dependencies = [
"ahash",
"bytemuck",
@@ -2910,7 +2910,7 @@ dependencies = [
[[package]]
name = "egui"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
dependencies = [
"accesskit",
"ahash",
@@ -2929,7 +2929,7 @@ dependencies = [
[[package]]
name = "egui-wgpu"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
dependencies = [
"ahash",
"bytemuck",
@@ -2948,7 +2948,7 @@ dependencies = [
[[package]]
name = "egui-winit"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
dependencies = [
"accesskit_winit",
"arboard",
@@ -2974,7 +2974,7 @@ dependencies = [
[[package]]
name = "egui_extras"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
dependencies = [
"ahash",
"egui",
@@ -2987,7 +2987,7 @@ dependencies = [
[[package]]
name = "egui_glow"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
dependencies = [
"bytemuck",
"egui",
@@ -3000,7 +3000,7 @@ dependencies = [
[[package]]
name = "egui_kittest"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
dependencies = [
"dify",
"eframe",
@@ -3026,7 +3026,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
[[package]]
name = "emath"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
dependencies = [
"bytemuck",
]
@@ -3107,7 +3107,7 @@ dependencies = [
[[package]]
name = "epaint"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
dependencies = [
"ahash",
"bytemuck",
@@ -3133,7 +3133,7 @@ dependencies = [
[[package]]
name = "epaint_default_fonts"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
dependencies = [
"brotli 9.1.3",
"brotli-decompressor 6.3.1",
@@ -3866,7 +3866,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"brotli 8.0.4",
"hayro-postscript",
@@ -3875,7 +3875,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -3893,7 +3893,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -3911,12 +3911,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -4645,7 +4645,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -4784,7 +4784,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
dependencies = [
"arrayvec",
"kurbo",
@@ -8454,6 +8454,19 @@ dependencies = [
"wayland-scanner",
]
[[package]]
name = "wayland-protocols-plasma"
version = "0.3.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91"
dependencies = [
"bitflags 2.13.2",
"wayland-backend",
"wayland-client",
"wayland-protocols",
"wayland-scanner",
]
[[package]]
name = "wayland-protocols-wlr"
version = "0.3.12"
@@ -8978,7 +8991,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winit"
version = "0.30.13"
source = "git+https://github.com/storytold/winit.git?rev=3fd7ae64762f82a73b78bd24f453f82c4291067d#3fd7ae64762f82a73b78bd24f453f82c4291067d"
source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45"
dependencies = [
"ahash",
"android-activity",
@@ -9017,6 +9030,7 @@ dependencies = [
"wayland-backend",
"wayland-client",
"wayland-protocols",
"wayland-protocols-plasma",
"web-sys",
"web-time",
"windows-sys 0.52.0",
@@ -10037,19 +10051,19 @@ dependencies = [
[[patch.unused]]
name = "egui_demo_lib"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
[[patch.unused]]
name = "egui_inspection"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
[[patch.unused]]
name = "egui_system_font_provider"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
[[patch.unused]]
name = "hayro"
version = "0.7.1"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
+54 -54
View File
@@ -37,22 +37,22 @@ wordcraft-pdf = { path = "crates/pdf" }
# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based
# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font
# store's `language-pack` kind is #486 (CP4.1).
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
wordcraft-engine = { path = "crates/engine" }
wordcraft-mcp = { path = "crates/mcp" }
wordcraft-zotero = { path = "crates/zotero" }
wordcraft-control-key = { path = "crates/control-key" }
wordcraft-ui-egui = { path = "crates/ui-egui" }
wordcraft-validate = { path = "crates/validate" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
@@ -85,28 +85,28 @@ wuff = "0.2.9"
brotli-decompressor = "5"
vello_cpu = "0.2"
image = { version = "0.25", default-features = false }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", default-features = false, features = ["write"] }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false, features = ["write"] }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
miniz_oxide = "0.9"
cfb = "0.15"
@@ -174,27 +174,27 @@ debug = 0
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
# and the egui and winit forks it builds with.
[patch.crates-io]
krilla = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
+2 -12
View File
@@ -36,11 +36,9 @@ USAGE:
page can't be drawn or a picture is missing or undecodable
(report on stderr, as for convert --strict)
wordcraft-cli run [--file F | --template T] [--script FILE|-] [--cmd 'id={json}' …]
[--save OUT …] [--page N] [--scale S] [--print] [--author NAME]
[--save OUT] [--page N] [--scale S] [--print] [--author NAME]
run commands headlessly, then save (--author names
who tracked changes and comments are by).
Repeat --save OUT to write multiple outputs in order,
after any outputs from --script.
PNG saves use --page (1-based, default 1) and --scale (default 2).
--script runs a JSON file (- is stdin) first:
{\"file\"?, \"template\"?, \"commands\": [{\"command\": id,
@@ -634,13 +632,6 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
}
}
validate_options("run", &rest, RUN_OPTIONS)?;
let mut cli_outputs = Vec::new();
for (i, arg) in rest.iter().enumerate() {
if arg == "--save" {
let path = rest.get(i + 1).filter(|value| !value.is_empty() && !value.starts_with("--")).ok_or("run: --save requires a path")?;
cli_outputs.push(path.clone());
}
}
let page = parse_page_arg("run", &rest)?;
let scale = parse_scale_arg("run", &rest)?;
let password = password_from(&rest)?;
@@ -689,7 +680,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
i += 1;
}
}
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(cli_outputs).collect();
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(arg_value(&rest, "--save")).collect();
// Check every output can be made before writing any, so a bad one leaves no half-done job.
for out in &outputs {
let parent = Path::new(out).parent().filter(|p| !p.as_os_str().is_empty());
@@ -1057,7 +1048,6 @@ fn launcher_profile_flag(args: &[OsString]) -> bool {
}
fn main() -> ExitCode {
wordcraft_engine::malloc_tuning::apply();
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
if launcher_profile_flag(&args) {
eprintln!("wordcraft-cli: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
-58
View File
@@ -564,64 +564,6 @@ fn script_builds_a_document_and_saves_docx_and_pdf_relative_to_the_script() {
assert!(json.contains("Hello script") && json.contains("\"bold\":true"));
}
#[test]
fn run_saves_each_cli_output_and_still_accepts_a_single_save() {
let dir = script_dir("cli-saves");
let input = dir.join("in.docx");
let docx = dir.join("out.docx");
let pdf = dir.join("out.pdf");
run(&args(&["run", "--template", "sample", "--save", &input.to_string_lossy()])).unwrap();
run(&args(&["run", "--file", &input.to_string_lossy(), "--save", &docx.to_string_lossy(), "--save", &pdf.to_string_lossy()])).unwrap();
assert_eq!(listed_text(&open(&docx, None).unwrap().doc).unwrap(), listed_text(&open(&input, None).unwrap().doc).unwrap());
assert!(std::fs::read(pdf).unwrap().starts_with(b"%PDF"));
}
#[test]
fn run_saves_script_and_cli_outputs() {
let dir = script_dir("mixed-saves");
let script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.txt","script.docx"]}"#);
let first = dir.join("cli.txt");
let second = dir.join("cli.docx");
run(&args(&["run", "--save", &first.to_string_lossy(), "--script", &script, "--save", &second.to_string_lossy()])).unwrap();
for path in [dir.join("script.txt"), dir.join("script.docx"), first, second] {
assert!(path.is_file(), "{} was not written", path.display());
}
}
#[test]
fn run_rejects_a_missing_second_save_path_before_writing() {
let dir = script_dir("missing-save");
let first = dir.join("first.docx");
let first_path = first.to_string_lossy();
for tail in [vec!["--save"], vec!["--save", "--print"], vec!["--save", ""]] {
let mut argv: Vec<&str> = vec!["run", "--save", &first_path];
argv.extend(tail);
assert_eq!(run(&args(&argv)), Err("run: --save requires a path".into()));
assert!(!first.exists());
}
}
#[test]
fn run_preflights_script_and_cli_outputs_in_order_before_writing() {
let dir = script_dir("preflight-saves");
let first = dir.join("first.docx");
let invalid = dir.join("missing/later.docx");
let last = dir.join("missing-too/last.docx");
let mut script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["missing-script/script.docx"]}"#);
let first_path = first.to_string_lossy();
let invalid_path = invalid.to_string_lossy();
let last_path = last.to_string_lossy();
let argv = |script: &str| args(&["run", "--save", &first_path, "--save", &invalid_path, "--script", script, "--save", &last_path]);
let err = run(&argv(&script)).unwrap_err().to_string();
assert!(err.contains("script.docx"), "{err}");
assert!(!first.exists());
script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.docx"]}"#);
let err = run(&argv(&script)).unwrap_err().to_string();
assert!(err.contains("later.docx"), "{err}");
assert!(!first.exists() && !dir.join("script.docx").exists());
}
#[test]
fn script_with_a_bad_output_writes_no_output() {
let dir = script_dir("badout");
-2
View File
@@ -3,8 +3,6 @@ mod closed_stdout;
mod convert_fields;
mod convert_region;
mod help;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
mod malloc_tuning;
mod mcp_roots;
#[cfg(all(unix, not(target_os = "macos")))]
mod non_utf8_args;
@@ -1,78 +0,0 @@
//! The CLI binary re-executes itself on Linux glibc with `MALLOC_TRIM_THRESHOLD_` fixed so freed
//! page/render buffers are returned to the OS while respecting caller-supplied values.
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use wordcraft_engine::malloc_tuning::{TRIM_THRESHOLD, TRIM_THRESHOLD_VAR};
struct TempDirs(PathBuf);
impl TempDirs {
fn new(tag: &str) -> Self {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let root = loop {
let n = NEXT.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("wc-cli-malloc-{tag}-{}-{n}", std::process::id()));
match std::fs::create_dir(&dir) {
Ok(()) => break dir,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(e) => panic!("temp dir {}: {e}", dir.display()),
}
};
std::fs::create_dir_all(root.join("in")).unwrap();
std::fs::create_dir_all(root.join("out")).unwrap();
Self(root)
}
}
impl Drop for TempDirs {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn s(p: &Path) -> String {
p.to_string_lossy().into_owned()
}
fn mcp_environ(tag: &str, set: Option<&str>) -> Vec<String> {
let dirs = TempDirs::new(tag);
let mut cmd = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
for var in [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX", "GLIBC_TUNABLES"] {
cmd.env_remove(var);
}
if let Some(v) = set {
cmd.env(TRIM_THRESHOLD_VAR, v);
}
let mut child = cmd
.args(["mcp", "--automation-read-root", &s(&dirs.0.join("in")), "--automation-write-root", &s(&dirs.0.join("out"))])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"ping"}}"#).unwrap();
let mut reply = String::new();
BufReader::new(child.stdout.take().unwrap()).read_line(&mut reply).unwrap();
assert!(reply.contains(r#""id":1"#), "mcp answered after re-exec: {reply}");
let environ = std::fs::read(format!("/proc/{}/environ", child.id())).unwrap();
drop(stdin);
assert!(child.wait().unwrap().success());
environ.split(|&b| b == 0).map(|e| String::from_utf8_lossy(e).into_owned()).collect()
}
#[test]
fn sets_the_trim_threshold() {
let env = mcp_environ("default", None);
assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}={TRIM_THRESHOLD}")), "{env:?}");
}
#[test]
fn keeps_a_value_the_user_set() {
let env = mcp_environ("explicit", Some("999999"));
assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}=999999")), "{env:?}");
}
+8 -3
View File
@@ -107,6 +107,7 @@ impl App {
embed::before_ui(ui.ctx(), frame);
}
self.app.ui(ui);
self.app.show_print_properties(ui.ctx());
self.panels.pump_with(self.app.dialog_host_mut(), frame);
}
@@ -243,6 +244,13 @@ fn services(spool: Spool, intake: FileIntake, nightly: bool) -> Services {
let make_default_app: Option<MakeDefault> = None;
Services {
print: Some(spool),
#[cfg(any(windows, unix))]
print_papers: Some(wordcraft_ui_egui::native_print_papers),
#[cfg(windows)]
print_properties: Some(Box::new(|job, ctx, viewport| {
let owner = WindowHost::of(ctx).native_window_handle(viewport).ok_or("the print window has no native owner")?;
craft::print::driver_settings_dialog(job, Some(owner.get())).map_err(|error| error.to_string())
})),
templates_dir: wordcraft_control_key::settings_dir().map(|d| d.join("Templates")),
make_default_app,
intake: Some(intake),
@@ -492,9 +500,6 @@ fn main() -> eframe::Result {
let updates_unsafe = start_over_failed.is_some();
#[cfg(not(target_os = "linux"))]
let updates_unsafe = false;
// Before any thread or logger starts: re-exec on Linux glibc with MALLOC_TRIM_THRESHOLD_
// fixed so large freed document/render buffers return to the OS.
wordcraft_engine::malloc_tuning::apply();
// First, so the panic hook (set once, by this call; the later one only gives it the crash-log
// folder) and every start-up warning are recorded.
let logger = logs::install(LogNames::new("wordcraft"));
+9 -37
View File
@@ -21,32 +21,26 @@ pub fn use_settings_dir(dir: PathBuf) -> Result<(), String> {
/// an environment variable a child or a wrapper might have inherited. `WORDCRAFT_PROFILE_DIR`
/// overrides the entire folder for isolated runs otherwise.
pub fn settings_dir() -> Option<PathBuf> {
settings_dir_with(CHOSEN.get(), |k| std::env::var_os(k))
}
fn settings_dir_with(chosen: Option<&PathBuf>, mut env: impl FnMut(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
if let Some(path) = chosen {
if let Some(path) = CHOSEN.get() {
return Some(path.clone());
}
if let Some(path) = env("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
if let Some(path) = std::env::var_os("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
return Some(PathBuf::from(path));
}
platform_settings_dir_for(env)
platform_settings_dir()
}
/// The platform's own folder, when nothing chose one (see [`settings_dir`]).
#[cfg(test)]
fn platform_settings_dir() -> Option<PathBuf> {
platform_settings_dir_for(|k| std::env::var_os(k))
}
fn platform_settings_dir_for(mut env: impl FnMut(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
if cfg!(target_os = "macos") {
env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
} else if cfg!(windows) {
env("APPDATA").map(|a| PathBuf::from(a).join("WordCraft"))
std::env::var_os("APPDATA").map(|a| PathBuf::from(a).join("WordCraft"))
} else {
env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))).map(|c| c.join("wordcraft"))
std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
.map(|c| c.join("wordcraft"))
}
}
@@ -115,26 +109,4 @@ mod tests {
assert_eq!(key_path(dir, 7981), dir.join("control-key.local-7981"));
}
}
#[test]
fn settings_dir_is_the_apps_folder() {
let default_dir = settings_dir_with(None, |key| match key {
"HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some("/tmp/base".into()),
_ => None,
})
.expect("settings_dir should return Some when platform env var is set");
let default_name = default_dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
assert!(default_name == "wordcraft" || default_name == "WordCraft", "{}", default_dir.display());
assert_eq!(settings_dir_with(None, |_| None), None);
let override_dir = settings_dir_with(None, |key| (key == "WORDCRAFT_PROFILE_DIR").then(|| "/tmp/profile".into()));
assert_eq!(override_dir.as_deref(), Some(Path::new("/tmp/profile")));
let empty_override = settings_dir_with(None, |key| match key {
"WORDCRAFT_PROFILE_DIR" => Some("".into()),
"HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some("/tmp/base".into()),
_ => None,
});
assert_eq!(empty_override, Some(default_dir));
}
}
+3 -52
View File
@@ -230,26 +230,10 @@ impl ChartAxis {
pub const MAX_FMT: usize = 128;
/// A number format code: control characters as spaces, ends trimmed, at most [`MAX_FMT`]
/// characters. A trailing space stays when it is part of the code: the character after `_`,
/// `*` or `\`, or text inside quotes.
/// characters.
pub fn clean_fmt(s: &str) -> String {
let chars: Vec<char> = s.chars().take(MAX_FMT * 4).skip_while(|c| c.is_whitespace() || c.is_control()).take(MAX_FMT).collect();
let mut keep = 0;
let mut quoted = false;
let mut operand = false;
for (i, &c) in chars.iter().enumerate() {
if !c.is_control() && (!c.is_whitespace() || operand || quoted) {
keep = i + 1;
}
if operand {
operand = false;
} else if c == '"' {
quoted = !quoted;
} else if !quoted && matches!(c, '_' | '*' | '\\') {
operand = true;
}
}
chars[..keep].iter().map(|&c| if c.is_control() { ' ' } else { c }).collect()
let s: String = s.chars().take(MAX_FMT * 4).map(|c| if c.is_control() { ' ' } else { c }).collect();
s.trim().chars().take(MAX_FMT).collect::<String>().trim_end().to_string()
}
/// A chart WordCraft can edit.
@@ -528,37 +512,4 @@ mod tests {
spec.sanitize();
assert_eq!(spec.series[0].line_w, Some(20.0), "a wild width clamps to 20 pt");
}
#[test]
fn format_keeps_a_trailing_space_that_is_an_operand() {
// `_`, `*` and `\` take the next character, so a final space after one is part of the code.
assert_eq!(clean_fmt("0_ "), "0_ ");
assert_eq!(clean_fmt("#,##0_ "), "#,##0_ ");
assert_eq!(clean_fmt("0* "), "0* ");
assert_eq!(clean_fmt("0\\ "), "0\\ ");
assert_eq!(clean_fmt("0_ \n "), "0_ ");
assert_eq!(clean_fmt("0\"a "), "0\"a ", "a space inside quotes is text");
// Other spaces at the ends, and control characters, still go.
assert_eq!(clean_fmt(" 0.00 \t"), "0.00");
assert_eq!(clean_fmt("0_\n"), "0_");
assert_eq!(clean_fmt("0\"a\" "), "0\"a\"");
assert_eq!(clean_fmt("\\_ "), "\\_", "an escaped `_` takes no operand");
assert_eq!(clean_fmt("0\u{1}0"), "0 0");
assert_eq!(clean_fmt("_\u{1}"), "_");
assert_eq!(clean_fmt(" \n "), "");
let long = format!("{}_ ", "0".repeat(MAX_FMT - 2));
assert_eq!(clean_fmt(&long), long, "a code of exactly MAX_FMT characters keeps its operand");
// Axis and series formats both go through the cleaner.
let mut a = ChartAxis { fmt: Some("0_ ".into()), ..Default::default() };
a.sanitize();
assert_eq!(a.fmt.as_deref(), Some("0_ "));
let mut spec = ChartSpec {
series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0)], fmt: Some("#,##0_ ".into()), ..Default::default() }],
categories: vec!["a".into()],
..Default::default()
};
spec.sanitize();
assert_eq!(spec.series[0].fmt.as_deref(), Some("#,##0_ "));
}
}
+1 -17
View File
@@ -619,8 +619,7 @@ impl Paragraph {
/// The word around `off` (double-click): (start, end) without trailing space.
pub fn word_at(&self, off: usize) -> (usize, usize) {
let off = self.clamp(off);
// Word's word unit takes a typographic apostrophe (’) like `'`, at either end too (#6517).
let is_w = |c: char| crate::bidi::is_word_char(c) || c == '’';
let is_w = |c: char| crate::bidi::is_word_char(c);
let mut a = off;
for (i, c) in self.text.get(..off).unwrap_or("").char_indices().rev() {
if !is_w(c) {
@@ -853,21 +852,6 @@ mod tests {
assert_eq!(p.prev_boundary(0), 0);
}
#[test]
fn word_at_takes_a_typographic_apostrophe_like_a_straight_one() {
// Byte offsets: `’` is three bytes. Word: `don’t ` (#6517).
let p = Paragraph::with_text("don’t stop", CharProps::default());
assert_eq!(p.word_at(1), (0, 8));
assert_eq!(p.word_at(2), (0, 8));
let p = Paragraph::with_text("the dogs’ bone", CharProps::default());
assert_eq!(p.word_at(5), (4, 12));
let p = Paragraph::with_text("’tis here", CharProps::default());
assert_eq!(p.word_at(3), (0, 7));
assert_eq!(p.word_at(4), (0, 7));
let p = Paragraph::with_text("well-known", CharProps::default());
assert_eq!(p.word_at(1), (0, 4));
}
proptest::proptest! {
#[test]
fn edits_keep_runs_consistent(ops in proptest::collection::vec((0u8..4, 0usize..40, 0usize..40, "[a-zé ]{0,5}"), 0..40)) {
+3 -22
View File
@@ -296,7 +296,6 @@ impl NumFormat {
use crate::cjk_numbers as cjk;
match self {
NumFormat::DecimalZero => format!("{n:02}"),
NumFormat::Hex => format!("{n:X}"),
NumFormat::ThaiNumbers => thai_digits(n),
NumFormat::UpperRoman => roman(n).to_uppercase(),
NumFormat::LowerRoman => roman(n),
@@ -342,6 +341,7 @@ impl NumFormat {
NumFormat::Chosung => cjk::chosung(n),
NumFormat::Decimal
| NumFormat::DecimalHalfWidth
| NumFormat::Hex
| NumFormat::VietnameseCounting
| NumFormat::Hebrew1
| NumFormat::Hebrew2
@@ -496,21 +496,13 @@ pub fn cardinal_text(n: u32) -> String {
let h = format!("{} hundred", words(n / 100));
if n.is_multiple_of(100) { h } else { format!("{h} {}", words(n % 100)) }
}
1_000..=999_999 => {
_ => {
let th = format!("{} thousand", words(n / 1000));
if n.is_multiple_of(1000) { th } else { format!("{th} {}", words(n % 1000)) }
}
1_000_000..=999_999_999 => {
let m = format!("{} million", words(n / 1_000_000));
if n.is_multiple_of(1_000_000) { m } else { format!("{m} {}", words(n % 1_000_000)) }
}
_ => {
let b = format!("{} billion", words(n / 1_000_000_000));
if n.is_multiple_of(1_000_000_000) { b } else { format!("{b} {}", words(n % 1_000_000_000)) }
}
}
}
capitalize(&words(n))
capitalize(&words(n.min(999_999)))
}
/// English ordinal words (`Twenty-First`).
@@ -1012,17 +1004,6 @@ mod tests {
assert_eq!(NumFormat::from_ooxml("klingon"), NumFormat::Decimal, "unknown formats are decimal");
}
#[test]
fn hex_and_large_number_text() {
assert_eq!(NumFormat::Hex.format(10), "A");
assert_eq!(NumFormat::Hex.format(15), "F");
assert_eq!(NumFormat::Hex.format(16), "10");
assert_eq!(NumFormat::Hex.format(255), "FF");
assert_eq!(NumFormat::CardinalText.format(1_000_000), "One Million");
assert_eq!(NumFormat::OrdinalText.format(1_000_000), "One Millionth");
assert_eq!(NumFormat::CardinalText.format(2_000_000_000), "Two Billion");
}
/// #5757: Thai numbers are the decimal number in Thai digits, every digit, at any length.
#[test]
fn thai_numbers_use_thai_digits() {
+2 -15
View File
@@ -177,19 +177,6 @@ fn glossary_value_from_shared(
})
}
fn note_separators_from_shared(
source: craft_wordmodel::NoteSeparators,
graphics: &mut GraphicCache,
) -> Result<wordcraft_doc::NoteSeparators, DocxError> {
let craft_wordmodel::NoteSeparators { separator, continuation_separator, continuation_notice } = source;
let mut blocks = |b: Option<craft_wordmodel::Blocks>| b.map(|b| blocks_from_shared(b, graphics)).transpose();
Ok(wordcraft_doc::NoteSeparators {
separator: blocks(separator)?,
continuation_separator: blocks(continuation_separator)?,
continuation_notice: blocks(continuation_notice)?,
})
}
fn missing_pictures_from_shared(source: craft_wordmodel::MissingPictures) -> Result<wordcraft_doc::MissingPictures, DocxError> {
let mut target = wordcraft_doc::MissingPictures::default();
target.truncated = source.truncated;
@@ -252,8 +239,8 @@ pub fn from_shared_model(mut source: craft_wordmodel::Document) -> Result<wordcr
document.core = convert(core)?;
document.sources = convert(sources)?;
document.custom_props = convert(custom_props)?;
document.footnote_separators = note_separators_from_shared(footnote_separators, &mut graphics)?;
document.endnote_separators = note_separators_from_shared(endnote_separators, &mut graphics)?;
document.footnote_separators = convert(footnote_separators)?;
document.endnote_separators = convert(endnote_separators)?;
document.media = media;
document.passthrough = passthrough;
document.glossary = glossary.into_iter().map(|g| glossary_value_from_shared(g, &mut graphics)).collect::<Result<_, _>>()?;
-30
View File
@@ -2444,36 +2444,6 @@ fn note_separators_and_continuation_notice_round_trip() {
check(&wordcraft_docx::read(&out).unwrap());
}
/// A picture frame shape in a footnote or endnote separator opens as the same shape kind as it does
/// in the body, instead of failing the whole document. (The test name dates from when the body
/// opened this shape as a rectangle.)
#[test]
fn a_frame_shape_in_a_note_separator_reads_as_a_rectangle() {
let frame = r#"<w:r><w:drawing><wp:inline><wp:extent cx="508000" cy="381000"/><wp:docPr id="1" name="F"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wps:wsp><wps:spPr><a:prstGeom prst="frame"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"#;
let notes = |root: &str, item: &str| {
format!(r#"<w:{root} {W_NS}><w:{item} w:type="separator" w:id="-1"><w:p>{frame}<w:r><w:separator/></w:r></w:p></w:{item}></w:{root}>"#)
};
let footnotes = notes("footnotes", "footnote");
let endnotes = notes("endnotes", "endnote");
let bytes = docx(
&format!("<w:p>{frame}</w:p>"),
&[("rId1", "footnotes", "footnotes.xml"), ("rId2", "endnotes", "endnotes.xml")],
&[("word/footnotes.xml", &footnotes), ("word/endnotes.xml", &endnotes)],
);
let d = wordcraft_docx::read(&bytes).unwrap();
let shapes = |p: &Paragraph| -> Vec<(ShapeKind, f32)> {
p.objects.iter().filter_map(|o| if let InlineObject::Shape { kind, w, .. } = o { Some((*kind, *w)) } else { None }).collect()
};
let in_body = shapes(d.body[0].as_para().unwrap());
assert_eq!(in_body.len(), 1, "{in_body:?}");
assert_eq!(in_body[0].1, 40.0);
assert_eq!(in_body[0].0, ShapeKind::Frame);
for separators in [&d.footnote_separators, &d.endnote_separators] {
let sep = separators.separator.as_ref().unwrap()[0].as_para().unwrap();
assert_eq!(shapes(sep), in_body);
}
}
/// Issue #534: East Asian number formats are read, labelled and written back as they were; a
/// value the format doesn't define is decimal, and a level without `w:ind` has no indent.
#[test]
+4 -4
View File
@@ -362,10 +362,10 @@ fn copy_member(s: &mut Session, pos: &Pos, index: usize) -> CmdResult {
if !copied {
return Err(CmdError::Failed("the member vanished".into()));
}
let text = f.clipboard_text();
let r = super::edit::copy_result(s, &f, &text)?;
s.clip_history.push(&f, &text);
Ok(r)
s.clipboard_text = f.clipboard_text();
s.clip_history.push(&f, &s.clipboard_text);
s.clipboard = Some(f);
Ok(super::edit::copy_result(s))
}
/// Take member `index` out of the canvas at `pos`; the canvas stays selected.
+1 -5
View File
@@ -300,11 +300,7 @@ fn page(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
}
let Some(c) = l.caret_on(&from, s.page_hint) else { return sel_result(s) };
let np = if dir < 0 { c.page.saturating_sub(1) } else { (c.page + 1).min(l.pages.len().saturating_sub(1)) };
let to = if np == c.page {
if dir < 0 { s.doc.start_of(from.story) } else { s.doc.end_of(from.story) }
} else {
l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from)
};
let to = l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from);
s.page_hint = np;
apply(s, to, ext);
sel_result(s)
+3 -3
View File
@@ -244,10 +244,10 @@ fn copy(s: &mut Session, segs: &[(Pos, Pos)]) -> CmdResult {
rows.push(row_text(s, &a, &b));
blocks.push(Block::Para(para));
}
let text = rows.join("\n");
s.clipboard_text = rows.join("\n");
let media = s.doc.media_of_blocks(&blocks);
let f = Fragment { blocks, parts, media };
super::edit::copy_result(s, &f, &text)
s.clipboard = Some(Fragment { blocks, parts, media });
Ok(super::edit::copy_result(s))
}
/// Delete each row's piece (bottom up, so earlier positions stay valid) and leave the caret at
+20 -25
View File
@@ -208,28 +208,29 @@ fn copy_with(s: &mut Session, whole: Option<&Path>) -> CmdResult {
None if a == b => return Ok(json!({"text": ""})),
None => s.doc.copy_range(&a, &b),
};
let text = f.clipboard_text();
let r = copy_result(s, &f, &text)?;
s.clip_history.push(&f, &text);
Ok(r)
s.clipboard_text = f.clipboard_text();
s.clip_history.push(&f, &s.clipboard_text);
s.clipboard = Some(f);
Ok(copy_result(s))
}
/// What Copy and Cut return: the clipboard's text, and the copy as HTML (equations as MathML,
/// #816) and as RTF for the host to put on the system clipboard too, so other programs keep the
/// formatting; and for a copy of one equation alone, its MathML (#1297).
///
/// The copy goes on the clipboard whole or not at all: a copy whose HTML or RTF cannot be made
/// is refused, and the clipboard keeps what it held.
pub(crate) fn copy_result(s: &mut Session, f: &Fragment, text: &str) -> CmdResult {
let mut d = f.to_document();
d.styles = s.doc.styles.clone();
if d.media.is_empty() {
d.media = s.doc.media.clone();
}
let html = wordcraft_formats::html::export_fragment(&d).map_err(|e| CmdError::Failed(format!("the copy cannot be exported as HTML: {e}")))?;
let rtf = wordcraft_formats::rtf::export(&d).map_err(|e| CmdError::Failed(format!("the copy cannot be exported as RTF: {e}")))?;
let mut r = json!({"text": text});
for (k, v) in [("html", &html), ("rtf", &rtf)] {
pub(crate) fn copy_result(s: &mut Session) -> Value {
(s.clipboard_html, s.clipboard_rtf) = match &s.clipboard {
Some(f) => {
let mut d = f.to_document();
d.styles = s.doc.styles.clone();
if d.media.is_empty() {
d.media = s.doc.media.clone();
}
(wordcraft_formats::html::export_fragment(&d), wordcraft_formats::rtf::export(&d))
}
None => (String::new(), String::new()),
};
let mut r = json!({"text": s.clipboard_text});
for (k, v) in [("html", &s.clipboard_html), ("rtf", &s.clipboard_rtf)] {
if !v.is_empty() {
r[k] = json!(v);
}
@@ -238,16 +239,10 @@ pub(crate) fn copy_result(s: &mut Session, f: &Fragment, text: &str) -> CmdResul
// ("MathML" on Windows, `public.mathml.presentation` on macOS; #1297). Word looks for them
// before anything else when it pastes; a copy with text around the equation doesn't offer
// them, so pasting it keeps the text.
if let Some((linear, display)) = f.sole_equation() {
if let Some((linear, display)) = s.clipboard.as_ref().and_then(|f| f.sole_equation()) {
r["mathml"] = json!(wordcraft_formats::mathml::linear_to_mathml(linear, display));
}
// The copy is on the clipboard now: its text, its fragment and its HTML and RTF flavours,
// all at once.
s.clipboard_text = text.to_string();
s.clipboard = Some(f.clone());
s.clipboard_html = html;
s.clipboard_rtf = rtf;
Ok(r)
r
}
/// Cut the selection, selected object, or whole table cells to the clipboard and remove it from the document.
-21
View File
@@ -703,24 +703,3 @@ fn a_math_name_is_corrected_by_any_character_that_cannot_continue_it() {
s.run("equation.type", &json!({"text": r"\alpha+"})).unwrap();
assert_eq!(linear(&s), r"\alpha+");
}
/// Paste Formatting keeps an open equation open (matching other formatting commands and
/// `cmd::column`), whereas content-pasting commands leave the equation first.
#[test]
fn paste_formatting_keeps_an_open_equation_open() {
let mut s = session();
s.run("text.insert", &json!({"text": "source "})).unwrap();
s.run("select.text", &json!({"text": "source"})).unwrap();
s.run("format.bold", &json!({})).unwrap();
s.run("edit.copyFormat", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("insert.equation", &json!({"linear": "x"})).unwrap();
let before = s.math.clone();
assert!(before.is_some());
s.run("edit.pasteFormat", &json!({})).unwrap();
assert_eq!(s.math, before, "edit.pasteFormat keeps the open equation open");
s.run("edit.pasteText", &json!({"text": "y"})).unwrap();
assert!(s.math.is_none(), "edit.pasteText closes the open equation");
}
+6 -22
View File
@@ -94,9 +94,9 @@ pub fn specs() -> Vec<CommandSpec> {
.pure(),
CommandSpec::new("file.save", "Save", "File", save)
.key("Mod+S / Shift+F12 / Alt+Shift+F2")
.params(r#"{"path"?: string (required with `copy`), "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport), "copy"?: bool (write a copy at `path`, as File › Export does: the document keeps its own file, unsaved changes and save stamps; not with `password`)}"#)
.params(r#"{"path"?: string, "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport)}"#)
.pure(),
CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save), "copy"?: bool (as file.save)}"#).pure(),
CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save)}"#).pure(),
// Pure: the password must not land in Repeat or a recorded macro, and it isn't an edit
// to undo; it marks the document as changed itself.
CommandSpec::new("file.encrypt", "Encrypt with Password", "File › Info › Protect Document", encrypt)
@@ -131,7 +131,7 @@ pub fn specs() -> Vec<CommandSpec> {
.pure(),
CommandSpec::new("file.printPdf", "Print to PDF", "File › Print", crate::print::print_pdf_to_file)
.params(
r#"{"path": string, "pagesPerSheet"?: 1 | 2 | 4 | 6 | 9 | 16 | "booklet" | "bookletReverse", "range"?: "all" | "current" | "selection" (the pages the selection touches) | "custom", "pages"?: "1-3,5" (implies custom), "parity"?: "all" | "odd" | "even", "copies"?: 1-999, "collate"?: bool (default true), "paper"?: "none" | "Letter" | "Legal" | "A4" | … (a Layout › Size name: scale every page to this paper, centred; the document keeps its size), "compress"?: bool (default true: compress the PDF's content streams; false writes the same pages uncompressed, which is larger)"#,
r#"{"path": string, "pagesPerSheet"?: 1 | 2 | 4 | 6 | 9 | 16 | "booklet" | "bookletReverse", "range"?: "all" | "current" | "selection" (the pages the selection touches) | "custom", "pages"?: "1-3,5" (implies custom), "parity"?: "all" | "odd" | "even", "copies"?: 1-999, "collate"?: bool (default true), "paper"?: "none" | Layout › Size name | [width,height] in points (scale every page to this paper, centred; the document keeps its size), "compress"?: bool (default true: compress the PDF's content streams; false writes the same pages uncompressed, which is larger)"#,
)
.pure(),
CommandSpec::new("file.print", "Print", "File", |s, _| {
@@ -342,8 +342,6 @@ pub(crate) fn new_from_template(s: &mut Session, v: &Value) -> CmdResult {
let path = p::req_str(v, "path")?;
let (mut doc, _) = read_document(s, path, v)?;
doc.settings.attached_template = Some(path.to_string());
// A new document: not created when the template was. Saving stamps its creation date.
doc.core.created.clear();
if p::bool(v, "replaceBlank") == Some(true) && s.used_because().is_none() {
s.set_document(doc);
} else {
@@ -395,14 +393,6 @@ fn encrypt(s: &mut Session, v: &Value) -> CmdResult {
/// Executes `file.save`: writes the document or text to disk, preserving exact file text for
/// unedited Markdown files, and updating session path and dirty state.
fn save(s: &mut Session, v: &Value) -> CmdResult {
// A copy (File › Export, #6131) is written and nothing else: the document keeps its own file,
// its unsaved changes and its save stamps, so the next Save still goes to the original.
// It never falls back to the document's own file or opens the Save As picker (whose answer is
// an ordinary save that adopts the file).
let as_copy = p::bool(v, "copy") == Some(true);
if as_copy && p::str(v, "path").is_none() {
return Err(CmdError::Params("`copy` needs a `path`: the copy has to go somewhere".into()));
}
let path = match p::str(v, "path").map(std::path::PathBuf::from).or_else(|| s.path.clone()) {
Some(p) => p,
None => {
@@ -411,9 +401,6 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
}
};
check_strict_output(p::bool(v, "strict").unwrap_or(false), &path.to_string_lossy())?;
if as_copy && v.get("password").is_some_and(|pw| !pw.is_null()) {
return Err(CmdError::Params("`password` changes the document's own saves, so it can't come with `copy` (use file.encrypt)".into()));
}
if let Some(pw) = v.get("password").filter(|pw| !pw.is_null()) {
let Some(pw) = pw.as_str().filter(|pw| !pw.is_empty()) else {
return Err(CmdError::Params("`password` must be a non-empty string (file.encrypt removes a password)".into()));
@@ -456,14 +443,11 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
Some(text) => crate::io::save_text_path(&path, text),
None => crate::io::save_path_with(&path, copy.as_ref().unwrap_or(&s.doc), password, &opts),
};
let encrypted = password.is_some() && crate::io::can_encrypt(&path.to_string_lossy());
if written.is_err() || as_copy {
if let Err(e) = written {
(s.doc.settings.zoom, s.doc.core.last_modified_by, s.doc.core.created, s.doc.core.modified, s.doc.core.revision) = before_stamp;
return Err(CmdError::Failed(e));
}
written.map_err(CmdError::Failed)?;
if as_copy {
return Ok(json!({"saved": true, "path": path.to_string_lossy(), "encrypted": encrypted, "copy": true}));
}
let encrypted = password.is_some() && crate::io::can_encrypt(&path.to_string_lossy());
// A save in a format that doesn't keep everything (plain text, Markdown, a page image) is a
// copy, except over the document's own file: a note.txt opened and saved is saved (#2376).
// A Markdown file saved as another one loses nothing its own save wouldn't: it moves there.
+3 -14
View File
@@ -209,8 +209,7 @@ fn target(s: &Session) -> Option<(Pos, Pos)> {
return Some((a, b));
}
let p = s.doc.para_at(&a)?;
// Word takes a typographic apostrophe (’) like `'` here (#6517).
let is_w = |c: char| c.is_alphanumeric() || matches!(c, '\'' | '’' | '_');
let is_w = |c: char| c.is_alphanumeric() || c == '\'' || c == '_';
let before = p.text.get(..a.off)?.chars().next_back();
let after = p.text.get(a.off..)?.chars().next();
if before.is_some_and(is_w) && after.is_some_and(is_w) {
@@ -352,16 +351,6 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
out
}
/// Whether a toggle without a `value` turns its format on. A selection follows its first character
/// in document order, as Word does: one that starts formatted loses the format, all of it (#6516).
fn turns_on(s: &Session, has: impl Fn(&ResolvedChar) -> bool) -> bool {
let chars = resolved(s);
if !s.sel.is_collapsed() || selected_text_box(s).is_some() || column_rows(s).is_some() {
return !chars.first().is_some_and(has);
}
!chars.iter().all(has)
}
/// Bold as drawn: a run marked complex script (`w:cs`) or right to left (`w:rtl`) shows its
/// complex-script bold.
fn shown_bold(r: &ResolvedChar) -> bool {
@@ -377,7 +366,7 @@ fn shown_italic(r: &ResolvedChar) -> bool {
fn toggle(s: &mut Session, v: &Value, get: fn(&ResolvedChar) -> bool, set: fn(&mut CharProps, bool)) -> CmdResult {
let on = match p::bool(v, "value") {
Some(b) => b,
None => turns_on(s, get),
None => !resolved(s).iter().all(get),
};
apply(s, &|c| set(c, on))
}
@@ -387,7 +376,7 @@ fn underline(s: &mut Session, v: &Value) -> CmdResult {
let on = match (p::bool(v, "value"), style) {
(Some(b), _) => b,
(None, Some(_)) => true,
(None, None) => turns_on(s, |r| r.underline != Underline::None),
(None, None) => !resolved(s).iter().all(|r| r.underline != Underline::None),
};
let u = if on { style.unwrap_or(Underline::Single) } else { Underline::None };
apply(s, &|c| c.underline = Some(u))
+10 -27
View File
@@ -188,14 +188,10 @@ fn range_index_after_text(s: &Session) -> bool {
fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
let instr = index_instr(v);
check_index_reachable(s)?;
// An index Word wrote as a range field is first made a plain field in its own paragraph, as
// Update Index makes it, so it takes the new settings rather than a second index being added
// beside it (#8034).
// An index Word wrote as a range field is rebuilt by Update Index; Insert Index would add a
// second one beside it (#8034).
if index_field(s).is_none() && has_index(s, true) {
super::citations::update_generated(s)?;
if index_field(s).is_none() {
return Err(CmdError::Failed("the document already has an index; use Update Index to rebuild it".into()));
}
return Err(CmdError::Failed("the document already has an index; use Update Index to rebuild it".into()));
}
match index_field(s) {
Some((i, _)) => {
@@ -644,10 +640,10 @@ End.",
assert!(!body_has_index(&s));
}
/// An index Word wrote as a range field in the main text takes Insert Index's settings and is
/// rebuilt, rather than a second index being added at the caret (#8034).
/// An index Word wrote as a range field in the main text is rebuilt by Update Index; Insert
/// Index says so instead of adding a second one (#8034).
#[test]
fn insert_index_gives_a_range_field_index_in_the_main_text_its_settings() {
fn insert_index_leaves_a_range_field_index_in_the_main_text_to_update_index() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
@@ -658,23 +654,10 @@ End.",
para.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
s.doc.insert_block(StoryRef::Body, &Path::top(at), wordcraft_doc::Block::Para(para)).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("references.index", &json!({"columns": 2})).unwrap();
let instrs: Vec<String> = s
.doc
.body
.iter()
.filter_map(|b| b.as_para())
.flat_map(|p| p.objects.iter())
.filter_map(|o| match o {
InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX" => {
Some(instr.clone())
}
_ => None,
})
.collect();
assert_eq!(instrs.len(), 1, "one index, not a second beside it: {instrs:?}");
assert!(FieldCode::parse(&instrs[0]).arg('c').is_some(), "the index took the new columns setting: {instrs:?}");
let before = s.doc.body.len();
assert!(s.run("references.index", &json!({})).is_err());
assert_eq!(s.doc.body.len(), before, "no second index was added");
s.run("references.updateIndex", &json!({})).unwrap();
let text: String =
s.doc.body.iter().filter_map(|b| b.as_para()).map(|p| p.text.replace(wordcraft_doc::para::OBJ, "")).collect::<Vec<_>>().join(
"
+1 -1
View File
@@ -21,7 +21,7 @@ pub use items::{
};
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
use links::{bookmark, delete_bookmark, link, link_targets};
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span, selection_is_one_line};
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span};
pub use objects::{MAX_TABLE_ROWS, base64_decode, base64_encode};
use objects::{icon, shape, table, text_box};
pub(crate) use objects::{image_ext, picture};
+11 -88
View File
@@ -205,26 +205,21 @@ pub fn format_date_at_in(fmt: &str, lang: Option<&str>, unix: u64, offset_secs:
format_date_parts_in(fmt, lang, y, m as usize, d, hms, days)
}
/// Month and weekday names of a language, as Word writes them in date fields: full names and the
/// abbreviations used by `MMM` and `ddd`. Weekdays start on Thursday (1970-01-01).
/// Month and weekday names of a language, as Word writes them in date fields: full names, the
/// three-letter forms (`MMM`, `ddd`) being their first three letters, without a full stop.
/// Weekdays start on Thursday (1970-01-01).
struct DateNames {
/// Full month names (January through December).
months: [&'static str; 12],
/// Abbreviated month names for `MMM` (January through December).
months_short: [&'static str; 12],
/// Weekday names starting on Thursday (1970-01-01).
days: [&'static str; 7],
/// Abbreviated weekday names for `ddd`, starting on Thursday (1970-01-01).
days_short: [&'static str; 7],
/// The picture of a `DATE` field without `\@`.
default: &'static str,
}
const ENGLISH: DateNames = DateNames {
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
months_short: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
days: ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"],
days_short: ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"],
default: "M/d/yyyy",
};
@@ -232,46 +227,14 @@ const ENGLISH: DateNames = DateNames {
/// `ddd` = `qui`, and `dd/MM/yyyy` for a field without a picture.
const PORTUGUESE: DateNames = DateNames {
months: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
months_short: ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez"],
days: ["quinta-feira", "sexta-feira", "sábado", "domingo", "segunda-feira", "terça-feira", "quarta-feira"],
days_short: ["qui", "sex", "sáb", "dom", "seg", "ter", "qua"],
default: "dd/MM/yyyy",
};
/// German (Word's Windows NLS forms): `MMMM` = `März`, `MMM` = `Mrz`, `ddd` = `Fr` (two
/// letters), and `dd.MM.yyyy` for a field without a picture. Covers de-DE, de-CH and bare `de`.
const GERMAN: DateNames = DateNames {
months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
months_short: ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
};
/// Austrian Standard German: January is `Jänner`, abbreviated `Jän` (Österreichisches
/// Wörterbuch; Windows NLS `de-AT`). Every other month and weekday matches [`GERMAN`].
const GERMAN_AUSTRIA: DateNames = DateNames {
months: ["Jänner", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
months_short: ["Jän", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
};
/// Choose month and weekday names from the language tag: the primary subtag picks the language,
/// and a region subtag refines it (`de-AT` writes `Jänner`). Tags compare case-insensitively, as
/// `w:lang` values do.
/// Choose month and weekday names according to the primary language subtag.
fn date_names(lang: Option<&str>) -> &'static DateNames {
let mut subtags = lang.unwrap_or("").trim().split(['-', '_']);
let primary = subtags.next().unwrap_or("");
if primary.eq_ignore_ascii_case("pt") {
&PORTUGUESE
} else if primary.eq_ignore_ascii_case("de") {
// Austria keeps `Jänner` / `Jän`; Germany and Switzerland keep `Januar` / `Jan`.
if subtags.any(|region| region.eq_ignore_ascii_case("AT")) { &GERMAN_AUSTRIA } else { &GERMAN }
} else {
&ENGLISH
}
let primary = lang.and_then(|l| l.trim().split(['-', '_']).next()).unwrap_or("");
if primary.eq_ignore_ascii_case("pt") { &PORTUGUESE } else { &ENGLISH }
}
/// The picture Word gives a `DATE` field that has no `\@` switch, in the field's language.
@@ -289,12 +252,9 @@ pub fn format_date_parts(fmt: &str, y: i64, m: usize, d: u32, hms: (u32, u32, u3
#[allow(clippy::too_many_arguments)]
pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d: u32, (hh, mm, ss): (u32, u32, u32), days_since: i64) -> String {
let names = date_names(lang);
let mi = m.saturating_sub(1);
let di = days_since.rem_euclid(7) as usize;
let month = names.months.get(mi).copied().unwrap_or(names.months[0]);
let month_short = names.months_short.get(mi).copied().unwrap_or(names.months_short[0]);
let day = names.days.get(di).copied().unwrap_or(names.days[0]);
let day_short = names.days_short.get(di).copied().unwrap_or(names.days_short[0]);
let month = names.months.get(m.saturating_sub(1)).copied().unwrap_or(names.months[0]);
let day = names.days.get(days_since.rem_euclid(7) as usize).copied().unwrap_or(names.days[0]);
let three = |s: &str| -> String { s.chars().take(3).collect() };
let mut out = String::new();
let chars: Vec<char> = fmt.chars().collect();
let mut i = 0;
@@ -336,11 +296,11 @@ pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d:
('y' | 'Y', 4..) => out.push_str(&format!("{y:04}")),
('y' | 'Y', _) => out.push_str(&format!("{:02}", y % 100)),
('M', 4..) => out.push_str(month),
('M', 3) => out.push_str(month_short),
('M', 3) => out.push_str(&three(month)),
('M', 2) => out.push_str(&format!("{m:02}")),
('M', 1) => out.push_str(&m.to_string()),
('d' | 'D', 4..) => out.push_str(day),
('d' | 'D', 3) => out.push_str(day_short),
('d' | 'D', 3) => out.push_str(&three(day)),
('d' | 'D', 2) => out.push_str(&format!("{d:02}")),
('d' | 'D', 1) => out.push_str(&d.to_string()),
('H', 2..) => out.push_str(&format!("{hh:02}")),
@@ -614,43 +574,6 @@ mod date_time_locale_tests {
assert_eq!(format("MMMM", 20), "outubro");
}
/// German month and weekday names, and the default picture, are chosen by the language tag
/// (de-DE, de-AT, de-CH), as in Word (#7146).
#[test]
fn german_date_names_render_for_de() {
assert_eq!(format_date_parts_in("dddd, d. MMMM yyyy", Some("de-DE"), 2026, 11, 21, (12, 0, 0), 2), "Samstag, 21. November 2026");
assert_eq!(default_date_picture(Some("de-CH")), "dd.MM.yyyy");
}
/// Windows NLS short forms: two-letter weekdays (`Mo`, `Di`…) and `Mrz` for March, with no
/// trailing full stop (#7146).
#[test]
fn german_short_names_match_windows_nls() {
let format = |pic| format_date_parts_in(pic, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3);
assert_eq!(format("ddd, d. MMM yyyy"), "So, 15. Mrz 2026");
assert_eq!(format("dddd"), "Sonntag");
assert_eq!(format("MMM"), "Mrz");
}
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland
/// and bare `de` keep `Januar` (`Jan`); every other name is shared (#7146).
#[test]
fn austrian_german_january_is_jaenner() {
let january = |lang, pic| format_date_parts_in(pic, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
assert_eq!(january("de-AT", "MMMM"), "Jänner");
assert_eq!(january("de-AT", "MMM"), "Jän");
assert_eq!(january("de_at", "MMMM"), "Jänner", "region subtags compare case-insensitively");
for lang in ["de-DE", "de-CH", "de"] {
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
}
// Only January differs: February and March read the same in Austria and Germany.
for month in [2, 3] {
let names = |lang| format_date_parts_in("MMMM MMM", Some(lang), 2026, month, 1, (12, 0, 0), 0);
assert_eq!(names("de-AT"), names("de-DE"));
}
}
/// A pt-BR dynamic field keeps its result after DOCX round-trip and refresh.
#[test]
fn pt_br_date_time_dialog_inserts_dynamic_field() {
+10 -30
View File
@@ -84,45 +84,25 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
sel_result(s)
}
/// What can't stand in one line of text: breaks, and pictures or fields.
const NOT_ONE_LINE: [char; 7] = {
/// The `text` to retype a selection with before linking it: only when it differs from the selected
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
use wordcraft_doc::para::{COLUMN_BREAK, LINE_BREAK, OBJ, PAGE_BREAK};
[LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ]
};
/// The raw text of the selection when it is one run of one paragraph without breaks, pictures or fields.
fn one_line_selection(s: &Session) -> Option<&str> {
// A column (block) selection has both ends in one paragraph but holds a piece of each line it
// covers: it isn't one line of text (#8581).
if s.column_segments().is_some_and(|segs| !segs.is_empty()) {
/// What can't stand in one line of text: breaks, and pictures or fields.
const NOT_ONE_LINE: [char; 7] = [LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ];
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
if text.contains(NOT_ONE_LINE) {
return None;
}
let (a, b) = s.sel.ordered();
if a.story != b.story || a.path != b.path {
return None;
}
s.doc.para(a.story, &a.path)?.text.get(a.off..b.off).filter(|t| !t.contains(NOT_ONE_LINE))
}
/// Whether the selection is plain text in one line of one paragraph: otherwise (as Word shows
/// `<<Selection in Document>>`) Text to display can't show it and linking keeps its content (#8286).
pub fn selection_is_one_line(s: &Session) -> bool {
one_line_selection(s).is_some()
}
/// The `text` to retype a selection with before linking it: only when it differs from the selected
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
if text.contains(NOT_ONE_LINE) {
let shown = s.doc.para(a.story, &a.path)?.text.get(a.off..b.off)?;
if shown.contains(NOT_ONE_LINE) || shown == text {
return None;
}
let shown = one_line_selection(s)?;
if shown == text {
return None;
}
let (a, b) = s.sel.ordered();
// A selection in a field's result (between its markers, which it doesn't hold) is retyped by
// the next update of the field, not here.
if s.doc.field_ranges(a.story).iter().any(|r| r.start < b && a <= r.end) {
+10 -24
View File
@@ -103,7 +103,7 @@ fn exact_text(s: &Session) -> Option<String> {
return res.clone();
}
let kept = [s.md_file.latest.as_deref(), s.md_file.saved.as_deref()];
let res = kept.into_iter().flatten().find(|text| parse(&s.doc, text).is_ok_and(|d| d.same_content(&s.doc))).map(str::to_string);
let res = kept.into_iter().flatten().find(|text| parse(&s.doc, text).same_content(&s.doc)).map(str::to_string);
*s.md_file.cached_exact.borrow_mut() = Some((s.rev(), res.clone()));
res
}
@@ -216,16 +216,15 @@ fn enter(s: &mut Session) -> Result<(), CmdError> {
// The file's own text when it still says what the document holds, so nothing is lost.
let (text, loses_content, block_lines) = match exact_text(s) {
Some(text) => {
let (_, lines) = parse_with_lines(&s.doc, &text)?;
let (_, lines) = parse_with_lines(&s.doc, &text);
(text, false, lines)
}
None => {
let text = wordcraft_formats::markdown::export(&s.doc)
.map_err(|e| CmdError::Failed(format!("the document cannot be written as Markdown: {e}")))?;
let text = wordcraft_formats::markdown::export(&s.doc);
if text.len() > MAX_SOURCE_BYTES {
return Err(CmdError::Failed(too_long()));
}
let (doc, lines) = parse_with_lines(&s.doc, &text)?;
let (doc, lines) = parse_with_lines(&s.doc, &text);
let loses_content = !doc.same_content(&s.doc);
(text, loses_content, lines)
}
@@ -290,19 +289,7 @@ pub fn apply(s: &mut Session) {
}
(src.text.clone(), src.entry_text.clone(), src.entry_doc.clone(), src.has_step, src.entry_lines.clone())
};
let (doc, lines) = if text == *entry_text {
((*entry_doc).clone(), entry_lines)
} else {
// The text cannot be read as Markdown: the document stays as it is, rather than
// becoming an empty one.
match parse_with_lines(&s.doc, &text) {
Ok(v) => v,
Err(e) => {
s.status = e.to_string();
return;
}
}
};
let (doc, lines) = if text == *entry_text { ((*entry_doc).clone(), entry_lines) } else { parse_with_lines(&s.doc, &text) };
let step = if !has_step {
s.checkpoint(LABEL);
Some(s.undo_mark())
@@ -326,20 +313,19 @@ pub fn apply(s: &mut Session) {
/// `text` as a document and block lines, with what isn't in Markdown from `current`: its page, settings,
/// properties and language, as opening the file gave it.
fn parse_with_lines(current: &Document, text: &str) -> Result<(Document, Vec<usize>), CmdError> {
let (mut doc, lines) = wordcraft_formats::markdown::import_on_with_lines(text, &current.last_section)
.map_err(|e| CmdError::Failed(format!("the Markdown cannot be read: {e}")))?;
fn parse_with_lines(current: &Document, text: &str) -> (Document, Vec<usize>) {
let (mut doc, lines) = wordcraft_formats::markdown::import_on_with_lines(text, &current.last_section);
doc.ensure_nonempty();
doc.settings = current.settings.clone();
doc.core = current.core.clone();
Arc::make_mut(&mut doc.styles).default_chr.lang = current.styles.default_chr.lang.clone();
Ok((doc, lines))
(doc, lines)
}
/// `text` as a document, with what isn't in Markdown from `current`: its page, settings,
/// properties and language, as opening the file gave it.
fn parse(current: &Document, text: &str) -> Result<Document, CmdError> {
parse_with_lines(current, text).map(|(doc, _)| doc)
fn parse(current: &Document, text: &str) -> Document {
parse_with_lines(current, text).0
}
/// The byte offset where `line` starts, or the end of a text with fewer lines.
-19
View File
@@ -278,23 +278,4 @@ mod tests {
assert_eq!(texts(&s), ["First one.", "Second one.", "Third one."]);
assert!(kinds(&mut s).is_empty());
}
/// A command that fails between a tracked cut and its paste changed nothing, so the move
/// the cut recorded is still there: the paste is a move, as it was before the command.
#[test]
fn a_failed_command_between_a_tracked_cut_and_its_paste_leaves_the_move() {
let mut s = Session::new(Document::new());
s.run("document.setText", &json!({"text": "First one.\nSecond one.\nThird one."})).unwrap();
s.run("file.setAuthor", &json!({"name": "Ana"})).unwrap();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("select.range", &json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 2, "off": 0}})).unwrap();
s.run("edit.cut", &json!({})).unwrap();
// A command that fails: there is no such character style.
assert!(s.run("format.charStyle", &json!({"style": "NoSuchStyle"})).is_err());
s.run("caret.set", &json!({"pos": {"block": 0, "off": 0}})).unwrap();
s.run("edit.paste", &json!({})).unwrap();
let k = kinds(&mut s);
assert!(k.iter().any(|(k, m)| k == "moveTo" && m == "move1"), "{k:?}");
assert!(k.iter().any(|(k, m)| k == "moveFrom" && m == "move1"), "{k:?}");
}
}
+13 -42
View File
@@ -187,7 +187,7 @@ fn paste_special(s: &mut Session, v: &Value) -> CmdResult {
return Ok(r);
}
"formatted" => s.clipboard.clone().ok_or_else(|| CmdError::Failed("the clipboard is empty".into()))?,
"html" => adopt(s, import_html(&src).map_err(|e| CmdError::Failed(format!("bad HTML: {e}")))?),
"html" => adopt(s, import_html(&src)),
_ => adopt(s, wordcraft_formats::rtf::import(src.as_bytes()).map_err(|e| CmdError::Failed(format!("bad RTF: {e}")))?),
};
insert(s, frag)?;
@@ -204,8 +204,8 @@ const BLOCKQUOTE_INDENT: f32 = 36.0;
/// (#1270): it pastes as a Normal paragraph indented by the page's `blockquote` margins, else half
/// an inch each side, rather than in the (centred, italic) Quote style. Opening an .html file keeps
/// `<blockquote>` as Quote, so HTML round-trips.
fn import_html(html: &str) -> Result<Document, String> {
let mut doc = wordcraft_formats::html::import(html_fragment(html))?;
fn import_html(html: &str) -> Document {
let mut doc = wordcraft_formats::html::import(html_fragment(html));
let (left, right) = blockquote_margins(html);
for b in &mut doc.body {
each_para(Arc::make_mut(b), 0, &mut |p| {
@@ -217,7 +217,7 @@ fn import_html(html: &str) -> Result<Document, String> {
}
});
}
Ok(doc)
doc
}
/// The left and right margins (points) the payload's `<style>` sheets give `blockquote` — LibreOffice
@@ -294,7 +294,7 @@ fn has_content(d: &Document) -> bool {
/// [`MAX_PASTE_BYTES`], or it holds nothing to paste (the caller pastes the text then).
pub fn rich_fragment(s: &mut Session, v: &Value) -> Option<Fragment> {
let fits = |k: &str| p::str(v, k).filter(|t| !t.trim().is_empty() && t.len() <= MAX_PASTE_BYTES);
let doc = fits("html").and_then(|html| import_html(html).ok());
let doc = fits("html").map(import_html);
let doc = match doc.filter(has_content) {
Some(d) => d,
None => {
@@ -373,22 +373,21 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
p.props = para.clone();
for run in &mut p.runs {
let src = std::mem::replace(&mut run.props, base.clone());
let e = emphasis_of(s, &src);
// Emphasis the source shows in either script is kept for both, as the Bold and
// Italic buttons set it: text pasted into a run marked `w:cs` (Thai from a WPS or
// Word file) is drawn with the complex-script bold and italic.
if shown(e.bold, e.bold_cs, &e) {
// Emphasis in either script is kept for both, as the Bold and Italic buttons set
// it: text pasted into a run marked `w:cs` (Thai from a WPS or Word file) is drawn
// with the complex-script bold and italic.
if src.bold == Some(true) || src.bold_cs == Some(true) {
run.props.bold = Some(true);
run.props.bold_cs = Some(true);
}
if shown(e.italic, e.italic_cs, &e) {
if src.italic == Some(true) || src.italic_cs == Some(true) {
run.props.italic = Some(true);
run.props.italic_cs = Some(true);
}
if e.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
run.props.underline = e.underline;
if src.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
run.props.underline = src.underline;
}
if e.strike == Some(true) {
if src.strike == Some(true) {
run.props.strike = Some(true);
}
run.props.link = src.link;
@@ -401,34 +400,6 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
}
}
/// The formatting a pasted run's emphasis is judged by: its own, over its character style
/// chain's. Word keeps the bold, italic, underline and strikethrough a character style gives the
/// source, as direct formatting, but not a paragraph style's (measured in Word for Windows), so
/// the paragraph style isn't consulted.
fn emphasis_of(s: &Session, src: &wordcraft_doc::CharProps) -> wordcraft_doc::CharProps {
use wordcraft_doc::styles::StyleKind;
let mut e = wordcraft_doc::CharProps::default();
if let Some(id) = src.style.as_deref() {
for st in s.doc.styles.chain(id) {
if st.kind == StyleKind::Character || st.kind == StyleKind::Paragraph {
e.overlay(&st.chr);
}
}
}
e.overlay(&wordcraft_doc::CharProps { style: None, ..src.clone() });
e
}
/// Whether a run with these Latin and complex-script values of a toggle (bold or italic) shows
/// it anywhere, as the resolved formatting draws it: a run marked `w:cs` or `w:rtl` draws all
/// its text with the complex-script value, which borrows the Latin one unless the run is marked
/// `w:cs`; other runs draw their Latin text with the Latin value.
fn shown(latin: Option<bool>, complex: Option<bool>, run: &wordcraft_doc::CharProps) -> bool {
let complex_shown = complex.or(latin.filter(|_| run.cs != Some(true))) == Some(true);
let all_complex = run.cs == Some(true) || run.rtl == Some(true);
complex_shown || (!all_complex && latin == Some(true))
}
/// Paste `frag` at the selection. A copied table pasted with the caret in a table cell goes the way
/// Word's Paste does it (rows inserted or cells overwritten, #6739; see [`super::paste_cells`]);
/// anything else is [`insert_as_is`].
+1 -10
View File
@@ -305,16 +305,7 @@ pub(crate) fn greyed_out(s: &Session, id: &str, facts: impl FnOnce() -> Facts) -
}
}
let comment_ok = id.starts_with("review.") && (id.contains("Comment") || id == "review.reply");
let tracked = matches!(
id,
"review.accept"
| "review.reject"
| "review.acceptAndNext"
| "review.rejectAndNext"
| "review.acceptAll"
| "review.rejectAll"
| "review.trackChanges"
);
let tracked = matches!(id, "review.accept" | "review.reject" | "review.acceptAll" | "review.rejectAll" | "review.trackChanges");
match mode {
"readOnly" => (!facts().exceptions).then_some("the document is protected (read only)"),
"forms" => (facts().fillable == 0).then_some("the document is protected (read only)"),
+1 -9
View File
@@ -213,15 +213,7 @@ fn tracked_changes_protection_keeps_revisions() {
select(&mut s, "text");
s.run("text.insert", &json!({"text": "words"})).unwrap();
let before = s.doc.clone();
for id in [
"review.acceptAll",
"review.rejectAll",
"review.accept",
"review.reject",
"review.acceptAndNext",
"review.rejectAndNext",
"review.trackChanges",
] {
for id in ["review.acceptAll", "review.rejectAll", "review.accept", "review.reject", "review.trackChanges"] {
assert!(s.run(id, &json!({})).is_err(), "{id}");
}
assert_eq!(s.doc, before);
+2 -35
View File
@@ -402,7 +402,7 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
}
let mut updates: Vec<(usize, String)> = Vec::new();
for (k, o) in p.objects.iter().enumerate() {
let InlineObject::Field { instr, result, locked: false, .. } = o else { continue };
let InlineObject::Field { instr, locked: false, .. } = o else { continue };
// A table formula reads the cells around its own cell again.
if instr.trim_start().starts_with('=') {
if let Some((tp, r, c)) = path.cell()
@@ -422,22 +422,7 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
"DATE" | "TIME" | "CREATEDATE" | "SAVEDATE" | "PRINTDATE" => {
let lang = field_lang(&s.doc, p, k);
let pic = date_picture(instr).unwrap_or_else(|| default_picture(&name, lang.as_deref()));
let created = s.doc.core.created.trim();
// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11). A new
// document, never saved, has no creation date yet and saving stamps now. A
// file opened without one, or with one that can't be read, keeps any result
// it already has; when inserted with none, it shows today's date (the date
// a save would stamp).
let text = if name == "CREATEDATE"
&& let Some((unix, offset)) = created_at(created)
{
crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset)
} else if name != "CREATEDATE" || result.is_empty() || (created.is_empty() && s.path.is_none()) {
crate::cmd::insert::format_date_in(&pic, lang.as_deref())
} else {
continue;
};
updates.push((k, text_result(instr, text)));
updates.push((k, text_result(instr, crate::cmd::insert::format_date_in(&pic, lang.as_deref()))));
}
"REF" | "PAGEREF" => {
let f = FieldCode::parse(instr);
@@ -587,24 +572,6 @@ fn field_lang(doc: &wordcraft_doc::Document, p: &wordcraft_doc::Paragraph, k: us
doc.styles.resolve_char(p.props.style.as_deref(), p.props_of_char(off)).lang
}
/// A core-properties creation date as seconds since the epoch and the UTC offset to show it at:
/// an instant (`2019-05-05T12:00:00Z`, any offset or fraction, or without the seconds,
/// `2019-05-05T12:00Z`, as W3CDTF allows) at the local offset, or a calendar date (`2019-05-05`)
/// at its own midnight, whatever the time zone. `None` for another form or a date before 1970.
fn created_at(stamp: &str) -> Option<(u64, i64)> {
let instant = chrono::DateTime::parse_from_rfc3339(stamp).ok().or_else(|| {
// `%:z` takes `+01:00` but not `Z`.
let utc = stamp.strip_suffix(['Z', 'z']).map(|t| format!("{t}+00:00"));
chrono::DateTime::parse_from_str(utc.as_deref().unwrap_or(stamp), "%Y-%m-%dT%H:%M%:z").ok()
});
if let Some(t) = instant {
let unix = u64::try_from(t.timestamp()).ok()?;
return Some((unix, crate::cmd::local_offset_secs(unix)));
}
let day = chrono::NaiveDate::parse_from_str(stamp, "%Y-%m-%d").ok()?;
Some((u64::try_from(day.and_hms_opt(0, 0, 0)?.and_utc().timestamp()).ok()?, 0))
}
/// Word's default date or time picture when a field instruction carries no `\@` picture switch.
fn default_picture(name: &str, lang: Option<&str>) -> String {
if name == "TIME" { "h:mm am/pm".into() } else { crate::cmd::insert::default_date_picture(lang).into() }
-70
View File
@@ -506,76 +506,6 @@ fn update_fields_all_covers_every_story() {
s.run("references.updateFields", &json!({"all": "yes"})).unwrap();
}
/// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11), not today's date.
#[test]
fn createdate_keeps_the_creation_date_on_update() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.doc.core.created = "2019-05-05T12:00:00Z".into();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
s.run("insert.field", &json!({"instr": "CREATEDATE"})).unwrap();
s.run("references.updateFields", &json!({})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
// 12:00 UTC is 5 May from UTC-12 to UTC+11:59, the next day east of that.
let unix = 1_557_057_600;
let (_, _, day, _, _) = crate::cmd::local_civil(unix, crate::cmd::local_offset_secs(unix));
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")]);
assert!(day == 5 || day == 6, "{day}");
// W3CDTF may leave out the seconds; that is the same instant.
for minutes in ["2019-05-05T12:00Z", "2019-05-05T14:00+02:00", "2019-05-05T07:00-05:00"] {
// From another date first, so an unread stamp, which keeps the result, shows.
s.doc.core.created = "2001-02-03".into();
s.run("references.updateFields", &json!({})).unwrap();
assert_eq!(fields(&s)[1].1, "2/3/2001");
s.doc.core.created = minutes.into();
s.run("references.updateFields", &json!({})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")], "{minutes}");
}
// A date without a time is that calendar day in every time zone.
s.doc.core.created = "2019-06-07".into();
s.run("references.updateFields", &json!({})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-06", "6/7/2019"]);
}
/// A creation date that can't be read leaves the field's result as it was; a document that has
/// never been saved is created now (saving stamps that time as its creation date).
#[test]
fn createdate_without_a_readable_creation_date() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.doc.core.created = "sometime in May".into();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
assert_eq!(fields(&s)[0].1, "2019-05");
// A file opened without a creation date keeps the result too.
s.doc.core.created.clear();
s.path = Some(std::env::temp_dir().join("opened.docx"));
s.run("references.updateFields", &json!({})).unwrap();
assert_eq!(fields(&s)[0].1, "2019-05");
s.path = None;
s.run("references.updateFields", &json!({})).unwrap();
assert_eq!(fields(&s)[0].1, crate::cmd::insert::format_date("yyyy-MM"));
}
/// Inserting CREATEDATE into an opened file that has no creation date (plain text, Markdown, or a
/// DOCX without `dcterms:created`) shows today's date rather than an empty result, while an
/// existing field with a cached result keeps it.
#[test]
fn createdate_inserted_into_opened_file_without_creation_date() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Notes"));
s.path = Some(std::env::temp_dir().join("notes.txt"));
s.doc.core.created.clear();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
let expected = crate::cmd::insert::format_date("yyyy-MM");
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-05".to_string(), expected.clone()]);
// An unreadable creation date behaves the same way: cached results stay, empty ones fill in.
s.doc.core.created = "sometime in May".into();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-05".to_string(), expected.clone(), expected]);
}
#[test]
fn toc_tabs_ignore_nonentries() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Before\nContents\nOld\t9\nAfter"));
-7
View File
@@ -12,7 +12,6 @@ use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
mod changes;
mod comments;
mod proofing;
pub use proofing::thesaurus_word;
pub(crate) use changes::StyleTarget;
pub use changes::{
@@ -62,12 +61,6 @@ pub fn specs() -> Vec<CommandSpec> {
.params(r#"{"next"?: bool (then select the next change)}"#),
CommandSpec::new("review.reject", "Reject", "Review › Changes", |s, v| resolve_sel_then(s, v, false))
.params(r#"{"next"?: bool (then select the next change)}"#),
CommandSpec::new("review.acceptAndNext", "Accept and Move to Next", "Review › Changes", |s, _| {
resolve_sel_then(s, &json!({"next": true}), true)
}),
CommandSpec::new("review.rejectAndNext", "Reject and Move to Next", "Review › Changes", |s, _| {
resolve_sel_then(s, &json!({"next": true}), false)
}),
CommandSpec::new("review.nextChange", "Next Change", "Review › Changes", |s, _| nav_change(s, 1)).pure(),
CommandSpec::new("review.previousChange", "Previous Change", "Review › Changes", |s, _| nav_change(s, -1)).pure(),
CommandSpec::new("review.markup", "Display for Review", "Review › Tracking", |s, v| {
+4 -30
View File
@@ -53,11 +53,10 @@ fn resolve_para(
}
// An inserted paragraph mark that is rejected, or a deleted one that is accepted, goes away:
// the next paragraph joins this one (the split is undone). A paragraph left empty goes away
// whole, so the next one keeps its own style and numbering, as in Word. The end mark of a
// story or cell has no follower to join here; `resolve_all` removes the whole paragraph
// instead when one is left over (see `remove_trailing_para`). An empty paragraph whose mark
// carries a section break goes whole too: its section joins the following one, as when the
// break is deleted (#5667). Joining instead gave the next paragraph its properties.
// whole, so the next one keeps its own style and numbering, as in Word. The mark at the end
// of a story or cell can't go, so it just stops being a revision. An empty paragraph whose
// mark carries a section break goes whole too: its section joins the following one, as when
// the break is deleted (#5667). Joining instead gave the next paragraph its properties.
if (del.is_some() && accept) || (ins.is_some() && !accept) {
let sectioned = story == StoryRef::Body
&& path.0.len() == 1
@@ -77,23 +76,6 @@ fn resolve_para(
Ok(())
}
/// Remove the whole paragraph at `path` when a whole-paragraph revision on its mark resolved to
/// removal and it is the last paragraph in its container and carries no section break: it goes
/// away, as long as the container keeps another paragraph (a story or cell must never end up
/// with none). `false`, changing nothing, otherwise.
fn remove_trailing_para(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path) -> Result<bool, CmdError> {
let Some(p) = s.doc.para(story, path) else { return Ok(false) };
if !p.is_empty() || p.section.is_some() {
return Ok(false);
}
let Some(container) = s.doc.container(story, path) else { return Ok(false) };
if container.iter().filter(|b| b.as_para().is_some()).count() <= 1 {
return Ok(false);
}
s.doc.remove_block(story, path)?;
Ok(true)
}
/// Accept or reject the changes of the table cell `path` is in: the table's, its row's and the
/// cell's own. Returns whether there were any.
fn resolve_cell(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, accept: bool) -> Result<bool, CmdError> {
@@ -263,16 +245,8 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
for st in stories {
for path in s.doc.para_paths(st).into_iter().rev() {
// A whole-paragraph mark that resolves to removal at the end of its container takes
// the paragraph with it (there is no follower for `resolve_para` to join). A paragraph
// followed by a table is not the end: removing it could make two tables adjacent.
let is_last = s.doc.block(st, &path.with_last(path.last().saturating_add(1))).is_none();
let trailing = is_last && s.doc.para(st, &path).is_some_and(|p| (p.mark.del.is_some() && accept) || (p.mark.ins.is_some() && !accept));
let len = s.doc.para(st, &path).map(|p| p.len()).unwrap_or(0);
resolve_para(s, st, &path, (0, len), (true, true), accept)?;
if trailing {
remove_trailing_para(s, st, &path)?;
}
}
}
// Tables, rows, cells, sections and style definitions.
+4 -16
View File
@@ -128,20 +128,6 @@ pub(super) fn suggestions(s: &mut Session, v: &Value) -> CmdResult {
}
}
/// The word at the caret that the thesaurus looks up and a chosen synonym replaces: the word unit
/// without the spaces after it or the quotes around it, so `‘good’` is `good` and its quotes stay
/// when it is replaced; an apostrophe inside a word (`don’t`) is kept (#6517).
pub fn thesaurus_word(s: &Session) -> Option<(Pos, Pos)> {
let f = &s.sel.focus;
let p = s.doc.para_at(f)?;
let (a, b) = p.word_at(f.off);
let w = p.text.get(a..b)?;
let edge = |c: char| c.is_whitespace() || matches!(c, '’' | '‘' | '\'');
let start = a + (w.len() - w.trim_start_matches(edge).len());
let end = (a + w.trim_end_matches(edge).len()).max(start);
Some((Pos { off: start, ..f.clone() }, Pos { off: end, ..f.clone() }))
}
/// A tiny built-in thesaurus of common words (our own list).
pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult {
const T: &[(&str, &[&str])] = &[
@@ -178,8 +164,10 @@ pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult {
let word = match p::str(v, "word") {
Some(w) => w.to_lowercase(),
None => {
let (a, b) = thesaurus_word(s).ok_or_else(|| CmdError::Failed("no word".into()))?;
s.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).unwrap_or("").to_lowercase()
let f = s.sel.focus.clone();
let p = s.doc.para_at(&f).ok_or_else(|| CmdError::Failed("no word".into()))?;
let (a, b) = p.word_at(f.off);
p.text.get(a..b).unwrap_or("").trim().to_lowercase()
}
};
let syn = T.iter().find(|(w, _)| *w == word).map(|(_, l)| l.to_vec()).unwrap_or_default();
+1 -15
View File
@@ -703,20 +703,6 @@ fn accept_and_reject_can_move_to_the_next_change() {
}
}
#[test]
fn review_shortcut_commands_resolve_and_select_the_next_change_without_parameters() {
for (command, accept) in [("review.acceptAndNext", true), ("review.rejectAndNext", false)] {
let mut s = three_changes();
s.run("caret.docStart", &json!({})).unwrap();
s.run(command, &serde_json::Value::Null).unwrap();
let remaining = change_spans(&mut s);
assert_eq!(remaining.iter().map(|change| change.0.as_str()).collect::<Vec<_>>(), ["delete", "insert"], "{command}");
let (_, start, end) = remaining[0];
assert_eq!(selected(&s), (start as usize, end as usize), "{command}: the deletion is selected next");
assert_eq!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).starts_with("new "), accept, "{command}");
}
}
/// With the caret on no change, Accept and Move to Next selects the next change without
/// resolving it, as Accept and Next Change do.
#[test]
@@ -1262,7 +1248,7 @@ fn rtf_tracked_changes_accept_and_reject_after_opening_and_round_trip() {
let rtf: &[u8] = br"{\rtf1\ansi\deff0{\fonttbl{\f0 Arial;}}{\*\revtbl {Unknown;}{Alice;}{Bob;}}
\pard Keep {\revised\revauth1\revdttm-1480361314 added }text{\deleted\revauthdel2\revdttmdel-2016341499 gone} end{\revised\revauth1\revdttm-1480361314\deleted\revauthdel2\revdttmdel-2016341499 both}.\par}";
let opened = wordcraft_formats::rtf::import(rtf).unwrap();
let again = wordcraft_formats::rtf::import(wordcraft_formats::rtf::export(&opened).unwrap().as_bytes()).unwrap();
let again = wordcraft_formats::rtf::import(wordcraft_formats::rtf::export(&opened).as_bytes()).unwrap();
for doc in [opened, again] {
for (cmd, want) in [("review.acceptAll", "Keep added text end."), ("review.rejectAll", "Keep text gone end.")] {
let mut s = Session::new(doc.clone());
@@ -136,30 +136,6 @@ fn a_selected_column_is_edited_cell_by_cell() {
assert_eq!(s.cell_range().map(|r| r.cols), Some((1, 1)), "undo brings the column selection back");
}
/// Toggling a format on a selected table column follows the first character in document order (#8589).
#[test]
fn toggle_on_a_selected_table_column_follows_first_character() {
let toggled = |bold_row: usize| -> Vec<bool> {
let mut s = table_session(3, 3);
fill(&mut s);
let p = cell_pos(&s, bold_row, 1);
s.sel = Selection { anchor: p.clone(), focus: Pos { off: 4, ..p } };
s.run("format.bold", &json!({"value": true})).unwrap();
// Start from the bottom row so the caret is not on row 0.
s.sel = Selection::caret(cell_pos(&s, 2, 1));
s.run("table.selectColumn", &json!({})).unwrap();
s.run("format.bold", &json!({})).unwrap();
for r in 0..3 {
assert!(!bold(&s, r, 0) && !bold(&s, r, 2), "row {r}'s other cells stay plain");
}
(0..3).map(|r| bold(&s, r, 1)).collect()
};
// First row bold, later rows plain: Bold turns off across the column.
assert_eq!(toggled(0), vec![false, false, false]);
// First row plain, middle row bold: Bold turns on across the column.
assert_eq!(toggled(1), vec![true, true, true]);
}
/// Numbering a column numbers its cells as one list, like Word.
#[test]
fn numbering_a_column_makes_one_list() {
+6 -5
View File
@@ -1622,11 +1622,12 @@ fn block_text(b: &Block, depth: usize) -> String {
/// the paragraph is empty (`format` returns early for a length-0 range). Walks nested tables
/// iteratively, without recursion or depth truncation.
///
/// A whole-paragraph revision on the last paragraph of a story or cell is removed together with
/// the paragraph on Accept/Reject All (see `remove_trailing_para` in `review::changes`), except
/// where the paragraph carries a section break or is the container's only paragraph. A
/// non-terminal section-carrying paragraph is removed whole too: `resolve_para` removes the
/// section break first (#5734, issue #5667), so the following paragraph keeps its own properties.
/// Known limitation: resolving a revision needs a following paragraph, so a paragraph inserted at
/// the very end (rejected) or deleted from the very end (accepted) still leaves one empty
/// paragraph. That is a separate follow-up, not handled here. A section-carrying inserted
/// paragraph is not such a case: `resolve_para` removes the section break first (#5734, issue
/// #5667), so rejecting it takes the paragraph out whole and the following paragraph keeps its
/// own properties.
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
let mut out = b.clone();
let mut todo = vec![&mut out];
+14 -77
View File
@@ -105,49 +105,31 @@ fn compare_keeps_another_authors_deletion_stamp() {
}
#[test]
fn compare_terminal_inserted_paragraph_resolves_fully() {
// A paragraph inserted at the very end is removed whole when rejected, leaving no empty
// paragraph behind.
fn compare_pins_the_terminal_inserted_paragraph_limitation() {
// Characterizes the limitation documented on `mark_block` (compare.rs): resolving a revision
// needs a following paragraph, so a paragraph inserted at the very end is rejected but leaves
// one empty paragraph behind. Flip this test when the follow-up fix lands.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nC"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "rejecting a terminal inserted paragraph left an empty paragraph behind");
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\n", "the rejected terminal paragraph still leaves a line");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 1, "the rejected terminal paragraph is left as one empty paragraph");
}
#[test]
fn compare_terminal_deleted_paragraph_resolves_fully() {
// The mirror of `compare_terminal_inserted_paragraph_resolves_fully`: a paragraph deleted
// from the very end is removed whole when accepted, leaving no empty paragraph behind.
fn compare_pins_the_terminal_deleted_paragraph_limitation() {
// The mirror of `compare_pins_the_terminal_inserted_paragraph_limitation`: a paragraph deleted
// from the very end is accepted but still leaves one empty paragraph. Characterizes the
// limitation documented on `mark_block` (compare.rs); flip when the follow-up fix lands.
let mut s = Session::new(Document::from_text("A\nB\nC"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "accepting a terminal deleted paragraph left an empty paragraph behind");
}
#[test]
fn reject_all_keeps_an_empty_inserted_paragraph_between_tables() {
// An empty paragraph between two tables is not the container's last block: removing it
// would make the tables adjacent, and they would join into one on reopen. Reject All only
// clears its mark.
use wordcraft_doc::{Block, Paragraph, para_block};
let mut doc = Document::from_text("");
doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Insert, "Alice", ""));
let table = || std::sync::Arc::new(Block::Table(wordcraft_doc::table::Table::new(1, 1, 100.0)));
let mut between = Paragraph::default();
between.mark.ins = Some(0);
doc.body = vec![table(), para_block(between), table(), para_block(Paragraph::with_text("end", Default::default()))];
let mut s = Session::new(doc);
s.run("review.rejectAll", &json!({})).unwrap();
let kinds: Vec<bool> = s.doc.body.iter().map(|b| matches!(**b, Block::Table(_))).collect();
assert_eq!(kinds, [true, false, true, false]);
let kept = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
assert!(kept.is_empty() && kept.mark.ins.is_none(), "{kept:?}");
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\n", "the accepted terminal deletion still leaves a line");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 1, "the accepted terminal deletion is left as one empty paragraph");
}
#[test]
@@ -219,51 +201,6 @@ fn compare_pins_accepting_a_deleted_section_keeps_the_next_paragraphs_style() {
assert_eq!(body.props.style.as_deref(), Some("Heading1"), "the following paragraph keeps its own properties (fixed on main by #5734)");
}
#[test]
fn compare_marks_the_last_paragraphs_mark() {
// Inserted last paragraph: rejecting removes it whole.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
assert!(s.doc.body[2].as_para().unwrap().mark.ins.is_some());
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0);
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nNEW");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0);
// Deleted last paragraph: accepting removes it whole.
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
assert!(s.doc.body[2].as_para().unwrap().mark.del.is_some());
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0);
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nOLD");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0);
}
#[test]
fn compare_keeps_the_only_paragraphs_mark() {
let mut s = Session::new(Document::from_text(""));
s.doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Insert, s.author.clone(), ""));
s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.ins = Some(0);
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.body.len(), 1);
assert!(s.doc.body[0].as_para().unwrap().mark.ins.is_none());
}
#[test]
fn compare_options_ignore_case_and_white_space() {
let original = "The Cat sat.\nTwo spaces here.";
-23
View File
@@ -337,29 +337,6 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
/// A document made from a template is created now, not when the template was: it has no
/// creation date until it is saved, so CREATEDATE in it shows today.
#[test]
fn new_from_template_has_no_creation_date_of_its_own_yet() {
let d = scratch("created");
let path = d.join("Dated.dotx");
let mut t = Session::new(wordcraft_doc::Document::new());
t.run("document.setText", &json!({"text": "Dated"})).unwrap();
t.doc.core.created = "2019-05-05T12:00:00Z".into();
crate::io::save_path(&path, &t.doc).unwrap();
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("file.newFromTemplate", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(s.doc.core.created, "");
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy""#, "result": "2019"})).unwrap();
s.run("references.updateFields", &json!({})).unwrap();
assert!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).contains(&crate::cmd::insert::format_date("yyyy")));
// The template itself keeps its date.
let mut again = Session::new(wordcraft_doc::Document::new());
again.run("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(again.doc.core.created, "2019-05-05T12:00:00Z");
let _ = std::fs::remove_dir_all(&d);
}
/// #3433: a template the platform hands the app takes an untouched blank document's place
/// (`replaceBlank`), as a file `file.open` opens does; otherwise, and without the flag, the
/// new document opens beside the others, as File › New's does. Either way the template on
+3 -6
View File
@@ -284,17 +284,14 @@ fn import_chunk(c: &wordcraft_docx::AltChunk) -> Option<Document> {
|| matches!(ext.as_str(), "mht" | "mhtml")
|| mht::is_mht(b)
{
mht::import(b).map_err(|e| log::warn!("altChunk {}: the MHT cannot be read: {e}", c.part)).ok()?
mht::import(b)
} else if ct.contains("rtf") || ext == "rtf" || b.starts_with(b"{\\rtf") {
rtf::import(b).map_err(|e| log::warn!("altChunk {}: the RTF cannot be read: {e}", c.part)).ok()?
rtf::import(b).ok()?
} else if ct.contains("html") || matches!(ext.as_str(), "html" | "htm" | "xhtml") {
html::import_page(&html::decode_as(b, charset), &|_| None)
.map_err(|e| log::warn!("altChunk {}: the HTML cannot be read: {e}", c.part))
.ok()?
} else if ct == "text/plain" || ext == "txt" {
txt::import(b)
} else {
log::warn!("altChunk {}: its type ({ct}) is not one WordCraft reads", c.part);
return None;
};
// shortcut: pictures fit the chunk's default page, not the section it lands in; fit them there if wide pictures in chunks overflow narrow sections.
@@ -499,7 +496,7 @@ pub fn open_path_in(path: &std::path::Path, password: Option<&str>, region: &wor
// Pictures referenced by a relative path load from beside the HTML file.
let images = LocalImages::new(path.parent().unwrap_or(std::path::Path::new("")));
let html = wordcraft_formats::html::decode(&bytes);
let mut doc = wordcraft_formats::html::import_on(&html, &|src| images.load(src), &region_page(region))?;
let mut doc = wordcraft_formats::html::import_on(&html, &|src| images.load(src), &region_page(region));
fit_pictures(&mut doc);
opened(&mut doc);
return Ok((doc, false));
-1
View File
@@ -16,7 +16,6 @@ pub mod io;
mod io_ext;
pub mod keymap;
pub(crate) mod locale;
pub mod malloc_tuning;
pub mod math_gallery;
pub mod packs;
pub(crate) mod prefs;
-80
View File
@@ -1,80 +0,0 @@
//! glibc malloc tuning for native binaries (adapted from Storytold's `photocraft` #8743).
//!
//! With glibc's defaults, transient large buffers (page render targets, autofit tables, decoded
//! images) raise glibc's dynamic `mmap` and `trim` thresholds (up to 32 MiB on 64-bit), so later
//! heap allocations stay in glibc arenas instead of returning freed pages to the OS. Fixing
//! `MALLOC_TRIM_THRESHOLD_` at 128 KiB (`131072`) disables dynamic threshold growth so freed
//! pages above 128 KiB are returned cleanly while preserving multi-arena allocation throughput.
//!
//! Because glibc reads its malloc environment variables once at process start and mutating the
//! process environment in Rust requires `unsafe` (forbidden workspace-wide) and happens after glibc
//! initialization, [`apply`] re-executes the current executable via `exec` when no malloc tuning
//! variable is already set (keeping PID, argv, `argv[0]`, and environment). Setting any `MALLOC_*`
//! variable or `glibc.malloc.*` tunable opts out.
use std::ffi::OsString;
/// The glibc environment variable [`apply`] sets.
pub const TRIM_THRESHOLD_VAR: &str = "MALLOC_TRIM_THRESHOLD_";
/// Fixed trim threshold (128 KiB, glibc's initial default) to disable dynamic threshold escalation.
pub const TRIM_THRESHOLD: &str = "131072";
/// glibc malloc variables that indicate callers or wrappers already configured malloc tuning.
const MALLOC_VARS: [&str; 5] = [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX"];
/// Whether startup should re-execute with [`TRIM_THRESHOLD_VAR`] set, given an environment reader:
/// true only when no malloc variable or `glibc.malloc.*` tunable is present.
pub fn needs_restart(var: impl Fn(&str) -> Option<OsString>) -> bool {
if MALLOC_VARS.iter().any(|v| var(v).is_some()) {
return false;
}
!var("GLIBC_TUNABLES").is_some_and(|t| t.to_string_lossy().contains("glibc.malloc."))
}
/// Re-execute this binary with [`TRIM_THRESHOLD_VAR`] set when [`needs_restart`] is true.
///
/// Must be called early in `main()` before worker threads start or logs/crash hooks initialize.
/// Returns immediately if tuning variables are already present or if `exec` fails.
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub fn apply() {
use std::io::Write;
use std::os::unix::process::CommandExt;
if !needs_restart(|k| std::env::var_os(k)) {
return;
}
let Ok(exe) = std::env::current_exe() else { return };
let mut args = std::env::args_os();
let mut cmd = std::process::Command::new(exe);
if let Some(argv0) = args.next() {
cmd.arg0(argv0);
}
// `exec` replaces the current process in place and only returns on error.
let err = cmd.args(args).env(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD).exec();
let _ = writeln!(std::io::stderr(), "wordcraft: could not restart with {TRIM_THRESHOLD_VAR} set ({err})");
}
/// No-op on platforms without Linux glibc.
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
pub fn apply() {}
#[cfg(test)]
mod tests {
use super::*;
fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
}
#[test]
fn restarts_only_without_malloc_tuning() {
assert!(needs_restart(env(&[])));
assert!(needs_restart(env(&[("HOME", "/home/a"), ("GLIBC_TUNABLES", "glibc.cpu.hwcaps=-AVX2")])));
assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD)])), "re-executed process stops");
assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, "")])), "any explicit value opts out");
assert!(!needs_restart(env(&[("MALLOC_MMAP_THRESHOLD_", "1048576")])));
assert!(!needs_restart(env(&[("MALLOC_ARENA_MAX", "2")])));
assert!(!needs_restart(env(&[("GLIBC_TUNABLES", "glibc.malloc.trim_threshold=0")])));
}
}
+17 -2
View File
@@ -148,6 +148,19 @@ pub fn paper(v: &Value) -> Result<Option<(&'static str, f32, f32)>, CmdError> {
}
}
/// Physical output dimensions from a system queue's form or a standard document paper.
fn paper_size(v: &Value) -> Result<Option<(f32, f32)>, CmdError> {
if let Some(Value::Array(size)) = v.get("paper") {
let invalid = || CmdError::Params("paper must be [width, height] in points, both from 1 to 14400".into());
let side = |value: &Value| value.as_f64().filter(|n| (1.0..=14_400.0).contains(n)).map(|n| n as f32).ok_or_else(invalid);
return match size.as_slice() {
[width, height] => Ok(Some((side(width)?, side(height)?))),
_ => Err(invalid()),
};
}
Ok(paper(v)?.map(|(_, width, height)| (width, height)))
}
/// Validate the physical sheet layout without touching document page setup.
pub fn imposition(v: &Value) -> Result<wordcraft_pdf::imposition::Imposition, CmdError> {
match v.get("pagesPerSheet") {
@@ -164,7 +177,7 @@ pub fn imposition(v: &Value) -> Result<wordcraft_pdf::imposition::Imposition, Cm
/// Resolve physical paper orientation for imposed jobs; ordinary export keeps its existing policy.
fn imposed_paper(v: &Value, lay: &DocLayout, pages: &[usize]) -> Result<Option<(f32, f32)>, CmdError> {
let paper = paper(v)?.map(|(_, w, h)| (w, h));
let paper = paper_size(v)?;
if imposition(v)? == Imposition::Single {
return Ok(paper);
}
@@ -361,11 +374,13 @@ mod tests {
let (bytes, _) = s.print_pdf(&json!({"range": "current", "paper": name})).unwrap();
assert_eq!(media(&bytes), vec![want], "{name}");
}
let (custom, _) = s.print_pdf(&json!({"range": "current", "paper": [421.0, 639.0]})).unwrap();
assert_eq!(media(&custom), vec![(421.0, 639.0)]);
for none in [json!(null), json!(""), json!("none"), json!("Document")] {
let (bytes, _) = s.print_pdf(&json!({"range": "current", "paper": none})).unwrap();
assert_eq!(media(&bytes), media(&own));
}
for bad in [json!("Quarto"), json!(5), json!({"w": 1}), json!("x".repeat(10_000))] {
for bad in [json!("Quarto"), json!(5), json!({"w": 1}), json!("x".repeat(10_000)), json!([421.0]), json!([0, 639]), json!([421, 14401])] {
assert!(s.print_pdf(&json!({"paper": bad})).is_err(), "{bad}");
}
assert_eq!((s.doc.last_section.page_w, s.doc.last_section.page_h, s.rev()), (w, h, rev), "the document is unchanged");
+1 -33
View File
@@ -80,12 +80,8 @@ impl Session {
};
let l = Arc::new(wordcraft_layout::layout(&self.doc, &mut self.cache, &opts));
let [newest, _] = std::mem::take(&mut self.layout);
// Only preserve the alternate layout slot for the current document revision (e.g. Print vs
// Web/Draft toggling); a superseded revision can never hit `fits()` again and would keep an
// obsolete DocLayout live in memory.
let prev = newest.filter(|e| e.0 == rev);
self.layout =
[Some((rev, width, height, mode, spacing, l.clone(), self.view.proofing, outline, deleted, self.view.numeral, typing, shown)), prev];
[Some((rev, width, height, mode, spacing, l.clone(), self.view.proofing, outline, deleted, self.view.numeral, typing, shown)), newest];
l
}
@@ -279,31 +275,3 @@ impl Session {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn layout_drops_stale_revision_slot_but_keeps_same_revision_mode() {
let mut session = Session::new(Document::new());
let first = session.layout();
let first_weak = Arc::downgrade(&first);
drop(first);
// Switching view mode at the same revision keeps the prior layout in `layout[1]`.
session.view.mode = ViewMode::Draft;
let same_rev_other_mode = session.layout();
assert!(first_weak.upgrade().is_some(), "same-revision alternate view mode stays cached");
let draft_weak = Arc::downgrade(&same_rev_other_mode);
drop(same_rev_other_mode);
// Advancing `rev` makes earlier layouts unreachable: building the new layout must drop them.
session.run("text.insert", &serde_json::json!({"text": "hello"})).expect("insert");
let after_edit = session.layout();
assert!(draft_weak.upgrade().is_none(), "superseded revision layout must be dropped");
assert!(first_weak.upgrade().is_none(), "older revision layout must not remain live");
drop(after_edit);
}
}
+4 -18
View File
@@ -27,18 +27,13 @@ struct ElsewhereContext {
blocks_before: Option<std::collections::BTreeMap<String, Fragment>>,
default_language_before: Option<String>,
pending_application_change_before: bool,
/// The tracked move the command would have dropped, put back when it fails.
move_before: Option<crate::cmd::moves::PendingMove>,
}
impl Session {
fn leave_math_for_command(&mut self, id: &str) {
self.math_left = false;
if self.math.is_some()
&& (id.starts_with("text.")
|| id.starts_with("caret.")
|| id.starts_with("select.")
|| (id.starts_with("edit.paste") && id != "edit.pasteFormat"))
&& (id.starts_with("text.") || id.starts_with("caret.") || id.starts_with("select.") || id.starts_with("edit.paste"))
&& let Some(m) = self.math.take()
{
let off = m.at.off + wordcraft_doc::para::OBJ.len_utf8();
@@ -218,9 +213,7 @@ impl Session {
} else if spec.id.starts_with("caret.") {
self.typing_open = false;
}
// Only the paste right after a tracked cut makes it a move. A command that fails
// changed nothing, so the move it would have dropped is put back (below).
let move_before = self.pending_move.clone();
// Only the paste right after a tracked cut makes it a move.
if (spec.mutates || matches!(id, "edit.undo" | "edit.undoTo" | "edit.redo")) && !matches!(id, "edit.cut" | "edit.paste" | "edit.pasteSpecial")
{
self.pending_move = None;
@@ -246,7 +239,7 @@ impl Session {
};
if self.document_id != home || (result.is_err() && self.order.iter().any(|d| *d >= mark)) {
return self.finish_elsewhere(
ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before, move_before },
ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before },
result,
);
}
@@ -311,9 +304,6 @@ impl Session {
self.join_anchor = false;
}
}
// The command failed, so the tracked move it would have dropped is still there:
// the paste after it is a move, as it was before the command.
self.pending_move = move_before;
if let Some(dirty) = dirty_before {
self.dirty = dirty;
}
@@ -492,8 +482,7 @@ impl Session {
/// as it was (opening a document is no edit to undo there). Failed: the documents the command opened close again and the first document is
/// active and as it was.
fn finish_elsewhere(&mut self, context: ElsewhereContext, result: Result<Value, CmdError>) -> Result<Value, CmdError> {
let ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before, move_before } =
context;
let ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before } = context;
// Another document is a state change the input method has to see, never an IME edit.
self.ime_edit_outcome = ImeEditOutcome::default();
match &result {
@@ -525,9 +514,6 @@ impl Session {
self.undo_evicted = ev;
self.column = c;
}
// The command failed, so the tracked move it would have dropped is still
// there: the paste after it is a move, as it was before the command.
self.pending_move = move_before;
}
if let Some(b) = blocks_before {
self.building_blocks = b;
+3 -424
View File
@@ -293,15 +293,6 @@ fn custom_dictionary_words_persist_through_their_file() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn confined_sessions_test_is_native_only() {
let source = include_str!("tests.rs");
assert!(source.contains(
"#[cfg(not(target_arch = \"wasm32\"))]\n#[test]\nfn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots()"
));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
@@ -1052,180 +1043,6 @@ fn bold_toggles_selection_and_caret_word() {
assert_eq!(p.props_of_char(9).italic, None);
}
/// A partly formatted selection toggles by its first character, as Word does (#6516).
#[test]
fn toggles_on_mixed_selection_follow_first_character() {
// `Abc abc` with `fmt` set by `cmd`, then `cmd` with `v` on the selection `from` → `to`.
let toggled = |cmd: &str, fmt: (usize, usize), from: usize, to: usize, v: serde_json::Value| -> String {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Abc abc"}));
let sel = |s: &mut Session, a: usize, b: usize| {
run(s, "select.range", json!({"anchor": {"block": 0, "off": a}, "focus": {"block": 0, "off": b}}));
};
sel(&mut s, fmt.0, fmt.1);
run(&mut s, cmd, json!({"value": true}));
sel(&mut s, from, to);
run(&mut s, cmd, v);
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
(0..7)
.map(|i| {
let c = p.props_of_char(i);
match cmd {
"format.italic" => c.italic == Some(true),
"format.underline" => c.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None),
_ => c.bold == Some(true),
}
})
.map(|on| if on { 'F' } else { '.' })
.collect()
};
let t = || json!({});
for cmd in ["format.bold", "format.italic", "format.underline"] {
// `FFF....`: a selection starting on formatted text removes the format from all of it.
assert_eq!(toggled(cmd, (0, 3), 2, 5, t()), "FF.....", "{cmd}");
assert_eq!(toggled(cmd, (0, 3), 0, 7, t()), ".......", "{cmd}");
assert_eq!(toggled(cmd, (0, 3), 1, 7, t()), "F......", "{cmd}");
// Made right to left: still the first character in document order.
assert_eq!(toggled(cmd, (0, 3), 5, 2, t()), "FF.....", "{cmd}");
assert_eq!(toggled(cmd, (0, 3), 7, 0, t()), ".......", "{cmd}");
// `....FFF`: a selection starting on plain text applies it to all of it.
assert_eq!(toggled(cmd, (4, 7), 0, 7, t()), "FFFFFFF", "{cmd}");
// An explicit value still sets.
assert_eq!(toggled(cmd, (0, 3), 0, 7, json!({"value": true})), "FFFFFFF", "{cmd}");
assert_eq!(toggled(cmd, (4, 7), 0, 7, json!({"value": false})), ".......", "{cmd}");
}
}
/// A selection that starts in an empty paragraph: Word decides from the first text character, not
/// from the empty paragraph's mark (observed in Word for Windows, #6516 review).
#[test]
fn toggle_on_a_selection_from_an_empty_paragraph_follows_the_first_text() {
let toggled = |mark_bold: bool, text_bold: bool| -> Option<bool> {
let mut s = s();
run(&mut s, "text.newParagraph", json!({}));
run(&mut s, "text.insert", json!({"text": "abc"}));
let first = Pos::body(0, 0);
s.doc.para_mut(first.story, &first.path).unwrap().mark.bold = Some(mark_bold);
run(&mut s, "select.range", json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 1, "off": 3}}));
run(&mut s, "format.bold", json!({"value": text_bold}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 1, "off": 3}}));
run(&mut s, "format.bold", json!({}));
s.doc.para_at(&Pos::body(1, 0)).unwrap().props_of_char(0).bold
};
// A bold empty paragraph before plain text: Bold goes on.
assert_eq!(toggled(true, false), Some(true));
// A plain empty paragraph before bold text: Bold comes off.
assert_eq!(toggled(false, true), Some(false));
}
/// Toggling a format on a selected text box follows the first character of its text (#8589).
#[test]
fn toggle_on_a_selected_text_box_follows_first_character() {
let toggled = |first_bold: bool, second_bold: bool, leading_empty_bold: Option<bool>| -> String {
let mut s = s();
let id = run(&mut s, "insert.textBox", json!({}))["story"].as_u64().unwrap() as u32;
let boxed = StoryRef::Part(id);
if let Some(mark_bold) = leading_empty_bold {
s.doc.para_mut(boxed, &wordcraft_doc::Path::top(0)).unwrap().mark.bold = Some(mark_bold);
run(&mut s, "text.newParagraph", json!({}));
}
let text_block = usize::from(leading_empty_bold.is_some());
run(&mut s, "text.insert", json!({"text": "ab"}));
let box_pos = |off| Pos { story: boxed, path: wordcraft_doc::Path::top(text_block), off };
run(&mut s, "select.range", json!({"anchor": box_pos(0), "focus": box_pos(1)}));
run(&mut s, "format.bold", json!({"value": first_bold}));
run(&mut s, "select.range", json!({"anchor": box_pos(1), "focus": box_pos(2)}));
run(&mut s, "format.bold", json!({"value": second_bold}));
let anchor = s.doc.text_box_anchor(id).unwrap();
run(&mut s, "select.range", json!({"anchor": Pos { off: anchor.off - "\u{FFFC}".len(), ..anchor.clone() }, "focus": anchor}));
run(&mut s, "format.bold", json!({}));
let p = s.doc.para(boxed, &wordcraft_doc::Path::top(text_block)).unwrap();
(0..2).map(|i| if p.props_of_char(i).bold == Some(true) { 'B' } else { '.' }).collect()
};
// First character bold, second plain: Bold turns off across the box.
assert_eq!(toggled(true, false, None), "..");
// First character plain, second bold: Bold turns on across the box.
assert_eq!(toggled(false, true, None), "BB");
// A bold empty paragraph at the top of the box does not override plain text after it.
assert_eq!(toggled(false, true, Some(true)), "BB");
}
/// Toggling a format on a column block follows the first character in document order (#8589).
#[test]
fn toggle_on_a_column_block_follows_first_character() {
let toggled = |bold_row: usize, top_to_bottom: bool| -> Vec<bool> {
let mut s = column_doc();
run(&mut s, "select.range", json!({"anchor": {"block": bold_row, "off": 2}, "focus": {"block": bold_row, "off": 4}}));
run(&mut s, "format.bold", json!({"value": true}));
let (a, f) = if top_to_bottom { (Pos::body(0, 2), Pos::body(2, 4)) } else { (Pos::body(2, 4), Pos::body(0, 2)) };
run(&mut s, "select.column", json!({"anchor": a, "focus": f}));
run(&mut s, "format.bold", json!({}));
(0..3).map(|i| s.doc.para_at(&Pos::body(i, 0)).unwrap().props_of_char(2).bold == Some(true)).collect()
};
// Row 0 bold, rows 1-2 plain: Bold turns off across the block even when selected bottom-to-top.
assert_eq!(toggled(0, true), vec![false, false, false]);
assert_eq!(toggled(0, false), vec![false, false, false]);
// Row 0 plain, row 1 bold: Bold turns on across the block even when selected bottom-to-top.
assert_eq!(toggled(1, true), vec![true, true, true]);
assert_eq!(toggled(1, false), vec![true, true, true]);
}
#[test]
fn bold_at_a_caret_takes_a_word_with_a_typographic_apostrophe() {
// Word bolds `don’t` and `dogs’` whole: `’` is part of the word like `'` (#6517).
let bold_word = |text: &str, caret: usize| {
let mut s = s();
run(&mut s, "text.insert", json!({"text": text}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}}));
run(&mut s, "format.bold", json!({}));
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap().clone();
p.text.char_indices().filter(|&(i, _)| p.props_of_char(i).bold == Some(true)).map(|(_, c)| c).collect::<String>()
};
assert_eq!(bold_word("don’t stop", 1), "don’t");
assert_eq!(bold_word("the dogs’ bone", 5), "dogs’");
assert_eq!(bold_word("’tis here", 3), "’tis");
}
#[test]
fn select_word_takes_a_typographic_apostrophe() {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "don’t stop"}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 1}}));
run(&mut s, "select.word", json!({}));
let (a, b) = s.sel.ordered();
assert_eq!((a.off, b.off), (0, 8), "`don’t ` with its trailing space, as Word selects it (#6517)");
}
#[test]
fn thesaurus_at_a_caret_looks_up_a_quoted_word_without_its_quotes() {
// The word unit now takes `’`, so `‘good’` gives `good’`; the lookup drops enclosing quotes.
let mut s = s();
run(&mut s, "text.insert", json!({"text": "a ‘good’ day"}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 6}}));
let r = run(&mut s, "review.thesaurus", json!({}));
assert_eq!(r["word"], json!("good"));
assert!(r["synonyms"].as_array().is_some_and(|a| !a.is_empty()), "{r}");
}
#[test]
fn a_synonym_replaces_the_word_and_keeps_its_quotes() {
// The range a chosen synonym replaces (the context menu's): the word without its quotes or the
// space after it, while an apostrophe inside a word stays part of it (#6517).
let word = |text: &str, caret: usize| {
let mut s = s();
run(&mut s, "text.insert", json!({"text": text, "raw": true}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}}));
let (a, b) = crate::cmd::review::thesaurus_word(&s).unwrap();
s.set_selection(crate::Selection { anchor: a, focus: b });
run(&mut s, "text.insert", json!({"text": "fine", "raw": true}));
s.doc.plain_text(StoryRef::Body)
};
assert_eq!(word("a ‘good’ day", 6), "a ‘fine’ day");
assert_eq!(word("a 'good' day", 4), "a 'fine' day");
assert_eq!(word("a good day", 3), "a fine day");
assert_eq!(word("don’t go", 1), "fine go");
}
#[test]
fn border_toggles_and_saves() {
use wordcraft_doc::props::Border;
@@ -2237,88 +2054,6 @@ fn paste_merge_formatting_keeps_bold_and_italic_in_a_complex_script_run() {
assert!(r.bold_cs, "drawn bold as complex script");
}
#[test]
fn paste_merge_formatting_leaves_plain_what_the_source_draws_plain() {
// #4852 review: a run marked `w:cs` is bold and italic only by `w:bCs` and `w:iCs`, so one
// with `w:b` and `w:i` alone is drawn plain and pastes plain; one with `w:bCs` pastes bold.
let mut s = s();
run(&mut s, "document.setText", json!({"text": "x"}));
run(&mut s, "caret.docEnd", json!({}));
let pasted = |s: &Session, props: wordcraft_doc::CharProps| {
let mut frag = wordcraft_doc::edit::Fragment::from_text("ไทย");
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| p.runs.iter_mut().for_each(|r| r.props = props.clone()));
}
crate::cmd::paste::merge_formatting(s, &mut frag);
let mut out = Vec::new();
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| out.extend(p.runs.iter().map(|r| s.doc.styles.resolve_char(None, &r.props))));
}
out
};
let cs = wordcraft_doc::CharProps { cs: Some(true), bold: Some(true), italic: Some(true), ..Default::default() };
for r in pasted(&s, cs.clone()) {
assert!(!r.bold && !r.bold_cs && !r.italic && !r.italic_cs, "{r:?}");
}
for r in pasted(&s, wordcraft_doc::CharProps { bold_cs: Some(true), ..cs }) {
assert!(r.bold && r.bold_cs && !r.italic_cs, "{r:?}");
}
// An unmarked run shows `w:b` in both scripts.
for r in pasted(&s, wordcraft_doc::CharProps { bold: Some(true), ..Default::default() }) {
assert!(r.bold && r.bold_cs, "{r:?}");
}
}
#[test]
fn paste_merge_formatting_keeps_a_character_styles_emphasis_not_a_paragraph_styles() {
// #7177 review, measured in Word for Windows: Merge Formatting keeps the bold, italic,
// underline and strikethrough a character style gives the source, as direct formatting, but
// drops a paragraph style's.
use wordcraft_doc::props::Underline;
use wordcraft_doc::styles::{Style, StyleKind};
let mut s = s();
run(&mut s, "document.setText", json!({"text": "x"}));
run(&mut s, "caret.docEnd", json!({}));
let on = wordcraft_doc::CharProps {
bold: Some(true),
bold_cs: Some(true),
italic: Some(true),
italic_cs: Some(true),
underline: Some(Underline::Single),
strike: Some(true),
..Default::default()
};
let sheet = Arc::make_mut(&mut s.doc.styles);
sheet.upsert(Style { id: "ChEmph".into(), name: "ChEmph".into(), kind: StyleKind::Character, chr: on.clone(), ..Default::default() });
sheet.upsert(Style { id: "PEmph".into(), name: "PEmph".into(), kind: StyleKind::Paragraph, chr: on, ..Default::default() });
let pasted = |s: &Session, para_style: Option<&str>, props: wordcraft_doc::CharProps| {
let mut frag = wordcraft_doc::edit::Fragment::from_text("ไทย Thai");
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| {
p.props.style = para_style.map(str::to_string);
p.runs.iter_mut().for_each(|r| r.props = props.clone());
});
}
crate::cmd::paste::merge_formatting(s, &mut frag);
let mut out = Vec::new();
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| {
out.extend(p.runs.iter().map(|r| s.doc.styles.resolve_char(p.props.style.as_deref(), &r.props)));
});
}
out
};
for cs in [None, Some(true)] {
for r in pasted(&s, None, wordcraft_doc::CharProps { style: Some("ChEmph".into()), cs, ..Default::default() }) {
assert!(r.bold && r.bold_cs && r.italic && r.italic_cs && r.strike, "character style, cs {cs:?}: {r:?}");
assert_eq!(r.underline, Underline::Single, "character style, cs {cs:?}");
}
for r in pasted(&s, Some("PEmph"), wordcraft_doc::CharProps { cs, ..Default::default() }) {
assert!(!r.bold && !r.bold_cs && !r.italic && !r.italic_cs && !r.strike, "paragraph style, cs {cs:?}: {r:?}");
assert_eq!(r.underline, Underline::None, "paragraph style, cs {cs:?}");
}
}
}
#[test]
fn pasted_rtf_sections_link_their_headers_to_the_previous() {
// #1378: the RTF's own header part ids mean nothing in this document; a pasted section
@@ -7566,64 +7301,6 @@ fn saving_a_text_file_over_itself_saves_the_document() {
let _ = std::fs::remove_dir_all(&dir);
}
/// #6131: File › Export to DOCX, ODT or RTF writes a copy (`copy: true`). It made the copy the
/// document's file and cleared its unsaved changes, so the next Save went to the copy and the
/// original kept its old text. The copy has the edits; the document keeps its file, its changes
/// and its save stamps.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn exporting_a_copy_keeps_the_documents_file() {
let dir = std::env::temp_dir().join(format!("wordcraft-engine-export-copy-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let body = |p: &std::path::Path| crate::io::open_path(p).unwrap().plain_text(wordcraft_doc::StoryRef::Body);
for ext in ["docx", "odt", "rtf"] {
let original = dir.join(format!("a-{ext}.docx"));
let mut s = Session::new(wordcraft_doc::Document::new());
run(&mut s, "text.insert", json!({"text": "first"}));
run(&mut s, "file.save", json!({"path": original.to_string_lossy()}));
run(&mut s, "text.insert", json!({"text": " edited"}));
let stamps = (s.doc.core.revision, s.doc.core.modified.clone());
let copy = dir.join(format!("copy.{ext}"));
let r = run(&mut s, "file.saveAs", json!({"path": copy.to_string_lossy(), "copy": true}));
assert_eq!(r["saved"], true, "{ext}");
assert_eq!(body(&copy), "first edited", "{ext}: the copy has the edits");
assert_eq!(s.path.as_deref(), Some(original.as_path()), "{ext}: the document keeps its file");
assert!(s.dirty, "{ext}: the document keeps its unsaved changes");
assert_eq!((s.doc.core.revision, s.doc.core.modified.clone()), stamps, "{ext}: the document's save stamps are untouched");
run(&mut s, "file.save", json!({}));
assert_eq!(body(&original), "first edited", "{ext}: Save still writes the original");
assert!(!s.dirty);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// A copy with no path would open the Save As picker on an untitled document (whose answer is an
/// ordinary save that adopts the file) or fall back to the open file's path and overwrite it while
/// leaving the document dirty: refused in both cases (#6131 review).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_copy_without_a_path_is_refused() {
let mut s = Session::new(wordcraft_doc::Document::new());
run(&mut s, "text.insert", json!({"text": "first"}));
let e = s.run("file.save", &json!({"copy": true})).unwrap_err();
assert!(e.to_string().contains("copy"), "{e}");
assert!(s.ui_requests.is_empty(), "no picker opens");
let dir = std::env::temp_dir().join(format!("wordcraft-engine-copy-no-path-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let original = dir.join("doc.docx");
run(&mut s, "file.save", json!({"path": original.to_string_lossy()}));
run(&mut s, "text.insert", json!({"text": " edited"}));
let e = s.run("file.save", &json!({"copy": true})).unwrap_err();
assert!(e.to_string().contains("copy"), "{e}");
assert!(s.dirty, "the document keeps its unsaved changes");
let on_disk = crate::io::open_path(&original).unwrap().plain_text(wordcraft_doc::StoryRef::Body);
assert_eq!(on_disk, "first", "the original file on disk was not overwritten");
let _ = std::fs::remove_dir_all(&dir);
}
/// A Markdown file saved as another Markdown file is that file from now on: the next save goes
/// there and the first file stays as it was. Other formats keep the #2376 rule.
#[cfg(not(target_arch = "wasm32"))]
@@ -7730,6 +7407,7 @@ fn scratch_dir(name: &str) -> std::path::PathBuf {
dir
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn tiny_png() -> Vec<u8> {
wordcraft_geom::picture::encode_format(
&image::DynamicImage::from(image::RgbaImage::from_pixel(2, 2, image::Rgba([200, 30, 30, 255])).clone()),
@@ -10056,77 +9734,6 @@ fn change_case_keeps_each_runs_formatting_when_lengths_change() {
assert_eq!(text(&s), "Q");
}
/// #3479: Change Case follows language-aware mapping for Turkish, Azerbaijani, and Crimean Tatar (i↔İ, ı↔I).
#[test]
fn change_case_follows_turkic_language_mapping() {
// 1. Turkish (tr-TR): all 5 modes
// Capitalize Each Word (title)
let mut s = s();
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul ışık", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul Işık");
// UPPERCASE
run(&mut s, "format.changeCase", json!({"mode": "upper"}));
assert_eq!(text(&s), "İSTANBUL IŞIK");
// lowercase
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
assert_eq!(text(&s), "istanbul ışık");
// sentence case
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul. ışık.", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "sentence"}));
assert_eq!(text(&s), "İstanbul. Işık.");
// toggle case
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
run(&mut s, "text.insert", json!({"text": "İstanbul Işık", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "toggle"}));
assert_eq!(text(&s), "iSTANBUL ıŞIK");
// 2. Azerbaijani (az-AZ)
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "az-AZ", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul");
// 3. Crimean Tatar (crh)
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "crh", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul");
// 4. English control (en-US): unchanged Unicode default
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "Istanbul");
// 5. Mixed-language selection: Turkish run followed by English run
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
run(&mut s, "text.insert", json!({"text": "istanbul ", "raw": true}));
run(&mut s, "review.language", json!({"lang": "en-US"}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul Istanbul");
}
#[test]
fn change_case_sentence_ignores_decimal_points() {
// #3485: Sentence case should not capitalize after decimal points.
@@ -12675,12 +12282,10 @@ fn outline_level_changes_are_undoable() {
assert!(s.run("outline.level", &json!({"level": 12})).is_err());
assert!(s.run("outline.level", &json!({})).is_err());
// Every outline command survives junk parameters in Outline view.
let reg = cmd::registry();
for spec in reg.all().iter().filter(|c| c.id.starts_with("outline.")) {
for spec in cmd::registry().all().iter().filter(|c| c.id.starts_with("outline.")) {
for j in [json!(null), json!({"block": 99999, "level": "x", "value": 5}), json!({"block": -1, "level": 0})] {
let mut s = outline_doc();
let r = s.run(spec.id, &j);
assert!(!caught_panic(&reg, &r), "{} panicked on {j}: {r:?}", spec.id);
let _ = s.run(spec.id, &j);
let _ = s.layout();
}
}
@@ -15739,32 +15344,6 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
}
#[test]
fn page_down_and_up_reach_the_ends_on_first_and_last_page() {
let mut s = s();
for i in 0..80 {
if i > 0 {
run(&mut s, "text.newParagraph", json!({}));
}
run(&mut s, "text.insert", json!({"text": format!("Paragraph {i}")}));
}
let pages = s.layout().pages.len();
assert!(pages >= 2, "expected a multi-page document, got {pages}");
run(&mut s, "caret.docStart", json!({}));
let start = s.sel.focus.clone();
// Advance page by page until the last page, then one more PageDown must reach the end.
for _ in 0..pages {
run(&mut s, "caret.pageDown", json!({}));
}
let end = s.doc.end_of(wordcraft_doc::StoryRef::Body);
assert_eq!(s.sel.focus, end, "PageDown on the last page reaches the end of the document");
// Step back page by page until page 0, then one more PageUp must reach the start.
for _ in 0..pages {
run(&mut s, "caret.pageUp", json!({}));
}
assert_eq!(s.sel.focus, start, "PageUp on the first page reaches the start of the document");
}
/// #5428: an inserted or pasted picture fits where it goes, as in Word: a table cell's width
/// (a nested cell's too), a column's, not the whole page's text width.
#[cfg(not(target_arch = "wasm32"))]
+1 -42
View File
@@ -1653,38 +1653,6 @@ fn a_link_keeps_a_selection_it_cannot_retype() {
assert_eq!(s.doc.field_ranges(StoryRef::Body).len(), 1);
}
#[test]
fn a_column_selection_in_one_paragraph_is_not_one_line() {
// A column (block) selection over the wrapped lines of one paragraph: both its ends are in
// that paragraph, but it holds a piece of each line, so Word shows <<Selection in Document>>
// for it and the text to display can't retype it (#8581).
let mut s = typed("alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau");
let (first, second) = {
let l = s.layout();
let len = s.doc.para_at(&Pos::body(0, 0)).unwrap().text.len();
let mut top = None;
let mut first = None;
let mut second = None;
for off in 0..=len {
let Some(c) = l.caret_on(&Pos::body(0, off), 0) else { continue };
if top.is_some_and(|t| t != c.top) && second.is_none() {
second = Some(off + 10);
break;
}
if top.is_none() {
top = Some(c.top);
first = Some(off);
}
}
(first.expect("the paragraph is laid out"), second.expect("the paragraph wraps"))
};
run(&mut s, "select.column", json!({"anchor": Pos::body(0, first), "focus": Pos::body(0, second)}));
let segs = s.column_segments().expect("the block is one paragraph's lines").to_vec();
assert_eq!(segs.len(), 2, "the block holds a piece of each of the paragraph's two lines");
assert!(segs.iter().all(|(a, b)| a.path == segs[0].0.path && b.path == segs[0].0.path), "both pieces are in one paragraph");
assert!(!crate::cmd::insert::selection_is_one_line(&s), "a column selection is not one line of text");
}
#[test]
fn typing_then_selecting_then_typing_are_two_undo_steps() {
// #419: a selection that moves the insertion point ends the typing group, like a caret move.
@@ -3448,22 +3416,13 @@ fn autocorrect_capitalisation_follows_turkic_case_mapping() {
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
typ(&mut s, "İNgilizce ");
assert_eq!(s.doc.plain_text(StoryRef::Body), "İngilizce ", "no combining dot in any language");
// #3503: two initial capitals and caps-lock with a stray İ in English.
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
typ(&mut s, "Wİrd ");
assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "two initial capitals lowercases İ to i in English");
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
typ(&mut s, "wİRD ");
assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "caps-lock slip fixes wİRD to Wird in English");
}
/// #3479: Format > Change Case follows the same Turkic case mapping as AutoCorrect, using
/// each run's own language; other languages keep the Unicode default.
#[test]
fn change_case_follows_turkic_case_mapping() {
for tag in ["tr-TR", "az-AZ", "crh"] {
for tag in ["tr-TR", "az-AZ"] {
for (mode, input, want) in [
("upper", "istanbul", "İSTANBUL"),
("lower", "IŞIK", "ışık"),
-99
View File
@@ -129,105 +129,6 @@ fn a_date_field_in_a_header_is_refreshed_too() {
assert_eq!(found, [today], "the header's field is refreshed as well as the body's");
}
/// A document whose `docDefaults` set `lang`, so a field run that names no language inherits it,
/// as a German Word document does.
fn open_body_in_lang(lang: &str, body: &str) -> wordcraft_doc::Document {
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let doc_rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
let styles = format!(
r#"<?xml version="1.0" encoding="UTF-8"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:docDefaults><w:rPrDefault><w:rPr><w:lang w:val="{lang}"/></w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style></w:styles>"#
);
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
wordcraft_engine::io::open_bytes(
"d.docx",
&zip(&[("_rels/.rels", rels), ("word/document.xml", &doc), ("word/_rels/document.xml.rels", doc_rels), ("word/styles.xml", &styles)]),
)
.expect("opens")
}
/// German documents carry their language in `docDefaults`, not on each field run. A `DATE` field
/// without `\@` therefore uses `dd.MM.yyyy`, and `MMMM`/`dddd` name the day in German, on open
/// and on an explicit refresh, for `de-DE`, `de-AT` and `de-CH` (#7146).
#[test]
fn german_date_fields_inherit_the_document_default_language() {
const PICTURE: &str = "dddd, d. MMMM yyyy";
for lang in ["de-DE", "de-AT", "de-CH"] {
let d = open_body_in_lang(
lang,
&format!(
"<w:p>{}</w:p><w:p>{}</w:p>",
field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false),
field("DATE", "1/1/2020", false)
),
);
let expected = wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some(lang));
let got = fields(&d);
assert_eq!(got.len(), 2, "{lang}");
assert_eq!(got[0].1, expected, "{lang}: weekday and month names come from docDefaults");
assert_ne!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, None), "{lang}: not the English names");
assert_eq!(
got[1].1,
wordcraft_engine::cmd::insert::format_date_in("dd.MM.yyyy", Some(lang)),
"{lang}: a DATE field without a picture uses the German default"
);
// Saving and reopening keeps the inherited language, and an explicit refresh does not
// fall back to English.
let written = wordcraft_docx::write(&d).unwrap();
let mut reopened = wordcraft_engine::io::open_bytes("reopened.docx", &written).unwrap();
wordcraft_engine::cmd::references::refresh_date_fields(&mut reopened);
let got = fields(&reopened);
assert_eq!(got[0].1, expected, "{lang}: after round-trip");
assert_eq!(got[1].1, wordcraft_engine::cmd::insert::format_date_in("dd.MM.yyyy", Some(lang)), "{lang}: after round-trip");
}
}
/// `MMM` and `ddd` use Word's Windows NLS short forms for German: two-letter weekdays (`So`,
/// `Mo`…) and `Mrz` for March, with no trailing full stop (#7146).
#[test]
fn a_german_short_date_field_uses_windows_nls_abbreviations() {
const PICTURE: &str = "ddd, d. MMM yyyy";
let d = open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wed, 1 Jan 2020", false)));
let got = fields(&d);
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
// The abbreviations at a fixed date, independent of when the test runs.
assert_eq!(wordcraft_engine::cmd::insert::format_date_parts_in(PICTURE, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3), "So, 15. Mrz 2026");
}
/// A `TIME` field whose picture carries German name tokens inherits the language too, so the
/// English result cached in the fixture is replaced with German weekday and month names.
#[test]
fn a_german_time_field_uses_german_names() {
const PICTURE: &str = "dddd, d. MMMM yyyy 'um' HH:mm";
let d =
open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"TIME \@ "{PICTURE}""#), "Wednesday, 1 January 2020 um 00:00", false)));
let got = fields(&d);
assert_eq!(got[0].0, format!(r#"TIME \@ "{PICTURE}""#));
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
}
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland and
/// bare `de` keep `Januar` (`Jan`), as in Windows NLS (#7146). A `de-AT` document reads German
/// through `docDefaults`; the refresh always uses the real clock, so the January names are asked
/// of the same formatter at a fixed January instant.
#[test]
fn austrian_german_documents_use_jaenner() {
const PICTURE: &str = "dddd, d. MMMM yyyy";
let d = open_body_in_lang("de-AT", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false)));
let got = fields(&d);
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-AT")), "an Austrian document reads German");
let january = |lang: &str, picture: &str| wordcraft_engine::cmd::insert::format_date_parts_in(picture, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
assert_eq!(january("de-AT", "MMMM"), "Jänner");
assert_eq!(january("de-AT", "MMM"), "Jän");
assert_eq!(january("de-AT", PICTURE), "Donnerstag, 15. Jänner 2026");
for lang in ["de-DE", "de-CH", "de"] {
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
}
}
/// A minimal Word 97-2003 file whose only paragraph holds a `DATE` field cached as " 2001":
/// FIB, one compressed text piece, and the Clx that points at it.
fn binary_doc_with_stale_date() -> Vec<u8> {
+7 -49
View File
@@ -25,7 +25,7 @@ mod lookup;
mod names;
use face::{BUNDLED, FontBytes};
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled, bundled_inter};
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled};
#[cfg(test)]
use fallback_data::{Coverage, RUN_FALLBACK_CACHE_CHARS, SYS_FALLBACK_MAX_FILE, file_coverage, ranges_hold};
#[cfg(not(target_arch = "wasm32"))]
@@ -42,52 +42,14 @@ pub(crate) use names::{last_resort_face, legacy_family};
static GLOBAL: std::sync::OnceLock<FontDb> = std::sync::OnceLock::new();
/// Fixed-capacity FIFO cache shared by outline and hinting tables so old zoom/script entries evict
/// incrementally instead of wiping the whole table at once.
pub(super) struct BoundedCache<K, V> {
map: HashMap<K, V>,
order: std::collections::VecDeque<K>,
cap: usize,
}
impl<K: Eq + std::hash::Hash + Clone, V> BoundedCache<K, V> {
pub(super) fn new(cap: usize) -> Self {
Self { map: HashMap::new(), order: std::collections::VecDeque::new(), cap: cap.max(1) }
}
pub(super) fn get(&self, key: &K) -> Option<&V> {
self.map.get(key)
}
pub(super) fn insert(&mut self, key: K, val: V) {
if let Some(existing) = self.map.get_mut(&key) {
*existing = val;
return;
}
while self.map.len() >= self.cap {
let Some(oldest) = self.order.pop_front() else {
break;
};
self.map.remove(&oldest);
}
self.order.push_back(key.clone());
self.map.insert(key, val);
}
#[cfg(test)]
pub(super) fn len(&self) -> usize {
self.map.len()
}
}
/// Process-wide font database.
pub struct FontDb {
faces: RwLock<Vec<Arc<FontFace>>>,
outlines: Mutex<BoundedCache<(u32, u32), Arc<BezPath>>>,
outlines: Mutex<HashMap<(u32, u32), Arc<BezPath>>>,
/// Screen-hinted outlines per (face, glyph, ppem bits); `None` where the face can't be hinted.
hinted: Mutex<BoundedCache<(u32, u32, u32), Option<Arc<BezPath>>>>,
hinted: Mutex<HashMap<(u32, u32, u32), Option<Arc<BezPath>>>>,
/// Light hinting instances per (face, ppem bits); `None` where the face can't be hinted.
hinters: Mutex<BoundedCache<(u32, u32), Option<Arc<HintingInstance>>>>,
hinters: Mutex<HashMap<(u32, u32), Option<Arc<HintingInstance>>>>,
/// Fallback faces found per (character, excluded face), valid while the face count is the
/// one stored (faces are only ever added). Layout asks once per uncovered character, and the
/// search sorts every loaded face, so without this text in a script the requested font lacks
@@ -101,8 +63,6 @@ pub struct FontDb {
diagram_search_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
#[cfg(test)]
diagram_publish_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
#[cfg(test)]
run_style_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
#[cfg(not(target_arch = "wasm32"))]
catalog: RwLock<Vec<CatalogEntry>>,
/// Fonts the user added at run time, and the folder they are stored in (#582).
@@ -161,9 +121,9 @@ impl FontDb {
}
Self {
faces: RwLock::new(faces),
outlines: Mutex::new(BoundedCache::new(face::OUTLINE_CACHE_MAX)),
hinted: Mutex::new(BoundedCache::new(face::HINTED_CACHE_MAX)),
hinters: Mutex::new(BoundedCache::new(face::HINTER_CACHE_MAX)),
outlines: Mutex::new(HashMap::new()),
hinted: Mutex::new(HashMap::new()),
hinters: Mutex::new(HashMap::new()),
fallbacks: RwLock::new(FallbackCache::default()),
run_fallbacks: RwLock::new(RunFallbackCache::default()),
diagram_fallbacks: RwLock::new(DiagramFallbackCache::default()),
@@ -173,8 +133,6 @@ impl FontDb {
diagram_search_hook: Mutex::new(None),
#[cfg(test)]
diagram_publish_hook: Mutex::new(None),
#[cfg(test)]
run_style_hook: Mutex::new(None),
#[cfg(not(target_arch = "wasm32"))]
catalog: RwLock::new(Vec::new()),
user: RwLock::new(user::UserFonts::default()),
+4 -18
View File
@@ -13,16 +13,6 @@ pub fn bundled() -> &'static [&'static [u8]] {
BUNDLED
}
/// The bundled Inter Regular and SemiBold, each with its style name: the same bytes as in [`bundled`], so a caller
/// adds no second copy to the binary. The interface draws with them behind the suite's Inter, which is cut to Latin,
/// Greek and Cyrillic.
pub fn bundled_inter() -> [(&'static str, &'static [u8]); 2] {
[("Regular", INTER_REGULAR), ("SemiBold", INTER_SEMIBOLD)]
}
static INTER_REGULAR: &[u8] = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
static INTER_SEMIBOLD: &[u8] = include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf");
pub(super) static BUNDLED: &[&[u8]] = &[
include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"),
include_bytes!("../../../../assets/fonts/SourceSans3-Semibold.ttf"),
@@ -33,9 +23,9 @@ pub(super) static BUNDLED: &[&[u8]] = &[
include_bytes!("../../../../assets/fonts/SourceSerif4-Semibold.ttf"),
include_bytes!("../../../../assets/fonts/SourceSerif4-Bold.ttf"),
include_bytes!("../../../../assets/fonts/SourceSerif4-BoldIt.ttf"),
INTER_REGULAR,
include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"),
include_bytes!("../../../../assets/fonts/Inter-Medium.ttf"),
INTER_SEMIBOLD,
include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf"),
include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf"),
];
@@ -551,13 +541,9 @@ fn is_explicit_serif(name: &str) -> bool {
pub(super) static NEXT_ID: AtomicU32 = AtomicU32::new(1);
/// Unhinted glyph outlines kept per (face, glyph).
pub(super) const OUTLINE_CACHE_MAX: usize = 16_384;
/// Screen-hinted outlines kept per (face, glyph, ppem bits); narrower than [`OUTLINE_CACHE_MAX`]
/// because zoom changes create entries per size.
pub(super) const HINTED_CACHE_MAX: usize = 8_192;
pub(super) const OUTLINE_CACHE_MAX: usize = 50_000;
/// Hinting instances kept (one per face and text size on screen).
pub(super) const HINTER_CACHE_MAX: usize = 128;
pub(super) const HINTER_CACHE_MAX: usize = 256;
/// Sizes hinted, in device pixels per em: below, text is too small to read anyway; above, the
/// half-pixel hinting moves is invisible (and each size would cost a cache entry).
pub(super) const HINT_PPEM: std::ops::RangeInclusive<f32> = 4.0..=96.0;
+9 -66
View File
@@ -1,10 +1,9 @@
use super::face::{FALLBACK_FAMILY, FontFace};
use super::fallback_data::{
BALLOT_BOXES, DiagramFallbackKey, FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block,
fallback_order,
};
#[cfg(not(target_arch = "wasm32"))]
use super::fallback_data::{CoverageIndex, IndexedFile, SYS_MISSES_MAX, SYSTEM_FALLBACKS, file_stamp, ranges_hold, read_fallback_file};
use super::fallback_data::{
DiagramFallbackKey, FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block, fallback_order,
};
use super::{Arc, FontDb};
#[cfg(not(target_arch = "wasm32"))]
use super::{HashMap, Ordering};
@@ -29,11 +28,7 @@ impl FontDb {
_ => "Italic",
};
let styled = self.face(&base.family, style);
Some(if styled.family.eq_ignore_ascii_case(&base.family) && styled_covers(&styled, &base, &[c]) && styled.id != exclude {
styled
} else {
base
})
Some(if styled.family.eq_ignore_ascii_case(&base.family) && styled.covers(c) && styled.id != exclude { styled } else { base })
}
/// The fallback search, cached per (character, excluded face) until loaded faces or font
@@ -75,9 +70,6 @@ impl FontDb {
if let Some(face) = self.circle_fallback(c, exclude) {
return (Some(face), self.read_faces().len());
}
if let Some((face, n)) = self.ballot_box_fallback(c, exclude) {
return (Some(face), n);
}
let (found, n) = self.loaded_fallback(c, exclude);
if found.is_some() {
return (found, n);
@@ -105,38 +97,6 @@ impl FontDb {
find()
}
/// A ballot box (☐ ☑ ☒, a check box's symbols) the face lacks: the first of the symbol faces
/// ([`crate::word::SYMBOL`], in that order) that has all three, so a check box looks the same
/// ticked and unticked (#7863). The UI fallback has ☐, drawn with a drop shadow, and ☑ but no
/// ☒, which put a box's two states in different fonts. `None` when no listed face has all
/// three: the ordinary fallback then. With the face, the number of loaded faces before the
/// search: a face loaded during it (by it, or by another thread for a family it had passed)
/// leaves that number behind, so the answer isn't cached for the new face list.
fn ballot_box_fallback(&self, c: char, exclude: u32) -> Option<(Arc<FontFace>, usize)> {
if !BALLOT_BOXES.contains(&c) {
return None;
}
let n = self.read_faces().len();
let all = |f: &Arc<FontFace>| f.id != exclude && BALLOT_BOXES.iter().all(|b| f.covers(*b));
for family in crate::word::SYMBOL {
if let Some(face) = self.find(family, "Regular").filter(all) {
return Some((face, n));
}
// An installed family is loaded only when its files map all three.
#[cfg(not(target_arch = "wasm32"))]
{
let enabled = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled;
if enabled && !self.is_loaded(family) && BALLOT_BOXES.iter().all(|b| self.family_maps(family, *b)) {
self.load_cataloged(family);
if let Some(face) = self.find(family, "Regular").filter(all) {
return Some((face, n));
}
}
}
}
None
}
/// [`Self::search_fallback`] when no loaded face covers `c`: load a system font that does,
/// one search at a time.
#[cfg(not(target_arch = "wasm32"))]
@@ -239,13 +199,8 @@ impl FontDb {
/// The face for a run, and the number of loaded faces the search last chose from.
fn search_run(&self, chars: &[char], exclude: u32, bold: bool, italic: bool) -> (Option<Arc<FontFace>>, usize) {
// A run of ballot boxes draws in their one face, as each of them alone does (#7863).
let ballot = chars.first().filter(|_| chars.iter().all(|c| BALLOT_BOXES.contains(c))).and_then(|c| self.ballot_box_fallback(*c, exclude));
#[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
let (mut base, mut checked) = match ballot {
Some((face, n)) => (Some(face), n),
None => self.loaded_covering(chars, exclude),
};
let (mut base, mut checked) = self.loaded_covering(chars, exclude);
#[cfg(not(target_arch = "wasm32"))]
if base.is_none() {
// A character no loaded face covers: load a system font for it, then retry (the run's
@@ -280,16 +235,12 @@ impl FontDb {
(true, false) => "Bold",
_ => "Italic",
};
// The count stays the one `base` was chosen from. `base` is loaded, so the style lookup
// only picks among the family's loaded faces and loads nothing: a later count could only
// take in a face another thread loaded meanwhile, and cache this answer for faces it never
// saw (#7863).
let before_style = self.read_faces().len();
let styled = self.face(&base.family, style);
#[cfg(test)]
if let Some(hook) = self.run_style_hook.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() {
hook(self);
if before_style == checked {
checked = self.read_faces().len();
}
let face = if styled.family.eq_ignore_ascii_case(&base.family) && styled_covers(&styled, &base, chars) && styled.id != exclude {
let face = if styled.family.eq_ignore_ascii_case(&base.family) && chars.iter().all(|c| styled.covers(*c)) && styled.id != exclude {
styled
} else {
base
@@ -606,11 +557,3 @@ impl FontDb {
false
}
}
/// Can `styled`, a bold or italic face of `base`'s family, draw `chars` in its place? It must map
/// them all, and all three ballot boxes when they are ballot boxes and `base` has all three, so a
/// check box's states stay in one face in bold or italic text too (#7863).
fn styled_covers(styled: &FontFace, base: &FontFace, chars: &[char]) -> bool {
let boxes = chars.iter().all(|c| BALLOT_BOXES.contains(c)) && BALLOT_BOXES.iter().all(|b| base.covers(*b));
chars.iter().chain(BALLOT_BOXES.iter().filter(|_| boxes)).all(|c| styled.covers(*c))
}
-3
View File
@@ -242,9 +242,6 @@ pub const RTL_FALLBACKS: &[&str] = &[
pub const RTL_FALLBACKS: &[&str] =
&["Noto Naskh Arabic", "Noto Sans Arabic", "Noto Sans Hebrew", "Vazirmatn", "Segoe UI", "Arial", "Tahoma", "DejaVu Sans"];
/// The ballot boxes ☐ ☑ ☒: a check box's unchecked symbol and its two usual checked ones.
pub(super) const BALLOT_BOXES: [char; 3] = ['\u{2610}', '\u{2611}', '\u{2612}'];
/// Families tried (when installed) for characters the loaded fonts lack: CJK, symbols, emoji.
#[cfg(not(target_arch = "wasm32"))]
pub(super) const SYSTEM_FALLBACKS: &[&str] = &[
+16 -4
View File
@@ -1,4 +1,4 @@
use super::face::{FALLBACK_FAMILY, FontBytes, FontFace, HINT_PPEM};
use super::face::{FALLBACK_FAMILY, FontBytes, FontFace, HINT_PPEM, HINTER_CACHE_MAX, OUTLINE_CACHE_MAX};
#[cfg(not(target_arch = "wasm32"))]
use super::fallback_data::read_fallback_file;
#[cfg(not(target_arch = "wasm32"))]
@@ -220,7 +220,11 @@ impl FontDb {
return p.clone();
}
let p = Arc::new(face.glyph_outline(gid));
self.outlines.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, p.clone());
let mut cache = self.outlines.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.len() >= OUTLINE_CACHE_MAX {
cache.clear();
}
cache.insert(key, p.clone());
p
}
@@ -243,13 +247,21 @@ impl FontDb {
None => {
// Built outside the lock: running a font's hinting programs takes a while.
let h = face.screen_hinter(ppem).map(Arc::new);
self.hinters.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(hkey, h.clone());
let mut cache = self.hinters.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.len() >= HINTER_CACHE_MAX {
cache.clear();
}
cache.insert(hkey, h.clone());
h
}
}
};
let p = hinter.and_then(|h| face.hinted_glyph_outline(gid, &h)).map(Arc::new);
self.hinted.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, p.clone());
let mut cache = self.hinted.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.len() >= OUTLINE_CACHE_MAX {
cache.clear();
}
cache.insert(key, p.clone());
p
}
}
-12
View File
@@ -154,18 +154,6 @@ fn screen_hinting_refuses_hostile_sizes() {
assert!(db.hinted_outline(&face, u32::MAX, 20.0).is_none_or(|o| o.elements().is_empty()));
}
#[test]
fn bounded_outline_cache_evicts_oldest_incrementally() {
let mut c = BoundedCache::new(2);
c.insert(1u32, "a");
c.insert(2u32, "b");
c.insert(3u32, "c");
assert_eq!(c.len(), 2);
assert!(c.get(&1).is_none(), "oldest entry evicted");
assert_eq!(c.get(&2), Some(&"b"), "newer entry retained");
assert_eq!(c.get(&3), Some(&"c"));
}
/// The issue's run (#1549): Thai letters and digits, Latin letters, digits and the baht sign.
const THAI_RUN: &str = "[D] น้ำ ค่ำ ปั้น ฝั่ง ปู่ ๑๒๓๔๕๖๗๘๙๐ ฿1,250.50";
-124
View File
@@ -866,130 +866,6 @@ fn circle_checks_face_coverage() {
assert_eq!(db.fallback_for('●', primary.id()).unwrap().family, FALLBACK_FAMILY);
}
/// A bundled Source Sans 3 Regular named `family` that maps ☒ (U+2612) too: its ☐–☑ cmap group
/// runs on one character further (the next group starts at U+2615, so the groups stay sorted).
fn with_every_ballot_box(family: &str) -> Vec<u8> {
let mut data = named_face("SourceSans3-Regular.ttf", family);
let (from, to) = ([0x2610_u32, 0x2611].map(u32::to_be_bytes).concat(), [0x2610_u32, 0x2612].map(u32::to_be_bytes).concat());
let mut patched = 0;
while let Some(at) = data.windows(from.len()).position(|w| w == from) {
data[at..at + to.len()].copy_from_slice(&to);
patched += 1;
}
assert!(patched > 0);
data
}
#[test]
fn a_check_box_draws_every_state_in_one_face() {
// #7863: with the check box's font missing, ☐ and ☑ came from the UI fallback, which has no
// ☒, and ☒ from another face, so ticking a box changed how it looked.
let db = FontDb::with_font_dirs(Vec::new());
db.set_system_fallback(false);
let primary = db.face("Inter", "Regular");
assert!(!primary.covers('☐'), "the requested face lacks the boxes");
// A listed symbol face with ☐ and ☑ only, then a later one with all three.
db.add_document_fonts(vec![
(named_face("SourceSerif4-Regular.ttf", "Apple Symbols"), "Apple Symbols".to_string()),
(with_every_ballot_box("DejaVu Sans"), "DejaVu Sans".to_string()),
]);
let faces: Vec<u32> = ['☐', '☑', '☒'].iter().map(|c| db.fallback_for(*c, primary.id()).expect("a face has it").id()).collect();
assert!(faces.iter().all(|f| *f == faces[0]), "one face for every state: {faces:?}");
let run = db.fallback_for_run(&['☐', '☑'], primary.id(), false, false).expect("a face has them");
assert_eq!(run.id(), faces[0], "a run of them takes the same face");
}
#[test]
fn a_bold_check_box_draws_every_state_in_one_face() {
// The listed family's Regular face has all three boxes and its Bold face only ☐ and ☑: bold ☐
// and ☑ took the Bold face, and ☒ the Regular one.
let db = FontDb::with_font_dirs(Vec::new());
db.set_system_fallback(false);
let primary = db.face("Inter", "Regular");
db.add_document_fonts(vec![
(with_every_ballot_box("DejaVu Sans"), "DejaVu Sans".to_string()),
(named_face("SourceSans3-Bold.ttf", "DejaVu Sans"), "DejaVu Sans".to_string()),
]);
let faces: Vec<u32> = ['☐', '☑', '☒'].iter().map(|c| db.fallback_styled(*c, primary.id(), true, false).expect("a face has it").id()).collect();
assert!(faces.iter().all(|f| *f == faces[0]), "one face for every state: {faces:?}");
let run = db.fallback_for_run(&['☐', '☑'], primary.id(), true, false).expect("a face has them");
assert_eq!(run.id(), faces[0], "a bold run of them takes the same face");
}
#[test]
fn ballot_boxes_load_an_installed_symbol_face() {
let dir = font_dir("ballot-boxes");
std::fs::write(dir.join("Symbols-Regular.ttf"), with_every_ballot_box("DejaVu Sans")).unwrap();
// An earlier listed family with only two of the boxes: never loaded for them.
std::fs::write(dir.join("TwoBoxes-Regular.ttf"), named_face("SourceSerif4-Regular.ttf", "Apple Symbols")).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
let primary = db.face("Inter", "Regular");
db.set_system_fallback(false);
assert!(db.fallback_for('☐', primary.id()).is_some());
assert!(!db.is_loaded("DejaVu Sans"), "nothing is loaded with the system fallback off");
db.set_system_fallback(true);
let found = db.fallback_for('☐', primary.id()).unwrap();
assert_eq!(found.family, "DejaVu Sans", "the installed face with all three");
assert_eq!(db.fallback_for('☒', primary.id()).unwrap().id(), found.id());
assert!(!db.is_loaded("Apple Symbols"), "a listed family without all three is not loaded");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_check_box_keeps_one_face_when_a_symbol_face_loads_during_its_search() {
// A search for ☐ passed Apple Symbols, not loaded yet, and was loading the installed Segoe UI
// Symbol when another thread loaded Apple Symbols. Its answer was remembered for the face count
// after both loads, so ☐ kept Segoe UI Symbol while ☑ and ☒ took Apple Symbols, the first
// listed face with all three.
let dir = font_dir("ballot-box-race");
std::fs::write(dir.join("Symbols-Regular.ttf"), with_every_ballot_box("Segoe UI Symbol")).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
let primary = db.face("Inter", "Regular");
let reads = || db.coverage.lock().unwrap().reads;
let unread = reads();
let loading = db.loading.lock().unwrap();
std::thread::scope(|s| {
let search = s.spawn(|| db.fallback_for('☐', primary.id()));
// Past Apple Symbols, the search reads the installed file's character map, then waits for
// `loading` to load the file. (A search that finishes without reading it ends the wait too.)
while reads() == unread && !search.is_finished() {
std::thread::yield_now();
}
// Another thread loads Apple Symbols meanwhile, as a font load adds faces (`loading` is
// held here).
db.add_fonts(vec![(with_every_ballot_box("Apple Symbols"), None)]);
drop(loading);
assert!(search.join().unwrap().is_some());
});
let faces: Vec<String> = ['☐', '☑', '☒'].iter().map(|c| db.fallback_for(*c, primary.id()).expect("a face has it").family.clone()).collect();
assert_eq!(faces, ["Apple Symbols"; 3], "the first listed face with all three, for every state");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_bold_run_of_check_boxes_keeps_one_face_when_a_symbol_face_loads_during_its_style_lookup() {
// A bold run of boxes chose DejaVu Sans, the first listed face loaded with all three, and
// looked up its bold face while another thread loaded Apple Symbols, listed earlier. The run's
// answer was remembered for the face count after that load, so the run kept DejaVu Sans while
// each box alone took Apple Symbols.
let db = FontDb::with_font_dirs(Vec::new());
db.set_system_fallback(false);
let primary = db.face("Inter", "Regular");
db.add_document_fonts(vec![(with_every_ballot_box("DejaVu Sans"), "DejaVu Sans".to_string())]);
let apple = with_every_ballot_box("Apple Symbols");
*db.run_style_hook.lock().unwrap() = Some(Box::new(move |db| {
// A font load adds faces and leaves the generation as it is.
db.add_fonts(vec![(apple, None)]);
}));
let run = ['☐', '☑', '☒'];
assert!(db.fallback_for_run(&run, primary.id(), true, false).is_some());
assert!(db.run_style_hook.lock().unwrap().is_none(), "Apple Symbols loaded during the run's style lookup");
let boxes: Vec<String> = run.iter().map(|c| db.fallback_styled(*c, primary.id(), true, false).expect("a face has it").family.clone()).collect();
assert_eq!(boxes, ["Apple Symbols"; 3], "the first listed face with all three, for every state");
let again = db.fallback_for_run(&run, primary.id(), true, false).expect("a face has them");
assert_eq!(again.family, "Apple Symbols", "the run takes the face each box takes");
}
#[test]
fn catalog_postscript_names() {
let dir = font_dir("postscript");
+1 -1
View File
@@ -17,7 +17,7 @@ pub mod word;
pub use fontdb::{
FALLBACK_FAMILY, FONT_FILE_EXTS, FaceRef, FontDb, FontFace, FontFormat, Installed, LocalName, MAX_FONT_FILE_BYTES, UserFont, UserFontError,
base_style, bundled, bundled_inter, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
base_style, bundled, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
};
pub use harfrust::Feature;
use harfrust::{Direction, ShapeOptions, ShapePlan, ShapePlanKey, Shaper, Tag, UnicodeBuffer};
+3 -5
View File
@@ -40,11 +40,6 @@ pub fn has_named_substitutes(family: &str) -> bool {
const SANS: &[&str] = &["Carlito", "Helvetica Neue", "Arial", "Liberation Sans", "Noto Sans", "DejaVu Sans", "Source Sans 3"];
/// Word's symbol fonts (Symbol, Wingdings…) are proprietary: their characters are drawn as their
/// Unicode equivalents (`wordcraft_doc::symbol_fonts`) from these faces or any face that has them.
/// A check box's ballot boxes take their face from this list too (`FontDb::fallback_for`, #7863).
pub(crate) const SYMBOL: &[&str] = &["Apple Symbols", "Segoe UI Symbol", "DejaVu Sans", "Noto Sans Symbols", "Noto Sans Symbols 2", "Source Sans 3"];
/// Serif faces known by name with no open clone of their own (lowercase): they take the generic
/// serif list, but as fonts we know, not by a guess from the name ([`has_own_substitutes`]).
const KNOWN_SERIFS: &[&str] = &[
@@ -80,6 +75,9 @@ fn substitutes_by_name(family: &str) -> (&'static [&'static str], bool) {
const ARIAL: &[&str] = &["Liberation Sans", "Helvetica", "Helvetica Neue", "Arimo", "Source Sans 3"];
const ARIAL_UNICODE: &[&str] = &["Arial", "Liberation Sans", "Helvetica", "Helvetica Neue", "Arimo", "Source Sans 3"];
const TIMES: &[&str] = &["Liberation Serif", "Times", "Tinos", "Source Serif 4"];
// Word's symbol fonts (Symbol, Wingdings…) are proprietary: their characters are drawn as their
// Unicode equivalents (`wordcraft_doc::symbol_fonts`) from these faces or any face that has them.
const SYMBOL: &[&str] = &["Apple Symbols", "Segoe UI Symbol", "DejaVu Sans", "Noto Sans Symbols", "Noto Sans Symbols 2", "Source Sans 3"];
// Persian / Arabic document fonts. Naskh (book) faces such as B Nazanin, B Lotus, B Zar and
// Traditional Arabic, then the sans faces (B Yekan, B Titr, IRANSans) people use for
// headings and screens. Open fonts with full Persian coverage first.
+24 -14
View File
@@ -4,28 +4,38 @@ use wordcraft_doc::{Document, SectionProps};
pub use craft_html::doc::{ImageLoader, PAGE_FONT, css_len_pt, decode, decode_as, decode_entity, esc, export_flow, parse, parse_with, unescape};
use crate::{from_shared, shared_section, to_shared};
pub fn import(html: &str) -> Result<Document, String> {
from_shared(craft_html::doc::import(html))
fn shared_section(page: &SectionProps) -> craft_wordmodel::SectionProps {
let mut d = Document::new();
d.last_section = page.clone();
wordcraft_docx::to_shared_model(&d).map(|s| s.last_section).unwrap_or_default()
}
pub fn import_page(html: &str, images: ImageLoader<'_>) -> Result<Document, String> {
from_shared(craft_html::doc::import_page(html, images))
pub fn import(html: &str) -> Document {
wordcraft_docx::from_shared_model(craft_html::doc::import(html)).unwrap_or_default()
}
pub fn import_with(html: &str, images: ImageLoader<'_>) -> Result<Document, String> {
from_shared(craft_html::doc::import_with(html, images))
pub fn import_page(html: &str, images: ImageLoader<'_>) -> Document {
wordcraft_docx::from_shared_model(craft_html::doc::import_page(html, images)).unwrap_or_default()
}
pub fn import_on(html: &str, images: ImageLoader<'_>, page: &SectionProps) -> Result<Document, String> {
from_shared(craft_html::doc::import_on(html, images, &shared_section(page)?))
pub fn import_with(html: &str, images: ImageLoader<'_>) -> Document {
wordcraft_docx::from_shared_model(craft_html::doc::import_with(html, images)).unwrap_or_default()
}
pub fn export(doc: &Document) -> Result<String, String> {
Ok(craft_html::doc::export(&to_shared(doc)?))
pub fn import_on(html: &str, images: ImageLoader<'_>, page: &SectionProps) -> Document {
wordcraft_docx::from_shared_model(craft_html::doc::import_on(html, images, &shared_section(page))).unwrap_or_default()
}
pub fn export_fragment(doc: &Document) -> Result<String, String> {
Ok(craft_html::doc::export_fragment(&to_shared(doc)?))
pub fn export(doc: &Document) -> String {
match wordcraft_docx::to_shared_model(doc) {
Ok(shared) => craft_html::doc::export(&shared),
Err(_) => String::new(),
}
}
pub fn export_fragment(doc: &Document) -> String {
match wordcraft_docx::to_shared_model(doc) {
Ok(shared) => craft_html::doc::export_fragment(&shared),
Err(_) => String::new(),
}
}
+10 -9
View File
@@ -4,22 +4,23 @@ use wordcraft_doc::{Document, SectionProps};
pub use craft_latex::{escape_text, latex_to_linear, linear_to_latex};
use crate::{from_shared, to_shared};
pub fn import(bytes: &[u8]) -> Result<Document, String> {
from_shared(craft_latex::import(bytes))
pub fn import(bytes: &[u8]) -> Document {
wordcraft_docx::from_shared_model(craft_latex::import(bytes)).unwrap_or_default()
}
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
let mut d = import(bytes)?;
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Document {
let mut d = import(bytes);
d.last_section = page.clone();
Ok(d)
d
}
pub fn parse(text: &str) -> craft_flow::Flow {
craft_latex::parse(text)
}
pub fn export(doc: &Document) -> Result<String, String> {
Ok(craft_latex::export(&to_shared(doc)?))
pub fn export(doc: &Document) -> String {
match wordcraft_docx::to_shared_model(doc) {
Ok(shared) => craft_latex::export(&shared),
Err(_) => String::new(),
}
}
+15 -39
View File
@@ -28,27 +28,6 @@ use wordcraft_doc::Document;
/// (`wordcraft_docx::package::MAX_ENTRIES`); checked before `zip` parses them (#3660).
pub const MAX_ZIP_ENTRIES: u64 = 20_000;
/// The document as the shared model the format crates read and write.
///
/// A conversion that fails is an error, never an empty document or an empty file: the caller
/// says so instead of writing a file with nothing in it.
pub(crate) fn to_shared(doc: &Document) -> Result<craft_wordmodel::Document, String> {
wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())
}
/// The shared model as the app's document model. A conversion that fails is an error, never
/// an empty document.
pub(crate) fn from_shared(shared: craft_wordmodel::Document) -> Result<Document, String> {
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
}
/// The page a file that gives no page size starts on, as the shared model.
pub(crate) fn shared_section(page: &wordcraft_doc::SectionProps) -> Result<craft_wordmodel::SectionProps, String> {
let mut d = Document::new();
d.last_section = page.clone();
Ok(to_shared(&d)?.last_section)
}
/// Extensions this crate handles.
pub const EXTENSIONS: &[&str] =
&["txt", "text", "md", "markdown", "html", "htm", "xhtml", "mht", "mhtml", "rtf", "odt", "ott", "fodt", "tex", "latex", "ltx"];
@@ -56,15 +35,15 @@ pub const EXTENSIONS: &[&str] =
/// Import `bytes` in the format named by `ext` (no dot, any case). `None` = not our format.
pub fn import(ext: &str, bytes: &[u8]) -> Option<Result<Document, String>> {
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
let r: Result<Document, String> = match ext.as_str() {
let r = match ext.as_str() {
"txt" | "text" => Ok(txt::import(bytes)),
"md" | "markdown" => markdown::import(&txt::decode(bytes)),
"html" | "htm" | "xhtml" => html::import_page(&html::decode(bytes), &|_| None),
"mht" | "mhtml" => mht::import(bytes),
"md" | "markdown" => Ok(markdown::import(&txt::decode(bytes))),
"html" | "htm" | "xhtml" => Ok(html::import_page(&html::decode(bytes), &|_| None)),
"mht" | "mhtml" => Ok(mht::import(bytes)),
"rtf" => rtf::import(bytes),
"odt" | "ott" => odt::import(bytes),
"fodt" => odt::import_flat(bytes),
"tex" | "latex" | "ltx" => latex::import(bytes),
"tex" | "latex" | "ltx" => Ok(latex::import(bytes)),
_ => return None,
};
Some(r.map(|mut d| {
@@ -78,36 +57,33 @@ pub fn import(ext: &str, bytes: &[u8]) -> Option<Result<Document, String>> {
/// formats keep the page their file gives.
pub fn import_on(ext: &str, bytes: &[u8], page: &wordcraft_doc::SectionProps) -> Option<Result<Document, String>> {
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
let mut doc: Result<Document, String> = match ext.as_str() {
let mut doc = match ext.as_str() {
"odt" | "ott" => return Some(odt::import_on(bytes, page)),
"fodt" => return Some(odt::import_flat_on(bytes, page)),
"txt" | "text" => Ok(txt::import_on(bytes, page)),
"txt" | "text" => txt::import_on(bytes, page),
"md" | "markdown" => markdown::import_on(&txt::decode(bytes), page),
"html" | "htm" | "xhtml" => html::import_on(&html::decode(bytes), &|_| None, page),
"mht" | "mhtml" => mht::import_on(bytes, page),
_ => return import(&ext, bytes),
};
if let Ok(d) = doc.as_mut() {
d.ensure_nonempty();
}
Some(doc)
doc.ensure_nonempty();
Some(Ok(doc))
}
/// Export `doc` in the format named by `ext`. `None` = not our format.
pub fn export(ext: &str, doc: &Document) -> Option<Result<Vec<u8>, String>> {
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
let out: Result<Vec<u8>, String> = match ext.as_str() {
Some(match ext.as_str() {
"txt" | "text" => Ok(txt::export(doc)),
"md" | "markdown" => markdown::export(doc).map(String::into_bytes),
"html" | "htm" | "xhtml" => html::export(doc).map(String::into_bytes),
"rtf" => rtf::export(doc).map(String::into_bytes),
"md" | "markdown" => Ok(markdown::export(doc).into_bytes()),
"html" | "htm" | "xhtml" => Ok(html::export(doc).into_bytes()),
"rtf" => Ok(rtf::export(doc).into_bytes()),
"odt" => odt::export(doc),
"ott" => odt::export_template(doc),
"fodt" => odt::export_flat(doc),
"tex" | "latex" | "ltx" => latex::export(doc).map(String::into_bytes),
"tex" | "latex" | "ltx" => Ok(latex::export(doc).into_bytes()),
_ => return None,
};
Some(out)
})
}
/// How [`export_with`] writes a copy.
+18 -11
View File
@@ -4,19 +4,23 @@ use wordcraft_doc::{Block, Document, SectionProps};
pub use craft_markdown::{Refs, escape, parse, parse_inlines};
use crate::{from_shared, shared_section, to_shared};
pub fn import(text: &str) -> Result<Document, String> {
from_shared(craft_markdown::import(text))
fn shared_section(page: &SectionProps) -> craft_wordmodel::SectionProps {
let mut d = Document::new();
d.last_section = page.clone();
wordcraft_docx::to_shared_model(&d).map(|s| s.last_section).unwrap_or_default()
}
pub fn import_on(text: &str, page: &SectionProps) -> Result<Document, String> {
from_shared(craft_markdown::import_on(text, &shared_section(page)?))
pub fn import(text: &str) -> Document {
wordcraft_docx::from_shared_model(craft_markdown::import(text)).unwrap_or_default()
}
pub fn import_on(text: &str, page: &SectionProps) -> Document {
wordcraft_docx::from_shared_model(craft_markdown::import_on(text, &shared_section(page))).unwrap_or_default()
}
/// [`import_on`] returning the document and the 0-based starting line of each top-level block.
pub fn import_on_with_lines(text: &str, page: &SectionProps) -> Result<(Document, Vec<usize>), String> {
let doc = import_on(text, page)?;
pub fn import_on_with_lines(text: &str, page: &SectionProps) -> (Document, Vec<usize>) {
let doc = import_on(text, page);
let src_lines: Vec<&str> = text.strip_prefix('\u{FEFF}').unwrap_or(text).lines().collect();
let mut out = Vec::with_capacity(doc.body.len());
let mut cursor = 0usize;
@@ -53,9 +57,12 @@ pub fn import_on_with_lines(text: &str, page: &SectionProps) -> Result<(Document
}
out.push(found.min(src_lines.len()));
}
Ok((doc, out))
(doc, out)
}
pub fn export(doc: &Document) -> Result<String, String> {
Ok(craft_markdown::export(&to_shared(doc)?))
pub fn export(doc: &Document) -> String {
match wordcraft_docx::to_shared_model(doc) {
Ok(shared) => craft_markdown::export(&shared),
Err(_) => String::new(),
}
}
+3 -3
View File
@@ -15,7 +15,7 @@ pub fn is_mht(bytes: &[u8]) -> bool {
}
/// Import an MHT file.
pub fn import(bytes: &[u8]) -> Result<Document, String> {
pub fn import(bytes: &[u8]) -> Document {
import_on(bytes, &SectionProps::default())
}
@@ -38,7 +38,7 @@ fn part_bytes(part: &Part) -> &[u8] {
}
/// [`import`] onto `page`.
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Document {
let msg = craft_mime::parse(bytes, &craft_mime::Limits::DEFAULT);
let mut leaves = Vec::new();
collect_leaves(&msg.root, &mut leaves);
@@ -46,7 +46,7 @@ pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String>
.or_else(|| leaves.iter().copied().find(|p| matches!(p.declared_media_type(), Some("text/html" | "application/xhtml+xml"))));
let Some(root) = root else {
let text = leaves.iter().copied().find(|p| p.declared_media_type().unwrap_or("text/plain") == "text/plain").map(part_bytes).unwrap_or(&[]);
return Ok(crate::txt::import_on(text, page));
return crate::txt::import_on(text, page);
};
let html = crate::html::decode_as(part_bytes(root), root.content_type.get("charset"));
let base = root.content_location().unwrap_or("");
+6 -5
View File
@@ -2,11 +2,9 @@
use wordcraft_doc::Document;
use crate::{from_shared, to_shared};
pub fn import(bytes: &[u8]) -> Result<Document, String> {
let shared = craft_rtf::doc::import(bytes)?;
from_shared(shared)
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
}
pub fn parse(bytes: &[u8]) -> Result<crate::model::Flow, String> {
@@ -14,6 +12,9 @@ pub fn parse(bytes: &[u8]) -> Result<crate::model::Flow, String> {
Ok(craft_flow::from_doc(&shared))
}
pub fn export(doc: &Document) -> Result<String, String> {
Ok(craft_rtf::doc::export(&to_shared(doc)?))
pub fn export(doc: &Document) -> String {
let Ok(shared) = wordcraft_docx::to_shared_model(doc) else {
return String::new();
};
craft_rtf::doc::export(&shared)
}
+9 -337
View File
@@ -95,7 +95,15 @@ pub fn read_rows(bytes: &[u8], pick: Pick<'_>) -> Result<(Vec<String>, Vec<Vec<S
let names: Vec<String> = book.sheets.iter().map(|s| s.name.clone()).collect();
let i = resolve(&names, pick)?;
let sheet = &book.sheets[i];
let rows = cells_to_rows(&sheet.cells, ods_value);
let rows = cells_to_rows(&sheet.cells, |c| {
if !c.text.is_empty() {
clamp_cell(c.text.clone())
} else if let Some(v) = c.value() {
format_value(&v)
} else {
String::new()
}
});
return Ok((names, rows));
}
Err("not an Excel or OpenDocument spreadsheet".into())
@@ -170,187 +178,6 @@ fn format_value(v: &Value) -> String {
}
}
/// An OpenDocument cell's display string, from `office:value-type`: floats from `office:value`,
/// dates and times from `office:date-value` / `office:time-value` in ISO 8601 form (`yyyy-mm-dd`,
/// `yyyy-mm-dd hh:mm[:ss]`, `hh:mm[:ss]`), booleans as `TRUE`/`FALSE`, and strings, percentages
/// and currencies as the cell's text (their value when the text is blank). A value that does not
/// parse falls back to the text. A covered cell under a merged cell is blank.
///
/// A float merges its value, not the text its number format shows: a ZIP code `01234` shown
/// through the format `00000` merges as `1234`, and `1,234` shown with a thousands separator
/// merges as `1234`.
fn ods_value(c: &craft_ods::Cell) -> String {
use craft_ods::ValueType as T;
if c.covered {
return String::new();
}
let typed = match (c.value_type, c.raw.as_deref().map(str::trim)) {
(Some(T::Float | T::Boolean), Some(_)) => c.value().map(|v| format_value(&v)),
(Some(T::Date), Some(v)) => iso_datetime(v),
(Some(T::Time), Some(v)) => iso_time(v),
(Some(T::Percentage | T::Currency | T::String), Some(_)) if c.text.is_empty() => c.value().map(|v| format_value(&v)),
_ => None,
};
typed.map(clamp_cell).unwrap_or_else(|| clamp_cell(c.text.clone()))
}
/// An ISO 8601 date or date-time (`2024-03-05`, `2024-03-05T13:45:00.000`) as `yyyy-mm-dd`,
/// with ` hh:mm[:ss]` when the time isn't midnight. `None` unless the whole value is a valid
/// calendar date and clock time.
fn iso_datetime(v: &str) -> Option<String> {
use chrono::Datelike;
let v = v.trim();
let (date, time) = match v.split_once('T') {
Some((date, time)) => (date, Some(time)),
None => (v, None),
};
// A date alone may carry a zone (`Z` or `±hh:mm`), which is left out.
let date = match (time, date.strip_suffix('Z')) {
(None, Some(d)) => d,
(None, None) if date.len() > 6 && date.get(date.len() - 6..).is_some_and(|z| z.starts_with(['+', '-']) && z.get(3..4) == Some(":")) => {
zone_offset(date.get(date.len() - 5..)?)?;
date.get(..date.len() - 6)?
}
_ => date,
};
let date = chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()?;
let mut out = format!("{:04}-{:02}-{:02}", date.year(), date.month(), date.day());
if let Some(time) = time {
let (clock, fraction) = clock_time(time)?;
if clock != chrono::NaiveTime::MIN || !fraction.is_empty() {
out.push(' ');
out.push_str(&hh_mm((clock, fraction)));
}
}
Some(out)
}
/// A clock time `hh:mm[:ss[.s…]]` with an optional `Z` or `±hh:mm` zone (one, not both), which is
/// left out. The seconds' fraction comes back as its digits as written, trailing zeros dropped,
/// so a fraction finer than a nanosecond is kept.
fn clock_time(t: &str) -> Option<(chrono::NaiveTime, String)> {
let t = match (t.strip_suffix('Z'), t.rfind(['+', '-'])) {
(Some(t), _) => t,
(None, Some(i)) => {
zone_offset(t.get(i + 1..)?)?;
t.get(..i)?
}
(None, None) => t,
};
let (clock, fraction) = match t.split_once('.') {
// A fraction needs whole seconds before it.
Some((t, frac)) => {
if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
(chrono::NaiveTime::parse_from_str(t, "%H:%M:%S").ok()?, frac.trim_end_matches('0'))
}
None => (chrono::NaiveTime::parse_from_str(t, "%H:%M:%S").or_else(|_| chrono::NaiveTime::parse_from_str(t, "%H:%M")).ok()?, ""),
};
// A leap second (`23:59:60`) is not a time a cell holds.
(chrono::Timelike::nanosecond(&clock) < 1_000_000_000).then(|| (clock, fraction.to_string()))
}
/// A zone offset's `hh:mm`, two digits each and at most `14:00` as XML Schema allows.
fn zone_offset(z: &str) -> Option<()> {
use chrono::Timelike;
let two_digit = z.len() == 5 && z.bytes().enumerate().all(|(i, b)| if i == 2 { b == b':' } else { b.is_ascii_digit() });
if !two_digit {
return None;
}
let z = chrono::NaiveTime::parse_from_str(z, "%H:%M").ok()?;
(z.hour() < 14 || (z.hour() == 14 && z.minute() == 0)).then_some(())
}
/// `hh:mm`, with `:ss` when the seconds aren't zero and their fraction when it isn't.
fn hh_mm((t, fraction): (chrono::NaiveTime, String)) -> String {
use chrono::Timelike;
let (h, m, s) = (t.hour(), t.minute(), t.second());
if !fraction.is_empty() {
format!("{h:02}:{m:02}:{s:02}.{fraction}")
} else if s == 0 {
format!("{h:02}:{m:02}")
} else {
format!("{h:02}:{m:02}:{s:02}")
}
}
/// An ISO 8601 duration (`PT13H45M00S`, `P1DT2H`, `-PT1H`) or clock time (`13:45[:00]`) as
/// `hh:mm[:ss]`, a duration's days counted as hours and a negative one with a leading `-`.
/// `None` for anything else, years and months included.
fn iso_time(v: &str) -> Option<String> {
let t = v.trim();
let (negative, t) = match t.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, t),
};
let Some(t) = t.strip_prefix('P') else {
return if negative { None } else { clock_time(t).map(hh_mm) };
};
let (days, t, has_t) = match t.split_once('T') {
Some((days, time)) => (days, time, true),
None => (t, "", false),
};
// A `T` needs a time after it.
if has_t && t.is_empty() {
return None;
}
let mut any = !days.is_empty();
let days: u64 = if days.is_empty() { 0 } else { days.strip_suffix('D')?.parse().ok()? };
let (mut h, mut m, mut s) = (0u64, 0u64, 0u64);
// The seconds' fraction digits, kept as written.
let mut fraction = String::new();
let mut num = String::new();
// Units come in the order H, M, S, each at most once.
let mut next_unit = 0;
for c in t.chars() {
let unit = match c {
'H' => 1,
'M' => 2,
'S' => 3,
'0'..='9' | '.' if num.len() < 20 => {
num.push(c);
continue;
}
_ => return None,
};
if unit <= next_unit {
return None;
}
next_unit = unit;
let n = std::mem::take(&mut num);
match unit {
1 => h = n.parse().ok()?,
2 => m = n.parse().ok()?,
_ => {
let (whole, frac) = n.split_once('.').unwrap_or((&n, ""));
if whole.is_empty() || (n.contains('.') && frac.is_empty()) || !frac.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
s = whole.parse().ok()?;
fraction = frac.trim_end_matches('0').to_string();
}
}
any = true;
}
if !any || !num.is_empty() {
return None;
}
// A duration too long to count in hours is not a time.
m = m.checked_add(s / 60)?;
s %= 60;
h = h.checked_add(m / 60)?.checked_add(days.checked_mul(24)?)?;
m %= 60;
let sign = if negative && ((h, m, s) != (0, 0, 0) || !fraction.is_empty()) { "-" } else { "" };
Some(if !fraction.is_empty() {
format!("{sign}{h:02}:{m:02}:{s:02}.{fraction}")
} else if s == 0 {
format!("{sign}{h:02}:{m:02}")
} else {
format!("{sign}{h:02}:{m:02}:{s:02}")
})
}
fn cells_to_rows<C>(cells: &BTreeMap<CellRef, C>, fmt: impl Fn(&C) -> String) -> Vec<Vec<String>> {
let mut grid: BTreeMap<(u32, u32), String> = BTreeMap::new();
for (r, c) in cells {
@@ -381,158 +208,3 @@ fn grid_to_rows(grid: &BTreeMap<(u32, u32), String>) -> Vec<Vec<String>> {
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
/// An `.ods` package whose body is `tables` (`table:table` elements).
fn spreadsheet(tables: &str) -> Result<Vec<u8>, craft_odf::Error> {
let content = format!(
r#"<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:spreadsheet>{tables}</office:spreadsheet></office:body></office:document-content>"#
);
let mut w = craft_odf::PackageWriter::new(craft_odf::mime::SPREADSHEET);
w.file("content.xml", "text/xml", content.as_bytes());
w.finish()
}
#[test]
fn ods_cells_read_their_typed_values() {
let book = spreadsheet(
r#"<table:table table:name="Guests">
<table:table-row><table:table-cell office:value-type="string"><text:p>Name</text:p></table:table-cell><table:table-cell table:number-columns-repeated="2"/><table:table-cell office:value-type="string"><text:p>When</text:p></table:table-cell><table:table-cell office:value-type="string" table:number-columns-repeated="2"><text:p>Tag</text:p></table:table-cell></table:table-row>
<table:table-row table:number-rows-repeated="2"><table:table-cell office:value-type="string" table:number-columns-spanned="2"><text:p>Ada<text:s text:c="2"/>L</text:p><text:p>x</text:p><office:annotation><text:p>note</text:p></office:annotation></table:table-cell><table:covered-table-cell office:value-type="string"><text:p>hidden</text:p></table:covered-table-cell><table:table-cell office:value-type="float" office:value="3.50"><text:p>3,5</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T00:00:00"><text:p>05/03/24</text:p></table:table-cell><table:table-cell office:value-type="boolean" office:boolean-value="false"><text:p>NO</text:p></table:table-cell><table:table-cell office:value-type="time" office:time-value="PT13H45M00S"><text:p>01:45 PM</text:p></table:table-cell></table:table-row>
<table:table-row><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:30"><text:p>Tue</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="not a date"><text:p>someday</text:p></table:table-cell><table:table-cell office:value-type="percentage" office:value="0.25"><text:p>25%</text:p></table:table-cell><table:table-cell office:value-type="currency" office:value="9"/></table:table-row>
</table:table>"#,
)
.unwrap();
let (_, rows) = read_rows(&book, Pick::Name("Guests")).unwrap();
assert_eq!(rows.len(), 4);
assert_eq!(rows[0], ["Name", "", "", "When", "Tag", "Tag"]);
assert_eq!(rows[1], ["Ada L\nx", "", "3.5", "2024-03-05", "FALSE", "13:45"]);
assert_eq!(rows[1], rows[2]);
assert_eq!(rows[3], ["2024-03-05 13:45:30", "someday", "25%", "9"]);
}
#[test]
fn an_ods_date_with_two_zones_reads_its_text() {
let book = spreadsheet(
r#"<table:table table:name="Dates">
<table:table-row><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00+02:00Z"><text:p>offset then Z</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00Z+02:00"><text:p>Z then offset</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00+02:00"><text:p>one zone</text:p></table:table-cell></table:table-row>
</table:table>"#,
)
.unwrap();
let (_, rows) = read_rows(&book, Pick::Name("Dates")).unwrap();
assert_eq!(rows, [["offset then Z", "Z then offset", "2024-03-05 13:45"]]);
}
#[test]
fn ods_dates_and_durations() {
assert_eq!(iso_time("PT1H59M59.6S").as_deref(), Some("01:59:59.6"));
assert_eq!(iso_time("PT0.25S").as_deref(), Some("00:00:00.25"));
assert_eq!(iso_time("PT59M60.50S").as_deref(), Some("01:00:00.5"));
assert_eq!(iso_time("PT0H0M59S").as_deref(), Some("00:00:59"));
assert_eq!(iso_time("PT1H2M3S").as_deref(), Some("01:02:03"));
assert_eq!(iso_time("PT1.S"), None);
assert_eq!(iso_time("P1000000000000000000D"), None);
}
#[test]
fn a_clock_time_keeps_its_seconds_fraction_as_written() {
assert_eq!(iso_datetime("2024-03-05T00:00:00.0000000001").as_deref(), Some("2024-03-05 00:00:00.0000000001"));
assert_eq!(iso_datetime("2024-03-05T13:45:30.1234567891Z").as_deref(), Some("2024-03-05 13:45:30.1234567891"));
assert_eq!(iso_datetime("2024-03-05T13:45:30.500+02:00").as_deref(), Some("2024-03-05 13:45:30.5"));
assert_eq!(iso_datetime("2024-03-05T00:00:00.000").as_deref(), Some("2024-03-05"));
assert_eq!(iso_time("13:45:00.1234567891").as_deref(), Some("13:45:00.1234567891"));
assert_eq!(iso_time("PT13H45M0.1234567891S").as_deref(), Some("13:45:00.1234567891"));
assert_eq!(iso_time("13:45:00."), None);
assert_eq!(iso_time("13:45:00.5x"), None);
assert_eq!(iso_time("13:45.5"), None);
assert_eq!(iso_time("23:59:60.5"), None);
assert_eq!(iso_time("13: 45.5"), None);
assert_eq!(iso_time("1:45:30.5").as_deref(), Some("01:45:30.5"));
}
#[test]
fn a_typed_ods_value_keeps_to_the_cell_limit() {
let long = format!("2024-03-05T13:45:30.{}", "1".repeat(MAX_CELL_CHARS));
let book = spreadsheet(&format!(
r#"<table:table table:name="Long"><table:table-row><table:table-cell office:value-type="date" office:date-value="{long}"><text:p>x</text:p></table:table-cell></table:table-row></table:table>"#
))
.unwrap();
let (_, rows) = read_rows(&book, Pick::Name("Long")).unwrap();
assert_eq!(rows[0][0].chars().count(), MAX_CELL_CHARS);
}
#[test]
fn a_date_alone_drops_its_zone() {
assert_eq!(iso_datetime("2024-03-05Z").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05+02:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05-05:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05+02:99"), None);
}
#[test]
fn a_zone_is_at_most_fourteen_hours() {
assert_eq!(iso_datetime("2024-03-05+14:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05-14:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05+14:01"), None);
assert_eq!(iso_datetime("2024-03-05-15:00"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00+14:00").as_deref(), Some("2024-03-05 13:45"));
assert_eq!(iso_datetime("2024-03-05T13:45:00+14:01"), None);
assert_eq!(iso_time("13:45:00-15:00"), None);
}
#[test]
fn a_zone_is_z_or_an_offset_not_both() {
assert_eq!(iso_datetime("2024-03-05T13:45:00+02:00Z"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00Z+02:00"), None);
assert_eq!(iso_datetime("2024-03-05+02:00Z"), None);
assert_eq!(iso_datetime("2024-03-05Z+02:00"), None);
assert_eq!(iso_time("13:45:00+02:00Z"), None);
assert_eq!(iso_time("13:45:00Z+02:00"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00Z").as_deref(), Some("2024-03-05 13:45"));
assert_eq!(iso_datetime("2024-03-05T13:45:00-05:00").as_deref(), Some("2024-03-05 13:45"));
assert_eq!(iso_time("13:45:00+02:00").as_deref(), Some("13:45"));
}
#[test]
fn a_zone_offset_has_two_digit_hours_and_minutes() {
assert_eq!(iso_datetime("2024-03-05T13:45:00+2:00"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00+ 2:00"), None);
assert_eq!(iso_time("13:45:00-5:00"), None);
}
#[test]
fn a_leap_second_is_not_a_time() {
assert_eq!(iso_datetime("2024-03-05T23:59:60Z"), None);
assert_eq!(iso_time("23:59:60"), None);
}
#[test]
fn a_duration_with_t_needs_a_time() {
assert_eq!(iso_time("P1DT"), None);
assert_eq!(iso_time("P0DT"), None);
assert_eq!(iso_time("P1D").as_deref(), Some("24:00"));
assert_eq!(iso_time("PT.S"), None);
assert_eq!(iso_time("13:45:00Z").as_deref(), Some("13:45"));
assert_eq!(iso_time("-PT1H").as_deref(), Some("-01:00"));
assert_eq!(iso_time("P2DT1H30M").as_deref(), Some("49:30"));
assert_eq!(iso_time("P1D").as_deref(), Some("24:00"));
assert_eq!(iso_time("P1Y2M"), None);
assert_eq!(iso_time("PT"), None);
assert_eq!(iso_time("PT5"), None);
assert_eq!(iso_time("PT1H2H"), None);
assert_eq!(iso_time("PT1S2H"), None);
assert_eq!(iso_datetime("2024-03-05T"), None);
assert_eq!(iso_datetime("2024-03-05T00:00:00.500").as_deref(), Some("2024-03-05 00:00:00.5"));
assert_eq!(iso_time("00:00:00.250").as_deref(), Some("00:00:00.25"));
assert_eq!(iso_time("25:00"), None);
assert_eq!(iso_datetime("2024-03-05T00:00:00.000").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05T13:45:30+02:00").as_deref(), Some("2024-03-05 13:45:30"));
assert_eq!(iso_datetime("2024-13-05"), None);
assert_eq!(iso_datetime("2023-02-29"), None);
assert_eq!(iso_datetime("2024-03-05junk"), None);
assert_eq!(iso_datetime("2024-03-05T13:99"), None);
}
}
+14 -24
View File
@@ -330,14 +330,6 @@ fn rtf_round_trip() {
assert_eq!(back.core.creator, "Ada Writer");
}
/// A file the format cannot read is an error, not a blank document: the reader says what it
/// could not read, so the caller can say so too.
#[test]
fn a_format_that_cannot_be_read_is_an_error_not_a_blank_document() {
let e = import("rtf", b"not an RTF document").unwrap().unwrap_err();
assert!(e.contains("RTF"), "{e}");
}
#[test]
fn odt_round_trip() {
check_round_trip("odt", true);
@@ -607,7 +599,7 @@ fn latex_export_carries_no_commands_from_the_document() {
assert_eq!(crate::latex::linear_to_latex("\\alpha+\\sin x+\\mathbb R"), "\\alpha+\\sin x+\\mathbb R");
assert_eq!(crate::latex::linear_to_latex("x^2^3"), "x^2^3");
// The same through a whole file, and for a bookmark name.
let d = crate::latex::import("Text $\\input secret.txt $ and \\hypertarget{^^5cinput secret.txt ^^5c}{here}.".as_bytes()).unwrap();
let d = crate::latex::import("Text $\\input secret.txt $ and \\hypertarget{^^5cinput secret.txt ^^5c}{here}.".as_bytes());
let out = String::from_utf8(export("tex", &d).unwrap().unwrap()).unwrap();
assert!(!out.contains("\\input") && !out.contains("^^"), "{out}");
}
@@ -620,11 +612,11 @@ fn latex_export_carries_no_commands_from_the_document() {
fn latex_labels_in_a_row_are_read_in_linear_time() {
let started = std::time::Instant::now();
for src in ["\\label{a} ".repeat(100_000) + "x", "\\label{a}".repeat(100_000) + "x", "\\hypertarget{a}{} ".repeat(100_000)] {
let d = crate::latex::import(src.as_bytes()).unwrap();
let d = crate::latex::import(src.as_bytes());
assert!(d.body.len() <= 2);
}
assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
let d = crate::latex::import("\\label{one}First \\label{two}second \\label{three}third.".as_bytes()).unwrap();
let d = crate::latex::import("\\label{one}First \\label{two}second \\label{three}third.".as_bytes());
let p = d.para_at(&wordcraft_doc::Pos::body(0, 0)).unwrap();
let names: Vec<&str> = p
.objects
@@ -741,8 +733,7 @@ fn html_img_sources_go_through_the_loader() {
let d = crate::html::import_with(html, &|src| {
seen.borrow_mut().push(src.to_string());
(src == "logo.png").then(|| std::sync::Arc::new(pic.clone()))
})
.unwrap();
});
assert_eq!(*seen.borrow(), ["logo.png", "gone.png"]);
assert_eq!(d.media.len(), 1);
let text = d.plain_text(wordcraft_doc::StoryRef::Body);
@@ -1130,7 +1121,7 @@ fn hidden_drawings_are_left_out_of_exports() {
d.insert_object(&wordcraft_doc::Pos::body(0, 0), image, &Default::default()).unwrap();
}
// Two pictures, one hidden: one comes out.
assert_eq!(crate::html::export(&d).unwrap().matches("<img").count(), 1);
assert_eq!(crate::html::export(&d).matches("<img").count(), 1);
}
/// Every text span of the flow, with its formatting.
@@ -1218,17 +1209,16 @@ fn dropped_names_and_links_are_logged_once_per_document() {
let count = |w: &[String], what: &str| w.iter().filter(|l| l.contains(what)).count();
for _ in 0..2 {
// Each import is its own document: the second is reported too.
let (doc, warned) = crate::test_log::warnings(|| crate::html::import(&html).unwrap());
let (doc, warned) = crate::test_log::warnings(|| crate::html::import(&html));
assert!(doc.body.len() == 1, "the text is kept");
assert_eq!(count(&warned, "font names longer"), 1, "{warned:?}");
assert_eq!(count(&warned, "links longer"), 1, "{warned:?}");
}
let (_, warned) =
crate::test_log::warnings(|| crate::html::import("<p><a href=\"https://e.com\" style=\"font-family:Georgia\">fine</a></p>").unwrap());
let (_, warned) = crate::test_log::warnings(|| crate::html::import("<p><a href=\"https://e.com\" style=\"font-family:Georgia\">fine</a></p>"));
assert!(warned.is_empty(), "nothing left out, nothing said: {warned:?}");
let md = format!("[a](https://e.com/{long}) [b](https://e.com/{long})");
let (_, warned) = crate::test_log::warnings(|| crate::markdown::import(&md).unwrap());
let (_, warned) = crate::test_log::warnings(|| crate::markdown::import(&md));
assert_eq!(count(&warned, "links longer"), 1, "{warned:?}");
let rtf =
@@ -1238,14 +1228,14 @@ fn dropped_names_and_links_are_logged_once_per_document() {
assert_eq!(count(&warned, "style names longer"), 1, "{warned:?}");
let tex = format!("\\href{{https://e.com/{long}}}{{a}} \\url{{https://e.com/{long}}}");
let (_, warned) = crate::test_log::warnings(|| crate::latex::import(tex.as_bytes()).unwrap());
let (_, warned) = crate::test_log::warnings(|| crate::latex::import(tex.as_bytes()));
assert_eq!(count(&warned, "links longer"), 1, "{warned:?}");
}
#[test]
fn html_title_outside_head_is_metadata_not_body() {
for html in ["<title>T</title><p>b</p>", "<html><title>T</title><body>b</body></html>"] {
let d = crate::html::import(html).unwrap();
let d = crate::html::import(html);
assert_eq!(para_texts(&d), vec!["b".to_string()], "{html}");
assert_eq!(d.core.title, "T", "{html}");
}
@@ -1271,7 +1261,7 @@ fn html_container_shading_is_paragraph_shading_while_inline_highlight_stays_on_r
r#"<div style="background-color:#1e1e1e"><p>text <code style="background-color:#eeeeee">x</code></p></div>"#,
r#"<div style="background-color:#1e1e1e"><div>a</div><div>&nbsp;</div><div>b</div></div>"#,
);
let doc = crate::html::import(html).unwrap();
let doc = crate::html::import(html);
assert_eq!(doc.body.len(), 7);
let Block::Para(code) = &*doc.body[0] else { panic!("expected code paragraph") };
@@ -1296,8 +1286,8 @@ fn html_container_shading_is_paragraph_shading_while_inline_highlight_stays_on_r
assert_eq!(line.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "line {idx} (blank included) keeps container shading");
}
for exported in [crate::html::export(&doc).unwrap(), crate::html::export_fragment(&doc).unwrap()] {
let back = crate::html::import(&exported).unwrap();
for exported in [crate::html::export(&doc), crate::html::export_fragment(&doc)] {
let back = crate::html::import(&exported);
let Block::Para(p0) = &*back.body[0] else { panic!("expected paragraph 0") };
let Block::Para(p1) = &*back.body[1] else { panic!("expected paragraph 1") };
let Block::Para(p2) = &*back.body[2] else { panic!("expected paragraph 2") };
@@ -1316,7 +1306,7 @@ fn odt_list_item_later_paragraphs_stay_in_the_item() {
let fodt = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text"><office:automatic-styles><text:list-style style:name="L1"><text:list-level-style-number text:level="1" style:num-format="1"/></text:list-style></office:automatic-styles><office:body><office:text><text:list text:style-name="L1"><text:list-item><text:p>One</text:p><text:p>Still one</text:p></text:list-item><text:list-item><text:p>Two</text:p></text:list-item></text:list></office:text></office:body></office:document>"#;
let doc = crate::odt::import_flat(fodt.as_bytes()).unwrap();
let html = crate::html::export(&doc).unwrap();
let html = crate::html::export(&doc);
assert_eq!(html.matches("<ol").count(), 1, "one list, not restarted: {html}");
let (one, still, two) = (html.find("One").unwrap(), html.find("Still one").unwrap(), html.find("Two").unwrap());
assert!(one < still && still < two, "{html}");
+1 -1
View File
@@ -152,7 +152,7 @@ pub(crate) fn add(ctx: &mut Ctx, lay: &mut DocLayout) {
author_name(&cm.author),
CharProps { bold: Some(true), size: Some(9.0), color: Some(TextColor::Rgb(color)), ..Default::default() },
);
let pl = ctx.para_labelled(&head, inner, None, &[], 0.0, None);
let pl = ctx.para_labelled(&head, inner, None, &[], None);
let lead = pl.lines.first().map_or(0.0, |l| l.top.max(0.0));
push_para(&mut items, (story, &[HEADER_PATH]), &pl, (0, pl.lines.len()), (x, y + lead), inner, Edges::own(&pl, 0, pl.lines.len()));
y += pl.height + 2.0;
+11 -20
View File
@@ -276,17 +276,17 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
Block::Para(p) => {
// A paragraph after one whose mark is hidden goes on from that one's last line
// (Word, #3986; see `Joint`); one that shows nothing passes the place on.
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table, cell_frame);
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table);
let p = taken.as_ref().map_or(p, |t| &t.para);
let label = ctx.next_label(p);
let listed = label.is_some();
let mut pl = ctx.para_labelled(p, width, table, &[], 0.0, label.clone());
let mut pl = ctx.para_labelled(p, width, table, &[], label.clone());
// A text frame (a footer's page number in a frame, say) is placed apart, like a
// floating object, and the text after it wraps around it; it takes no room in
// the flow.
if let Some(fr) = pl.rp.frame.clone().filter(|fr| frames && cell_frame(fr)) {
let fw = fr.w.unwrap_or_else(|| natural_width(&pl)).clamp(1.0, 1584.0);
let pf = if (fw - width).abs() > 0.01 { ctx.para_labelled(p, fw, table, &[], 0.0, label) } else { pl };
let pf = if (fw - width).abs() > 0.01 { ctx.para_labelled(p, fw, table, &[], label) } else { pl };
let h = match fr.h {
Some(h) if fr.h_exact => h,
Some(h) => h.max(pf.height),
@@ -318,8 +318,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
// body path. Keep text and wrap exclusions relative to the text's actual top.
// A paragraph going on from a shared line has its origin at that line's top.
let para_top = taken.as_ref().map_or(y, |t| t.joint.top);
let applied = if i == 0 { before } else { before.max(0.0) };
y += applied;
y += if i == 0 { before } else { before.max(0.0) };
TakenUp::start(taken.as_ref(), &mut y, &mut excl);
// Floating objects anchored here: place them, then wrap the text around them.
// One left out of the layout (hidden, or deleted in the final text) takes no room.
@@ -363,9 +362,9 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
}
floats.insert(oi, r);
}
let rel = rel_exclusions(&excl, 0.0, y, applied);
let rel = rel_exclusions(&excl, 0.0, y);
if !rel.is_empty() {
pl = ctx.para_labelled(p, width, table, &rel, applied, label);
pl = ctx.para_labelled(p, width, table, &rel, label);
}
TakenUp::clear(taken.as_ref(), &mut excl);
// Bordered paragraphs: room for their borders, those of a group joined in one box.
@@ -478,7 +477,7 @@ fn natural_width(pl: &ParaLayout) -> f32 {
}
/// A text frame's placement as a floating object's (`w:framePr` → anchors, alignment, wrap).
pub(crate) fn frame_float(fr: &wordcraft_doc::props::TextFrame) -> Float {
fn frame_float(fr: &wordcraft_doc::props::TextFrame) -> Float {
let anchor = |a: &str, text: Anchor| match a {
"page" => Anchor::Page,
"margin" => Anchor::Margin,
@@ -778,14 +777,13 @@ impl Joint {
(i, p): (usize, &Paragraph),
(width, frames): (f32, bool),
table: Option<&para::CellText>,
cell_frame: impl Fn(&wordcraft_doc::props::TextFrame) -> bool,
) -> (bool, bool, Option<TakenUp>) {
let chr = table.map(|t| &t.chr);
let mark_hidden = ctx.mark_hidden(p, chr);
let shows_nothing = mark_hidden && ctx.text_hidden(p, chr);
let came = joint.take().filter(|j| j.next == i);
*joint = came.filter(|_| shows_nothing).map(|j| Joint { next: i + 1, ..j });
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table, cell_frame));
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table));
(mark_hidden, shows_nothing, taken)
}
@@ -801,7 +799,7 @@ impl Joint {
/// taller than the text going on from it), with the room for its bottom border (Word).
pub(crate) fn fit(&self, ctx: &mut Ctx, q: &Paragraph, width: f32, table: Option<&para::CellText>) -> (f32, Vec<WrapArea>) {
let eq = ctx.eq_count;
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], 0.0, None));
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], None));
let (gap, height) = probe.lines.first().map_or((0.0, self.height), |l| ((self.baseline - (l.baseline - l.top)).max(0.0), l.height));
let rect = Rect::new(self.left, self.top, (self.end - self.left).max(0.0), (gap + height - 0.01).max(0.01));
let mut areas = vec![(rect, false, None, WrapText::Right, false)];
@@ -829,16 +827,9 @@ impl Joint {
/// Paragraph `p` of a box `width` wide going on from here, unless a page break comes before
/// it, it runs right to left or it is a text frame (`frames`: placed apart, sharing no line):
/// without its space before, as [`Joint::fit`] lays it out.
fn take_up(
self,
ctx: &mut Ctx,
p: &Paragraph,
(width, frames): (f32, bool),
table: Option<&para::CellText>,
cell_frame: impl Fn(&wordcraft_doc::props::TextFrame) -> bool,
) -> Option<TakenUp> {
fn take_up(self, ctx: &mut Ctx, p: &Paragraph, (width, frames): (f32, bool), table: Option<&para::CellText>) -> Option<TakenUp> {
let own = ctx.doc.styles.resolve_para_in(&p.props, table.map(|t| &t.para));
if own.page_break_before || own.bidi || own.frame.as_ref().is_some_and(|fr| frames && cell_frame(fr)) {
if own.page_break_before || own.bidi || (frames && own.frame.is_some()) {
return None;
}
let mut para = p.clone();
+3 -60
View File
@@ -16,9 +16,6 @@ pub(crate) struct Key {
pub(crate) table: u64,
pub(crate) notes: u64,
pub(crate) excl: u64,
/// The space before the paragraph layout applied above it, which a Top-and-Bottom object in
/// it is laid out again below ([`para::ParaEnv::space_before`]).
pub(crate) space_before: u32,
pub(crate) eq: u32,
pub(crate) read_spacing: Option<u32>,
pub(crate) grid: (u32, u32, u32, bool),
@@ -35,14 +32,6 @@ pub(crate) struct Key {
pub(crate) joined: Option<(u32, bool)>,
}
pub(crate) struct StylesEnv {
styles: std::sync::Weak<wordcraft_doc::styles::StyleSheet>,
numbering: std::sync::Weak<wordcraft_doc::numbering::Numbering>,
default_tab: u32,
footnote_format: wordcraft_doc::section::NumFormat,
hash: u64,
}
/// Memoised paragraph layouts.
#[derive(Default)]
pub struct LayoutCache {
@@ -55,7 +44,6 @@ pub struct LayoutCache {
/// kept, so no other picture's bytes can come to have its address ([`Outlines`]).
pub(crate) outlines: Outlines,
pub(crate) env: u64,
pub(crate) styles_env: Option<StylesEnv>,
pub(crate) used: HashSet<Key>,
/// The STYLEREF style index of the last pass and what it was built from: the body blocks
/// (shared, so an edited block is a different pointer) and `env` (styles and numbering). Kept
@@ -79,7 +67,6 @@ impl LayoutCache {
self.paras.clear();
self.measures.clear();
self.outlines.clear();
self.styles_env = None;
self.styleref = None;
}
@@ -104,56 +91,12 @@ pub(crate) fn hash_of<T: Hash>(t: &T) -> u64 {
h.finish()
}
struct HashWriter<'a>(&'a mut std::collections::hash_map::DefaultHasher);
impl std::io::Write for HashWriter<'_> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.write(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
/// Fingerprint of stylesheet, numbering, default tab, and footnote format, memoised on
/// [`LayoutCache::styles_env`] via `Weak` pointers so unchanged passes skip JSON serialisation.
/// Holding live `Weak` references keeps the underlying `ArcInner` allocations reserved, ensuring a
/// fresh `Arc` allocation cannot reuse a still-cached address.
fn styles_env_hash(doc: &Document, cache: &mut LayoutCache) -> u64 {
let tab = doc.settings.default_tab.to_bits();
if let Some(cached) = &cache.styles_env
&& cached.styles.as_ptr() == Arc::as_ptr(&doc.styles)
&& cached.styles.strong_count() > 0
&& cached.numbering.as_ptr() == Arc::as_ptr(&doc.numbering)
&& cached.numbering.strong_count() > 0
&& cached.default_tab == tab
&& cached.footnote_format == doc.settings.footnote_format
{
return cached.hash;
}
let mut sh = std::collections::hash_map::DefaultHasher::new();
let _ = serde_json::to_writer(HashWriter(&mut sh), &(&doc.styles, &doc.numbering, doc.settings.default_tab, &doc.settings.footnote_format));
let hash = sh.finish();
cache.styles_env = Some(StylesEnv {
styles: Arc::downgrade(&doc.styles),
numbering: Arc::downgrade(&doc.numbering),
default_tab: tab,
footnote_format: doc.settings.footnote_format,
hash,
});
hash
}
pub(crate) fn env_hash(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions) -> u64 {
let styles = styles_env_hash(doc, cache);
pub(crate) fn env_hash(doc: &Document, opts: &LayoutOptions) -> u64 {
let s = serde_json::to_string(&(&doc.styles, &doc.numbering, doc.settings.default_tab, &doc.settings.footnote_format)).unwrap_or_default();
// Outline view lays paragraphs out changed (no indents; plain without text formatting).
let outline = (opts.view == ViewMode::Outline).then(|| opts.outline.as_ref().is_some_and(|o| o.plain));
let mut h = std::collections::hash_map::DefaultHasher::new();
styles.hash(&mut h);
// The compatibility mode changes paragraph layout too (widow control in table cells).
doc.settings.compat_mode.hash(&mut h);
s.hash(&mut h);
opts.show_hidden.hash(&mut h);
opts.hide_deleted.hash(&mut h);
opts.hide_marked.hash(&mut h);
+5 -23
View File
@@ -113,21 +113,12 @@ struct ParaEnvInput<'a> {
label: Option<(String, Level)>,
table: Option<&'a para::CellText>,
exclusions: &'a [para::Exclusion],
space_before: f32,
eq_number: u32,
typing_word: Option<(usize, usize)>,
fitted: &'a [(usize, f32)],
joined: bool,
}
/// The flow's wrap context for a paragraph's layout, as its cache key needs it: the areas text
/// flows around (relative to its first line) and the space before it the flow laid out, which
/// reaches up to them (see [`para::ParaEnv::space_before`]).
struct WrapAreas<'a> {
exclusions: &'a [para::Exclusion],
space_before: f32,
}
/// A header or footer (`story`) laid out for page `number` of a section (`sect`, `mirror`): its
/// table cells' floats placed on the page rather than in their cell ([`Float::outside_cell`],
/// Word's picture watermark in a header that starts with a table), drawn behind the header's
@@ -261,7 +252,6 @@ impl Ctx<'_> {
typing_word: None,
numeral: self.opts.numeral,
exclusions: &[],
space_before: 0.0,
eq_number: 0,
read_line_spacing: None,
grid: para::Grid::default(),
@@ -309,18 +299,16 @@ impl Ctx<'_> {
/// Lay out `p` with its already counted `label`, so laying a paragraph out again (around
/// floating objects, or after it moved) doesn't advance the list counters twice.
/// `space_before` is the space before `p` that the flow laid out above it ([`para::ParaEnv`]).
pub(crate) fn para_labelled(
&mut self,
p: &Paragraph,
width: f32,
table: Option<&para::CellText>,
exclusions: &[para::Exclusion],
space_before: f32,
label: Option<(String, Level)>,
) -> Arc<ParaLayout> {
let fitted = self.fitted_boxes(p);
let (key, eq_number) = self.para_key(p, width, table, WrapAreas { exclusions, space_before }, label.as_ref(), &fitted);
let (key, eq_number) = self.para_key(p, width, table, exclusions, label.as_ref(), &fitted);
self.cache.used.insert(key.clone());
if let Some(pl) = self.cache.paras.get(&key) {
self.cache.hits += 1;
@@ -335,7 +323,6 @@ impl Ctx<'_> {
label,
table,
exclusions,
space_before,
eq_number,
typing_word: typing,
fitted: &fitted,
@@ -360,7 +347,7 @@ impl Ctx<'_> {
return None;
}
let kept = (self.eq_count, self.uses_totals);
let (key, eq_number) = self.para_key(p, width, None, WrapAreas { exclusions: &[], space_before: 0.0 }, label.as_ref(), &[]);
let (key, eq_number) = self.para_key(p, width, None, &[], label.as_ref(), &[]);
(self.eq_count, self.uses_totals) = kept;
if key.typing.is_some() {
return None;
@@ -378,7 +365,6 @@ impl Ctx<'_> {
label,
table: None,
exclusions: &[],
space_before: 0.0,
eq_number,
typing_word: None,
fitted: &[],
@@ -401,7 +387,7 @@ impl Ctx<'_> {
measure: impl FnOnce(&ParaLayout) -> (f32, f32),
) -> (f32, f32) {
let fitted = self.fitted_boxes(p);
let (key, eq_number) = self.para_key(p, width, table, WrapAreas { exclusions: &[], space_before: 0.0 }, label.as_ref(), &fitted);
let (key, eq_number) = self.para_key(p, width, table, &[], label.as_ref(), &fitted);
self.cache.used.insert(key.clone());
if let Some(m) = self.cache.measures.get(&key) {
self.cache.hits += 1;
@@ -416,7 +402,6 @@ impl Ctx<'_> {
label,
table,
exclusions: &[],
space_before: 0.0,
eq_number,
typing_word: typing,
fitted: &fitted,
@@ -470,11 +455,10 @@ impl Ctx<'_> {
p: &Paragraph,
width: f32,
table: Option<&para::CellText>,
wrap: WrapAreas<'_>,
exclusions: &[para::Exclusion],
label: Option<&(String, Level)>,
fitted: &[(usize, f32)],
) -> (Key, u32) {
let WrapAreas { exclusions, space_before } = wrap;
let page = if has_page_fields(p) { Some(self.fields.page_key()) } else { None };
if self.track_totals && !self.uses_totals && has_total_fields(p) {
self.uses_totals = true;
@@ -499,7 +483,6 @@ impl Ctx<'_> {
table: table.map(|t| self.table_key(t)).unwrap_or(0),
notes: if p.objects.iter().any(|o| matches!(o, InlineObject::NoteRef { .. })) { self.notes_hash } else { 0 },
excl: if exclusions.is_empty() { 0 } else { hash_of(&format!("{exclusions:?}")) },
space_before: space_before.to_bits(),
eq: if eq_here > 0 { eq_number } else { 0 },
read_spacing: if self.opts.view == ViewMode::Read { self.opts.read_line_spacing.map(f32::to_bits) } else { None },
grid: self.grid.key(),
@@ -529,7 +512,7 @@ impl Ctx<'_> {
}
fn para_env<'b>(&'b self, input: ParaEnvInput<'b>) -> para::ParaEnv<'b> {
let ParaEnvInput { width, label, table, exclusions, space_before, eq_number, typing_word, fitted, joined } = input;
let ParaEnvInput { width, label, table, exclusions, eq_number, typing_word, fitted, joined } = input;
para::ParaEnv {
doc: self.doc,
width,
@@ -543,7 +526,6 @@ impl Ctx<'_> {
typing_word,
numeral: self.opts.numeral,
exclusions,
space_before,
eq_number,
read_line_spacing: if self.opts.view == ViewMode::Read { self.opts.read_line_spacing } else { None },
grid: self.grid,
+6 -12
View File
@@ -219,10 +219,8 @@ pub(crate) fn wrap_area(r: Rect, float: &Float, outline: Option<&[(f32, f32)]>)
Some((Rect::new(r.x - side, r.y - top, r.w + side * 2.0, r.h + top + bottom), float.wrap == Wrap::TopAndBottom, None, float.wrap_text, false))
}
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`, with
/// `space_before` the space before it that the flow laid out above it.
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before: f32) -> Vec<para::Exclusion> {
let before = if space_before > 0.0 { space_before } else { 0.0 };
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`.
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32) -> Vec<para::Exclusion> {
excl.iter()
.map(|(r, tb, c, side, table)| para::Exclusion {
top: r.y - y0,
@@ -234,11 +232,7 @@ pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before:
side: *side,
table: *table,
})
// Top-and-Bottom areas ending within the paragraph's applied space before can still take
// room, with that space laid out again below them (#7143). Any ending at or above it
// (like side-wrapping areas above the first line) cannot reach the paragraph and is
// dropped so paragraphs below keep empty exclusions and hit the cache (#8613).
.filter(|e| e.bottom > 0.0 || (e.top_bottom && e.bottom > -before))
.filter(|e| e.bottom > 0.0)
.collect()
}
@@ -531,8 +525,8 @@ fn anchor_floats_but(
}
}
}
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0, before);
let pl = ctx.para_labelled(p, width, None, &rel, before, label.clone());
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0);
let pl = ctx.para_labelled(p, width, None, &rel, label.clone());
(rects, pl, rel)
}
@@ -867,7 +861,7 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
/// touch its lines and are left out.
pub(crate) fn continued_exclusions(rel: &[para::Exclusion], excl: &[WrapArea], x0: f32, y: f32, t: f32, width: f32) -> Vec<para::Exclusion> {
let before = rel.iter().filter(|e| e.top < t).map(|e| para::Exclusion { bottom: e.bottom.min(t), ..e.clone() });
let here = rel_exclusions(excl, x0, y - t, 0.0)
let here = rel_exclusions(excl, x0, y - t)
.into_iter()
.filter(|e| e.bottom > t && e.right > -width && e.left < 2.0 * width)
.map(|e| if e.top < t && e.contour.is_none() { para::Exclusion { top: t, ..e } } else { e });
+20 -81
View File
@@ -1,9 +1,9 @@
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, frame_float, joined, layout_box, push_para};
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, joined, layout_box, push_para};
use super::cache::has_page_number_fields;
use super::ctx::{Ctx, Joining};
use super::floats::{
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, float_rect, late_floats,
place_late, place_objects, wrap_area,
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, late_floats, place_late,
place_objects,
};
use super::notes::{DECOR_STORY, NoteBox, para_notes};
use super::page::{PageBuilder, PageFrame, item_bottom};
@@ -19,9 +19,6 @@ use crate::WRAP_RELAYS;
/// A body paragraph. One after a paragraph whose mark is hidden goes on from that one's last line,
/// as Word shows them, on one line (#3986): see [`Joint`].
pub(crate) fn place_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
if place_page_text_frame(ctx, pb, p, block) {
return;
}
let joint = pb.joint.take().filter(|j| !pb.web && j.next == block && j.page == pb.pages.len() && j.col == pb.col);
let mark_hidden = ctx.mark_hidden(p, None);
// Nothing of it is shown: the place passes on to the paragraph after it.
@@ -99,39 +96,6 @@ fn unjoin(ctx: &mut Ctx, p: &Paragraph) {
}
}
fn place_page_text_frame(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize) -> bool {
if pb.web {
return false;
}
let Some(fr) = ctx.doc.styles.resolve_para_in(&p.props, None).frame else { return false };
if fr.h_anchor != "page" || fr.v_anchor != "page" {
return false;
}
let width = fr.w.unwrap_or_else(|| pb.col_w()).clamp(1.0, 1584.0);
let label = ctx.next_label(p);
let pl = ctx.para_labelled(p, width, None, &[], 0.0, label);
let notes = para_notes(ctx.doc, p, &pl);
let mut new_notes = Vec::new();
for line in &pl.lines {
new_notes.extend(notes_on_line(ctx, pb, line, &notes, &new_notes));
}
add_notes(pb, new_notes, &notes, pl.lines.last().map_or(0, |line| line.c1));
let height = fr.h.map_or(pl.height, |h| if fr.h_exact { h } else { h.max(pl.height) });
let float = frame_float(&fr);
let page = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
let rect = float_rect(Some(page), (pb.col_x(), pb.col_w()), pb.y, width, height, &float);
let path = [block as u32];
if let Some(page) = pb.page() {
push_para(&mut page.items, (StoryRef::Body, &path), &pl, (0, pl.lines.len()), (rect.x, rect.y), width, Edges::own(&pl, 0, pl.lines.len()));
}
// The body text after the frame wraps around it as its wrap mode says.
if let Some(area) = wrap_area(rect, &float, None) {
pb.framed.push(area.0);
pb.excl.push(area);
}
true
}
/// A closing mark before a continuous section takes no room after content. An otherwise empty
/// section starting a new page retains its paragraph line.
fn place_para_alone(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
@@ -272,10 +236,6 @@ struct Flow<'a> {
label: Option<(String, Level)>,
/// Where it was expected to start; floats anchored here are placed again if it starts elsewhere.
guess: f32,
/// The space before it that its layout (`pl`) was broken with: the declared space before
/// until the flow settles what it really lays out, then that, so a later relay keeps a
/// Top-and-Bottom object in it pushing the first line to the same place.
space_applied: f32,
excl_mark: usize,
/// Where its automatic equation numbers start: each layout of it again counts from here.
eq_start: u32,
@@ -309,21 +269,6 @@ struct Flow<'a> {
}
impl<'a> Flow<'a> {
/// [`PageBuilder::fresh`] for this paragraph's text, which its negative indents take past the
/// column's edges: the first line's indent while it is still to place, the other lines'
/// indent while lines after the first are, on the physical sides the paragraph's direction
/// puts them.
fn fresh(&self, pb: &PageBuilder) -> bool {
let rp = &self.pl.rp;
let first = rp.indent_left + rp.indent_first;
let leading = match (self.l0 == 0, self.pl.lines.len() > 1) {
(true, true) => rp.indent_left.min(first),
(true, false) => first,
(false, _) => rp.indent_left,
};
let (leading, trailing) = ((-leading).max(0.0), (-rp.indent_right).max(0.0));
pb.fresh(if rp.bidi { (trailing, leading) } else { (leading, trailing) })
}
fn new(ctx: &mut Ctx, pb: &mut PageBuilder, p: &'a Paragraph, (block, body_top): (usize, f32)) -> Self {
let width = pb.col_w();
// Floating objects anchored here join the page's wrap areas before the text is laid out; if
@@ -343,7 +288,6 @@ impl<'a> Flow<'a> {
width,
label,
guess,
space_applied: space_before,
excl_mark,
eq_start,
float_rects,
@@ -380,14 +324,13 @@ impl<'a> Flow<'a> {
});
(self.float_rects, self.pl, self.rel) = (rects, pl, rel);
self.late = LateFloats::new(&late);
self.space_applied = before;
(self.laid_page, self.laid_width) = (pb.number, pb.col_w());
}
/// Lay the paragraph out again around the wrap areas `rel`, with its fields on their pages.
fn relay(&mut self, ctx: &mut Ctx, rel: &[para::Exclusion]) -> Arc<ParaLayout> {
let (p, width, eq_start, label, space_before) = (self.p, self.laid_width, self.eq_start, &self.label, self.space_applied);
with_page_map(ctx, &mut self.page_map, |ctx| again(ctx, eq_start, |ctx| ctx.para_labelled(p, width, None, rel, space_before, label.clone())))
let (p, width, eq_start, label) = (self.p, self.laid_width, self.eq_start, &self.label);
with_page_map(ctx, &mut self.page_map, |ctx| again(ctx, eq_start, |ctx| ctx.para_labelled(p, width, None, rel, label.clone())))
}
/// The space before the paragraph, after the one between it and the previous paragraph is
@@ -424,7 +367,7 @@ impl<'a> Flow<'a> {
// space before (Word's PDFs: 0 pt and 12 pt before put the text after it at the same place).
// Only that shape is observed: later pages and columns keep theirs.
if self.block == 1
&& self.fresh(pb)
&& pb.fresh()
&& !pb.web
&& pb.pages.last().is_some_and(|pg| pg.float_tables.contains(&Path::top(0)))
&& only_markers(self.p, 0..self.p.text.len())
@@ -501,7 +444,7 @@ impl<'a> Flow<'a> {
// (Against the whole column: balanced columns grow to hold it.)
// With the 0.01 pt of slack the other fit checks take. Balancing from Word 2013's layout
// keeps the lines and the next paragraph together at the top of a column too (#6821).
if pb.y + need > pb.bottom + 0.01 && (!self.fresh(pb) || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
if pb.y + need > pb.bottom + 0.01 && (!pb.fresh() || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
pb.advance(self.block, self.body_top);
unjoin(ctx, self.p);
pb.y += rp.space_before.min(0.0);
@@ -515,7 +458,7 @@ impl<'a> Flow<'a> {
/// paragraph, together there too: asks again, and places the paragraph's floats again where it
/// ends up (#6821).
fn keep_again(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder, rooms: Rooms) {
while self.l0 == 0 && (self.pl.rp.keep_lines || self.pl.rp.keep_next) && self.fresh(pb) && Self::strict_widow_control(ctx, pb) {
while self.l0 == 0 && (self.pl.rp.keep_lines || self.pl.rp.keep_next) && pb.fresh() && Self::strict_widow_control(ctx, pb) {
let (col, pages) = (pb.col, pb.pages.len());
let before = self.keep_together(ctx, pb, rooms, 0.0);
if (pb.col, pb.pages.len()) == (col, pages) {
@@ -607,7 +550,7 @@ impl<'a> Flow<'a> {
if over && fit.l1 > l0 && !split {
break;
}
if over && fit.l1 == l0 && !self.fresh(pb) && !split && !self.stays_at_bottom(pb, l) {
if over && fit.l1 == l0 && !pb.fresh() && !split && !self.stays_at_bottom(pb, l) {
break;
}
fit.notes.extend(line_notes);
@@ -665,11 +608,11 @@ impl<'a> Flow<'a> {
// one (#6821).
let strict = Self::strict_widow_control(ctx, pb);
if fit.forced.is_none() && l1 < n && self.pl.rp.widow_control && n >= 2 {
if l1 - l0 == 1 && l0 == 0 && (!self.fresh(pb) || strict) {
if l1 - l0 == 1 && l0 == 0 && (!pb.fresh() || strict) {
l1 = l0; // orphan: move the first line to the next page
} else if n - l1 == 1 && (l1 - l0 >= 3 || (l0 > 0 && l1 - l0 >= 2)) {
l1 -= 1; // widow: take one more line along
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && (!self.fresh(pb) || strict) {
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && (!pb.fresh() || strict) {
// Neither split of a three-line paragraph is allowed (two and a widow, or an
// orphan and two): it moves whole, as in Word.
l1 = l0;
@@ -833,7 +776,6 @@ impl<'a> Flow<'a> {
(self.float_rects, self.pl, self.rel) = (rects, relaid, relaid_rel);
(self.laid_page, self.laid_width) = (pb.number, pb.col_w());
self.anchor_y = y0;
self.space_applied = 0.0;
self.l0 = k;
}
}
@@ -948,10 +890,10 @@ fn notes_limit(pb: &PageBuilder, new_notes: &[NoteBox], line_notes: &[NoteBox])
/// the text (see `baseline_offset`), and Word lets that leading of a page's last line run into the
/// bottom margin: only the text has to fit (observed: a double-spaced 12pt line stays on the page
/// while its text ends above the margin, about half a line lower than when the whole line must
/// fit). Only the bottom margin takes that leading, or the top of a footer that reaches above it
/// (see [`PageBuilder::at_margin`]): footnotes (`free` is false) keep the whole line clear of them.
/// fit). Only the bottom margin takes that leading: a footer taller than the margin, or
/// footnotes (`free` is false), keep the whole line clear of them.
fn fit_height(pb: &PageBuilder, l: &para::Line, rp: &wordcraft_doc::resolve::ResolvedPara, free: bool) -> f32 {
let at_margin = pb.at_margin();
let at_margin = pb.bottom >= pb.sect.page_h - pb.sect.margin_bottom - 0.01;
match rp.line_spacing {
// The text (or a taller picture) ends `leading` above the line's bottom.
wordcraft_doc::props::LineSpacing::Multiple(m) if m > 1.0 && at_margin && free => (l.height - l.leading).clamp(0.0, l.height),
@@ -1047,10 +989,8 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
let mut f = Flow::new(ctx, pb, p, (block, body_top));
let spot = |pb: &PageBuilder| (pb.pages.len(), pb.col);
let placed_at = spot(pb);
// A continuous section's top mid-page is not a page top, so the break still applies. A
// page-anchored frame is not content above the paragraph, so it does not make the break
// apply either: the frame's wrap area moves the text below or beside it (#8577).
let broke_before = f.pl.rp.page_break_before && !pb.at_page_top() && !pb.web;
// A continuous section's top mid-page is not a page top, so the break still applies.
let broke_before = f.pl.rp.page_break_before && !pb.fresh() && !pb.web;
if broke_before {
pb.new_page(block, body_top);
}
@@ -1083,7 +1023,7 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
fit.l1 = end;
// On a fresh column an unfitting line can overflow. Strict widow control instead moves
// the lines on without emitting anything and must release their late floats as well.
let overflow = end == f.l0 && f.fresh(pb) && !widowed;
let overflow = end == f.l0 && pb.fresh() && !widowed;
if f.settle_late(pb, end, overflow) {
continue;
}
@@ -1145,7 +1085,7 @@ pub(crate) fn place_outline_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragr
let width = (pb.col_w() - indent - outline::SYMBOL_W).max(72.0);
let q = outline::outline_para(ctx.doc, p, o.view.plain);
ctx.fields.page = pb.number;
let pl = ctx.para_labelled(&q, width, None, &[], 0.0, label);
let pl = ctx.para_labelled(&q, width, None, &[], label);
pb.y += pl.rp.space_before.max(0.0);
let n = pl.lines.len();
let l1 = if o.view.first_line_only && level >= outline::BODY { n.min(1) } else { n };
@@ -1257,7 +1197,6 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
typing_word: None,
numeral: ctx.opts.numeral,
exclusions: &[],
space_before: 0.0,
eq_number: ctx.eq_count,
read_line_spacing: if ctx.opts.view == ViewMode::Read { ctx.opts.read_line_spacing } else { None },
grid: ctx.grid,
@@ -1372,7 +1311,7 @@ mod tests {
// Continue after the first line. The balance attempt can fit only one of the two lines left.
flow.l0 = 1;
pb.advance(0, top);
assert!(flow.fresh(pb));
assert!(pb.fresh());
assert!((pb.bottom - pb.top - height).abs() < 0.01);
flow.place_due_late(ctx, pb);
assert_eq!(pb.excl.len(), 1, "the anchor line fits before widow control");
@@ -1381,7 +1320,7 @@ mod tests {
assert_eq!(fit.l1, 2);
let (end, widowed) = flow.settled_end(ctx, pb, &fit);
assert_eq!((end, widowed), (1, true));
let overflow = end == flow.l0 && flow.fresh(pb) && !widowed;
let overflow = end == flow.l0 && pb.fresh() && !widowed;
assert!(!flow.settle_late(pb, end, overflow));
assert!(pb.excl.is_empty(), "no text is emitted here, so no wrap area may remain here");
});
+9 -26
View File
@@ -36,27 +36,6 @@ pub(crate) fn section_side(start: SectionStart, restart: Option<u32>, last: u32,
}
}
/// Whether `page` (after `prev`) is its section's first page, the one a different first page's
/// header and footer go on: the page where the section begins. A page's section is the one at its
/// top, so a section that starts continuously part-way down `prev` has no first page of its own:
/// Word shows the earlier section's header there and the section's default one from the next page
/// on, also when its first paragraph begins on `prev` and runs over. `sections` as
/// [`Document::sections`] gives them (each with its last block).
pub(crate) fn begins_section(sections: &[(usize, &SectionProps)], prev: Option<&Page>, page: &Page) -> bool {
if prev.is_some_and(|p| p.section == page.section) {
return false;
}
let start = page.section.checked_sub(1).and_then(|k| sections.get(k)).map_or(0, |(end, _)| end.saturating_add(1));
// A first paragraph (or table) that begins part-way down `prev` and runs over still began
// the section there.
let began_before = prev.is_some_and(|p| {
p.items
.iter()
.any(|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if path.0.first().is_some_and(|&b| b as usize >= start)))
});
start >= page.first_block && !began_before
}
/// The document's sections with their headers and footers (Word's "link to previous"), each
/// section's resolved once for the whole layout in document order rather than by looking back
/// over the sections before it whenever one is needed.
@@ -195,12 +174,12 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
return Vec::new();
}
let Some(page) = pb.pages.last() else { return Vec::new() };
let hf = Arc::clone(&ctx.hf);
let first = begins_section(&hf.sections, pb.pages.iter().rev().nth(1), page);
let first = pb.pages.iter().rev().nth(1).is_none_or(|prev| prev.section != page.section);
let key = (page.section, page.number, first);
if let Some(areas) = ctx.header_tables.get(&key) {
return areas.clone();
}
let hf = Arc::clone(&ctx.hf);
let Some((_, sect)) = hf.sections.get(page.section) else { return Vec::new() };
if sect.text_direction.is_turned() {
return Vec::new();
@@ -426,9 +405,13 @@ pub(crate) fn headers_footers(ctx: &mut Ctx, pages: &mut [Page], sections: &[(us
let hf = Arc::clone(&ctx.hf);
let even_odd = ctx.doc.settings.even_odd_headers;
let styles = styleref::headers_use_styleref(ctx.doc).then(|| ctx.cache.style_index(ctx.doc));
let first_of_section: HashSet<usize> = (0..pages.len())
.filter(|&i| pages.get(i).is_some_and(|p| begins_section(sections, i.checked_sub(1).and_then(|k| pages.get(k)), p)))
.collect();
let mut first_of_section: HashSet<usize> = HashSet::new();
let mut seen = HashSet::new();
for (i, p) in pages.iter().enumerate() {
if seen.insert(p.section) {
first_of_section.insert(i);
}
}
for (i, page) in pages.iter_mut().enumerate() {
let Some((_, sect)) = sections.get(page.section) else { continue };
// Inherit header/footer references from earlier sections (Word's "link to previous").
+3 -24
View File
@@ -210,31 +210,10 @@ impl NoteBox {
cuts
}
/// Whether widow/orphan control in the note's paragraphs forbids splitting at `cut`: a
/// paragraph's first line alone above it (an orphan) or its last line alone below it (a
/// widow), as in Word for Mac 16.114.4.
pub(crate) fn breaks_widow_control(&self, cut: f32) -> bool {
self.items.iter().filter(|it| self.splittable(it)).any(|it| {
let Placed::Lines { para, l0, l1, y, .. } = it else { return false };
let Some(first) = para.lines.get(*l0) else { return false };
let ends_at = |k: usize| para.lines.get(k).is_some_and(|l| (y + l.top - first.top + l.height - cut).abs() < 0.01);
let n = para.lines.len();
para.rp.widow_control && n >= 2 && ((*l0 == 0 && *l1 >= 2 && ends_at(0)) || (*l1 == n && ends_at(n - 2)))
})
}
/// Where the note may be split with its paragraphs' widow/orphan control kept, ascending.
pub(crate) fn kept_cuts(&self) -> Vec<f32> {
let mut cuts = self.cuts();
cuts.retain(|&c| !self.breaks_widow_control(c));
cuts
}
/// The least of the note that must stay with its reference: its first line, or more under
/// widow/orphan control (all of it if it can't be split).
/// The least of the note that must stay with its reference: its first line (all of it if it
/// can't be split).
pub(crate) fn first_piece(&self) -> f32 {
// Widow/orphan control may keep more lines together (two, or a short paragraph whole).
self.kept_cuts().first().copied().unwrap_or(self.h).min(self.h)
self.cuts().first().copied().unwrap_or(self.h).min(self.h)
}
/// Split the note at line bottom `cut`: the part above (`cut` tall) and the rest, moved up to
+5 -53
View File
@@ -89,16 +89,10 @@ pub(crate) struct PageBuilder<'a> {
/// Top of the footer of the pages being started: a footer reaching above the bottom margin
/// pushes the body up (`f32::MAX`: no footer).
pub(crate) foot_top: f32,
/// How low the last line's leading may reach on the current page: the bottom margin, or the
/// top of a footer reaching above it (set as the page starts, from that page's footer).
pub(crate) leading_floor: f32,
/// The wrap areas pages start with ([`EarlyFloats`]) ...
pub(crate) early: &'a EarlyFloats,
/// ... and how many of the current page's `excl` they are (its first ones).
pub(crate) seeded: usize,
/// The wrap areas of the page-anchored body text frames on the current page. Text at the top
/// of a column that one of them reaches into gains room by moving on.
pub(crate) framed: Vec<Rect>,
/// No layout pass follows for floats found above their anchors: each is kept clear of the
/// text laid out before it ([`settle_early`]).
pub(crate) settle: bool,
@@ -166,7 +160,7 @@ impl PageBuilder<'_> {
// The note area starts below the text (a page of continued notes alone: at its top).
let area = self.bottom.max(self.body_floor());
let fits = total <= self.orig_bottom - area + 0.01;
let mut top = match (fits, self.beneath) {
let top = match (fits, self.beneath) {
(false, _) => area,
// Below the page's last line of text.
(true, true) => self.body_floor().min(self.orig_bottom - total),
@@ -179,15 +173,12 @@ impl PageBuilder<'_> {
let mut placed = Vec::new();
// Where the continuation notice goes, below a note that continues on the next page.
let mut notice_y = None;
// The bottom of what is placed (with the notice).
let mut end = y;
let mut rest = notes.into_iter();
while let Some(n) = rest.next() {
let room = self.orig_bottom - y;
if fits || n.h <= room + 0.01 {
let ny = y;
y += n.h;
end = y;
placed.push((n, ny));
continue;
}
@@ -195,38 +186,21 @@ impl PageBuilder<'_> {
// always leaves something here (its first line, or all of it if it can't be split),
// so continuing ends.
let first = placed.is_empty();
// Widow/orphan control in the note keeps two of a paragraph's lines on either side;
// the page's first note gives that up before it gives up the page's room.
let cuts = n.cuts();
let room = room - self.seps.notice_h();
let fit = |cuts: Vec<f32>| cuts.into_iter().rev().find(|&c| c <= room + 0.01);
let cut = fit(n.kept_cuts()).or_else(|| if first { fit(n.cuts()).or(n.cuts().first().copied()) } else { None });
match cut {
match cuts.iter().rev().find(|&&c| c <= room + 0.01).or(cuts.first().filter(|_| first)).copied() {
Some(c) => {
let (head, tail) = n.split(c);
notice_y = Some(y + head.h);
end = y + head.h + self.seps.notice_h();
placed.push((head, y));
self.carry.push(tail);
}
None if first => {
end = y + n.h;
placed.push((n, y));
}
None if first => placed.push((n, y)),
None => self.carry.push(n),
}
self.carry.extend(rest.by_ref());
break;
}
// Notes that continue on the next page still end on the bottom margin, the room left
// going above the separator (Word for Mac 16.114.4), unless they go beneath the text.
if !fits && !self.beneath {
let shift = (self.orig_bottom - end).max(0.0);
top += shift;
notice_y = notice_y.map(|ny| ny + shift);
for (_, ny) in &mut placed {
*ny += shift;
}
}
if let Some(pg) = self.pages.last_mut() {
match if cont { &self.seps.cont } else { &self.seps.sep } {
Some((items, _)) => pg.items.extend(items.iter().cloned().map(|mut it| {
@@ -377,7 +351,6 @@ impl PageBuilder<'_> {
let early = self.early;
self.excl.extend(early.get(&self.pages.len()).into_iter().flatten().map(|(_, _, a)| a.clone()));
self.seeded = self.excl.len();
self.framed.clear();
self.float_tables.clear();
if self.sect.line_numbers.as_ref().is_some_and(|l| l.restart == wordcraft_doc::section::LineNumberRestart::Page) {
self.line_no = 0;
@@ -386,7 +359,6 @@ impl PageBuilder<'_> {
self.number = self.restart_at.take().unwrap_or_else(|| self.number.saturating_add(1));
let (w, h) = if self.web { (s.page_w, f32::MAX / 4.0) } else { (s.page_w, s.page_h) };
let bottom = self.body_bottom(body_top);
self.leading_floor = (s.page_h - s.margin_bottom).min(self.foot_top);
let body = Rect::new(s.margin_left + s.gutter, body_top, s.text_width(), (bottom - body_top).max(36.0));
let mut decor = Vec::new();
if !self.web {
@@ -465,13 +437,6 @@ impl PageBuilder<'_> {
self.bottom = self.bottom.min(self.top + h);
}
}
/// Whether the body ends at the bottom margin, or at the top of a footer that reaches above
/// it: the page's last multiple-spaced line may leave its leading there (see `fit_height`).
/// Word lets it run past the footer's top as into the margin, whatever the footer holds (a
/// page number, several lines of text, an empty paragraph): only the text has to end above it.
pub(crate) fn at_margin(&self) -> bool {
self.bottom >= self.leading_floor - 0.01
}
/// The bottom of the body on a page started with its body at `body_top`: a footer taller than
/// the bottom margin pushes it up (Word: no gap), leaving it at least a little room.
fn body_bottom(&self, body_top: f32) -> f32 {
@@ -511,22 +476,9 @@ impl PageBuilder<'_> {
/// At the top with nothing above on this page, so moving on gains no room. A continuous
/// section starting mid-page is at its top but not fresh: what doesn't fit there goes to the
/// next page (#3907).
/// `reach` is how far the text reaches past the column's left and right edges (a paragraph's
/// negative indents).
pub(crate) fn fresh(&self, reach: (f32, f32)) -> bool {
self.at_page_top() && !self.framed_here(reach)
}
/// At the top of the page's text with nothing placed above it. A page-anchored frame is not
/// content above it: a paragraph with a page break before needs no new page for one.
pub(crate) fn at_page_top(&self) -> bool {
pub(crate) fn fresh(&self) -> bool {
self.at_top() && self.top <= self.page_top + 0.01
}
/// A page-anchored body text frame's wrap area reaches into the current column's text,
/// widened by `reach` on the left and right.
fn framed_here(&self, (left, right): (f32, f32)) -> bool {
let (x0, x1) = (self.col_x() - left, self.col_x() + self.col_w() + right);
self.framed.iter().any(|r| r.x < x1 && r.right() > x0 && r.y < self.bottom && r.bottom() > self.y)
}
/// Move to the next column or page.
pub(crate) fn advance(&mut self, block: usize, body_top: f32) {
if self.col + 1 < self.cols.len() {
-2
View File
@@ -367,7 +367,6 @@ mod label_spacing_tests {
field_codes: false,
grid: Grid::default(),
exclusions: &[],
space_before: 0.0,
eq_number: 0,
numeral: crate::NumeralMode::default(),
read_line_spacing: None,
@@ -514,7 +513,6 @@ mod tests {
field_codes: false,
grid: Grid::default(),
exclusions: &[],
space_before: 0.0,
eq_number: 0,
numeral: Default::default(),
read_line_spacing: None,
+11 -143
View File
@@ -5,7 +5,7 @@ use super::chars::{
};
use super::grid::east_asian;
use super::model::{ClKind, Cluster, Enclosed, Glyph, ParaEnv, RubyLayout, StyleRun, SymbolRun};
use super::{Arc, Document, FaceRef, NumeralMode, OBJ, ResolvedChar, RubyAlign, SOFT_HYPHEN};
use super::{Arc, Document, FaceRef, NumeralMode, ResolvedChar, RubyAlign, SOFT_HYPHEN};
use wordcraft_fonts::ShapeContext;
pub(super) struct Builder<'a> {
@@ -52,25 +52,6 @@ struct SegmentInput<'a> {
context: &'a [bool],
}
/// Whether `face` draws `cluster`, a character and its combining marks, with no missing glyph.
/// The shaper composes a pair the face has a precomposed glyph for (`=` and U+0338 as `≠`), so a
/// face without the mark itself can still draw the pair.
fn draws_all(face: FaceRef, cluster: &str) -> bool {
let glyphs = wordcraft_fonts::shape_in(&face, cluster, &[], |c| c, ShapeContext::default());
!glyphs.is_empty() && glyphs.iter().all(|g| g.gid != 0)
}
/// A face other than `current` that draws all of `cluster` (CSS Fonts 4 §5.3, cluster matching):
/// the run's Thai face or its own font when one does, else the first face in fallback order with
/// every character of it that draws something.
fn cluster_face(cluster: &str, current: FaceRef, run_face: Option<FaceRef>, primary: FaceRef, bold: bool, italic: bool) -> Option<FaceRef> {
if let Some(f) = run_face.into_iter().chain([primary]).filter(|f| f.id() != current.id()).find(|f| draws_all(*f, cluster)) {
return Some(f);
}
let chars: Vec<char> = cluster.chars().filter(|c| draws_something(*c)).collect();
wordcraft_fonts::FontDb::global().fallback_for_run(&chars, primary.id(), bold, italic).map(|f| FaceRef::of(&f))
}
impl<'a> Builder<'a> {
/// Displayed form of `c` at run-relative byte `at` (Word › Numeral): one char in, one
/// char out. `rtl` is the shaping direction; in Context mode `context` (from
@@ -87,10 +68,6 @@ impl<'a> Builder<'a> {
let mut seg_start = 0;
let mut cur: Option<SegKey> = None;
let mut segs = Vec::new();
// The character the marks after it belong to: where it starts, and as drawn.
let mut base: Option<(usize, char)> = None;
// The character whose cluster was matched, and whether its marks stay with it.
let mut matched: Option<(usize, bool)> = None;
for (i, c) in text.char_indices() {
let rtl = use_levels && levels.get(lbase + i).is_some_and(|l| l % 2 == 1);
let c = show(c);
@@ -101,67 +78,19 @@ impl<'a> Builder<'a> {
_ => rc_cs.is_some() && rc.uses_complex(dc),
};
let primary = if complex { primary_cs.unwrap_or(primary) } else { primary };
let (bold, italic) = if complex { (rc.bold_cs, rc.italic_cs) } else { (rc.bold, rc.italic) };
// A mark stays in the face of the character it belongs to (Arabic harakat with their
// letter, so the letters join) while that face draws it. When it doesn't, the
// character and its marks go together to a face that draws them all (CSS Fonts 4
// §5.3, cluster matching). With no such face, a mark in left-to-right text that isn't
// complex script is matched on its own like any other character; in right-to-left or
// complex-script text it stays with its letter (#7865). A cluster is matched once, at
// its first mark the face lacks: matching it again at every later mark would make a
// long run of marks quadratic.
let mut with_base = false;
let mut moved = None;
if let Some(k) = cur.filter(|_| mark) {
let current = k.face.unwrap_or(primary);
with_base = !draws_something(c) || current.covers(dc);
if !with_base {
match (base.filter(|(at, _)| *at >= seg_start), matched) {
(Some((at, _)), Some((done, stays))) if done == at => with_base = stays,
(Some((at, b)), _) => {
let marks = text.get(at..).unwrap_or("").chars().skip(1).map(show).take_while(|m| is_mark(*m));
let all: String = std::iter::once(b).chain(marks).inspect(|_| crate::work::steps(1)).collect();
if draws_all(current, &all) {
with_base = true;
} else if let Some(f) = cluster_face(&all, current, run_face, primary, bold, italic) {
// The character goes to that face with its marks.
if at > seg_start {
segs.push((seg_start, at, k));
seg_start = at;
}
let face = (f.id() != primary.id()).then_some(f);
cur = Some(SegKey { face, ..k });
moved = Some(face);
} else {
with_base = k.complex || k.rtl;
}
matched = Some((at, with_base || moved.is_some()));
}
(None, _) => with_base = k.complex || k.rtl,
}
}
}
if !mark {
base = (!c.is_control() && c != OBJ).then_some((i, dc));
}
let face = match (moved, cur) {
(Some(face), _) => face,
(None, Some(k)) if with_base => k.face,
let face = match cur {
Some(k) if mark => k.face,
_ if !complex && east_asian(c) && primary_ea.is_some_and(|f| f.covers(c)) => primary_ea,
_ if !c.is_control() && c != SOFT_HYPHEN && run_face.is_some_and(|f| f.covers(dc)) => run_face,
_ if primary.covers(dc) || c.is_whitespace() || c.is_control() || c == SOFT_HYPHEN => None,
(None, Some(SegKey { face: Some(face), .. })) if face.covers(dc) => Some(face),
Some(SegKey { face: Some(face), .. }) if face.covers(dc) => Some(face),
_ if !complex && ea_face.is_some() && crate::kinsoku::is_east_asian(c) => ea_face,
_ => wordcraft_fonts::FontDb::global().fallback_styled(dc, primary.id(), bold, italic).map(|f| FaceRef::of(&f)),
_ => {
let (bold, italic) = if complex { (rc.bold_cs, rc.italic_cs) } else { (rc.bold, rc.italic) };
wordcraft_fonts::FontDb::global().fallback_styled(dc, primary.id(), bold, italic).map(|f| FaceRef::of(&f))
}
};
// A mark is set like the character it belongs to, as for `complex`: in small capitals at
// that character's size, so the two stay in one shaping run and its cluster is matched
// whole.
let small = match cur {
Some(k) if mark => k.small,
_ => rc.small_caps && !rc.caps && c.is_lowercase(),
};
let key = SegKey { face, small, complex, rtl };
let key = SegKey { face, small: rc.small_caps && !rc.caps && c.is_lowercase(), complex, rtl };
match cur {
Some(previous) if previous.same(&key) => {}
Some(previous) => {
@@ -210,15 +139,6 @@ impl<'a> Builder<'a> {
// the height Word gives it.
let (a, d) = match wordcraft_fonts::word::symbol_line(&rc.font, &r) {
Some((a, d)) => (a * face.upem, d * face.upem),
// A character Times New Roman or its metric twin lacks: the twin lacks more than
// Times New Roman ("‒", "₽" in Liberation Serif), so the line is as tall as the run's
// font, as with Times New Roman in Word, not as the taller fallback. East Asian text
// keeps its face's height.
None if face_override.is_some() && is_times_twin(&r.face.family) && !face.is_east_asian() => {
let (a, d) = wordcraft_fonts::word::line_metrics(&r.face);
let k = face.upem / r.face.upem.max(1.0);
(a * k, d * k)
}
None => wordcraft_fonts::word::line_metrics(&face),
};
let k = size as f64 / face.upem.max(1.0);
@@ -502,15 +422,12 @@ impl<'a> Builder<'a> {
let ge = bounds.get(bi + 1).copied().unwrap_or(shape_text.len());
let g0 = self.glyphs.len() as u32;
let mut adv = 0.0f32;
// What kerning added to the last glyph's advance: its pair with the next glyph.
let mut kern = 0.0f32;
while let Some(g) = shaped.get(gi) {
if g.cluster >= ge {
break;
}
self.glyphs.push(Glyph { gid: g.gid, dx: adv + g.x_offset as f32 * k * hscale, dy: g.y_offset as f32 * k });
adv += g.x_advance as f32 * k * hscale;
kern = if rc.kerned() && !key.rtl { pair_with_next(g, st.face.advance(g.gid)) * k * hscale } else { 0.0 };
gi += 1;
}
let g1 = self.glyphs.len() as u32;
@@ -538,7 +455,6 @@ impl<'a> Builder<'a> {
obj_h: 0.0,
obj_d: 0.0,
dot: s == "." || s == ",",
kern: if kind == ClKind::Text && g1 == g0 + 1 { kern } else { 0.0 },
});
}
if matches!(dir, Dir::Para) {
@@ -581,13 +497,6 @@ impl<'a> Builder<'a> {
}
}
}
// The ligature glyph's kerning pair with the following glyph belongs after its last
// letter, not on the head inside the ligature (#8618).
if let Some((head, rest)) = self.clusters.get_mut(i..=i + n).and_then(|cs| cs.split_first_mut())
&& let Some(last) = rest.last_mut()
{
last.kern = std::mem::take(&mut head.kern);
}
i += n + 1;
}
}
@@ -618,7 +527,6 @@ impl<'a> Builder<'a> {
obj_h: 0.0,
obj_d: 0.0,
dot: false,
kern: 0.0,
});
return;
};
@@ -652,20 +560,7 @@ impl<'a> Builder<'a> {
let style = first.style;
let g1 = added.last().map(|c| c.g1).unwrap_or(g0);
self.shown.push((self.clusters.len(), text.to_string(), ranges));
self.clusters.push(Cluster {
start,
end,
adv: x,
kind: ClKind::Text,
style,
g0,
g1,
break_after: false,
obj_h: 0.0,
obj_d: 0.0,
dot: false,
kern: 0.0,
});
self.clusters.push(Cluster { start, end, adv: x, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false });
}
/// Shape `texts` on top of one another as one cluster for `start..end`: each aligned within
@@ -715,38 +610,11 @@ impl<'a> Builder<'a> {
if !text.is_empty() {
self.shown.push((k, text, ranges));
}
self.clusters.push(Cluster {
start,
end,
adv,
kind: ClKind::Text,
style,
g0,
g1,
break_after: false,
obj_h: 0.0,
obj_d: 0.0,
dot: false,
kern: 0.0,
});
self.clusters.push(Cluster { start, end, adv, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false });
Some(k)
}
}
/// What kerning added to a glyph's advance (in font units) for its pair with the next glyph. An
/// old-style `kern` table's pair is split between its two glyphs, the second's half in its advance
/// and its offset alike: that half is the pair with the glyph before, which stays on the line.
fn pair_with_next(g: &wordcraft_fonts::ShapedGlyph, plain_advance: f64) -> f32 {
let added = g.x_advance as f32 - plain_advance as f32;
let before = if added != 0.0 { g.x_offset as f32 } else { 0.0 };
added - before
}
/// Times New Roman or one of its metric twins.
fn is_times_twin(family: &str) -> bool {
["Times New Roman", "Liberation Serif", "Tinos"].iter().any(|f| family.eq_ignore_ascii_case(f))
}
/// Lay out an `EQ \o` field (ECMA-376 Part 1 §17.16.5.20): its arguments drawn on top of one
/// another, as one cluster. An enclosure symbol among them (○ □ △ ◇, see
/// [`wordcraft_doc::eq::EncloseShape`]) is drawn as a shape around the text rather than as a
+1 -2
View File
@@ -55,8 +55,7 @@ pub(super) fn caps_expands(c: char) -> bool {
}
/// Combining marks and joiners (bidi classes NSM, BN: harakat, ZWNJ, ZWJ) belong to the
/// character before them: same font, same shaping run, so Arabic joining isn't broken. A mark
/// that font can't draw takes its character to a face that draws both (`segment_keys`, #7865).
/// character before them: same font, same shaping run, so Arabic joining isn't broken.
pub(super) fn is_mark(c: char) -> bool {
use unicode_bidi::BidiClass::{BN, NSM};
// No ASCII character is a mark (its BN characters are controls).
+5 -15
View File
@@ -70,8 +70,6 @@ pub(super) fn snap_chars(b: &mut Builder, text: &str, grid: &Grid) {
g.dx += shift;
}
c.adv = adv;
// The snapped advance no longer includes the shaped kerning adjustment.
c.kern = 0.0;
}
}
@@ -101,17 +99,14 @@ fn auto_space_room(st: &StyleRun) -> f32 {
/// size for Times New Roman, 0.2203 for Arial, 0.2575 for Calibri, 0.2980 for Courier New,
/// 0.3041 for Cambria — which is half each face's average character width. With different sizes
/// either side, the room after the Latin run takes the Latin size, not the Asian one.
///
/// `ea_lacks(at, c)`: the run at byte `at` names an installed East Asian font that has no glyph
/// for `c`. Word adds no room beside such a character, though a substituted face draws it (#6591).
pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool, ea_lacks: impl Fn(usize, char) -> bool) -> Vec<(usize, f32)> {
pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec<(usize, f32)> {
let mut out = Vec::new();
if !de && !dn {
return out;
}
let mut shown = b.shown.iter().map(|s| (s.0, s.1.as_str())).peekable();
// The previous text cluster: index, its last character and its start byte.
let mut prev: Option<(usize, char, usize)> = None;
// The previous text cluster: index and its last character.
let mut prev: Option<(usize, char)> = None;
for k in 0..b.clusters.len() {
let Some(c) = b.clusters.get(k) else { break };
match c.kind {
@@ -131,13 +126,8 @@ pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool, ea_lac
prev = None;
continue;
};
let start = c.start;
if let Some((pk, pc, pstart)) = prev
if let Some((pk, pc)) = prev
&& let Some(side) = crate::kinsoku::auto_space(pc, first, de, dn)
&& !match side {
crate::kinsoku::AsianSide::Left => ea_lacks(pstart, pc),
crate::kinsoku::AsianSide::Right => ea_lacks(start, first),
}
{
let style = b.clusters.get(pk).map(|p| p.style as usize);
let st = style.and_then(|i| b.styles.get(i));
@@ -152,7 +142,7 @@ pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool, ea_lac
out.push((pk, gap));
}
}
prev = Some((k, last, start));
prev = Some((k, last));
}
out
}
+11 -78
View File
@@ -14,9 +14,6 @@ const MIN_LINE_WIDTH: f32 = 1.0;
struct Breaker<'e> {
level: Option<&'e Level>,
rp: wordcraft_doc::resolve::ResolvedPara,
/// The space before the paragraph that the flow laid out above it, which a Top-and-Bottom
/// object in it is laid out again below (see [`ParaEnv::space_before`]).
space_before: f32,
mark_style: u32,
exclusions: &'e [Exclusion],
n: usize,
@@ -223,7 +220,6 @@ impl<'e> Breaker<'e> {
// Exact spacing fixes the table-contact boundary even when the mark has other metrics.
// Keep the existing estimate for shapes and for non-exact spacing.
table_h: if let LineSpacing::Exactly(h) = rp.line_spacing { h } else { est_h },
space_before: env.space_before,
rp,
first_x0: None,
hcache: Vec::new(),
@@ -266,26 +262,6 @@ impl<'e> Breaker<'e> {
let mut guard = 0;
loop {
let lo = self.row_left(pl);
// A Top-and-Bottom object ending in the paragraph's space before (or reaching into
// its first line) is a block the first line must start below, with that space before
// laid out again under it (#7143). Exclusions are relative to the first line's
// original top (0), so keep the band anchored there (`[-before, est_h]`) even after
// `row_spans` or `skip_row` moves `self.top` down past a side-wrapping object (#8614):
// only the space the flow actually laid out above 0 holds a space-before obstruction.
if self.first && self.space_before > 0.0 {
let before = self.space_before;
let row = (-before, self.est_h + before, self.table_h);
if let Some(below) = self
.exclusions
.iter()
.filter(|e| e.top_bottom)
.filter(|e| e.intersects_row(row.0, row.1, row.2, lo, self.base_right))
.map(|e| e.bottom)
.reduce(f32::max)
{
self.top = self.top.max(below + before);
}
}
let row = (self.top, self.est_h, self.table_h);
match row_spans(self.exclusions, row, (lo, self.base_right), self.tight_indent).map(|mut spans| (spans.pop_front(), spans)) {
Ok((Some((a, b)), rest)) => {
@@ -466,7 +442,7 @@ impl<'e> Breaker<'e> {
/// tallest picture on it (which sits on the baseline).
fn extents(&self, pl: &ParaLayout, (c0, c1): (usize, usize)) -> Extents {
let rp = &self.rp;
let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, obj_desc: 0.0, text: false, single: 0.0 };
let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, obj_desc: 0.0, text: false };
let mut any = false;
let dropped = pl.drop_cap.map_or(0, |d| d.0);
for (k, c) in pl.clusters.get(c0..c1).into_iter().flatten().enumerate() {
@@ -510,7 +486,6 @@ impl<'e> Breaker<'e> {
};
ex.asc = ex.asc.max(a);
ex.desc = ex.desc.max(d);
ex.single = ex.single.max(a + d);
any = true;
// Text needs its descent below the line; so do inline math (an object with its own
// descent) and a check box. A line break ending the line is no text.
@@ -528,7 +503,7 @@ impl<'e> Breaker<'e> {
/// The line's height, baseline and text extent.
fn measure(&self, pl: &ParaLayout, range: (usize, usize)) -> Measure {
let rp = &self.rp;
let Extents { mut asc, mut desc, obj_asc, obj_desc, text, single } = self.extents(pl, range);
let Extents { mut asc, mut desc, obj_asc, obj_desc, text } = self.extents(pl, range);
let mut text_natural = asc + desc;
let font_desc = desc;
desc = desc.max(obj_desc);
@@ -541,8 +516,8 @@ impl<'e> Breaker<'e> {
// Word, measured with Arial at 10 and 20 pt, single, 1.15 and 1.5 spacing: a 30 pt picture
// alone takes 30, 30 + 0.15 and 30 + 0.5 times the font's height, lowered 10 or 30 pt or
// not; raised 10 pt, 10 more; a 6 pt one, the font's height; beside text and lowered
// 10 pt, 30; lowered 30 pt, a 6 pt one makes a 30 pt line (`drawing` leaves the lowering
// whole; exact spacing keeps it to the picture's height, see `extents`).
// 10 pt, 30. Not on a line lowered further than the picture's height, which layout limits
// to that height where Word's line keeps growing.
let spacing = if let LineSpacing::Multiple(m) = rp.line_spacing { Some(m) } else { None };
let pictures_alone = !text && obj_asc + obj_desc > 0.0 && spacing.is_some();
let below = if pictures_alone { obj_desc } else { desc };
@@ -579,10 +554,6 @@ impl<'e> Breaker<'e> {
}
}
}
// Multiple spacing adds (m - 1) x the tallest of the line's runs, not of the line: a line
// mixing fonts is as much taller as its runs' extents make it, once (Word for Mac and
// Windows: 10 pt Times New Roman with 10 pt Courier New at 1.5 and double spacing).
let run_leading = if single > 0.0 && !pictures_alone { single.min(text_natural) } else { text_natural };
// Keep the picture floor independent of list-label metrics.
let natural = asc + desc;
let pictures = if obj_asc > asc { obj_asc + desc } else { 0.0 };
@@ -591,9 +562,7 @@ impl<'e> Breaker<'e> {
let (height, centred) = match (rp.line_spacing, grid) {
(LineSpacing::Multiple(m), Some(g)) => ((g.snap_height(natural) * m).max(g.snap_height(pictures)), true),
(LineSpacing::AtLeast(v), Some(g)) => (g.snap_height(natural.max(pictures)).max(v), true),
(LineSpacing::Multiple(m), None) => {
((text_natural + (m - 1.0) * run_leading + label_extra).max(text_pictures + (m - 1.0).max(0.0) * font_natural), false)
}
(LineSpacing::Multiple(m), None) => ((text_natural * m + label_extra).max(text_pictures + (m - 1.0).max(0.0) * font_natural), false),
(LineSpacing::AtLeast(v), None) => (natural.max(text_pictures).max(v), false),
(LineSpacing::Exactly(v), _) => (v, false),
};
@@ -776,8 +745,6 @@ struct Extents {
obj_desc: f32,
/// Whether the line holds text besides its pictures (spaces and tabs don't count).
text: bool,
/// The tallest of its runs' own heights (ascent plus descent): the multiple's leading.
single: f32,
}
/// A line's height and baseline, and the extent of its text.
@@ -909,14 +876,6 @@ impl Scan {
bk.wrapped_tab = Some(j);
return true;
}
if bk.wrapped_tab == Some(j) && self.narrowed && stop.pos > bk.base_right + 0.01 && bk.skipped < 50 {
// A left tab past the right indent that wrapped into a span narrowed by a
// floating object (the far side of it, say): like Word, it goes on to the
// first line clear of the object (#6577). A stop inside the right indent
// keeps the zero-width path below.
self.skip = true;
return true;
}
if bk.wrapped_tab == Some(j) {
// Still past the right indent on the line it wrapped to: it takes no
// room, and its text starts at the indent rather than on a line of its own.
@@ -950,33 +909,19 @@ impl Scan {
}
self.x += w;
}
_ => {
// A right tab's room grows from nothing with its text (a tab moved on from the
// line before may still hold the width it had there).
if stop.align == TabAlign::Right
&& let Some(c) = pl.clusters.get_mut(j)
{
c.adv = 0.0;
}
self.pending_tab = Some((j, stop, self.x));
}
_ => self.pending_tab = Some((j, stop, self.x)),
}
if stop.leader != TabLeader::None {
self.leaders.push((j, stop.leader));
}
}
/// Whether text after a right/centre tab grows leftwards into the tab's space first. Up to a
/// right stop it fits even past the right indent (Word: a TOC entry whose text ends
/// less than a digit short of the indent keeps its page number on its line when the stop is
/// at the margin); unshifted, the text after the tab ends at `x - room`.
/// Whether text after a right/centre tab grows leftwards into the tab's space first.
fn absorbs(&self, pl: &ParaLayout, advance: f32) -> bool {
self.pending_tab.is_some_and(|(tj, stop, _)| {
let room = pl.clusters.get(tj).map(|t| t.adv).unwrap_or(0.0);
match stop.align {
// Not where a floating object narrows the line: the text would run into it.
TabAlign::Right => room >= advance || (!self.narrowed && self.x - room + advance <= stop.pos + 0.01),
TabAlign::Decimal => room >= advance,
TabAlign::Right | TabAlign::Decimal => room >= advance,
TabAlign::Center => room >= advance / 2.0 && self.x + advance / 2.0 <= self.right_edge + 0.01,
_ => false,
}
@@ -1002,7 +947,7 @@ impl Scan {
0.0
};
let fits = absorbs
|| self.x + advance - pl.auto_space_after(j) - line_end_kern(pl, j) <= self.right_edge + shrink + 0.01
|| self.x + advance - pl.auto_space_after(j) <= self.right_edge + shrink + 0.01
|| c.kind == ClKind::Space
|| c.kind == ClKind::Marker;
if !fits && pl.is_edit_boundary(c.start) && (c0..j).any(|k| pl.clusters.get(k).is_some_and(takes_room)) {
@@ -1052,9 +997,7 @@ impl Scan {
/// Text after a decimal/centre/right tab shifts as it grows.
fn shift_pending_tab(&mut self, pl: &mut ParaLayout) {
let Some((tj, stop, tx)) = self.pending_tab else { return };
// For a right tab `x` includes the room the tab has so far (it starts from none).
let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0);
let seg_w = self.x - tx - if stop.align == TabAlign::Right { old } else { 0.0 };
let seg_w = self.x - tx;
let shift = match stop.align {
TabAlign::Right => stop.pos - tx - seg_w,
TabAlign::Center => stop.pos - tx - seg_w / 2.0,
@@ -1063,6 +1006,7 @@ impl Scan {
_ => 0.0,
};
let shift = shift.max(0.0);
let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0);
if (shift - old).abs() > 0.001 {
let delta = shift - old;
if let Some(c) = pl.clusters.get_mut(tj) {
@@ -1170,17 +1114,6 @@ impl Scan {
}
}
/// The kerning cluster `j` loses when the line ends after it inside a word: Word measures a line's
/// last letter without its pair with the letter that goes on to the next line (a cell's width
/// swept a twip at a time in Word: the letters before a broken kerning pair fit only where they
/// fit on their own, without the pair).
fn line_end_kern(pl: &ParaLayout, j: usize) -> f32 {
match (pl.clusters.get(j), pl.clusters.get(j + 1)) {
(Some(c), Some(next)) if next.kind == ClKind::Text => c.kern,
_ => 0.0,
}
}
/// Narrowest span text flows into beside a floating object, points. Word puts an empty
/// paragraph beside a floating table in a 21.3pt gap but not in an 18.6pt one.
const MIN_SPAN: f32 = 20.0;
+1 -10
View File
@@ -147,9 +147,6 @@ pub struct Cluster {
pub obj_d: f32,
/// The cluster is a decimal separator (decimal tabs align on it).
pub dot: bool,
/// The kerning between this cluster and the next (part of `adv`, usually negative): a line
/// that ends between them lays the cluster out without it.
pub kern: f32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -394,14 +391,8 @@ pub struct ParaEnv<'a> {
/// How digits look on screen (an unresolved `System` shows Western digits).
pub numeral: NumeralMode,
/// Areas text must flow around (floating objects), relative to the paragraph: x from the
/// column's left edge, y from the top of the first line (its top with the space before
/// applied, which is where [`ParaEnv::space_before`] reaches up to).
/// column's left edge, y from the top of the first line.
pub exclusions: &'a [Exclusion],
/// The space before the paragraph that the flow above it actually laid out: its declared
/// space before less what collapsing against the previous paragraph's space after, contextual
/// spacing or a page top took away (and the negative space applied at a page top). A
/// Top-and-Bottom object reaching into it is laid out again below it (#7143).
pub space_before: f32,
/// Automatic equation numbers used before this paragraph.
pub eq_number: u32,
pub read_line_spacing: Option<f32>,
+4 -54
View File
@@ -62,7 +62,6 @@ impl Slot {
obj_h,
obj_d,
dot: false,
kern: 0.0,
}
}
}
@@ -102,11 +101,6 @@ fn is_special(c: char) -> bool {
fn paragraph_props(p: &Paragraph, env: &ParaEnv) -> ResolvedPara {
let doc = env.doc;
let mut rp = doc.styles.resolve_para_in(&p.props, env.table.map(|t| &t.para));
// Before Word 2013 layout (compatibility mode 15) a row split across pages divides its cells'
// text at any line: widow/orphan control doesn't apply in a table (measured in modes 12, 14).
if env.table.is_some() && doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT {
rp.widow_control = false;
}
if let Some(spacing) = env.read_line_spacing.filter(|s| s.is_finite() && (1.0..=2.0).contains(s)) {
rp.line_spacing = wordcraft_doc::props::LineSpacing::Multiple(spacing);
}
@@ -398,11 +392,6 @@ impl<'a> Shaped<'a> {
},
_ => w,
};
// Word keeps the height in whole twips and drops the rest of the EMUs: 2007874 EMU
// (3161.99tw) is drawn 158.05pt high, and only that has to fit above the bottom margin
// (Word for Mac and Windows). Back to whole EMUs first: f32 points keep them to the EMU
// for pictures up to a page high.
let h = (((h as f64 * 12_700.0).round() / 635.0).floor() / 20.0) as f32;
let (w, h) = (w.clamp(1.0, 4000.0), h.clamp(1.0, 4000.0));
let s = if env.fit_objects && w > maxw { maxw / w } else { 1.0 };
// The line makes room for effects (shadows) around the picture too, and
@@ -552,12 +541,7 @@ fn list_label(cx: &Cx, b: &mut Builder, mark_style: u32) -> Option<Label> {
let break_only =
b.clusters.iter().any(|c| c.kind == ClKind::PageBreak) && b.clusters.iter().all(|c| matches!(c.kind, ClKind::PageBreak | ClKind::Marker));
let (text, lvl) = cx.env.label.as_ref().filter(|_| !break_only && !cx.env.joined)?;
let mut rc = cx.res.char(&p.mark.clone().overlaid(&lvl.chr));
// Word never kerns a list number, whatever the kerning of the paragraph mark or the level
// (measured in Word for Mac: "11)" in Times New Roman with kerning on is 16 pt wide, not
// the 15.55 pt of the kerned "11", so it passes a 312-twip hanging indent and the text goes on
// to the next tab stop).
Arc::make_mut(&mut rc).kern = 0.0;
let rc = cx.res.char(&p.mark.clone().overlaid(&lvl.chr));
// A bullet no installed font can draw would come from whatever icon font has its
// private-use code (Font Awesome's Twitter logo at U+F081, #1683): it shows the level's
// default bullet instead.
@@ -663,22 +647,6 @@ fn shown_text(cx: &Cx) -> Option<String> {
Some(shown)
}
/// Each run's end byte and the installed East Asian font (`w:eastAsia`) it names, `None` when it
/// names none or one that isn't installed. Empty when `wanted` is false or the text is ASCII, which
/// has no East Asian characters to look the fonts up for.
fn installed_east_asian_fonts(cx: &Cx, wanted: bool) -> Vec<(usize, Option<wordcraft_fonts::FaceRef>)> {
if !wanted || cx.p.text.is_ascii() {
return Vec::new();
}
cx.p.run_ranges()
.map(|(range, props)| {
let rc = cx.res.char(props);
let face = rc.font_ea.as_deref().filter(|f| !f.trim().is_empty()).map(|f| wordcraft_fonts::word::resolve(f, rc.bold, rc.italic));
(range.end, face.filter(|r| !r.substituted).map(|r| r.face))
})
.collect()
}
/// Lay out one paragraph.
pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
#[cfg(test)]
@@ -709,18 +677,9 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
if rp.snap_to_grid {
snap_chars(&mut sh.b, &p.text, &env.grid);
}
// Text snapping to every cell of a character grid (`snapToChars`) keeps to its cells. On a
// `linesAndChars` grid Word keeps the automatic space, as on a line grid (#6584).
let auto_space = if rp.snap_to_grid && env.grid.snap_all && env.grid.chars.is_some() {
Vec::new()
} else {
let ea = installed_east_asian_fonts(&cx, rp.auto_space_de || rp.auto_space_dn);
// Runs come in order, so their ends rise: the run holding `at` is a binary search away.
let ea_lacks = |at: usize, c: char| {
ea.get(ea.partition_point(|(end, _)| *end <= at)).and_then(|(_, face)| *face).is_some_and(|f: wordcraft_fonts::FaceRef| !f.covers(c))
};
auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn, ea_lacks)
};
// Text on a character grid keeps to its cells.
let auto_space =
if rp.snap_to_grid && env.grid.chars.is_some() { Vec::new() } else { auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn) };
let mut skip = sh.left.clone();
skip.extend(sh.bare.iter().cloned());
let bt = BreakText::new(&p.text, skip);
@@ -895,15 +854,6 @@ fn break_positions(text: &str, rp: &wordcraft_doc::resolve::ResolvedPara) -> Vec
if !before_slash.is_empty() {
found.extend(before_slash);
}
// Word breaks after a space whatever follows it, where UAX #14 keeps a space with a closing
// bracket or punctuation after it (LB13: "x :=", "false );", "JDK} ,") and an opening bracket
// with the space after it (LB14: "( word"). Measured in Word for Mac and Windows: the next line
// starts with ":=", ";", ",", ".", ")", "]", "}", "!", "?", "%", or with "word" after "( ". Not
// before another space or a no-break space: the spaces stay together; nor before a word joiner
// or a zero-width space, which UAX #14 never lets start a line (LB11, LB7).
found.extend(text.match_indices(' ').map(|(i, _)| i + 1).filter(|&i| {
text.get(i..).and_then(|t| t.chars().next()).is_some_and(|c| !c.is_whitespace() && !matches!(c, '\u{2060}' | '\u{FEFF}' | '\u{200B}'))
}));
// Word breaks after a hyphen even when a digit follows ("2016-" / "2022"), where UAX #14
// keeps a hyphen and a number together (LB25), and when a slash and a letter follow
+7 -16
View File
@@ -54,7 +54,7 @@ struct Sec<'p> {
/// Forget cached layouts made for another environment, and what the last pass used.
fn reset_cache(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions) {
let env = env_hash(doc, cache, opts);
let env = env_hash(doc, opts);
if env != cache.env {
cache.paras.clear();
cache.measures.clear();
@@ -234,10 +234,8 @@ fn new_page_builder<'p>(
sect_beneath: false,
beneath: false,
foot_top: f32::MAX,
leading_floor: 0.0,
early,
seeded: 0,
framed: Vec::new(),
settle,
column_lines: None,
}
@@ -447,10 +445,9 @@ fn section_endnotes(ctx: &mut Ctx, pb: &mut PageBuilder, endnotes: &mut VecDeque
/// the turned pages of vertical sections.
fn finish_pages(pb: PageBuilder, doc: &Document, sections: &[(usize, &SectionProps)], web: bool) -> Vec<Page> {
let mut pb = pb;
// Each page is aligned once, before its notes go on it: `finish_page` leaves the page
// top-aligned after, so a page of continued notes isn't moved down again past the bottom
// margin when the next one starts.
pb.finish_page();
pb.close_column_lines();
pb.apply_valign();
pb.flush_notes();
let last_block = doc.body.len().saturating_sub(1);
for _ in 0..MAX_NOTE_PAGES {
if pb.carry.is_empty() {
@@ -458,7 +455,7 @@ fn finish_pages(pb: PageBuilder, doc: &Document, sections: &[(usize, &SectionPro
}
let top = pb.top;
pb.new_page(last_block, top);
pb.finish_page();
pb.flush_notes();
}
pb.carry.clear();
pb.raise_front();
@@ -524,18 +521,12 @@ fn fill_headers_footers(
None
}
/// Evict paragraph layouts that weren't used this pass if the cache accumulated too many stale entries.
/// Evict paragraph layouts that weren't used this pass if the cache grew large.
fn evict_unused(cache: &mut LayoutCache) {
if cache.paras.len() + cache.measures.len() > cache.used.len() + cache.used.len().clamp(512, 1024) {
if cache.paras.len() + cache.measures.len() > 4 * cache.used.len().max(1024) {
let used = std::mem::take(&mut cache.used);
cache.paras.retain(|k, _| used.contains(k));
cache.measures.retain(|k, _| used.contains(k));
if cache.paras.capacity() > cache.paras.len().max(512) * 4 {
cache.paras.shrink_to(cache.paras.len() * 2);
}
if cache.measures.capacity() > cache.measures.len().max(256) * 4 {
cache.measures.shrink_to(cache.measures.len() * 2);
}
cache.used = used;
}
}
+9 -69
View File
@@ -248,7 +248,6 @@ pub fn measure_table_columns(doc: &wordcraft_doc::Document, t: &Table) -> Vec<(f
// Measurement uses a fixed environment (like show_hidden/proofing above).
numeral: crate::NumeralMode::default(),
exclusions: &[],
space_before: 0.0,
eq_number: 0,
read_line_spacing: None,
grid: crate::para::Grid::default(),
@@ -590,8 +589,7 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
indent - first_cell_left_margin_in(t, margins_def)
};
// The reading view fits the table into what the start offset leaves of the column, mirrored or not (#7988).
// Keep at least half the fitted width so the position clamp can reduce an excessive indent (#8063).
let room = (avail - start_offset.max(0.0)).max(acc.min(avail) / 2.0).max(1.0);
let room = (avail - start_offset.max(0.0)).max(1.0);
if ctx.opts.view == ViewMode::Read && acc > room && !matches!(t.props.align, Some(Align::Center | Align::Right)) {
let k = room / acc;
colx.iter_mut().for_each(|c| *c *= k);
@@ -617,51 +615,6 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
}
pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], avail: f32, depth: usize) -> TableLayout {
layout_table_rows(ctx, story, t, path, avail, depth, None)
}
/// Row `ri` of the body table laid out again for where it lands on a page, `room` points above the
/// bottom of the page body: a merged cell starting in it that runs on past the page end is
/// aligned (and its turned text laid out) within that room, as its text is drawn with this row.
/// The row's height is the one [`layout_table`] gave it.
pub fn layout_table_row_in(ctx: &mut Ctx, t: &Table, path: &[u32], avail: f32, ri: usize, room: f32) -> Option<RowLayout> {
// A look ahead: list and equation numbers in the cells don't count again.
let (counters, eq_count) = (ctx.counters.clone(), ctx.eq_count);
let mut tl = layout_table_rows(ctx, StoryRef::Body, t, path, avail, 1, Some((ri, room)));
(ctx.counters, ctx.eq_count) = (counters, eq_count);
tl.rows.pop()
}
/// How many rows after row `ri` the merged cells starting in it run on (0 without any).
pub(crate) fn merge_rows_after(t: &Table, ri: usize) -> usize {
let Some(row) = t.rows.get(ri) else { return 0 };
let mut gx = row.first_grid();
let mut most = 0;
for c in &row.cells {
let g = gx;
gx += c.span();
if c.props.vmerge != VMerge::Restart {
continue;
}
let mut k = ri + 1;
while t.rows.get(k).is_some_and(|r| {
let mut gx = r.first_grid();
r.cells.iter().any(|x| {
let at = gx;
gx += x.span();
at == g && x.props.vmerge == VMerge::Continue
})
}) {
k += 1;
}
most = most.max(k - ri - 1);
}
most
}
/// [`layout_table`], or with `only` = (row, room) just that row, its merged cells aligned within
/// `room` (see [`layout_table_row_in`]).
fn layout_table_rows(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], avail: f32, depth: usize, only: Option<(usize, f32)>) -> TableLayout {
let style = table_style(ctx, t);
// Cell text formatting and looks per set of style parts, built once per table.
let mut cell_text: Vec<(Region, CellText)> = Vec::new();
@@ -695,13 +648,11 @@ fn layout_table_rows(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], av
let span = cell.span();
let x0 = colx.get(g).copied().unwrap_or(acc);
let x1 = colx.get((g + span).min(ncols)).copied().unwrap_or(acc);
// Right to left: grid columns run from the right edge. The margins stay on the sides
// they name: Word for Windows keeps a cell's `w:left` (or `w:start`) margin on its
// left in a right-to-left table, the cell's and the table's alike, though it draws the
// cell's `w:left` border on its right.
// Right to left: grid columns run from the right edge, and the start (left) margin
// is on the cell's right.
let (x0, x1) = if rtl { ((acc - x1).max(0.0), (acc - x0).max(0.0)) } else { (x0, x1) };
let m = cell.props.resolved_margins(margins_def);
let margins = [row_top, m[1], row_bottom, m[3]];
let margins = if rtl { [row_top, m[3], row_bottom, m[1]] } else { [row_top, m[1], row_bottom, m[3]] };
let cw = (x1 - x0 - margins[1] - margins[3]).max(4.0);
let region = region_of(t, style.as_ref(), ri, g, span, ncols);
// Conditional formatting, later parts winning (ECMA-376 §17.7.6): whole table, column
@@ -843,7 +794,7 @@ fn layout_table_rows(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], av
rows.push(cells);
}
grow_vertical_merges(&rows, &mut heights);
finish_table_rows(ctx, TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total, only })
finish_table_rows(ctx, TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total })
}
fn grow_vertical_merges(rows: &[Vec<CellBox>], heights: &mut [f32]) {
@@ -878,15 +829,13 @@ struct TableRows<'a> {
edges: Vec<f32>,
x: f32,
total: f32,
/// Only this row (and the room under its top for its merged cells), when set.
only: Option<(usize, f32)>,
}
/// Place the laid-out cells of every row: vertical alignment, turned text, borders and the cell
/// rectangles, clipped where the row's exact height or a fixed table's column is too small for
/// the cell's text.
fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
let TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total, only } = input;
let TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total } = input;
// Grid columns holding a vertical-merge continuation, per row.
let cont: Vec<Vec<usize>> = t
.rows
@@ -906,9 +855,6 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
// Second pass: place cells with their row height, fills and borders.
let mut out = Vec::with_capacity(rows.len());
for (ri, cells) in rows.into_iter().enumerate() {
if only.is_some_and(|(row, _)| row != ri) {
continue;
}
let rh = heights.get(ri).copied().unwrap_or(0.0);
let exact = t.rows.get(ri).is_some_and(|r| r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0));
let mut items = Vec::new();
@@ -949,16 +895,10 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
_ => None,
})
.fold(c.h, f32::max);
// A merged cell's text is drawn with its restart row, even when the merge runs on
// over later pages: only the room left on the page it starts on can align it.
let align_span = match only {
Some((_, room)) if c.vmerge == VMerge::Restart => span_h.min(room.max(0.0)),
_ => span_h,
};
let mut dy = match c.valign {
VAlign::Top => 0.0,
VAlign::Center => ((align_span - align_h) / 2.0).max(0.0),
VAlign::Bottom => (align_span - align_h).max(0.0),
VAlign::Center => ((span_h - align_h) / 2.0).max(0.0),
VAlign::Bottom => (span_h - align_h).max(0.0),
};
let end = (c.vmerge != VMerge::Continue && c.turned.is_none()).then_some(c.end + dy);
let mut cell_items = c.items;
@@ -966,7 +906,7 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
dy = 0.0;
let m = c.margins;
// The lines run the cell's whole height (laid out again if the row grew).
let len = (align_span - (c.h - tn.len)).clamp(4.0, TURNED_LIMIT);
let len = (span_h - (c.h - tn.len)).clamp(4.0, TURNED_LIMIT);
let mut across = tn.across;
if (len - tn.len).abs() > 0.01
&& let Some(cell) = t.rows.get(ri).and_then(|r| r.cells.get(tn.ci))
+6 -23
View File
@@ -2,7 +2,7 @@ use super::boxes::{BoxInput, clear_of_float_tables, layout_box};
use super::ctx::{Ctx, with_pct_base};
use super::floats::{WrapArea, align_in, body_wraps};
use super::flow::again;
use super::headers::{begins_section, header_items_cap, header_table_areas, placed_cost};
use super::headers::{header_items_cap, header_table_areas, placed_cost};
use super::notes::table_notes;
use super::page::{PageBuilder, PageFrame, page_frame};
use super::placed::Placed;
@@ -14,14 +14,14 @@ pub(crate) fn footer_table_wraps(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<WrapAre
return Vec::new();
}
let Some(page) = pb.pages.last() else { return Vec::new() };
let hf = Arc::clone(&ctx.hf);
let first = begins_section(&hf.sections, pb.pages.iter().rev().nth(1), page);
let first = pb.pages.iter().rev().nth(1).is_none_or(|prev| prev.section != page.section);
let key = (page.section, page.number, first);
if let Some(areas) = ctx.footer_wraps.get(&key) {
return areas.clone();
}
ctx.footer_wraps.insert(key, Vec::new());
let doc = ctx.doc;
let hf = Arc::clone(&ctx.hf);
let Some((_, sect)) = hf.sections.get(page.section) else { return Vec::new() };
if sect.text_direction.is_turned() {
return Vec::new();
@@ -73,8 +73,6 @@ pub(crate) fn footer_table_wraps(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<WrapAre
/// The room a table in the text needs to start on a page: its repeated header rows and the least
/// room its first row can start in (whole, or the part of it that splits off). A paragraph kept
/// with the table goes over with it when that much is not left, as in Word.
/// Before Word 2013 layout (compatibility mode 15) the header rows may stay alone at the foot of a
/// page, so the paragraph keeps with them only.
pub(crate) fn table_start_need(ctx: &mut Ctx, t: &wordcraft_doc::Table, block: usize, width: f32) -> f32 {
// A look ahead: list and equation numbers in the cells don't count yet.
let (counters, eq_count) = (ctx.counters.clone(), ctx.eq_count);
@@ -82,10 +80,6 @@ pub(crate) fn table_start_need(ctx: &mut Ctx, t: &wordcraft_doc::Table, block: u
(ctx.counters, ctx.eq_count) = (counters, eq_count);
let headers = t.rows.iter().take_while(|r| r.props.header).count();
let head: f32 = tl.rows.iter().take(headers).map(|r| r.height).sum();
if headers > 0 && ctx.doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT {
// With the border below the last of them, as `place_table` places them.
return head + tl.rows.get(headers - 1).map_or(0.0, |r| r.edge);
}
let (Some(row), Some(laid)) = (t.rows.get(headers), tl.rows.get(headers)) else { return head };
// ponytail: bisection assumes starting a row gets no harder with more room.
let (mut lo, mut hi) = (0.0f32, laid.height + laid.edge);
@@ -265,11 +259,9 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
t.rows.get(ri).is_some_and(|r| r.props.height_rule == HeightRule::AtLeast && r.props.height.is_some_and(|h| h > room + 0.01))
};
// Like Word, repeated header rows don't stay alone at the bottom of a page: when the first row
// after them can't start under them there, the table starts on the next page. Before Word
// 2013 layout (compatibility mode 15) they do (measured in modes 12 and 14).
// after them can't start under them there, the table starts on the next page.
let first = header_rows.len();
if !header_rows.is_empty()
&& ctx.doc.settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT
&& !pb.at_top()
&& let Some(row) = tl.rows.get(first)
{
@@ -296,22 +288,13 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
.get(ri)
.is_some_and(|r| r.props.cant_split && !(r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0)));
let mut rest: Option<table::RowLayout> = None;
// The row laid out again for where it lands, when a merge starting in it runs past the
// end of that page (its text is drawn with this row, so it can't be aligned below it).
let mut aligned: Option<table::RowLayout> = None;
let merge_rows = table::merge_rows_after(t, ri);
let merge_h: f32 = tl.rows.iter().skip(ri).take(merge_rows + 1).map(|r| r.height).sum();
// On a new page holding only the repeated header rows.
let mut fresh = false;
// Nothing but this table's header rows above it on a page it started at the top of.
let under_top_headers = ri == first && table_at_top;
// Each pass places the part of the row that fits, then breaks the page.
for _ in 0..1000 {
if rest.is_none() && merge_rows > 0 {
let room = (pb.bottom - pb.y).max(0.0);
aligned = (merge_h > room + 0.01).then(|| table::layout_table_row_in(ctx, t, &[block as u32], width, ri, room)).flatten();
}
let cur = rest.as_ref().or(aligned.as_ref()).unwrap_or(row);
let cur = rest.as_ref().unwrap_or(row);
// A fitting kept row follows the next row when that row cannot start below it.
// Move only the prefix's start; an oversized follower cannot separate its kept rows.
let defer_kept = pb.y + cur.height <= pb.bottom + 0.01
@@ -368,7 +351,7 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
}
fresh = true;
}
let last = rest.as_ref().or(aligned.as_ref()).unwrap_or(row);
let last = rest.as_ref().unwrap_or(row);
place(pb, last);
table_notes(ctx, pb, &last.items);
}
File diff suppressed because it is too large Load Diff
+9 -49
View File
@@ -133,34 +133,6 @@ fn spaces_punctuation_hangul_and_latin_alone_get_nothing() {
}
}
/// Word adds no automatic space, on either side, beside an ideograph whose run names an installed
/// East Asian font without ideographs, even though a substituted face draws it (#6591: 0.00 pt
/// with `w:eastAsia="Times New Roman"`). A font that isn't installed keeps the space.
#[test]
fn an_east_asian_font_without_ideographs_turns_it_off() {
crate::test_fonts();
let with = |latin: Option<&str>, asian: &str| {
let mut d = Document::from_text("法院94年A字");
let p = para0(&mut d);
let len = p.text.len();
p.format(0, len, &|c: &mut CharProps| {
c.font = latin.map(str::to_string);
c.font_ea = Some(asian.to_string());
})
.unwrap();
d
};
// Source Serif 4 is installed for the tests and has no ideographs.
for d in [with(None, "Source Serif 4"), with(Some("Source Serif 4"), "Source Serif 4")] {
assert!(gaps(&d).iter().all(|g| *g == 0.0), "{:?}", gaps(&d));
}
let d = with(None, "No Such East Asian Font 6591");
let q = quarter(&d);
// The room after each Latin character follows the face that draws it, as without a
// `w:eastAsia` font at all (#6583).
assert_eq!(gaps(&d), [0.0, q, 0.0, after(&d, 7), q, after(&d, 11), 0.0], "a font that isn't installed");
}
#[test]
fn a_field_result_is_classed_by_the_text_it_shows() {
crate::test_fonts();
@@ -179,34 +151,22 @@ fn a_field_result_is_classed_by_the_text_it_shows() {
}
#[test]
fn a_snap_to_chars_grid_the_paragraph_snaps_to_turns_it_off() {
fn a_character_grid_the_paragraph_snaps_to_turns_it_off() {
crate::test_fonts();
let d = with_grid(DocGridType::SnapToChars, true);
let with = |kind: DocGridType, snap: bool| {
let mut d = Document::from_text("法院94年");
d.last_section.doc_grid = Some(DocGrid { kind, line_pitch: 18.0, char_space: 0 });
para0(&mut d).props.snap_to_grid = Some(snap);
d
};
let d = with(DocGridType::LinesAndChars, true);
assert!(gaps(&d).iter().all(|g| *g == 0.0), "{:?}", gaps(&d));
// A line grid alone, or a paragraph that doesn't snap, keeps it.
for d in [with_grid(DocGridType::Lines, true), with_grid(DocGridType::SnapToChars, false)] {
for d in [with(DocGridType::Lines, true), with(DocGridType::LinesAndChars, false)] {
assert_eq!(gaps(&d), [0.0, quarter(&d), 0.0, after(&d, 7), 0.0]);
}
}
/// Measured in Word (#6584): on a `linesAndChars` grid every character stands where it does on a
/// line grid, the automatic space included. Only `snapToChars` drops it.
#[test]
fn a_lines_and_chars_grid_keeps_it() {
crate::test_fonts();
for snap in [true, false] {
let d = with_grid(DocGridType::LinesAndChars, snap);
assert_eq!(gaps(&d), [0.0, quarter(&d), 0.0, after(&d, 7), 0.0], "snap_to_grid {snap}");
}
}
fn with_grid(kind: DocGridType, snap: bool) -> Document {
let mut d = Document::from_text("法院94年");
d.last_section.doc_grid = Some(DocGrid { kind, line_pitch: 18.0, char_space: 0 });
para0(&mut d).props.snap_to_grid = Some(snap);
d
}
#[test]
fn the_space_takes_no_room_at_the_end_of_a_justified_line() {
crate::test_fonts();
+4 -6
View File
@@ -564,8 +564,7 @@ fn inline_picture_in_rtl_text_sits_in_its_place() {
/// A right-to-left table (`w:bidiVisual`, #362): the first logical column stands at the right
/// edge, the table is start-aligned against the right margin, and each cell's start (left)
/// border is drawn on its right. Its left margin stays on its left, as Word for Windows lays it
/// out (`w:left` and `w:start` alike). Clicks find cells by where they are drawn.
/// margin and border are drawn on its right. Clicks find cells by where they are drawn.
#[test]
fn rtl_table_lays_its_columns_out_right_to_left() {
crate::test_fonts();
@@ -574,7 +573,7 @@ fn rtl_table_lays_its_columns_out_right_to_left() {
let mut d = Document::from_text("before\nafter");
let mut t = Table::new(1, 3, 300.0);
t.props.bidi_visual = true;
// Left margin 10pt, right margin 2pt.
// Start margin 10pt, end margin 2pt.
t.props.cell_margins = Some([0.0, 10.0, 0.0, 2.0]);
for (i, c) in t.rows[0].cells.iter_mut().enumerate() {
c.blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(&format!("c{i}"), Default::default()))];
@@ -593,11 +592,10 @@ fn rtl_table_lays_its_columns_out_right_to_left() {
assert!(c0.x > c1.x && c1.x > c2.x, "{c0:?} {c1:?} {c2:?}");
assert!((c1.right() - c0.x).abs() < 0.01 && (c2.right() - c1.x).abs() < 0.01);
assert!((c2.x - (right - 300.0)).abs() < 2.0, "{c2:?}");
// The first cell's text sits its left margin (10pt) in from the cell's left edge, not its
// right margin (2pt): Word doesn't mirror the margins (measured in Word for Windows).
// The first cell's text sits its end margin (2pt) in from the cell's left edge.
let text_x =
items.iter().find_map(|i| if let Placed::Lines { path, x, .. } = i { (path.0 == [1, 0, 0, 0]).then_some(*x) } else { None }).unwrap();
assert!((text_x - (c0.x + 10.0)).abs() < 0.5, "text at {text_x}, cell {c0:?}");
assert!((text_x - (c0.x + 2.0)).abs() < 0.5, "text at {text_x}, cell {c0:?}");
// The thick start border is drawn on the cell's right edge.
let thick: Vec<f32> = items
.iter()
-154
View File
@@ -1,154 +0,0 @@
//! A combining mark the face of its character can't draw (#7865): the character and its marks are
//! drawn together in a face that has them all (CSS Fonts 4 §5.3, cluster matching), and with no
//! such face the mark on its own from a face that has it, except in right-to-left and
//! complex-script text, where it stays with its letter. Marks the face draws and pairs it composes
//! stay with their character. Fixed test fonts: Source Serif 4 lacks U+0336 and U+0338; Source
//! Sans 3 has U+0338; only JetBrains Mono has U+0336.
use std::sync::Arc;
use wordcraft_doc::{CharProps, Document, Paragraph, para_block};
use wordcraft_fonts::{FaceRef, FontDb};
use super::lay;
use super::linear::assert_linear_steps;
use crate::display::DisplayOptions;
use crate::{ParaLayout, Placed};
const SERIF: &str = "Source Serif 4";
fn serif() -> FaceRef {
crate::test_fonts();
let face = wordcraft_fonts::word::resolve(SERIF, false, false).face;
assert_eq!(face.family, SERIF, "the fixed test fonts include {SERIF}");
face
}
/// A document of one paragraph, `text` set in Source Serif 4; `cs`: with complex-script
/// formatting (`w:cs`), its complex-script font Source Serif 4 too.
fn doc(text: &str, cs: bool) -> Document {
let chr = CharProps { font: Some(SERIF.into()), font_cs: Some(SERIF.into()), cs: Some(cs), size: Some(12.0), ..Default::default() };
let mut d = Document::new();
d.body = vec![para_block(Paragraph::with_text(text, chr))];
d
}
/// [`doc`] laid out: its paragraph and the characters drawn as missing glyphs.
fn laid(text: &str, cs: bool) -> (Arc<ParaLayout>, Vec<char>) {
laid_doc(&doc(text, cs))
}
/// `d`, a document of one paragraph, laid out: the paragraph and the characters drawn as missing
/// glyphs.
fn laid_doc(d: &Document) -> (Arc<ParaLayout>, Vec<char>) {
crate::test_fonts();
let l = lay(d);
let missing = l.missing_glyphs(d, &DisplayOptions::default(), None).chars.iter().map(|(c, _)| *c).collect();
let para = l
.pages
.iter()
.flat_map(|p| &p.items)
.find_map(|it| match it {
Placed::Lines { para, .. } => Some(para.clone()),
_ => None,
})
.expect("the paragraph is laid out");
(para, missing)
}
/// The face that draws the character at byte `at` of the paragraph.
fn face_at(para: &ParaLayout, at: usize) -> FaceRef {
let c = para.clusters.iter().find(|c| c.start <= at && at < c.end).expect("a cluster holds the character");
para.styles[c.style as usize].face
}
#[test]
fn a_mark_its_letters_font_lacks_goes_with_its_letter_to_a_face_that_has_both() {
let serif = serif();
let (letter, mark) = ('∞', '\u{338}');
assert!(serif.covers(letter) && !serif.covers(mark), "{SERIF} has {letter} and lacks U+0338");
let text = format!("x {letter}{mark} y");
let (para, missing) = laid(&text, false);
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
let at = text.find(letter).expect("the letter is in the text");
let face = face_at(&para, at);
assert_eq!(face.id(), face_at(&para, at + letter.len_utf8()).id(), "the letter and its mark are drawn in one face");
assert!(face.covers(letter) && face.covers(mark), "that face has both");
assert_eq!(face_at(&para, 0).id(), serif.id(), "the text before stays in the run's font");
assert_eq!(face_at(&para, text.len() - 1).id(), serif.id(), "the text after goes back to the run's font");
}
/// In small capitals a mark is set at the size of the lower-case letter it belongs to, so the
/// letter and its marks still go together to a face that has them all, also when the run's font has
/// the first mark and lacks the second.
#[test]
fn in_small_capitals_a_letter_and_its_marks_go_together_to_a_face_that_has_them_all() {
let serif = serif();
let (letter, has, lacks) = ('x', '\u{301}', '\u{336}');
assert!(serif.covers(letter) && serif.covers(has) && !serif.covers(lacks), "{SERIF} has x and U+0301 and lacks U+0336");
let text: String = [letter, has, lacks].iter().collect();
let chr = CharProps { font: Some(SERIF.into()), size: Some(12.0), small_caps: Some(true), ..Default::default() };
let mut d = Document::new();
d.body = vec![para_block(Paragraph::with_text(&text, chr))];
let (para, missing) = laid_doc(&d);
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
let style_at = |at: usize| para.clusters.iter().find(|c| c.start <= at && at < c.end).expect("a cluster holds the character").style;
let face = face_at(&para, 0);
assert!(face.covers(lacks), "the letter is drawn in a face that has U+0336");
for (at, c) in text.char_indices().skip(1) {
assert_eq!(face_at(&para, at).id(), face.id(), "U+{:04X} is drawn in its letter's face", c as u32);
assert_eq!(style_at(at), style_at(0), "U+{:04X} is set at its letter's size", c as u32);
}
}
#[test]
fn a_mark_the_font_composes_with_its_letter_stays_in_the_run_font() {
let serif = serif();
// The font has no U+0338, but the shaper draws = with it as ≠, which the font has.
assert!(!serif.covers('\u{338}') && serif.covers('≠'), "{SERIF} lacks U+0338 and has ≠");
let text = "x =\u{338} y";
let (para, missing) = laid(text, false);
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
for (at, c) in text.char_indices() {
assert_eq!(face_at(&para, at).id(), serif.id(), "U+{:04X} stays in the run's font", c as u32);
}
}
#[test]
fn a_mark_no_face_draws_with_its_letter_is_drawn_from_a_face_that_has_it() {
let serif = serif();
let (letter, mark) = ('ǹ', '\u{336}');
let db = FontDb::global();
assert!(serif.covers(letter) && !serif.covers(mark), "{SERIF} has {letter} and lacks U+0336");
assert!(db.fallback_for_run(&[letter, mark], serif.id(), false, false).is_none(), "no face has both");
assert!(db.fallback_for(mark, serif.id()).is_some(), "a face has U+0336");
let text = format!("{letter}{mark}");
let (para, missing) = laid(&text, false);
assert!(missing.is_empty(), "the mark is drawn, but {missing:?} were missing glyphs");
assert_eq!(face_at(&para, 0).id(), serif.id(), "the letter stays in the run's font");
assert!(face_at(&para, letter.len_utf8()).covers(mark), "the mark comes from a face that has it");
}
/// In complex-script text a mark no face draws with its letter stays in the letter's face, so it is
/// never split from its letter (Arabic harakat would lose their place on it).
#[test]
fn in_complex_script_text_a_mark_no_face_draws_with_its_letter_stays_with_it() {
let serif = serif();
let (letter, mark) = ('ǹ', '\u{336}');
assert!(FontDb::global().fallback_for_run(&[letter, mark], serif.id(), false, false).is_none(), "no face has both");
let (para, _) = laid(&format!("{letter}{mark}"), true);
assert_eq!(face_at(&para, 0).id(), serif.id(), "the letter stays in the run's font");
assert_eq!(face_at(&para, letter.len_utf8()).id(), serif.id(), "the mark stays with its letter");
}
/// A letter followed by many marks no face draws with it, in complex-script text, where they stay
/// with it: their cluster is matched once, not again at every mark, which made the layout quadratic
/// in their number.
#[test]
fn a_long_run_of_marks_after_one_letter_lays_out_in_linear_time() {
let serif = serif();
let (letter, mark) = ('ǹ', '\u{336}');
assert!(FontDb::global().fallback_for_run(&[letter, mark], serif.id(), false, false).is_none(), "no face has both");
let text = |n: usize| std::iter::once(letter).chain(std::iter::repeat_n(mark, n)).collect::<String>();
assert_linear_steps("marks after one letter", 200, |n| doc(&text(n), true), |d| drop(std::hint::black_box(lay(d))));
}
+2 -42
View File
@@ -3,7 +3,6 @@
#[allow(unused_imports)]
use crate::*;
use wordcraft_doc::Pos;
use wordcraft_doc::props::LineSpacing;
use wordcraft_doc::section::{DocGrid, DocGridType};
@@ -83,54 +82,15 @@ fn character_grid_places_east_asian_text_on_the_pitch() {
let (g, p) = (first(&l), first(&plain));
let line = &g.lines[0];
let latin = text.find('a').unwrap();
let last_asian = text[..latin].char_indices().last().unwrap().0;
for (k, c) in g.clusters.iter().enumerate() {
let x = line.xs[k] - line.xs[0];
if c.start < latin {
// Ideographs and kana sit on the pitch, one cell each; the last one before the Latin
// text keeps the automatic space after it, as on a line grid (#6584).
// Ideographs and kana sit on the pitch, one cell each.
assert!((x - pitch * k as f32).abs() < 0.01, "cluster {k} at {x}, pitch {pitch}");
let auto_space = if c.start == last_asian { size / 4.0 } else { 0.0 };
assert!((c.adv - pitch - auto_space).abs() < 0.01, "cluster {k} advances {}", c.adv);
assert!((c.adv - pitch).abs() < 0.01);
} else {
// Latin text keeps its own advances.
assert!((c.adv - p.clusters[k].adv).abs() < 0.01, "latin cluster {k}");
}
}
}
#[test]
fn an_exact_character_grid_line_fits_all_its_cells_with_kerning() {
crate::test_fonts();
let text = "AVAVAVAVAVAVAVAVAVAV";
let mut grid = with_grid(text, DocGridType::SnapToChars, 0);
let styles = std::sync::Arc::make_mut(&mut grid.styles);
styles.default_chr.font = Some("Inter".into());
styles.default_chr.kern = Some(1.0);
let set_width = |doc: &mut Document, width: f32| {
let indent = doc.last_section.text_width() - width;
doc.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent)).unwrap();
};
// In proportional text the fifth letter still needs its unkerned width at a line break.
let mut plain = grid.clone();
plain.last_section.doc_grid = None;
let wide = lay(&plain);
let para = wide.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
let kern = para.clusters[4].kern;
assert!(kern < -0.02, "the test font must kern the pair across the break");
set_width(&mut plain, paired - kern / 2.0);
assert_eq!(super::body_lines(&lay(&plain), text)[0], "AVAV");
let size = para::Grid::of(&grid, &grid.last_section).font_size;
grid.last_section.doc_grid.as_mut().unwrap().char_space = DocGrid::char_space_for(20.0, size);
let pitch = grid.last_section.grid_char_pitch(size).unwrap();
set_width(&mut grid, 5.0 * pitch);
for kern in [0.0, 1.0] {
std::sync::Arc::make_mut(&mut grid.styles).default_chr.kern = Some(kern);
let got = super::body_lines(&lay(&grid), text);
assert_eq!(got[0], "AVAVA", "kerning threshold {kern}: {got:?}");
}
}
-14
View File
@@ -89,20 +89,6 @@ fn a_joined_paragraphs_drawings_are_relative_to_the_shared_line() {
assert!(boxed < alpha + 12.0, "the box's text at {boxed} is below the shared line at {alpha}");
}
#[test]
fn a_margin_anchored_frame_in_a_cell_joins_after_a_hidden_mark() {
let mut d = Document::from_text("Alpha\nOmega");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.frame =
Some(TextFrame { h_anchor: "page".into(), v_anchor: "margin".into(), ..Default::default() });
in_cell(&mut d);
let l = lay(&d);
let alpha = top_of(&l, &Path(vec![0, 0, 0, 0]));
let omega = top_of(&l, &Path(vec![0, 0, 0, 1]));
assert!((omega - alpha).abs() < 1.0, "framed paragraph should share hidden-mark line: {alpha} vs {omega}");
}
#[test]
fn a_text_frame_after_a_hidden_mark_is_not_joined() {
// A framed paragraph is placed apart, so it shares no line with the one before: its number is
-160
View File
@@ -1,160 +0,0 @@
//! A long word broken by letters: the letter ending the line is measured without its kerning
//! pair with the letter that goes on to the next line (Word, a line's width swept a twip at a
//! time: the letters before a broken kerning pair fit only where they fit on their own).
use super::*;
#[test]
fn a_word_broken_by_letters_ends_without_its_kerning_pair() {
let text = "AVAVAVAVAVAVAVAVAVAV";
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
Arc::make_mut(&mut d.styles).default_chr.kern = Some(1.0);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
d
};
// The word on one line: the first five letters' width with the "AV" pair after the fifth
// and without it.
let l = lay(&doc(0.0));
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - para.clusters[4].kern;
assert!(alone - paired > 0.1, "the test font kerns \"AV\": {paired} vs {alone}");
// A line between the two takes four letters, as in Word; with the pair it took five.
let got = body_lines(&lay(&doc(468.0 - (paired + alone) / 2.0)), text);
assert_eq!(got.first().map(String::as_str), Some("AVAV"), "{got:?}");
// A line as wide as the five letters alone takes them.
let got = body_lines(&lay(&doc(468.0 - alone - 0.004)), text);
assert_eq!(got.first().map(String::as_str), Some("AVAVA"), "{got:?}");
}
/// Inter under the family name "Kernx" with its `GPOS` hidden and an old-style `kern` table that
/// kerns "AV" by `units` (and nothing else): a shaper splits such a pair between the two letters,
/// half in the first one's advance and half in the second one's advance and offset.
fn legacy_kern_family(units: i16) -> &'static str {
const FAMILY: &str = "Kernx";
let inter = wordcraft_fonts::word::resolve("Inter", false, false).face;
let (a, v) = (inter.glyph_for('A') as u16, inter.glyph_for('V') as u16);
let src = inter.data().to_vec();
let u16_at = |d: &[u8], o: usize| u16::from_be_bytes([d[o], d[o + 1]]) as usize;
let u32_at = |d: &[u8], o: usize| u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]) as usize;
// The tables, `GPOS` renamed so no shaper reads it, and the new `kern` table.
let mut tables: Vec<([u8; 4], Vec<u8>)> = (0..u16_at(&src, 4))
.map(|i| {
let r = 12 + 16 * i;
let tag: [u8; 4] = src[r..r + 4].try_into().unwrap();
let tag = if &tag == b"GPOS" { *b"XPOS" } else { tag };
(tag, src[u32_at(&src, r + 8)..u32_at(&src, r + 8) + u32_at(&src, r + 12)].to_vec())
})
.collect();
let mut kern = Vec::new();
for x in [0u16, 1, 0, 20, 0x0001, 1, 6, 0, 0, a, v] {
kern.extend(x.to_be_bytes());
}
kern.extend(units.to_be_bytes());
tables.push((*b"kern", kern));
tables.sort_by_key(|t| t.0);
// The font file again: its header, the table records, then the tables (4-byte aligned).
let n = tables.len();
let mut data = src[..12].to_vec();
data[4..6].copy_from_slice(&(n as u16).to_be_bytes());
let mut at = 12 + 16 * n;
let mut body = Vec::new();
for (tag, t) in &tables {
data.extend(tag);
data.extend(0u32.to_be_bytes());
data.extend((at as u32).to_be_bytes());
data.extend((t.len() as u32).to_be_bytes());
body.extend(t);
while body.len() % 4 != 0 {
body.push(0);
}
at = 12 + 16 * n + body.len();
}
data.extend(body);
// The family name, in the name table's UTF-16 and single-byte records alike.
let name = tables.iter().take_while(|t| &t.0 != b"name").map(|t| t.1.len().div_ceil(4) * 4).sum::<usize>() + 12 + 16 * n;
let len = tables.iter().find(|t| &t.0 == b"name").map_or(0, |t| t.1.len());
let wide = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(wide("Inter"), wide(FAMILY)), (b"Inter".to_vec(), FAMILY.as_bytes().to_vec())] {
for i in name..name + len - from.len() {
if data[i..i + from.len()] == from[..] {
data[i..i + from.len()].copy_from_slice(&to);
}
}
}
wordcraft_fonts::FontDb::global().add_font(data);
FAMILY
}
/// A letter ending a line whose kerning pair with the letter before it the shaper split between
/// them keeps that pair: only its pair with the letter going on to the next line is dropped
/// (Word for Windows, a font with only an old-style `kern` table: "...3Vy" of a base64 token on
/// one line, where the "y" carrying half the "Vy" pair measured it wider and moved it on).
#[test]
fn a_letter_ending_a_line_keeps_its_pair_with_the_letter_before() {
crate::test_fonts();
let text = "AVAVAVAVAVAVAVAVAVAV";
let family = legacy_kern_family(-300);
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
d
};
let l = lay(&doc(0.0));
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
// "AVAVAV" on a line: the "AV" pairs in it kerned, the "VA" after it not kerned at all.
let six: f32 = para.clusters[..6].iter().map(|c| c.adv).sum();
assert!(para.clusters[0].kern < -0.5, "the test font kerns \"AV\": {}", para.clusters[0].kern);
let got = body_lines(&lay(&doc(468.0 - six - 0.004)), text);
assert_eq!(got.first().map(String::as_str), Some("AVAVAV"), "{got:?}");
}
/// A ligature's kerning pair with the letter after it belongs on the ligature's last cluster, not
/// on its head (#8618): a forced character wrap inside the ligature must not subtract the pair
/// after the whole ligature, and a line ending after the ligature drops that pair.
#[test]
fn a_ligatures_kerning_pair_sits_on_its_last_cluster() {
crate::test_fonts();
let text = "flYflYflYflY";
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
st.default_chr.font = Some("Source Serif 4".into());
st.default_chr.size = Some(14.0);
st.default_chr.kern = Some(1.0);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
d
};
let l = lay(&doc(0.0));
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
assert!(para.clusters[0].g1 > para.clusters[0].g0 && para.clusters[1].g1 == para.clusters[1].g0, "fixture forms an \"fl\" ligature");
assert_eq!(para.clusters[0].kern, 0.0, "the ligature's head cluster carries no kerning pair");
assert!(para.clusters[1].kern < -0.3, "the ligature's last cluster carries its pair with \"Y\": {}", para.clusters[1].kern);
assert_eq!(para.clusters[3].kern, 0.0);
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - para.clusters[4].kern;
assert!(alone - paired > 0.3, "Source Serif 4 kerns \"fl\" + \"Y\": {paired} vs {alone}");
// Between paired and alone: "flYfl" fits only with its pair with "Y", so "fl" wraps whole.
let got = body_lines(&lay(&doc(468.0 - (paired + alone) / 2.0)), text);
assert_eq!(got.first().map(String::as_str), Some("flY"), "{got:?}");
// Wide enough for "flYfl" without the pair after it.
let got = body_lines(&lay(&doc(468.0 - alone - 0.004)), text);
assert_eq!(got.first().map(String::as_str), Some("flYfl"), "{got:?}");
// A three-letter ligature ("ffi") also puts its pair with "V" only on its last cluster.
let mut d3 = Document::from_text("ffiV");
let st3 = Arc::make_mut(&mut d3.styles);
st3.default_chr.font = Some("Source Serif 4".into());
st3.default_chr.size = Some(14.0);
st3.default_chr.kern = Some(1.0);
let l3 = lay(&d3);
let p3 = l3.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
assert!(p3.clusters[0].g1 > p3.clusters[0].g0 && p3.clusters[1].g1 == p3.clusters[1].g0 && p3.clusters[2].g1 == p3.clusters[2].g0);
assert_eq!(p3.clusters[0].kern, 0.0);
assert_eq!(p3.clusters[1].kern, 0.0);
assert!(p3.clusters[2].kern < -0.2, "last cluster of \"ffi\" carries pair with \"V\": {}", p3.clusters[2].kern);
}
-64
View File
@@ -874,70 +874,6 @@ fn a_roman_page_number_in_the_footer_stays_roman_with_the_page_count_in_the_body
}
}
#[test]
fn a_multiple_spaced_lines_leading_may_run_past_a_footer_above_the_margin() {
// A footer reaching above the bottom margin: Word lets the leading of the page's last
// 1.5-spaced line run past its top as into the margin, only the text has to fit, whatever the
// footer holds. Word for Mac and Windows, a 1.5-spaced 12pt line pushed down by half a point:
// it stays while its text ends above the footer (up to 0.4pt above), with a one-line
// page-number footer above the margin by 6.6pt and by 28pt, with a four-line footer, and with
// an empty exact-height 120pt paragraph. Also when the footer is the first page's own (a title
// page footer, the other pages' footer short): the first page's footer counts there.
use wordcraft_doc::props::LineSpacing;
// (footer lines, their text, the title page's own footer, footer distance from the page bottom)
let cases: [(usize, &str, bool, Option<f32>); 4] =
[(1, "", false, None), (1, "", true, None), (1, "7", false, Some(72.0)), (4, "Footer line", false, None)];
for (lines, text, first, from_bottom) in cases {
let mut past_footer = 0;
for shift in (0..28).step_by(2) {
let mut d = Document::from_text(&"Several words wrap onto many lines of a long paragraph. ".repeat(60));
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(0).map(Arc::make_mut) {
p.props.line_spacing = Some(LineSpacing::Multiple(1.5));
p.props.space_before = Some(shift as f32);
p.props.widow_control = Some(false);
}
let foot_paras = (0..lines)
.map(|_| {
let mut f = Paragraph::with_text(text, Default::default());
if text.is_empty() {
f.props.line_spacing = Some(LineSpacing::Exactly(120.0));
}
para_block(f)
})
.collect();
let id = d.add_part(PartKind::Footer, foot_paras);
if let Some(f) = from_bottom {
d.last_section.footer = f;
}
if first {
d.last_section.title_page = true;
d.last_section.footers.first = Some(id);
} else {
d.last_section.footers.default = Some(id);
}
let l = lay(&d);
let foot = l.pages[0].body.bottom();
let what = format!("footer of {lines} x {text:?}, shift {shift}");
assert!(foot < d.last_section.page_h - d.last_section.margin_bottom - 1.0, "{what}: the footer reaches above the margin: {foot}");
let Some(Placed::Lines { y, para, l0, l1, .. }) =
l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { story: StoryRef::Body, .. }))
else {
panic!("{what}: no body lines on page 1")
};
let (first, last, next) = (&para.lines[*l0], &para.lines[*l1 - 1], &para.lines[*l1]);
let top = y + last.top - first.top;
let text_end = top + (last.baseline - last.top) + last.text_desc;
assert!(text_end <= foot + 0.01, "{what}: the last line's text ends at {text_end}, below the footer at {foot}");
let next_text_end = top + last.height + (next.baseline - next.top) + next.text_desc;
assert!(next_text_end > foot + 0.01, "{what}: the next line's text would end at {next_text_end}, above the footer at {foot}");
if top + last.height > foot + 0.01 {
past_footer += 1;
}
}
assert!(past_footer > 0, "footer of {lines} x {text:?}: some shift should leave the last line's leading past the footer");
}
}
#[test]
fn a_page_ends_when_a_multiple_spaced_lines_text_no_longer_fits() {
// Multiple spacing puts its extra leading below the text, and Word lets that leading of a
@@ -1,52 +0,0 @@
//! A character Times New Roman's metric twin lacks ("‒", "₽" in Liberation Serif) is drawn from
//! a fallback face, but the line is as tall as the twin's: Times New Roman has those characters,
//! so Word's line is as tall as Times New Roman's, not the taller UI sans.
use crate::{Document, LayoutCache, LayoutOptions, Placed, layout};
/// Inter under the family name "Tinos" (a metric twin of Times New Roman), from the bundled font
/// so the test needs no installed font. Inter lacks "☐"; Source Sans 3 (the fallback) has it and
/// its line is taller (1.326 em against 1.21).
fn fake_tinos() -> &'static str {
const FAMILY: &str = "Tinos";
let inter = wordcraft_fonts::word::resolve("Inter", false, false).face;
assert!(!inter.covers('☐'));
let mut data = inter.data().to_vec();
let u16_at = |d: &[u8], o: usize| u16::from_be_bytes([d[o], d[o + 1]]) as usize;
let u32_at = |d: &[u8], o: usize| u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]) as usize;
let (name, len) = (0..u16_at(&data, 4))
.map(|i| 12 + 16 * i)
.find(|&r| &data[r..r + 4] == b"name")
.map(|r| (u32_at(&data, r + 8), u32_at(&data, r + 12)))
.unwrap();
let wide = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(wide("Inter"), wide(FAMILY)), (b"Inter".to_vec(), FAMILY.as_bytes().to_vec())] {
for i in name..name + len - from.len() {
if data[i..i + from.len()] == from[..] {
data[i..i + from.len()].copy_from_slice(&to);
}
}
}
wordcraft_fonts::FontDb::global().add_font(data);
FAMILY
}
fn line_height(text: &str, font: &str) -> f32 {
let chr = wordcraft_doc::CharProps { font: Some(font.into()), size: Some(14.0), ..Default::default() };
let mut d = Document::new();
d.body = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(text, chr))];
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
l.pages.iter().flat_map(|p| &p.items).find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.lines[0].height) } else { None }).unwrap()
}
#[test]
fn a_twin_fallback_keeps_the_twins_line_height() {
crate::test_fonts();
let tinos = fake_tinos();
assert_eq!(wordcraft_fonts::word::resolve(tinos, false, false).face.family, tinos, "the test font is installed under its own name");
let plain = line_height("Aa", tinos);
let boxed = line_height("A☐a", tinos);
assert!((boxed - plain).abs() < 0.01, "a line with a fallback character is {boxed} pt, without it {plain} pt");
// Other fonts keep the fallback's taller line.
assert!(line_height("A☐a", "Inter") > line_height("Aa", "Inter") + 1.0);
}
+2 -10
View File
@@ -107,7 +107,6 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us
objects: crate::exporter::ObjectLookup::new(doc),
at: (0, 0),
links: Vec::new(),
last_link: None,
bookmarks: std::cell::OnceCell::new(),
};
if let Some(o) = ex.outline(pages) {
@@ -137,15 +136,8 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us
}
}
surface.finish();
for (annotation, tag_slot) in annotations {
if opts.tagged
&& let Some((para_idx, child_idx)) = tag_slot
{
let annot_id = kp.add_tagged_annotation(annotation);
ex.attach_link_annotation(para_idx, child_idx, annot_id);
} else {
kp.add_annotation(annotation);
}
for annotation in annotations {
kp.add_annotation(annotation);
}
kp.finish();
}
+28 -72
View File
@@ -3,7 +3,7 @@ use super::glyphs::{baseline, cluster_ends, glyph_id, glyph_outlines, left_to_ri
use super::options::{PdfError, PdfOptions};
use super::paint::{append_path, fill, grown, norm, ok, paint_fill, pdf_line_cap, rect_path, shape_effects, shape_path};
use super::picture::{Vector, build_vector, load_image, paint_of, vector_picture};
use super::tags::{Role, TagEntry, build_tag_tree, figure_alt, graphic_alt, holds_picture, holds_text};
use super::tags::{Role, TagEntry, figure_alt, graphic_alt, holds_picture, holds_text};
use super::{
Annotation, Arc, Artifact, ArtifactType, ClKind, ContentTag, DocLayout, DocPath, Document, Draw, FaceRef, Fill, FillRule, Font, HashMap, HashSet,
Identifier, Image, InlineObject, ItemDisplay, KrillaGlyph, LineCap, LineEnd, LineJoin, LineStyle, LinkAnnotation, Node, NonZeroU16, Outline,
@@ -18,16 +18,6 @@ mod objects;
pub(crate) use objects::ObjectLookup;
mod text;
pub(crate) struct LinkRect {
pub(crate) x0: f32,
pub(crate) y0: f32,
pub(crate) x1: f32,
pub(crate) y1: f32,
pub(crate) target: String,
/// `(para_idx, child_idx)` in `Exporter::tags` for this link's `Tag::Link` group.
pub(crate) tag: Option<(usize, usize)>,
}
pub(crate) struct Exporter<'a> {
pub(crate) doc: &'a Document,
pub(crate) lay: &'a DocLayout,
@@ -52,10 +42,8 @@ pub(crate) struct Exporter<'a> {
pub(crate) objects: ObjectLookup<'a>,
/// Where the item being drawn is read ([`TagEntry::at`]).
pub(crate) at: (usize, usize),
/// Link rectangles on the current page.
pub(crate) links: Vec<LinkRect>,
/// Index in `links` touched by the most recent `Draw::Glyphs` item, if any.
pub(crate) last_link: Option<usize>,
/// Link rectangles on the current page: (x0, y0, x1, y1, target).
pub(crate) links: Vec<(f32, f32, f32, f32, String)>,
/// Bookmark positions by name (the first of a name wins), gathered once: looking each internal
/// link up by walking the whole document made a long document with a linked table of contents
/// take seconds to export.
@@ -158,14 +146,13 @@ impl Exporter<'_> {
e.children.push(Node::Leaf(id));
}
}
Role::Figure(source) => {
Role::Figure => {
let id: Identifier = s.start_tagged(ContentTag::Other);
f(self, s);
s.end_tagged();
let alt = alt.map(str::to_string).filter(|a| !a.is_empty()).or_else(|| Some("picture".to_string()));
let g = TagGroup::with_children(Tag::Figure(alt), vec![Node::Leaf(id)]);
let source = source.filter(|(_, p)| p.0.len() >= 4).map(|(st, p)| (st, p.clone()));
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)], source, at: self.at });
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)], at: self.at });
}
}
}
@@ -173,7 +160,7 @@ impl Exporter<'_> {
/// A rotated inline picture or group: turned as a whole, with each picture in it tagged on its
/// own, so a decorative picture is an artifact while the others stay figures with their alt
/// text. A described shape's figure keeps its description; anything else is an artifact.
fn rotated_pictures(&mut self, s: &mut Surface, d: &Draw, source: Option<(StoryRef, &DocPath)>) {
fn rotated_pictures(&mut self, s: &mut Surface, d: &Draw) {
match d {
Draw::Rotated { cx, cy, spin, items } => {
if !ok(*cx) || !ok(*cy) {
@@ -182,7 +169,7 @@ impl Exporter<'_> {
let [a, b, c, d, e, f] = spin.matrix(*cx, *cy);
s.push_transform(&Transform::from_row(a, b, c, d, e, f));
for it in items {
self.rotated_pictures(s, it, source);
self.rotated_pictures(s, it);
}
s.pop();
}
@@ -191,13 +178,13 @@ impl Exporter<'_> {
let Some(clip) = rect_path(rect) else { return };
s.push_clip_path(&clip, &FillRule::NonZero);
for it in items {
self.rotated_pictures(s, it, source);
self.rotated_pictures(s, it);
}
s.pop();
}
Draw::Image { decorative: true, .. } => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)),
Draw::Image { alt, .. } => self.tagged(s, Role::Figure(source), Some(alt), |me, s| me.draw(s, d)),
Draw::Figure { alt, draws, .. } => self.tagged(s, Role::Figure(source), Some(alt), |me, s| {
Draw::Image { alt, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| me.draw(s, d)),
Draw::Figure { alt, draws, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| {
for d in draws {
me.draw(s, d);
}
@@ -206,62 +193,24 @@ impl Exporter<'_> {
}
}
/// Attach a paragraph's marked-content `id` to its `Tag::Link` group when `draw` recorded a
/// link rectangle, or directly to the paragraph entry otherwise.
fn attach_para_link(&mut self, idx: usize, id: Identifier) {
if let Some(li) = self.last_link.take()
&& let Some(link) = self.links.get_mut(li)
{
if let Some((p_idx, c_idx)) = link.tag
&& let Some(Node::Group(g)) = self.tags.get_mut(p_idx).and_then(|e| e.children.get_mut(c_idx))
{
g.push(Node::Leaf(id));
return;
}
if let Some(e) = self.tags.get_mut(idx) {
let c_idx = e.children.len();
e.children.push(Node::Group(TagGroup::with_children(Tag::Link, vec![Node::Leaf(id)])));
link.tag = Some((idx, c_idx));
return;
}
}
if let Some(e) = self.tags.get_mut(idx) {
e.children.push(Node::Leaf(id));
}
}
/// Insert a link annotation's `OBJR` identifier as the first child of its `Tag::Link` group.
pub(crate) fn attach_link_annotation(&mut self, para_idx: usize, child_idx: usize, annot_id: Identifier) {
if let Some(Node::Group(g)) = self.tags.get_mut(para_idx).and_then(|e| e.children.get_mut(child_idx)) {
g.children.insert(0, Node::Leaf(annot_id));
}
}
/// One draw of a paragraph's line, tagged for what it is: text as the paragraph's content
/// (structure entry `idx`), pictures and figures on their own, anything else an artifact.
fn line_item(&mut self, s: &mut Surface, d: &Draw, idx: usize, story: StoryRef, path: &DocPath) {
fn line_item(&mut self, s: &mut Surface, d: &Draw, idx: usize) {
match d {
Draw::Glyphs { link: Some(_), .. } if self.opts.tagged && self.opts.links => {
self.last_link = None;
let id = s.start_tagged(ContentTag::Span(SpanTag::empty()));
self.draw(s, d);
s.end_tagged();
self.attach_para_link(idx, id);
}
Draw::Glyphs { .. } | Draw::Turned { .. } => self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d)),
// A picture marked decorative: an artifact screen readers skip.
Draw::Image { decorative: true, .. } => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)),
Draw::Image { alt, .. } => self.tagged(s, Role::Figure(Some((story, path))), Some(alt), |me, s| me.draw(s, d)),
Draw::Image { alt, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| me.draw(s, d)),
// A rotated inline picture, or a rotated group holding pictures: turned as a
// whole, each picture tagged on its own (see `rotated_pictures`).
Draw::Rotated { items, .. } if items.iter().any(holds_picture) => self.rotated_pictures(s, d, Some((story, path))),
Draw::Rotated { items, .. } if items.iter().any(holds_picture) => self.rotated_pictures(s, d),
// A clip (a turned picture cut at its line, an exact-height cell's lines, a canvas's
// members): each draw in it tagged as it would be outside it.
Draw::Clip { rect, items } => {
let Some(clip) = rect_path(rect) else { return };
s.push_clip_path(&clip, &FillRule::NonZero);
for it in items {
self.line_item(s, it, idx, story, path);
self.line_item(s, it, idx);
}
s.pop();
}
@@ -269,7 +218,7 @@ impl Exporter<'_> {
// without text falls to the artifacts below.
Draw::Rotated { items, .. } if items.iter().any(holds_text) => self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d)),
// An inline chart, diagram or described shape: its text is part of the figure, not the paragraph.
Draw::Figure { alt, kind, draws: inner } => self.tagged(s, Role::Figure(Some((story, path))), Some(figure_alt(alt, *kind)), |me, s| {
Draw::Figure { alt, kind, draws: inner } => self.tagged(s, Role::Figure, Some(figure_alt(alt, *kind)), |me, s| {
for d in inner {
me.draw(s, d);
}
@@ -318,7 +267,7 @@ impl Exporter<'_> {
Placed::Lines { story, path, para, .. } => {
let idx = self.entry(*story, path, para);
for d in &draws {
self.line_item(s, d, idx, *story, path);
self.line_item(s, d, idx);
}
}
Placed::Image { story, path, off, .. } => {
@@ -327,7 +276,7 @@ impl Exporter<'_> {
let role = if obj.is_some_and(InlineObject::is_decorative) || *off == usize::MAX {
Role::Artifact(ArtifactType::Other)
} else {
Role::Figure(Some((*story, path)))
Role::Figure
};
let alt = match obj {
Some(InlineObject::Image { alt, .. }) => alt.clone(),
@@ -340,7 +289,7 @@ impl Exporter<'_> {
});
}
// A floating shape with a description: a figure (see `shape_figure_alt`).
Placed::Shape { alt, .. } if !alt.is_empty() => self.tagged(s, Role::Figure(None), Some(alt), |me, s| {
Placed::Shape { alt, .. } if !alt.is_empty() => self.tagged(s, Role::Figure, Some(alt), |me, s| {
for d in &draws {
me.draw(s, d);
}
@@ -350,7 +299,7 @@ impl Exporter<'_> {
Some(InlineObject::Graphic { alt, .. }) => graphic_alt(alt, graphic.kind).to_string(),
_ => graphic.kind.noun().to_string(),
};
self.tagged(s, Role::Figure(Some((*story, path))), Some(&alt), |me, s| {
self.tagged(s, Role::Figure, Some(&alt), |me, s| {
for d in &draws {
me.draw(s, d);
}
@@ -388,19 +337,26 @@ impl Exporter<'_> {
}
_ => Tag::P.into(),
};
self.tags.push(TagEntry { kind, children: Vec::new(), source: Some((story, path.clone())), at: self.at });
self.tags.push(TagEntry { kind, children: Vec::new(), at: self.at });
let i = self.tags.len() - 1;
self.tag_index.insert((story, path.clone()), i);
i
}
pub(crate) fn tag_tree(&mut self) -> TagTree {
let mut tree = TagTree::new().with_lang(self.doc.styles.default_chr.lang.clone());
// In reading order: a floating object drawn over the text after it is read after its
// anchor (#5534). The sort is stable, so what is read at one place keeps its order.
let mut tags = std::mem::take(&mut self.tags);
tags.sort_by_key(|e| e.at);
self.tag_index.clear();
build_tag_tree(self.doc, tags)
for e in tags {
if e.children.is_empty() {
continue;
}
tree.push(TagGroup::with_children(e.kind, e.children));
}
tree
}
/// The watermark text stretched over its box (Word's `v:textpath fitshape`): its advance across

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