diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index e78fe1ea3b..983bdf8ad5 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -18,4 +18,7 @@ jobs: sonarcloud: # Tracked at @main so org-wide CI improvements propagate without PR churn. uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main + with: + # Same craft-fonts commit as ci.yml: the UI glyph tests need its CJK and Arabic fonts. + fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 secrets: inherit diff --git a/AGENTS.md b/AGENTS.md index 702f630871..698c64ef5b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -138,3 +138,7 @@ Progress docs: `ROADMAP.md` (stage, headline numbers, progress log), `docs/targe - Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. New workspace crates include `workspace = true` under `[lints]` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them. + +## Shared-library reuse + +Before implementing file formats, codecs, protocols or reusable UI components, check [storytold/craft-libs](https://github.com/storytold/craft-libs) and relevant open PRs; reuse or extend shared APIs instead of duplicating app-local implementations. Keep app-specific policy and adapters local, preserve behavior and format fidelity, security and resource limits, repository layering and regression tests, and document any shared-API gap rather than silently reducing functionality. diff --git a/Cargo.lock b/Cargo.lock index 01400750b0..a720a0bc46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -185,6 +185,12 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +[[package]] +name = "ambient-authority" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b" + [[package]] name = "android-activity" version = "0.6.1" @@ -739,6 +745,24 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "cap-primitives" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18" +dependencies = [ + "ambient-authority", + "fs-set-times", + "io-extras", + "io-lifetimes 3.0.1", + "ipnet", + "maybe-owned", + "rustix 1.1.5", + "rustix-linux-procfs", + "windows-sys 0.61.2", + "winx", +] + [[package]] name = "cc" version = "1.6.0" @@ -1036,7 +1060,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=762a06a4c6b48b522b7d4de84a87917ef90265e6#762a06a4c6b48b522b7d4de84a87917ef90265e6" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "rustix 1.1.5", ] @@ -1044,17 +1068,25 @@ dependencies = [ [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" + +[[package]] +name = "craft-dds" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" +dependencies = [ + "rayon", +] [[package]] name = "craft-doc-binary" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "chrono", "craft-cfb", @@ -1070,7 +1102,7 @@ dependencies = [ [[package]] name = "craft-docx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "base64 0.23.1", "chrono", @@ -1090,7 +1122,7 @@ dependencies = [ [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-xml", "kurbo", @@ -1101,7 +1133,7 @@ dependencies = [ [[package]] name = "craft-flow" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-wordmodel", "image", @@ -1111,19 +1143,24 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=762a06a4c6b48b522b7d4de84a87917ef90265e6#762a06a4c6b48b522b7d4de84a87917ef90265e6" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "fontique", + "harfrust 0.13.3", + "kurbo", "skrifa 0.47.0", "thiserror 2.0.21", + "unicode-bidi", + "unicode-segmentation", "windows-registry", ] [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=762a06a4c6b48b522b7d4de84a87917ef90265e6#762a06a4c6b48b522b7d4de84a87917ef90265e6" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ + "cap-primitives", "craft-atomic", "craft-font-catalog", "flate2", @@ -1142,12 +1179,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" [[package]] name = "craft-html" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-codepage", "craft-flow", @@ -1160,7 +1197,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1183,13 +1220,17 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ + "craft-dds", "craft-jpeg", "craft-metadata", + "craft-tiff", + "crc32fast", "exr", "flate2", "half", + "hayro-jpeg2000", "image", "image-webp", "jpeg-encoder", @@ -1206,7 +1247,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "thiserror 2.0.21", ] @@ -1214,7 +1255,7 @@ dependencies = [ [[package]] name = "craft-latex" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-flow", "craft-math", @@ -1225,7 +1266,7 @@ dependencies = [ [[package]] name = "craft-markdown" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-flow", "craft-html", @@ -1235,16 +1276,24 @@ dependencies = [ [[package]] name = "craft-math" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-xml", "serde", ] +[[package]] +name = "craft-mcp-server" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" +dependencies = [ + "serde_json", +] + [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "brotli-decompressor 6.3.1", "chrono", @@ -1256,7 +1305,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "encoding_rs", "image", @@ -1267,7 +1316,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "chardetng", "chrono", @@ -1278,7 +1327,7 @@ dependencies = [ [[package]] name = "craft-odf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "aes", "base64 0.23.1", @@ -1304,7 +1353,7 @@ dependencies = [ [[package]] name = "craft-ods" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-odf", "craft-sheet", @@ -1315,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-offcrypto" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "aes", "base64 0.23.1", @@ -1332,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-xml", "craft-zip", @@ -1343,7 +1392,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "krilla", "thiserror 2.0.21", @@ -1352,7 +1401,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a3e0b5a9440d18f19422a9dca13516747b7d3181#a3e0b5a9440d18f19422a9dca13516747b7d3181" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-winprint-gdi", "log", @@ -1366,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=01315d9c92b5b0e69082d35ca56099461a1efd45#01315d9c92b5b0e69082d35ca56099461a1efd45" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1377,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-rtf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-codepage", "craft-flow", @@ -1390,12 +1439,17 @@ dependencies = [ [[package]] name = "craft-sheet" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" + +[[package]] +name = "craft-ssip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "serde", "thiserror 2.0.21", @@ -1404,7 +1458,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1424,7 +1478,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "chrono", "dunce", @@ -1451,7 +1505,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "js-sys", "serde_json", @@ -1462,7 +1516,7 @@ dependencies = [ [[package]] name = "craft-web-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "wasm-bindgen", "web-sys", @@ -1471,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "egui", "objc2 0.6.5", @@ -1482,7 +1536,7 @@ dependencies = [ [[package]] name = "craft-winprint-gdi" version = "0.1.0" -source = "git+https://github.com/storytold/winprint.rs?rev=417ac3c4d14d3da5485a99c7d5ce8f05664ec312#417ac3c4d14d3da5485a99c7d5ce8f05664ec312" +source = "git+https://github.com/storytold/winprint.rs?rev=64e7afd4d1483512385012c340ecaaaf0f3beb7f#64e7afd4d1483512385012c340ecaaaf0f3beb7f" dependencies = [ "windows-sys 0.61.2", ] @@ -1490,7 +1544,7 @@ dependencies = [ [[package]] name = "craft-wordmodel" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "base64 0.23.1", "craft-math", @@ -1504,7 +1558,7 @@ dependencies = [ [[package]] name = "craft-xls" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-cfb", "craft-sheet", @@ -1517,7 +1571,7 @@ dependencies = [ [[package]] name = "craft-xlsx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-drawingml", "craft-opc", @@ -1529,16 +1583,17 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "quick-xml 0.41.0", + "serde", "thiserror 2.0.21", ] [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2316,6 +2371,17 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs-set-times" +version = "0.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" +dependencies = [ + "io-lifetimes 2.0.4", + "rustix 1.1.5", + "windows-sys 0.52.0", +] + [[package]] name = "fs_extra" version = "1.3.0" @@ -3186,6 +3252,28 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "io-extras" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f" +dependencies = [ + "io-lifetimes 3.0.1", + "windows-sys 0.52.0", +] + +[[package]] +name = "io-lifetimes" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983" + +[[package]] +name = "io-lifetimes" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96" + [[package]] name = "ipnet" version = "2.12.2" @@ -3341,7 +3429,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3477,6 +3565,12 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +[[package]] +name = "maybe-owned" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" + [[package]] name = "md-5" version = "0.10.6" @@ -4970,6 +5064,16 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rustix-linux-procfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056" +dependencies = [ + "once_cell", + "rustix 1.1.5", +] + [[package]] name = "rustls" version = "0.23.46" @@ -7149,7 +7253,7 @@ dependencies = [ [[package]] name = "winprint" version = "0.2.1" -source = "git+https://github.com/storytold/winprint.rs?rev=5f80b9baf6b58937c401656634e42d33f00ddf49#5f80b9baf6b58937c401656634e42d33f00ddf49" +source = "git+https://github.com/storytold/winprint.rs?rev=8ae097ef941b432b0e7671b1ec3a506800e65e57#8ae097ef941b432b0e7671b1ec3a506800e65e57" dependencies = [ "flate2", "fmt-derive", @@ -7164,6 +7268,7 @@ dependencies = [ "windows", "windows-core", "windows-implement", + "windows-numerics", "xml", ] @@ -7193,6 +7298,16 @@ version = "0.0.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6" +[[package]] +name = "winx" +version = "0.36.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d" +dependencies = [ + "bitflags 2.13.2", + "windows-sys 0.52.0", +] + [[package]] name = "wit-bindgen" version = "0.57.1" @@ -7283,6 +7398,8 @@ name = "wordcraft-doc" version = "0.18.1" dependencies = [ "base64 0.23.1", + "craft-codepage", + "craft-zip", "log", "proptest", "serde", @@ -7333,6 +7450,7 @@ dependencies = [ "craft-font-store", "craft-mime", "craft-proof", + "craft-ssip", "craft-zip", "encoding_rs", "getrandom 0.3.4", @@ -7366,6 +7484,7 @@ dependencies = [ "harfrust 0.13.3", "kurbo", "log", + "serde_json", "skrifa 0.47.0", "unicode-bidi", "unicode-script", @@ -7407,6 +7526,7 @@ name = "wordcraft-geom" version = "0.18.1" dependencies = [ "craft-image-codecs", + "craft-tiff", "image", "serde", ] @@ -7435,6 +7555,7 @@ dependencies = [ name = "wordcraft-mcp" version = "0.18.1" dependencies = [ + "craft-mcp-server", "log", "serde_json", "wordcraft-control-key", diff --git a/Cargo.toml b/Cargo.toml index 63ca129867..e9a7630354 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,19 +24,21 @@ wordcraft-pdf = { path = "crates/pdf" } # Proofing is craft-libs' craft-proof (it was crates/proof); its Language data is craft-i18n's # language-data/, embedded from CRAFT_I18N_DIR (craft-i18n.rev). The package keeps the # `wordcraft-proof` name here so `wordcraft_proof::` paths are unchanged. -# craft-proof is storytold/craft-libs main at the merge of #590 (ca-ES-valencia reads the ca-valencia -# pack), after #589 (French elision suggestions first) and #497 (flag-based compounding), which also -# has #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 = "01315d9c92b5b0e69082d35ca56099461a1efd45", version = "=0.1.0" } -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "762a06a4c6b48b522b7d4de84a87917ef90265e6", version = "=0.1.0" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "762a06a4c6b48b522b7d4de84a87917ef90265e6", version = "=0.1.0" } +# craft-proof is storytold/craft-libs main at 93dac78c. That tree has #590 (ca-ES-valencia +# 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 = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", 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" } -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } # foundation kurbo = { version = "0.13", features = ["serde"] } @@ -67,34 +69,37 @@ 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 = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", version = "=0.1.0", default-features = false, features = ["write"] } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", default-features = false, features = ["write"] } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } -craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["doc"] } -craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["text"] } -craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-html = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["flow"] } -craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-math = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["detect"] } -craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", features = ["egui"] } +craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", features = ["doc"] } +craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", features = ["text"] } +craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-html = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", features = ["flow"] } +craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-math = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", features = ["detect"] } +craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", 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" # Legacy text encodings (GBK/GB18030, Big5, Shift_JIS, EUC-KR, single-byte code pages) for plain -# text and CSV recipient lists (#778): encoding_rs ((Apache-2.0 OR MIT) AND BSD-3-Clause) and its -# detector chardetng (Apache-2.0 OR MIT), both pure Rust (Firefox's). +# text and CSV recipient lists (#778): encoding_rs ((Apache-2.0 OR MIT) AND BSD-3-Clause), pure +# Rust (Firefox's). Detection is craft-mime's `detect` feature. encoding_rs = "0.8" +# chardetng (Apache-2.0 OR MIT): only the formats test oracle for the old detector uses it directly. chardetng = "1" # Password-protected (agile-encrypted) Word documents: pure-Rust RustCrypto primitives. aes = "0.9" @@ -122,6 +127,8 @@ arboard = { version = "3.7", default-features = false, features = ["wayland-data [workspace.lints.rust] unsafe_code = "forbid" +# cargo llvm-cov sets `--cfg coverage`; timing tests skip themselves under its instrumentation. +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(coverage)"] } [workspace.lints.clippy] cognitive_complexity = "deny" @@ -150,7 +157,7 @@ debug = 0 # Required by craft-pdf: the backend rejects writers that failed during unwinding. [patch.crates-io] -krilla = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/README.md b/README.md index 42d0e27b82..ee41a08d2d 100644 --- a/README.md +++ b/README.md @@ -451,8 +451,10 @@ Copyright (c) 2026 ArtCraft Team and the WordCraft contributors. Required notice Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md). -The English spelling dictionary and hyphenation come from Grady Ward's public-domain Moby -Hyphenator II word list. Polish spelling reads the Hunspell `pl_PL` dictionary installed on the system (not bundled), as +English spelling first tries a matching Hunspell dictionary from the Dictionaries folder. +Otherwise it uses dialect-specific SCOWL 2026 dictionaries when built with language data; +without it, spelling falls back to system Hunspell dictionaries or Grady Ward's public-domain +Moby Hyphenator II word list. English hyphenation uses the Moby list and patterns trained from it. Polish spelling reads the Hunspell `pl_PL` dictionary installed on the system (not bundled), as do Russian, Portuguese, Czech, Italian, Croatian and Turkish spelling (how to install them: [docs/spelling-dictionaries.md](docs/spelling-dictionaries.md)), and Polish hyphenation the TeX patterns by Hanna Kołodziejska, Bogusław Jackowski and Marek Ryćko (MIT diff --git a/ROADMAP.md b/ROADMAP.md index d193359773..af21a56cc6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -8,7 +8,7 @@ **Stage: alpha** · next: beta, ~15 points (60% → 75% ready for real work) and ~150–230 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** trivial (progress log: Save As and Export offer Browse in WordCraft… on Linux/BSD, #3535); previously trivial (progress log: Review › Language can set the whole document's proofing language, #3518); previously trivial (progress log: Auto interface size capped to the screen, #4030); previously trivial (progress log: DOCX section line numbering stays off without a positive `w:countBy`, #6209); previously trivial (progress log: Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (progress log: #4501 refactor regressions restored: per-section header grid, ODT default font, link tooltip, #4683); previously trivial (progress log: the window moves by its title bar behind a modal dialog, #5124); previously trivial (progress log: `convert --strict` and `render --strict` refuse a silently incomplete PDF or PNG (#6005, #6008)); ; trivial (progress log: ODT columns stating only their shares); previously trivial (progress log: ODT font size for every script); previously trivial (progress log: ODT text turning off what its style turns on); previously trivial (progress log: edited ODT paragraphs keep custom styles with an outline level); previously trivial (progress log: ODT pictures keep the size their file gives); previously trivial (progress log: ODT frames keep the page they are anchored to); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux no longer looks semi-bold); previously trivial (Control/MCP #2596 review: partial-write outcomes, path-bearing image exports, accept-thread startup cleanup and malformed UTF-8 handling); previously trivial (progress log: a turned inline picture whose file keeps no room for the turn keeps its line to its frame); previously trivial (progress log: the Arabic interface's Styles gallery reads from the right (#5566)); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT heading text of another size); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: a shape dropped just after a page break inside a paragraph stays on the new page, #4262); previously trivial (progress log: a float anchored on a later page of a long paragraph is drawn there, #4250); previously minor (progress log: `file.closeDocument` over the control channel and MCP bridge is refused while the document it names has unsaved changes; previously trivial (progress log: ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: Shape Format › Size in the interface unit, #4196); previously trivial (progress log: typed n-ary operators such as ∫ and ∑ wait for their limits, observed in Word for Windows on #4938 (#4917)); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: justified and distributed lines keep the width of the spaces before their first character); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (progress log: a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (progress log: the Print panel's printer list no longer waits on printer drivers, #5710); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (progress log: Times and Courier take their Windows counterparts' line spacing; previously trivial (progress log: the status bar's count can be words, characters or characters without spaces, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (progress log: Linux Read Aloud through Speech Dispatcher, #4576); previously trivial (progress log: a click just outside a floating table by turned cell text, #4181; previously minor: progress log: Spanish proofing, #3360, #3553; previously trivial: progress log: Insert › Table's grid previews the hovered table on the page, #3931; previously trivial (progress log: MHT quoted MIME parameters); previously trivial (progress log: CLI convert format options); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` is preserved through style resolution and ordered DOCX saves); previously trivial (per-page ink object lookups, #3614); previously trivial (progress log: ODT display settings removed); previously trivial (progress log: dialogs are modal except the five Word keeps modeless, and a press beside one shakes it, #3859); previously trivial (progress log: picture brightness, contrast and transparency, ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (progress log: fonts that aren't installed are flagged in the font box and status bar); previously trivial (progress log: ODT sections inside text boxes); previously trivial (progress log: ODT definitions sharing a name, sections around tables, stacking order); previously trivial (progress log: ODT forms and indexes written as read); previously trivial (progress log: ODT table styles saved, WordCraft-origin documents checked in LibreOffice); previously trivial (progress log: ODT interpretation profile); previously trivial (progress log: ODT controls, custom shapes, in-line placement); previously trivial (progress log: ODT charts kept, frame outlines, header height); previously trivial (progress log: ODT header rows); previously trivial (progress log: ODT layout setting, padding, columns); previously trivial (progress log: ODT tables, header spacing, picture paragraphs); previously trivial (progress log: ODT round trips keep their page count); previously trivial (progress log: emphasis marks, SET fields, ODT page backgrounds and tables); previously trivial (progress log: ODT checked against LibreOffice's templates); previously trivial (progress log: ODT at ~90%); previously trivial (progress log: ODT read and written nearly whole); previously trivial (progress log: ODT text boxes); previously trivial (progress log: ODT layout settings); previously trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: Options › Language redesign, CP4.3); previously trivial (progress log: the missing-pack bar on a fresh install, the caret's typing language, and the spelling menu heading in the interface language, CP4.3); previously trivial (progress log: Language pack languages in every language list, CP4.3); previously trivial (progress log: craft-proof pin, French elision and Valencian, CP4.3); previously trivial (progress log: a long comment's card and balloon stop at ten lines, #3382); previously trivial (progress log: a pasted text box story is charged for the formatting it copies); previously trivial (progress log: a .doc table row keeps one override per cell); previously trivial (progress log: a .doc file's sections find their paragraphs by index); previously minor (Arabic interface language with mirrored UI, #1195); previously trivial (progress log: Replace and Remove Table of Contents with Word's title above a section break, #4041); previously trivial (progress log: a password-protected file named on the command line asks for its password after the startup document is replaced, #5299); previously trivial (progress log: language-packs-2 published and pinned, 75 Language packs); previously trivial (progress log: language-packs-1 published and pinned, CP4.4); previously trivial (progress log: Language packs, CP4);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (progress log: a list inside a Markdown block quote stays quoted); previously trivial (progress log: arrowheads keep their kind, width and length and are drawn at Word's sizes); previously trivial (progress log: the line between columns for selected text, #5178); previously trivial (progress log: .doc standard font, #5066); previously trivial (progress log: a table row doesn't split off a picture that doesn't fit, #4272); previously trivial (progress log: a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (progress log: tab leader dots spaced and placed as in Word); previously trivial (progress log: a list level above counts its first number at the first deeper item); previously trivial (progress log: paragraph side borders lie outside the text, #5036); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured); previously trivial (progress log: ODT documents keep their language); previously trivial (progress log: ODT table and row backgrounds) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** trivial (progress log: border boxes close their corners; previously trivial: progress log: file formats, codecs and protocols from craft-libs, #778); previously trivial (progress log: Get the Missing Fonts); previously trivial (progress log: a deleted list item's number is drawn as deleted text under Track Changes (#4828)); previously trivial (progress log: Save As and Export offer Browse in WordCraft… on Linux/BSD, #3535); previously trivial (progress log: Review › Language can set the whole document's proofing language, #3518); previously trivial (progress log: Auto interface size capped to the screen, #4030); previously trivial (progress log: DOCX section line numbering stays off without a positive `w:countBy`, #6209); previously trivial (progress log: Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (progress log: #4501 refactor regressions restored: per-section header grid, ODT default font, link tooltip, #4683); previously trivial (progress log: the window moves by its title bar behind a modal dialog, #5124); previously trivial (progress log: `convert --strict` and `render --strict` refuse a silently incomplete PDF or PNG (#6005, #6008)); ; trivial (progress log: ODT columns stating only their shares); previously trivial (progress log: ODT font size for every script); previously trivial (progress log: ODT text turning off what its style turns on); previously trivial (progress log: edited ODT paragraphs keep custom styles with an outline level); previously trivial (progress log: ODT pictures keep the size their file gives); previously trivial (progress log: ODT frames keep the page they are anchored to); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux no longer looks semi-bold); previously trivial (Control/MCP #2596 review: partial-write outcomes, path-bearing image exports, accept-thread startup cleanup and malformed UTF-8 handling); previously trivial (progress log: a turned inline picture whose file keeps no room for the turn keeps its line to its frame); previously trivial (progress log: the Arabic interface's Styles gallery reads from the right (#5566)); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT heading text of another size); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: a shape dropped just after a page break inside a paragraph stays on the new page, #4262); previously trivial (progress log: a float anchored on a later page of a long paragraph is drawn there, #4250); previously minor (progress log: `file.closeDocument` over the control channel and MCP bridge is refused while the document it names has unsaved changes; previously trivial (progress log: ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: Shape Format › Size in the interface unit, #4196); previously trivial (progress log: typed n-ary operators such as ∫ and ∑ wait for their limits, observed in Word for Windows on #4938 (#4917)); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: justified and distributed lines keep the width of the spaces before their first character); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (progress log: a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (progress log: the Print panel's printer list no longer waits on printer drivers, #5710); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (progress log: Times and Courier take their Windows counterparts' line spacing; previously trivial (progress log: the status bar's count can be words, characters or characters without spaces, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (progress log: Linux Read Aloud through Speech Dispatcher, #4576); previously trivial (progress log: a click just outside a floating table by turned cell text, #4181; previously minor: progress log: Spanish proofing, #3360, #3553; previously trivial: progress log: Insert › Table's grid previews the hovered table on the page, #3931; previously trivial (progress log: MHT quoted MIME parameters); previously trivial (progress log: CLI convert format options); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` is preserved through style resolution and ordered DOCX saves); previously trivial (per-page ink object lookups, #3614); previously trivial (progress log: ODT display settings removed); previously trivial (progress log: dialogs are modal except the five Word keeps modeless, and a press beside one shakes it, #3859); previously trivial (progress log: picture brightness, contrast and transparency, ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (progress log: fonts that aren't installed are flagged in the font box and status bar); previously trivial (progress log: ODT sections inside text boxes); previously trivial (progress log: ODT definitions sharing a name, sections around tables, stacking order); previously trivial (progress log: ODT forms and indexes written as read); previously trivial (progress log: ODT table styles saved, WordCraft-origin documents checked in LibreOffice); previously trivial (progress log: ODT interpretation profile); previously trivial (progress log: ODT controls, custom shapes, in-line placement); previously trivial (progress log: ODT charts kept, frame outlines, header height); previously trivial (progress log: ODT header rows); previously trivial (progress log: ODT layout setting, padding, columns); previously trivial (progress log: ODT tables, header spacing, picture paragraphs); previously trivial (progress log: ODT round trips keep their page count); previously trivial (progress log: emphasis marks, SET fields, ODT page backgrounds and tables); previously trivial (progress log: ODT checked against LibreOffice's templates); previously trivial (progress log: ODT at ~90%); previously trivial (progress log: ODT read and written nearly whole); previously trivial (progress log: ODT text boxes); previously trivial (progress log: ODT layout settings); previously trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: Options › Language redesign, CP4.3); previously trivial (progress log: the missing-pack bar on a fresh install, the caret's typing language, and the spelling menu heading in the interface language, CP4.3); previously trivial (progress log: Language pack languages in every language list, CP4.3); previously trivial (progress log: craft-proof pin, French elision and Valencian, CP4.3); previously trivial (progress log: a long comment's card and balloon stop at ten lines, #3382); previously trivial (progress log: a pasted text box story is charged for the formatting it copies); previously trivial (progress log: a .doc table row keeps one override per cell); previously trivial (progress log: a .doc file's sections find their paragraphs by index); previously minor (Arabic interface language with mirrored UI, #1195); previously trivial (progress log: Replace and Remove Table of Contents with Word's title above a section break, #4041); previously trivial (progress log: a password-protected file named on the command line asks for its password after the startup document is replaced, #5299); previously trivial (progress log: language-packs-2 published and pinned, 75 Language packs); previously trivial (progress log: language-packs-1 published and pinned, CP4.4); previously trivial (progress log: Language packs, CP4);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (progress log: a list inside a Markdown block quote stays quoted); previously trivial (progress log: arrowheads keep their kind, width and length and are drawn at Word's sizes); previously trivial (progress log: the line between columns for selected text, #5178); previously trivial (progress log: .doc standard font, #5066); previously trivial (progress log: a table row doesn't split off a picture that doesn't fit, #4272); previously trivial (progress log: a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (progress log: tab leader dots spaced and placed as in Word); previously trivial (progress log: a list level above counts its first number at the first deeper item); previously trivial (progress log: paragraph side borders lie outside the text, #5036); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured); previously trivial (progress log: ODT documents keep their language); previously trivial (progress log: ODT table and row backgrounds) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > > **Recipient CSV update:** 2026-10-27 · Complete quoted header records choose the delimiter (#4249); detection and regressions follow the current mailings module split. Recipient limits and readiness estimates are unchanged. @@ -151,6 +151,9 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm ## Progress log +- 2026-11-17: File formats, codecs and protocols now come from the shared libraries (storytold/craft-libs#778): legacy code pages (craft-codepage, #6785), plain-text encoding detection (craft-mime, #6950), the ZIP entry-count guard (craft-zip, #6948), Read Aloud's Speech Dispatcher wire format (craft-ssip, #6951), picture probes for clipboard DIBs, JPEG memory, PNG and WebP (craft-image-codecs, #6949, #6955) and the MCP stdio server (craft-mcp-server, #6956), all with craft-libs pinned at main `93dac78c` (#6954, #6960). Opening documents and pictures behaves as before, except that large non-interleaved JPEGs are refused sooner (a 4:4:4 picture from about 60 Mpx, was 67 Mpx), invalid PNGs are refused more strictly, a lossless WebP's transparency is now seen, and MCP clients get tool errors for unknown or mistyped arguments and a 1,000-message batch cap (docs/mcp.md). The old code stays as test-only references the shared code is checked against. +- 2026-11-15: Get the Missing Fonts. A document opened from a file that is missing fonts their publisher gives away (Microsoft's Aptos family, the default in recent Word documents; Cascadia Code and Mono) brings up a box naming each font, the font drawn instead, the publisher's download page and how to install the download, with Don't show this again. `font.missing` reports the same page, so agents get it without the box. WordCraft links to the page only; it downloads and bundles nothing. +- 2026-10-30: Track Changes: a list item deleted whole, text and paragraph mark, shows its number as deleted text, in the deletion's colour and with its mark (struck through by default, or caret, #, bold, italic, underline), and hides it with No Markup or when Track Changes Options hide deletions (#4828). Readiness unchanged. fix/6146-touchpad-scroll-speed - 2026-11-09: Touchpad and mouse-wheel scroll speed settings (#6146): scales Wayland touchpad point input by default (4×) so two-finger scrolling matches desktop speed rather than crawling 1:1, and scales mouse wheel line distance; File › Options › Advanced › Scrolling; commands ui.scrollSpeed and ui.touchpadScrollSpeed. @@ -228,6 +231,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm - 2026-11-02: ODT files follow their standard wherever it says something, and a setting wherever it doesn't (gap 19). File › Options › Advanced › OpenDocument files (and `file.options` `odf`) chooses between two display styles, Microsoft Word style (the default) and LibreOffice style, or custom values for each of twelve cases the standard leaves open: header heights and spacing, column gaps, shape colours and hairlines, where tab stops are measured from, frame relations the standard doesn't define, and lines of only pictures. A page layout that states no margins follows the setting too: 0 in Microsoft Word style (XSL's initial value), 2 cm for LibreOffice. Every case is listed in docs/odf-interpretation.md; Google Docs and ONLYOFFICE files checked, and neither needs a preset of its own yet. - 2026-11-02: ODT form controls keep their place on the line and multi-line text fields their lines; custom shapes keep their own geometry (LibreOffice draws its own shape after a save). In-line pictures placed against the text are raised from its size, and saved standing on the baseline. The corpus round-trip difference falls to 41k pixels, 90% below this morning's 408k; 42 of 125 documents round-trip pixel-identical (gap 19). Readiness unchanged. - 2026-11-02: ODT charts keep their whole look through a save: the chart object as read is written back while the chart is unchanged (edited, it's written from WordCraft's chart). Frames outlined by a drawn stroke keep it, and a header with no stated height is LibreOffice's 0.5 cm. The corpus round-trip difference falls to 47k pixels (408k this morning); 41 of 125 documents round-trip pixel-identical (gap 19). Readiness unchanged. +- 2026-11-17: DOCX charts keep each series' fill, line, markers, smooth lines, data labels and number format, and each axis's title, bounds, number format, gridlines, labels and line, through an open and a save; a vertical axis title is drawn turned. Change Chart Type between a pie or doughnut chart and another type gives the value axis the new type's gridlines and axis line unless it was changed. Picture frame shapes open as rectangles, and a gutter set at the top (`w:gutterAtTop`) is kept on save; layout does not move the gutter to the top. Readiness unchanged. - 2026-11-02: ODT: saving no longer makes a table's first row repeat on every page (a table style's header row had been taken for Repeat as header row), so LibreOffice's 16 agenda templates round-trip with their text the same; 91 of the 125 corpus documents now do, and the round-trip difference falls to 60k pixels (408k this morning) (gap 19). Readiness unchanged. - 2026-11-02: ODT documents open with LibreOffice's layout where it differs from Word (new `Settings::odf_layout`): a line of only pictures is as tall as they are, and a paragraph's padding without a border takes room. Unequal columns and column breaks are kept. The corpus round-trip difference falls to 82k pixels, 80% below this morning's 408k; LibreOffice's report templates and one-page résumé now round-trip almost pixel-identical (gap 19). Readiness unchanged. - 2026-11-02: ODT, from LibreOffice's report templates and agenda: tables filling the margins fit them, and a table's own space above and below is kept and laid out (new `TableProps::space_before`/`space_after`); a header's spacing stays below one taller than its band (new `SectionProps::header_gap`/`footer_gap`); a picture alone in a paragraph keeps the paragraph's size and its raise. The corpus round-trip difference falls from 241k to 155k pixels, 62% below this morning's 408k (gap 19). Readiness unchanged. @@ -254,6 +258,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm - 2026-10-31: ODT: headers and footers are saved (they were dropped on every save), each page's header sits where LibreOffice puts it on open, and page numbers, page counts, dates and other text fields open as fields that update and are saved as ODF fields (gap 19). Readiness unchanged. - 2026-10-31: ODT: paragraph spacing, indents and line spacing are read and written, and an ODT's own default spacing (none, single lines) replaces Word's 8 pt after and 1.15 lines, so LibreOffice documents keep their vertical rhythm on open and save (gap 19). Readiness unchanged. - 2026-11-01: PDF export, printing and page images show the body's SEQ, STYLEREF and REF fields with their current results, as Word fills them in when it prints or exports even with Update fields before printing off: a caption numbered 7 when it is the first shows 1 on paper, and a REF to a bookmark the document lacks prints Word's "Error! Reference source not found.". NUMWORDS, FILENAME, the document properties, formulas and locked fields keep their stored results there, as in Word; the editor and the saved document keep every stored result. +- 2026-10-31: PDFs, prints and page images show each `PAGEREF` in the body with the page its bookmark is on, as Word fills them in when it prints or exports, so a table of contents saved with stale page numbers prints the pages its headings are on; on screen they keep their stored result until fields are updated, as in Word, and a locked one keeps it everywhere. A reference to a bookmark the document lacks prints Word's "Error! Bookmark not defined." Readiness unchanged. - 2026-10-28: Print Markup HTML, Markdown and text copies discover comment anchors in one paragraph walk, so unrelated bookmark markers no longer cause repeated prefix scans (#3614). Existing quotes, replies, order and export limits are unchanged; original synthetic semantic and scaling regressions cover the traversal. - 2026-11-04: Table Sort refuses malformed and nonexistent explicit columns before reordering rows (#5531). Omitted column 0, valid columns, header/order/language behavior and Undo/Redo are retained. Original Linux CLI/MCP controls and repeated native/DOCX reopens cover the command; native Word and desktop comparison remain untested. Readiness estimates unchanged. - 2026-10-30: Layout resource caps (#3867, #4385) and linear-time passes (#3866, #4392): repeated table-header rows are capped by item counts, a clipped group counting every nested member, the wrap cache by decoded pixels and the widths a linked text box chain lays out by their lines and items; PDF export, hit testing, tracked-change and clipped-table costs, and long endnote selections no longer grow quadratically. Synthetic regression tests only; no new Word comparison. @@ -300,6 +305,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm - 2026-11-01: Tab leaders are drawn as Word draws them: the dots are spaced by their advance in whole 600-dpi pixels (2.64 pt for TH SarabunPSK at 16 pt, not 2.59), from the first place on that grid after the text before the tab to the last one that ends before the text after it. - 2026-10-31: List numbers count as Word counts them when a deeper item comes first: a list that opens with 10.1–10.4 goes on with 11, not a second 10, and 1.1, 1.2 are followed by 2. A level above that hasn't counted yet takes its first number at the first deeper item. - 2026-11-01: Paragraph side borders lie outside the text, so a thick border no longer covers the first letter (#5036). +- 2026-10-31: Percentage cell widths size table columns as in Word, whichever rows give them: where rows disagree a column takes the largest, a merged cell's percentage is shared by the columns under it, a header row of percentages over rows without cell widths now sets the columns, in autofit and fixed tables, scaled to the table's width or, without one, the text width (a fixed table's grid width); past 100% the columns take their shares left to right until the width runs out, and the ones after it get their longest words, or 2 pt each with their text clipped in a fixed table. Conflicting percentages, unsized columns, spans and absolute widths keep the grid. - 2026-10-31: DOCX: a paragraph naming a style the file doesn't define is formatted as Normal, as in Word, not with the document defaults alone, so a Pandoc footer naming an undefined `Footer` style is as tall as Word's and no longer pushes the last paragraph to the next page (#5077). Readiness unchanged. - 2026-10-31: Table of contents: with Word's table over entries in columns, where the title sits in a one-column section above a continuous break, Insert Table of Contents with new settings keeps the title above the break and the entries in their columns (the new title went under the break, into the columns), and Remove Table of Contents takes the title, the blank paragraph and its break with the entries, as Word does (observed in Word for Mac); a paragraph of another style above the break stays (#4041). - 2026-10-31: A table of contents writes its page numbers as `PAGEREF` fields to the headings' bookmarks, as Word does, so updating the fields in Word moves the numbers with the headings; they were plain text (#5097). @@ -337,6 +343,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm - 2026-10-22: The desktop window works with several open documents (one window per document comes next). View › Window › Switch Windows lists them and shows the one chosen, back where it was left; New, Open and the mailings open beside unsaved work instead of asking about it; File › Close shows the next document; quitting asks about every document with unsaved changes, one at a time, and Cancel keeps the app open. - 2026-10-22: Several open documents in one session (engine part of one window per document). File › New opens a new document beside the open ones; File › Open opens beside them too, replaces a blank document nobody has used, and shows a file that is already open instead of opening it twice. Each document keeps its own text, selection, undo history, find state, view and recovery copy. View › Window › Switch Windows (`view.switchWindows`) lists the open documents and switches between them; `file.closeDocument` closes one where no window asks about unsaved changes (agents, headless sessions). Envelopes, Labels, Finish & Merge and New from Template open their result as a new document and leave the main document open as it was. Document ids are unique in the process. The desktop app still shows one document per window; the windows come next. - 2026-10-22: Legacy form names and selected drop-down labels decode numeric XML references, including saved whitespace, without decoding escaped reference text twice. +- 2026-10-26: Lines on the page: a selected floating line shows a handle at each end, as a connector does and as in Word, and dragging one moves that end (lines don't glue to shapes); pressing anywhere else on it moves it. A level line (0 high, as Word files store a rule) used to show the frame's top and bottom handles on itself, so pressing it in the middle resized it into a slant; and moving any object no longer re-applies the minimum size to a size the move doesn't change, which gave a level line a 4 pt height. A turned line's or connector's ends are where they are drawn. - 2026-10-25: Interface catalogs are still the shared storytold/craft-i18n ones embedded from `craft-i18n.rev` (`9205108c…`): 27 WordCraft languages with English fallback for missing strings, and the equation “Delete Around Caret in Equation” translation preserved. Native-speaker review remains human. - 2026-10-25: Input methods (egui 0.37): character- and byte-counted surrounding deletions, a fresh composition after body/equation replacement, rejection of queued stale replacements before mutation, transactional equation deletes and one undo group, with tracked and placeholder length mapping. Synthetic regressions document these paths; managed CI passed, and native IME acceptance (#155–#164) plus browser IME behavior remain open. - 2026-10-25: Justified and distributed lines keep the width of the spaces before their first character, as Word does: Thai official letters indent paragraphs with a run of spaces, and their first line no longer moves right by the line's slack (86 pt in a measured case). A distributed line's text reaches the margin even when the line ends with the space it wrapped at. @@ -397,6 +404,8 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target - 2026-10-15: Find opens Navigation on Results; editing the query restores Results after manual Headings/Pages navigation. Typed and selected-text searches retain document contents (#2096). | Date | What landed | +| 2026-11-17 | trivial | Progress log: file formats, codecs and protocols come from craft-libs (#778) | +| 2026-11-15 | trivial | Progress log: Get the Missing Fonts (download pages for missing fonts their publisher gives away) | | 2026-11-05 | trivial | Progress log: ODT documents keep their language (gap 19) | | 2026-11-04 | The CLI opens a non-Unicode input filename even after options such as `--page 2` or `--format flatopc`; text option values still require Unicode; `run --file` and `run --script` retain native paths. | | 2026-11-06 | Accept All and Reject All no longer restyle the paragraph after an empty one carrying a section break (#5667): a Compare that added a section, then Reject All, left `Body` in the removed paragraph's Normal style and indents. The empty paragraph now goes whole and its section joins the following one, as deleting the break does. | @@ -418,6 +427,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target | 2026-11-01 | Rulers: in a section of several text columns the horizontal ruler shades the space between each two columns like the margins (Print Layout, in the main text outside tables, with the selection in one section); dragging an edge of a space changes the spacing (equal columns stay equal, as in Word for Mac), one undo step per drag (#5197) | | 2026-10-29 | Window sizing falls back to the screen rectangle when the reported inner size is invalid, and an Equation symbol tooltip no longer repeats a missing glyph's name or code point | | 2026-10-29 | A NUL in a document title no longer reaches the native window title, which panicked on X11 (#3634): displayed titles and suggested file names drop NUL characters and fall back to the untitled name when empty; the stored title is unchanged | +| 2026-10-30 | Paragraph dialog: Word's Special box (none, First line, Hanging) and By replace the signed First line box, so a hanging indent is set as Hanging by a positive length instead of a negative first-line indent. Picking a kind from (none) starts at 0.5", as Word does, and switching between First line and Hanging keeps By. A By typed in counts once committed, so the 0 of 0.25 doesn't turn Special to (none) mid-typing. | | 2026-10-28 | The Traditional Chinese interface draws hanzi to the Taiwan standard: on the desktop an installed Traditional Chinese font (PingFang TC on macOS, Microsoft JhengHei on Windows, Noto Sans CJK TC on Linux) comes before the embedded Noto Sans CJK SC, which drew 說, 這, 為, 戶 in mainland shapes; without one, and on the web, nothing changes. | | 2026-10-17 | macOS launch arguments (`-psn_*`, `-NS*`, `-Apple*`) are no longer opened as files, and a file that fails to open names the file and the real cause on the status bar and in the log (#1103). The reported "corrupt" error could not be reproduced. | | 2026-10-19 | Linux: File › Options › Advanced › Linux display server picks Automatic (the default: XWayland where there's an X server, for file drag-and-drop), Wayland or X11 (XWayland), so people who don't start WordCraft from a terminal can switch without an environment variable (#2184). It's kept in `ui.json` and applies at the next launch; `WORDCRAFT_WAYLAND` still overrides it, and `WORDCRAFT_WAYLAND=0` now asks for X11. A choice that isn't available falls back to the other instead of failing to start, and the log's `display:` line says which ran and why. Hidden on Windows, macOS and the web; `ui.displayServer` for agents. | @@ -680,6 +690,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target | 2026-10-14 | Hebrew and Arabic in exported PDFs copy and search as whole words (#1383): right-to-left glyphs are written left to right as they appear, the order Chrome and Edge (PDFium) and poppler read text back from (checked by hand), instead of in reading order, which they reversed (`שלום` came back as `םולש`, Arabic in pieces). Lam-alef stays whole and vowel marks follow their letters, though Chrome and poppler can still break a fully vowelled word with spaces. The page looks the same. Readers that take glyphs strictly in file order get only plain Hebrew runs right, through `/ReversedChars`; screen readers are unverified | | 2026-10-14 | HTML import (#1381): header cells (``) are bold unless their own CSS says otherwise, and `text-align` on a cell, its row, row group or table aligns the cell's paragraphs (a paragraph's own alignment wins), so `wordcraft-cli convert page.html out.docx` writes the bold header and `w:jc` right-aligned cells. HTML, Markdown and plain text, which give no page size, open on the region's paper (A4 in Italy, Letter in the US) like a new blank document, in the app and in `wordcraft-cli`; documents with their own page size keep it | | 2026-10-14 | Custom page sizes (#1433): Layout › Size ends with More Paper Sizes…, which opens Page Setup's new Paper group — a Paper size list (the named sizes, or Custom size) and Width and Height in the measurement unit; OK sets the size only when it changed, and a wider-than-tall size comes out landscape. `layout.size` now clamps each side to Word's 0.1"–22" and refuses a page the margins don't fit (the margins rule: 36 pt of text room), and Page Setup checks the size and margins together before applying either | +| 2026-10-19 | Border boxes close their corners, as in Word: paragraph, page and character border boxes had a notch at each corner now that lines end flat; top and bottom lines now run on over the side lines, and lines without a neighbour end half their width past the edge | | 2026-10-14 | Bold text in Arial Black and other Black or Heavy fonts looks as in Word: older copies of these fonts (Arial Black in the core fonts) call themselves regular weight, so bold was drawn with an extra synthetic bold; a family named Black/Heavy now counts as that heavy | | 2026-10-14 | German text hyphenates by German rules: runs in German (`de`, `de-DE`, `de-AT`, `de-CH`) use hyph-utf8's German patterns for the reformed spelling (MIT), so automatic hyphenation gives `un-ter-lie-gen-de` and `öf-fent-lich-recht-li-cher` instead of English-pattern breaks like `unterlieg-ende` and `rechtli-cher`; Swiss `ss` splits like any double consonant (`Stras-se`). German still has no spelling or grammar marks (#1564) | | 2026-10-13 | Highlighted text reads on a dark page (View › Switch Modes, #1252): highlights and character shading are dimmed, keeping their hue (yellow turns a dim olive, as in Word), and the text on them is drawn light (coloured text below 4.5:1 is drawn white, and underlines and strikethroughs follow the same rule), instead of white text on bright yellow; light page, print and exports unchanged | @@ -728,6 +739,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target | 2026-10-12 | Table style editor (#714): New/Modify Table Style edits each of the 13 table style parts (header row, total row, first/last column, odd/even bands, corner cells) with font, colour, fill, borders and cell alignment; every table using the style follows; all parts round-trip in DOCX; `table.modifyStyle` takes `part`/`parts` and per-edge borders | | 2026-10-12 | STYLEREF fields (#775): running headers and footers show each page's chapter title (page's first, or `\l` last, paragraph of the style, else the nearest before), style names, ids, heading levels and character styles, number switches; body STYLEREF updates with the other fields; STYLEREF in the Field dialog; PDF export follows the layout | | 2026-10-24 | Document information fields: SUBJECT, KEYWORDS, COMMENTS, LASTSAVEDBY, REVNUM and NUMCHARS update with the other fields and are listed in the Field dialog; a quoted text after TITLE, SUBJECT, AUTHOR, KEYWORDS or COMMENTS replaces that document property (at most 255 characters), and NUMWORDS, NUMCHARS and REVNUM take a `\*` number format | +| 2026-10-31 | Field dialog capitalization: AUTHOR, COMMENTS, FILENAME, KEYWORDS, LASTSAVEDBY, SUBJECT, TITLE, REF, STYLEREF and MERGEFIELD have a Format list with Uppercase, Lowercase, First capital and Title case, which writes `\* Upper`, `\* Lower`, `\* FirstCap` or `\* Caps` before `\* MERGEFORMAT`; Hide Codes sets the list from the typed code's last such switch and keeps every capitalization switch the code had, in order, until another Format is chosen; Preview Results and Finish & Merge apply a MERGEFIELD's capitalization switch to the record's value, and IF, NEXTIF and SKIPIF rules apply the tested MERGEFIELD's capitalization switch before comparing | | 2026-10-24 | Field capitalization switches: `\* Upper`, `\* Lower`, `\* Caps` and `\* FirstCap` apply to the document information, DOCPROPERTY, FILENAME, date, REF, PAGEREF, SEQ, STYLEREF and table formula results that Update Field computes and to the page-number fields, and `\* CardText` and `\* OrdText` results are lowercase unless one of them follows (`\* CardText \* Caps` shows "Seven Hundred Ninety"); a table formula takes a `\*` number format (`=SUM(A1:B2) \* CardText`), and other `\*` switches such as `\* MERGEFORMAT` no longer make it a syntax error | | 2026-10-24 | Field `\* DollarText` and `\* Hex` switches: `{ = 9.20 + 5.35 \* DollarText \* Upper }` shows "FOURTEEN AND 55/100" and `\* Hex` writes uppercase hexadecimal digits (458 shows "1CA"), in table formulas and in the page-number, SEQ, PAGEREF and count fields; `{ PAGE \* ArabicDash }` shows "- 31 -"; cardinal, ordinal and dollar text past 999,999 keep their digits | | 2026-10-12 | Undo history list (#701): a ▾ beside the Quick Access Toolbar's Undo lists recent steps newest first; hovering highlights what a click undoes ("Undo 3 Actions"), and a click undoes them in one go. `edit.undoTo {count}` and `edit.undoHistory` (newest first, up to 100) for CLI and MCP | @@ -922,6 +934,8 @@ MATH glyphs that reference the same construction now share its immutable variant | Date | Change | Summary | |---|---|---| +| 2026-11-18 | trivial | Progress log: border boxes close their corners | +| 2026-10-30 | trivial | Progress log: under Track Changes a list item deleted whole shows its number as deleted text, in the deletion's colour and mark (#4828); readiness unchanged | | 2026-11-10 | trivial | Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf (#6180) | | 2026-11-04 | trivial | Progress log: #4501 refactor regressions restored (#4683) | | 2026-11-06 | trivial | Progress log: edited ODT paragraphs keep custom styles with an outline level (gap 19) | @@ -985,6 +999,7 @@ MATH glyphs that reference the same construction now share its immutable variant | 2026-11-07 | trivial | Progress log: `.doc` brace and bracket shapes unfilled by default (#5943) | | 2026-11-04 | trivial | PR #4609: relative REF keeps context already displayed by the own or a needed ancestor label; six synthetic legal-template cases and separate-list context follow the Word for Windows measurements reported by @pakiat in PR discussion. Existing unknown-switch/cache boundaries and readiness estimates unchanged; no new native Word run. | | 2026-11-01 | trivial | Progress log: SEQ, STYLEREF and REF fields show fresh results in output | +| 2026-10-31 | trivial | Progress log: PDFs and prints show a table of contents' current page numbers | | 2026-10-29 | trivial | Progress log: Print Markup balloon anchors use one object walk per paragraph (#3614); readiness estimates unchanged | | 2026-10-28 | trivial | Print Markup text-copy comment discovery walks paragraph objects once (#3614); quotes, order, limits and readiness estimates unchanged | | 2026-11-03 | trivial | Progress log: Language pack languages in every language list (CP4.3) | @@ -1018,6 +1033,7 @@ MATH glyphs that reference the same construction now share its immutable variant | 2026-11-01 | trivial | Progress log: proofing moved to craft-proof (craft-libs) and its data to craft-i18n `language-data/` (CP1) | | 2026-11-01 | trivial | #3915: preserve guarded whole-line ordinary-tab alignment with current main. Existing controls retained; source checks only, primary qualification pending. | | 2026-11-01 | trivial | #2437: Preserve finite paragraph-border flow extents and terminal-break keep preflight with current-main changes. Recursive terminal-successor lookahead remains outside scope. Source checks only; primary qualification pending. | +| 2026-10-31 | trivial | Progress log: percentage cell widths size table columns whichever rows give them | | 2026-10-31 | trivial | Progress log: a paragraph naming an undefined DOCX style is formatted as Normal (#5077) | | 2026-10-31 | minor | #3398: persistent screen-only green, cream and gray paper presets, with document backgrounds and export colors retained. Read Mode None follows the screen preset; Sepia/Inverse retain priority. | | 2026-10-31 | trivial | Progress log: TOC page numbers are PAGEREF fields (#5097) | @@ -1043,6 +1059,7 @@ MATH glyphs that reference the same construction now share its immutable variant | 2026-10-29 | trivial | HTML import keeps preformatted lines with CR, CRLF or LF input newlines (#4810); numeric character references retain their separate meaning; readiness estimates unchanged. | | 2026-10-29 | trivial | Progress log: window fallback geometry and equation symbol tooltips | | 2026-10-29 | trivial | Progress log: window titles omit NUL characters (#3634) | +| 2026-10-30 | trivial | Progress log: the Paragraph dialog's Special box sets First line and Hanging indents | | 2026-10-29 | trivial | Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880). Filtered/sorted order, product geometry and single-label mode retained; readiness estimates unchanged. | | 2026-10-19 | trivial | Progress log: Linux display server setting (#2184) | | 2026-10-19 | trivial | Progress log: the status bar's count can be words, characters or characters without spaces (#2797) | @@ -1058,6 +1075,7 @@ MATH glyphs that reference the same construction now share its immutable variant | 2026-10-22 | trivial | Progress log: several open documents in the desktop window | | 2026-10-22 | trivial | Progress log: several open documents in one session | | 2026-10-22 | trivial | Decode numeric XML references once in legacy form names and drop-down labels | +| 2026-10-26 | trivial | Progress log: floating lines move by their body and resize by their ends, and a level line stays level | | 2026-10-25 | trivial | Progress log: egui 0.37 migration records the `craft-i18n.rev` catalog pin (9205108…; 27 languages) and the input-method handling; managed CI passed; native acceptance and native-speaker review remain open | | 2026-10-25 | trivial | Progress log: justified and distributed lines keep the width of the spaces before their first character | | 2026-10-17 | trivial | Progress log: Standard-encrypted (AES) Word files open (gap 9) | @@ -1444,6 +1462,7 @@ MATH glyphs that reference the same construction now share its immutable variant | 2026-10-27 | trivial | Progress log: AutoCorrect Options with no document open (#4585) | | 2026-10-28 | trivial | Progress log: RTF metafile pictures are imported (#4259) | | 2026-10-28 | trivial | Progress log: Chinese and Japanese text counts a word per character (#4547) | +| 2026-10-31 | trivial | Progress log: Field dialog capitalization Format list for text fields | | 2026-10-27 | trivial | 2026-10-27 · #4533 review: numeric REF updates lazily index body bookmarks once per update, retaining the first body bookmark for duplicate names. Unsupported switches and ordinary REF/PAGEREF behavior are unchanged; a synthetic 64-reference regression covers repeated updates and duplicate names. Estimates unchanged. | | 2026-10-27 | trivial | 2026-10-27 · #4533: numeric REF fields use paragraph list numbers for no/full/relative context, reusing bounded numbering. Shared context already embedded in a level label is removed; merged-away cells do not count. Unsupported separator/text/position switches and ambiguous contexts or delimiter-free joins retain cached results. Synthetic OOXML regressions; no native Word or real-document validation, estimates unchanged. | > 2026-10-29 · Port #3915 to split layout modules: ordinary LTR tab groups follow paragraph alignment. Positional tabs, lists, RTL and display math retain their alignment paths. Source port only; no test execution or new native measurements. diff --git a/apps/wordcraft-cli/src/main.rs b/apps/wordcraft-cli/src/main.rs index a7c38c628c..63d4abf3c2 100644 --- a/apps/wordcraft-cli/src/main.rs +++ b/apps/wordcraft-cli/src/main.rs @@ -35,10 +35,11 @@ USAGE: --strict writes nothing and exits 3 if a character on the 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}' [--cmd …] - [--save OUT] [--print] [--author NAME] + wordcraft-cli run [--file F | --template T] [--script FILE|-] [--cmd 'id={json}' …] + [--save OUT] [--page N] [--scale S] [--print] [--author NAME] run commands headlessly, then save (--author names who tracked changes and comments are by). + 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, \"params\"?: {…}} | id, …], \"save\"?: [OUT, …]}; save @@ -265,7 +266,7 @@ fn parse_scale_arg(command: &str, args: &[String]) -> Result, String OptionArg::Value(val) => { let scale = val.parse::().map_err(|_| format!("{command}: invalid --scale `{val}`: not a number"))?; if !scale.is_finite() || scale <= 0.0 { - return Err(format!("{command}: invalid --scale `{val}`: scale must be a positive number")); + return Err(format!("{command}: invalid --scale `{val}`: scale must be a finite positive number")); } Ok(Some(scale)) } @@ -602,6 +603,11 @@ fn run>(args: &[S]) -> Result<(), Failure> { write_stdout(|o| writeln!(o, "{r}")) } "run" => { + for (i, arg) in rest.iter().enumerate() { + if arg == "--cmd" && rest.get(i + 1).is_none_or(|value| value.starts_with("--")) { + return Err("--cmd needs a value".into()); + } + } validate_options("run", &rest, RUN_OPTIONS)?; let page = parse_page_arg("run", &rest)?; let scale = parse_scale_arg("run", &rest)?; @@ -635,7 +641,7 @@ fn run>(args: &[S]) -> Result<(), Failure> { let mut i = 0; while i < rest.len() { if rest.get(i).map(String::as_str) == Some("--cmd") { - let spec = rest.get(i + 1).ok_or("--cmd needs a value")?; + let spec = rest.get(i + 1).filter(|value| !value.starts_with("--")).ok_or("--cmd needs a value")?; let (id, params) = match spec.split_once('=') { Some((id, p)) => { (id.to_string(), serde_json::from_str::(p).map_err(|e| engine_error(format!("{id}: bad JSON params: {e}")))?) diff --git a/apps/wordcraft-cli/src/tests.rs b/apps/wordcraft-cli/src/tests.rs index c44143fb41..e22d4791fb 100644 --- a/apps/wordcraft-cli/src/tests.rs +++ b/apps/wordcraft-cli/src/tests.rs @@ -267,19 +267,19 @@ fn render_rejects_missing_or_invalid_page_and_scale() { assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "-1"])), Err("render: invalid --page `-1`: not a valid integer".into())); assert_eq!( run(&args(&["render", "missing.docx", "out.png", "--scale", "0"])), - Err("render: invalid --scale `0`: scale must be a positive number".into()) + Err("render: invalid --scale `0`: scale must be a finite positive number".into()) ); assert_eq!( run(&args(&["render", "missing.docx", "out.png", "--scale", "-2"])), - Err("render: invalid --scale `-2`: scale must be a positive number".into()) + Err("render: invalid --scale `-2`: scale must be a finite positive number".into()) ); assert_eq!( run(&args(&["render", "missing.docx", "out.png", "--scale", "NaN"])), - Err("render: invalid --scale `NaN`: scale must be a positive number".into()) + Err("render: invalid --scale `NaN`: scale must be a finite positive number".into()) ); assert_eq!( run(&args(&["render", "missing.docx", "out.png", "--scale", "inf"])), - Err("render: invalid --scale `inf`: scale must be a positive number".into()) + Err("render: invalid --scale `inf`: scale must be a finite positive number".into()) ); // Duplicate options @@ -322,19 +322,19 @@ fn run_rejects_missing_or_invalid_page_and_scale() { ); assert_eq!( run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "0"])), - Err("run: invalid --scale `0`: scale must be a positive number".into()) + Err("run: invalid --scale `0`: scale must be a finite positive number".into()) ); assert_eq!( run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "-1"])), - Err("run: invalid --scale `-1`: scale must be a positive number".into()) + Err("run: invalid --scale `-1`: scale must be a finite positive number".into()) ); assert_eq!( run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "NaN"])), - Err("run: invalid --scale `NaN`: scale must be a positive number".into()) + Err("run: invalid --scale `NaN`: scale must be a finite positive number".into()) ); assert_eq!( run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "inf"])), - Err("run: invalid --scale `inf`: scale must be a positive number".into()) + Err("run: invalid --scale `inf`: scale must be a finite positive number".into()) ); // Duplicate options @@ -497,6 +497,27 @@ fn command_line_template_wins_over_the_scripts_file() { assert!(std::fs::read_to_string(&b).unwrap().contains("FROM FILE")); } +#[test] +fn cmd_value_missing_is_reported() { + let missing = std::env::temp_dir().join(format!( + "wc-cli-missing-cmd-{}-{}.docx", + std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos() + )); + assert!(!missing.exists()); + let missing = missing.to_string_lossy(); + for argv in [ + vec!["run", "--cmd"], + vec!["run", "--cmd", "--save", "out.docx"], + vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"], + vec!["run", "--cmd", "--bogus"], + vec!["run", "--cmd", "--file", &missing], + ] { + assert_eq!(run(&args(&argv)), Err("--cmd needs a value".into()), "{argv:?}"); + } + assert!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])).is_ok()); +} + #[test] fn script_value_missing_is_reported() { let e = run(&args(&["run", "--script", "--cmd", "caret.docEnd"])).unwrap_err().to_string(); diff --git a/apps/wordcraft-web/Cargo.toml b/apps/wordcraft-web/Cargo.toml index 8c42c988b1..721ee5cd36 100644 --- a/apps/wordcraft-web/Cargo.toml +++ b/apps/wordcraft-web/Cargo.toml @@ -18,8 +18,8 @@ wordcraft-engine = { workspace = true } wordcraft-ui-egui = { workspace = true } # The host messages (storytold/craft-libs): one contract and one bridge for the web builds. # The page command API (storytold/craft-libs#413): window.wordcraft over the control channel. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" } -craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "0.1.0" } +craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "0.1.0" } egui = { workspace = true } log = { workspace = true } serde_json = { workspace = true } diff --git a/apps/wordcraft-web/src/web.rs b/apps/wordcraft-web/src/web.rs index fb808decf8..b6f765d05b 100644 --- a/apps/wordcraft-web/src/web.rs +++ b/apps/wordcraft-web/src/web.rs @@ -81,6 +81,7 @@ pub fn start() { // Pasted pictures wait apart from dropped files: the app inserts one only when the page is the edit target (#1349). app.services.pasted = Some(pasted); app.autosave = false; + app.tell_about_font_downloads(); // Preferences from an earlier visit (#2132), as the desktop app reads `ui.json`. let stored = stored_prefs(); crate::prefs::restore(&mut app, stored.as_deref()); diff --git a/apps/wordcraft/Cargo.toml b/apps/wordcraft/Cargo.toml index c7768b0dae..ccf00cfcc8 100644 --- a/apps/wordcraft/Cargo.toml +++ b/apps/wordcraft/Cargo.toml @@ -84,9 +84,9 @@ windows = { version = "0.62", features = ["UI_ViewManagement", "System_UserProfi clipboard-win = { version = "5.4", features = ["std"] } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -# Pinned apart from craft-ui, which doesn't depend on it: `printer_queues`, the printer list that +# At the same craft-libs commit as the workspace's crates: `printer_queues`, the printer list that # asks no driver (#5710, storytold/craft-libs#618), and `submit_cancellable` (storytold/craft-libs#622). -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a3e0b5a9440d18f19422a9dca13516747b7d3181" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a" } rfd = { workspace = true } # Waits for an `rfd::AsyncFileDialog` on a background thread (the dialogs don't block the UI, #94); # rfd itself already depends on it. diff --git a/apps/wordcraft/src/linux_gpu.rs b/apps/wordcraft/src/linux_gpu.rs new file mode 100644 index 0000000000..198708f366 --- /dev/null +++ b/apps/wordcraft/src/linux_gpu.rs @@ -0,0 +1,298 @@ +//! Linux: draw on the GPU that drives the screen. +//! +//! egui-wgpu picks the discrete GPU by default (`PowerPreference::HighPerformance`). On a laptop +//! whose integrated GPU drives the panel, every frame drawn on the discrete one is copied across +//! to it, and the discrete GPU leaves its idle state whenever the window redraws: on an Intel HD +//! 530 + NVIDIA Quadro M4000M laptop, from 7 W at P8 to over 20 W at P0/P1. Forcing the integrated +//! GPU instead breaks desktops whose screen is on the discrete card (storytold/pdfcraft#96), and a +//! desktop with a monitor on each card needs the discrete one (storytold/pdfcraft#445). So the +//! choice follows the connected displays, as in craft-anything (storytold/craft-anything#571): +//! +//! 1. `WGPU_ADAPTER_NAME` (part of the adapter's name) or `WGPU_POWER_PREF` (`high`, `low`, +//! `none`), when set, decide; +//! 2. a connected built-in panel: the GPU behind it; +//! 3. displays on only one GPU: that GPU; +//! 4. otherwise (displays on several GPUs, or nothing readable): the discrete GPU, as before. + +mod drm; + +use drm::DisplayCard; +use eframe::wgpu::{DeviceType, PowerPreference}; + +/// What we know of one adapter wgpu offers. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Candidate { + pub name: String, + pub vendor: u32, + pub device: u32, + /// `0000:05:00.0`, lowercase; empty when the driver doesn't say (always, under GL). + pub pci_slot: String, + pub device_type: DeviceType, + pub gl: bool, +} + +/// What the person asked for through wgpu's environment variables. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct Asked { + pub adapter_name: Option, + pub power: Option, +} + +/// Why an adapter was chosen, for the log. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Why { + AskedByName, + AskedPower, + BuiltInPanel, + OnlyGpuWithDisplays, + Fallback, +} + +/// The index of the adapter to draw with, and why; `None` when there is none. +pub(crate) fn choose(candidates: &[Candidate], cards: &[DisplayCard], asked: &Asked) -> Option<(usize, Why)> { + if let Some(want) = asked.adapter_name.as_deref().map(str::to_lowercase).filter(|w| !w.is_empty()) { + // As wgpu's own `WGPU_ADAPTER_NAME`: part of the name, any case. No match: the usual choice. + if let Some(i) = candidates.iter().position(|c| c.name.to_lowercase().contains(&want)) { + return Some((i, Why::AskedByName)); + } + log::warn!("WGPU_ADAPTER_NAME={want}: no graphics adapter has that in its name"); + } + if let Some(power) = asked.power { + return by_kind(candidates, power).map(|i| (i, Why::AskedPower)); + } + let panels: Vec<&DisplayCard> = cards.iter().filter(|c| c.built_in_panel).collect(); + let with_displays: Vec<&DisplayCard> = cards.iter().filter(|c| c.displays > 0).collect(); + let target = if !panels.is_empty() { + Some((panels, Why::BuiltInPanel)) + } else if with_displays.len() == 1 { + Some((with_displays, Why::OnlyGpuWithDisplays)) + } else { + None + }; + if let Some((wanted, why)) = target { + // Vulkan before GL for the same card; otherwise wgpu's order. + let found = candidates.iter().enumerate().filter(|(_, c)| wanted.iter().any(|card| drives(card, c, cards))).min_by_key(|(_, c)| c.gl); + if let Some((i, _)) = found { + return Some((i, why)); + } + } + by_kind(candidates, PowerPreference::HighPerformance).map(|i| (i, Why::Fallback)) +} + +/// Whether `card` is the GPU behind `adapter`: by PCI address when the driver gives one, else by +/// PCI ids, which count only when no other card has the same ids (two cards of one model); GL +/// gives only a vendor, which counts only when no other card has that vendor. +fn drives(card: &DisplayCard, adapter: &Candidate, all: &[DisplayCard]) -> bool { + if !adapter.pci_slot.is_empty() && !card.pci_slot.is_empty() { + return adapter.pci_slot == card.pci_slot; + } + if adapter.device != 0 { + return adapter.vendor == card.vendor + && adapter.device == card.device + && all.iter().filter(|c| c.vendor == card.vendor && c.device == card.device).count() == 1; + } + adapter.vendor != 0 && adapter.vendor == card.vendor && all.iter().filter(|c| c.vendor == card.vendor).count() == 1 +} + +/// The first adapter in wgpu's own order for that power preference. +fn by_kind(candidates: &[Candidate], power: PowerPreference) -> Option { + let rank = |t: DeviceType| match (power, t) { + (PowerPreference::None, _) => 0, + (PowerPreference::LowPower, DeviceType::IntegratedGpu) | (PowerPreference::HighPerformance, DeviceType::DiscreteGpu) => 1, + (_, DeviceType::IntegratedGpu | DeviceType::DiscreteGpu) => 2, + (_, DeviceType::Other) => 3, + (_, DeviceType::VirtualGpu) => 4, + (_, DeviceType::Cpu) => 5, + }; + candidates.iter().enumerate().min_by_key(|(_, c)| rank(c.device_type)).map(|(i, _)| i) +} + +#[cfg(target_os = "linux")] +impl Candidate { + fn of(info: &eframe::wgpu::AdapterInfo) -> Self { + Candidate { + name: info.name.clone(), + vendor: info.vendor, + device: info.device, + pci_slot: info.device_pci_bus_id.to_ascii_lowercase(), + device_type: info.device_type, + gl: info.backend == eframe::wgpu::Backend::Gl, + } + } +} + +#[cfg(target_os = "linux")] +impl Asked { + fn from_env() -> Self { + Asked { adapter_name: std::env::var("WGPU_ADAPTER_NAME").ok(), power: PowerPreference::from_env() } + } +} + +/// The adapter that draws the window, among those that can draw to it. +#[cfg(target_os = "linux")] +pub(crate) fn pick_adapter(adapters: &[eframe::wgpu::Adapter], surface: Option<&eframe::wgpu::Surface<'_>>) -> Result { + let usable: Vec<&eframe::wgpu::Adapter> = adapters.iter().filter(|a| surface.is_none_or(|s| a.is_surface_supported(s))).collect(); + let candidates: Vec = usable.iter().map(|a| Candidate::of(&a.get_info())).collect(); + let cards = drm::display_cards(); + let picked = choose(&candidates, &cards, &Asked::from_env()).and_then(|(i, why)| Some((*usable.get(i)?, why))); + match picked { + Some((a, why)) => { + log::info!("drawing with {:?} ({why:?}); displays: {cards:?}", a.get_info()); + Ok(a.clone()) + } + None => Err(format!("None of the {} graphics adapters found can draw this window.", adapters.len())), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const AMD: (u32, u32, &str) = (0x1002, 0x1638, "0000:05:00.0"); + const NVIDIA: (u32, u32, &str) = (0x10de, 0x25a2, "0000:01:00.0"); + const INTEL: (u32, u32, &str) = (0x8086, 0xa780, "0000:00:02.0"); + + fn vulkan(name: &str, (vendor, device, slot): (u32, u32, &str), device_type: DeviceType) -> Candidate { + Candidate { name: name.into(), vendor, device, pci_slot: slot.into(), device_type, gl: false } + } + + fn gl(name: &str, vendor: u32, device_type: DeviceType) -> Candidate { + Candidate { name: name.into(), vendor, device: 0, pci_slot: String::new(), device_type, gl: true } + } + + fn card((vendor, device, slot): (u32, u32, &str), displays: u32, built_in_panel: bool) -> DisplayCard { + DisplayCard { vendor, device, pci_slot: slot.into(), displays, built_in_panel } + } + + /// What wgpu offers on a laptop whose AMD iGPU drives the panel, in its order (Vulkan, then GL). + fn laptop_adapters() -> Vec { + vec![ + vulkan("AMD Radeon Graphics (RADV RENOIR)", AMD, DeviceType::IntegratedGpu), + vulkan("NVIDIA GeForce RTX 3050 Laptop GPU", NVIDIA, DeviceType::DiscreteGpu), + gl("AMD Radeon Graphics (radeonsi, renoir)", 0x1002, DeviceType::IntegratedGpu), + ] + } + + /// The iGPU drives the panel; egui-wgpu's default drew on the discrete GPU. + #[test] + fn a_laptop_draws_on_the_gpu_behind_its_panel() { + let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)]; + assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((0, Why::BuiltInPanel))); + // The same with the discrete GPU listed first. + let mut swapped = laptop_adapters(); + swapped.swap(0, 1); + assert_eq!(choose(&swapped, &cards, &Asked::default()), Some((1, Why::BuiltInPanel))); + } + + /// The panel's GPU stays the choice with an external monitor on the discrete card as well. + #[test] + fn the_panel_wins_over_a_monitor_on_the_other_card() { + let cards = [card(NVIDIA, 1, false), card(AMD, 1, true)]; + assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((0, Why::BuiltInPanel))); + } + + /// A desktop with its monitor on the discrete card and the iGPU left on (a low-power default + /// draws on the iGPU there, and the window can't start: the case the panel rule must not break). + #[test] + fn a_desktop_draws_on_the_only_card_with_a_monitor() { + let adapters = + [vulkan("Intel(R) Graphics (RPL-S)", INTEL, DeviceType::IntegratedGpu), vulkan("NVIDIA GeForce RTX", NVIDIA, DeviceType::DiscreteGpu)]; + let cards = [card(INTEL, 0, false), card(NVIDIA, 1, false)]; + assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays))); + // And on the iGPU when that's where the only monitor is. + let cards = [card(INTEL, 2, false), card(NVIDIA, 0, false)]; + assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((0, Why::OnlyGpuWithDisplays))); + } + + /// A desktop with a monitor on each card: the discrete GPU, as before (an iGPU choice there + /// lost its surface as soon as it was set up). + #[test] + fn monitors_on_two_cards_keep_the_discrete_gpu() { + let adapters = + [vulkan("Intel(R) Graphics (RPL-S)", INTEL, DeviceType::IntegratedGpu), vulkan("NVIDIA GeForce RTX", NVIDIA, DeviceType::DiscreteGpu)]; + let cards = [card(INTEL, 1, false), card(NVIDIA, 1, false)]; + assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::Fallback))); + } + + /// Nothing readable (no `/sys`, or a card the drivers don't name): the discrete GPU, as before. + #[test] + fn without_display_facts_the_old_choice_stands() { + assert_eq!(choose(&laptop_adapters(), &[], &Asked::default()), Some((1, Why::Fallback))); + let unknown = [card((0x1234, 0x1, "0000:09:00.0"), 1, true)]; + assert_eq!(choose(&laptop_adapters(), &unknown, &Asked::default()), Some((1, Why::Fallback))); + assert_eq!(choose(&[], &[card(AMD, 1, true)], &Asked::default()), None); + } + + /// The environment variables still decide: prime-run style requests reach the NVIDIA card. + #[test] + fn wgpu_environment_variables_decide_when_set() { + let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)]; + let asked = |name: Option<&str>, power: Option| Asked { adapter_name: name.map(Into::into), power }; + assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::HighPerformance))), Some((1, Why::AskedPower))); + assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::LowPower))), Some((0, Why::AskedPower))); + assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::None))), Some((0, Why::AskedPower))); + assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("nvidia"), None)), Some((1, Why::AskedByName))); + assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("RadeonSI"), Some(PowerPreference::HighPerformance))), Some((2, Why::AskedByName))); + // A name nothing has: the usual choice, not a failure. + assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("matrox"), None)), Some((0, Why::BuiltInPanel))); + assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some(""), None)), Some((0, Why::BuiltInPanel))); + } + + /// Under `WGPU_BACKEND=gl` there's no PCI address or device id: the vendor alone finds the + /// card, but only when no other card shares it. + #[test] + fn gl_adapters_are_matched_by_vendor_only_when_unambiguous() { + let adapters = + [gl("NVIDIA GeForce RTX 3050", 0x10de, DeviceType::Other), gl("AMD Radeon Graphics (radeonsi)", 0x1002, DeviceType::IntegratedGpu)]; + let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)]; + assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::BuiltInPanel))); + // Two AMD cards: the vendor can't tell them apart, so the old choice stands. + let two_amd = [card((0x1002, 0x73df, "0000:03:00.0"), 0, false), card(AMD, 1, true)]; + let adapters = [gl("AMD Radeon RX 6700", 0x1002, DeviceType::Other), gl("AMD Radeon Graphics", 0x1002, DeviceType::IntegratedGpu)]; + assert_eq!(choose(&adapters, &two_amd, &Asked::default()), Some((1, Why::Fallback))); + } + + /// Two adapters for the panel's card (Vulkan and GL): Vulkan, whatever the order. + #[test] + fn vulkan_comes_before_gl_for_the_same_card() { + let adapters = [ + gl("AMD Radeon Graphics (radeonsi)", 0x1002, DeviceType::IntegratedGpu), + vulkan("AMD Radeon Graphics (RADV RENOIR)", AMD, DeviceType::IntegratedGpu), + ]; + assert_eq!(choose(&adapters, &[card(AMD, 1, true)], &Asked::default()), Some((1, Why::BuiltInPanel))); + } + + /// A laptop with the lid closed and a monitor on the NVIDIA card: the switched-off panel isn't + /// read as one (`drm` skips it), so the card with the monitor draws. + #[test] + fn a_closed_laptop_draws_on_the_card_with_the_monitor() { + let cards = [card(NVIDIA, 1, false), card(AMD, 0, false)]; + assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays))); + } + + /// Two cards of one model have the same PCI ids: only the PCI address tells them apart. Without + /// one from the driver the display rule gives way to the old choice instead of guessing. + #[test] + fn identical_cards_are_told_apart_only_by_pci_address() { + const SECOND: (u32, u32, &str) = (0x10de, 0x25a2, "0000:02:00.0"); + let cards = [card(NVIDIA, 0, false), card(SECOND, 1, false)]; + let with_slots = [vulkan("NVIDIA A", NVIDIA, DeviceType::DiscreteGpu), vulkan("NVIDIA B", SECOND, DeviceType::DiscreteGpu)]; + assert_eq!(choose(&with_slots, &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays))); + let without: Vec = with_slots.iter().cloned().map(|c| Candidate { pci_slot: String::new(), ..c }).collect(); + assert_eq!(choose(&without, &cards, &Asked::default()), Some((0, Why::Fallback))); + } + + /// The laptop this was measured on: Intel HD 530 behind the panel (`card2-eDP-1`), a Quadro + /// M4000M with nothing connected, and the Quadro offered first by wgpu. + #[test] + fn an_intel_and_nvidia_laptop_draws_on_intel() { + const HD530: (u32, u32, &str) = (0x8086, 0x191b, "0000:00:02.0"); + const M4000M: (u32, u32, &str) = (0x10de, 0x13f9, "0000:01:00.0"); + let adapters = [ + vulkan("Quadro M4000M", M4000M, DeviceType::DiscreteGpu), + vulkan("Intel(R) HD Graphics 530 (SKL GT2)", HD530, DeviceType::IntegratedGpu), + ]; + let cards = [card(M4000M, 0, false), card(HD530, 1, true)]; + assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::BuiltInPanel))); + } +} diff --git a/apps/wordcraft/src/linux_gpu/drm.rs b/apps/wordcraft/src/linux_gpu/drm.rs new file mode 100644 index 0000000000..cee58e0bb0 --- /dev/null +++ b/apps/wordcraft/src/linux_gpu/drm.rs @@ -0,0 +1,237 @@ +//! Which graphics cards drive displays, as the system reports them (Linux: `/sys/class/drm`). +//! +//! A window drawn on one card and shown on a screen attached to another is copied across on every +//! frame, so the app draws on the card that drives the screen (see the parent module). + +use std::io::Read as _; +use std::path::Path; + +/// A graphics card and the displays connected to it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct DisplayCard { + /// PCI vendor id: 0x1002 AMD, 0x10de NVIDIA, 0x8086 Intel. + pub vendor: u32, + /// PCI device id. + pub device: u32, + /// PCI address in the form `0000:05:00.0`, lowercase; empty when the system doesn't give one. + pub pci_slot: String, + /// Connected displays that are switched on, of any kind, built-in panel included. + pub displays: u32, + /// A connected, switched-on built-in panel (eDP, LVDS or DSI): this card drives a laptop's + /// own screen. + pub built_in_panel: bool, +} + +/// Connector kinds that are a computer's own screen rather than a monitor plugged into it. +const BUILT_IN_PANELS: &[&str] = &["eDP", "LVDS", "DSI"]; + +/// At most this many entries are read from the DRM folder. +const MAX_ENTRIES: usize = 512; + +/// At most this many bytes are read from one sysfs file. +const MAX_FILE: u64 = 4096; + +/// The graphics cards on this computer and what's connected to them. Empty where the system +/// doesn't say (a sandbox without `/sys`). +#[cfg(target_os = "linux")] +pub(crate) fn display_cards() -> Vec { + display_cards_in(Path::new("/sys/class/drm")) +} + +/// [`display_cards`] read from a DRM folder laid out like `/sys/class/drm`: a `cardN` entry per +/// card, with the card's PCI ids in `cardN/device/uevent`, and a `cardN--` entry per +/// connector, with `connected` or `disconnected` in its `status` and, where the kernel gives it, +/// `enabled` or `disabled` in its `enabled`. Cards without PCI ids (a firmware framebuffer) are +/// left out. +pub(crate) fn display_cards_in(drm: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(drm) else { + return Vec::new(); + }; + let mut names: Vec = entries.take(MAX_ENTRIES).filter_map(|e| e.ok()?.file_name().into_string().ok()).collect(); + names.sort(); + let cards = names.iter().filter(|n| is_card(n)); + cards + .filter_map(|card| { + let uevent = read_small(&drm.join(card).join("device").join("uevent"))?; + let (vendor, device) = pci_ids(&uevent)?; + let pci_slot = uevent_value(&uevent, "PCI_SLOT_NAME").unwrap_or_default().to_ascii_lowercase(); + let prefix = format!("{card}-"); + let mut out = DisplayCard { vendor, device, pci_slot, displays: 0, built_in_panel: false }; + for connector in names.iter().filter_map(|n| n.strip_prefix(&prefix)) { + let dir = drm.join(format!("{prefix}{connector}")); + let status = read_small(&dir.join("status")).unwrap_or_default(); + // A panel can be connected but switched off (a closed lid with a monitor in use): + // `enabled` then reads `disabled`, and it drives nothing. No `enabled`: as before. + let enabled = read_small(&dir.join("enabled")).unwrap_or_default(); + if status.trim() != "connected" || enabled.trim() == "disabled" { + continue; + } + out.displays = out.displays.saturating_add(1); + if BUILT_IN_PANELS.contains(&connector_kind(connector)) { + out.built_in_panel = true; + } + } + Some(out) + }) + .collect() +} + +/// `card0`, `card12`: a card, not a connector (`card0-eDP-1`) or a render node. +fn is_card(name: &str) -> bool { + name.strip_prefix("card").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) +} + +/// `eDP-1` → `eDP`, `HDMI-A-1` → `HDMI-A`: the connector's name without its number. +fn connector_kind(connector: &str) -> &str { + match connector.rsplit_once('-') { + Some((kind, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => kind, + _ => connector, + } +} + +/// `PCI_ID=1002:1638` → (0x1002, 0x1638). +fn pci_ids(uevent: &str) -> Option<(u32, u32)> { + let (vendor, device) = uevent_value(uevent, "PCI_ID")?.split_once(':')?; + Some((u32::from_str_radix(vendor.trim(), 16).ok()?, u32::from_str_radix(device.trim(), 16).ok()?)) +} + +fn uevent_value<'a>(uevent: &'a str, key: &str) -> Option<&'a str> { + uevent.lines().find_map(|l| l.strip_prefix(key)?.strip_prefix('=')).map(str::trim) +} + +fn read_small(path: &Path) -> Option { + let mut text = String::new(); + std::fs::File::open(path).ok()?.take(MAX_FILE).read_to_string(&mut text).ok()?; + Some(text) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::path::PathBuf; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// A folder of its own under the system's temporary folder, removed when dropped. + struct TempDir(PathBuf); + + impl TempDir { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("wordcraft-drm-test-{}-{n}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("temp dir"); + TempDir(dir) + } + + fn path(&self) -> &Path { + &self.0 + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + /// A fake `/sys/class/drm`: cards as (name, PCI_ID, PCI_SLOT_NAME), connectors as + /// (name, status). + fn drm(cards: &[(&str, &str, &str)], connectors: &[(&str, &str)]) -> TempDir { + let dir = TempDir::new(); + for (card, id, slot) in cards { + let device = dir.path().join(card).join("device"); + fs::create_dir_all(&device).expect("card folder"); + fs::write(device.join("uevent"), format!("DRIVER=x\nPCI_CLASS=30000\nPCI_ID={id}\nPCI_SLOT_NAME={slot}\n")).expect("uevent"); + } + for (connector, status) in connectors { + let c = dir.path().join(connector); + fs::create_dir_all(&c).expect("connector folder"); + fs::write(c.join("status"), format!("{status}\n")).expect("status"); + } + fs::create_dir_all(dir.path().join("renderD128")).expect("render node"); + fs::write(dir.path().join("version"), "drm 1.1.0\n").expect("version"); + dir + } + + /// A laptop whose AMD iGPU drives the panel, with an NVIDIA card that has no outputs. + #[test] + fn a_laptop_panel_is_found_on_the_integrated_gpu() { + let d = drm( + &[("card0", "10DE:25A2", "0000:01:00.0"), ("card1", "1002:1638", "0000:05:00.0")], + &[("card1-DP-1", "disconnected"), ("card1-eDP-1", "connected"), ("card1-HDMI-A-1", "disconnected")], + ); + let cards = display_cards_in(d.path()); + assert_eq!( + cards, + vec![ + DisplayCard { vendor: 0x10de, device: 0x25a2, pci_slot: "0000:01:00.0".into(), displays: 0, built_in_panel: false }, + DisplayCard { vendor: 0x1002, device: 0x1638, pci_slot: "0000:05:00.0".into(), displays: 1, built_in_panel: true }, + ] + ); + } + + /// A desktop with a monitor on each card: displays on both, no built-in panel. + #[test] + fn monitors_on_two_cards_are_counted_on_each() { + let d = drm( + &[("card0", "8086:A780", "0000:00:02.0"), ("card1", "10de:2206", "0000:01:00.0")], + &[("card0-HDMI-A-1", "connected"), ("card1-DP-1", "connected"), ("card1-DP-2", "connected"), ("card1-DP-3", "disconnected")], + ); + let cards = display_cards_in(d.path()); + assert_eq!(cards.iter().map(|c| (c.displays, c.built_in_panel)).collect::>(), vec![(1, false), (2, false)]); + } + + /// `card10` is a different card from `card1`, and its connectors aren't `card1`'s. + #[test] + fn card_numbers_are_not_prefixes_of_each_other() { + let d = drm(&[("card1", "1002:1638", "0000:05:00.0"), ("card10", "10de:25a2", "0000:01:00.0")], &[("card10-DP-1", "connected")]); + let cards = display_cards_in(d.path()); + assert_eq!(cards.iter().map(|c| (c.vendor, c.displays)).collect::>(), vec![(0x1002, 0), (0x10de, 1)]); + } + + /// LVDS and DSI panels are built in too; HDMI-A is a monitor, whatever its number. + #[test] + fn built_in_panels_are_told_from_monitors_by_connector_kind() { + assert_eq!(connector_kind("eDP-1"), "eDP"); + assert_eq!(connector_kind("HDMI-A-1"), "HDMI-A"); + assert_eq!(connector_kind("DSI-12"), "DSI"); + assert_eq!(connector_kind("Virtual"), "Virtual"); + let d = drm(&[("card0", "8086:9a49", "0000:00:02.0")], &[("card0-LVDS-1", "connected")]); + assert!(display_cards_in(d.path()).iter().all(|c| c.built_in_panel)); + } + + /// A firmware framebuffer has no PCI ids; unreadable or odd entries are skipped, never a panic. + #[test] + fn what_cant_be_read_is_left_out() { + let d = drm(&[("card0", "nonsense", ""), ("card1", "1002:", "")], &[("card0-Virtual-1", "connected")]); + fs::create_dir_all(d.path().join("card2")).expect("card without device"); + fs::create_dir_all(d.path().join("card")).expect("bare name"); + assert!(display_cards_in(d.path()).is_empty()); + assert!(display_cards_in(&d.path().join("missing")).is_empty()); + assert_eq!(pci_ids("PCI_ID=10de:25a2"), Some((0x10de, 0x25a2))); + assert_eq!(pci_ids("PCI_IDX=10de:25a2"), None); + } + + /// A status of `unknown` (some virtual outputs) isn't a connected display. + #[test] + fn only_connected_counts() { + let d = drm(&[("card0", "1af4:1050", "0000:00:01.0")], &[("card0-Virtual-1", "unknown")]); + assert_eq!(display_cards_in(d.path()).first().map(|c| c.displays), Some(0)); + } + + /// A laptop with its lid closed and a monitor on the discrete card: the panel still reads + /// `connected` but is switched off, so it neither counts nor marks its card as the panel's. + #[test] + fn a_switched_off_panel_does_not_count() { + let d = drm( + &[("card0", "10de:25a2", "0000:01:00.0"), ("card1", "1002:1638", "0000:05:00.0")], + &[("card0-HDMI-A-1", "connected"), ("card1-eDP-1", "connected")], + ); + fs::write(d.path().join("card0-HDMI-A-1").join("enabled"), "enabled\n").expect("enabled"); + fs::write(d.path().join("card1-eDP-1").join("enabled"), "disabled\n").expect("enabled"); + let cards = display_cards_in(d.path()); + assert_eq!(cards.iter().map(|c| (c.vendor, c.displays, c.built_in_panel)).collect::>(), vec![(0x10de, 1, false), (0x1002, 0, false)]); + } +} diff --git a/apps/wordcraft/src/main.rs b/apps/wordcraft/src/main.rs index 18b7b7935f..65cdca1dc2 100644 --- a/apps/wordcraft/src/main.rs +++ b/apps/wordcraft/src/main.rs @@ -20,9 +20,12 @@ mod default_apps; mod file_dialogs; #[cfg(any(target_os = "windows", target_os = "macos", test))] mod graphics; +#[cfg(any(target_os = "linux", test))] +mod linux_gpu; mod logging; #[cfg(all(unix, not(target_os = "macos")))] mod portal_save; +mod prefs_merge; mod print; mod region; #[cfg(target_os = "macos")] @@ -222,31 +225,44 @@ fn user_dict_path() -> Option { wordcraft_control_key::settings_dir().map(|b| b.join(wordcraft_engine::Session::USER_DICT_FILE)) } -fn load_user_dictionary(app: &mut WordApp) { - if !prefs_enabled() { - return; - } - if let Some(p) = user_dict_path() { - wordcraft_proof::load_user_dictionary(&p); - app.session.user_dict_path = Some(p); - } -} - /// Runs without preferences (`WORDCRAFT_NO_PREFS`, agents' test runs) neither read nor write them. fn prefs_enabled() -> bool { std::env::var_os("WORDCRAFT_NO_PREFS").is_none() } +/// The preferences as this process last loaded or saved them, which `save_prefs` compares with +/// to write only what this process changed since (#3773, see `prefs_merge`). +static LOADED_PREFS: std::sync::Mutex> = std::sync::Mutex::new(None); + +/// Apply the saved preferences (`ui.json`) and the user dictionary to `app`, and remember the +/// result for `save_prefs`. Runs without preferences neither read nor keep them. fn load_prefs(app: &mut WordApp) { if !prefs_enabled() { return; } - if let Some(p) = prefs_path() - && let Ok(bytes) = std::fs::read(&p) + let loaded = load_prefs_from(app, prefs_path().as_deref(), user_dict_path()); + if let Ok(mut slot) = LOADED_PREFS.lock() { + *slot = loaded; + } +} + +/// Apply the preferences saved at `prefs` to `app`, then load the user dictionary at `dict` +/// (`custom-dictionary.txt`, #40), and give back the preferences as `prefs()` does after both: +/// the words only the dictionary file has are part of what was loaded, so a word another process +/// removes from `ui.json` isn't written back as one added here (#3773). +fn load_prefs_from(app: &mut WordApp, prefs: Option<&std::path::Path>, dict: Option) -> Option { + if let Some(p) = prefs + && let Ok(bytes) = std::fs::read(p) && let Some(ui) = UiState::from_json(&bytes) { app.apply_prefs(ui); } + if let Some(p) = dict { + wordcraft_proof::load_user_dictionary(&p); + app.session.user_dict_path = Some(p); + } + // As `prefs()` gives them back, so a setting nobody touched compares equal at exit. + serde_json::to_value(app.prefs()).ok() } /// Fonts the user added (#582) live in `fonts` in the settings folder: load them, and store fonts @@ -332,6 +348,8 @@ fn x11_libraries() -> Result<(), String> { if missing.is_empty() { Ok(()) } else { Err(missing.join("; ")) } } +/// Write `app`'s preferences to `ui.json`, merged with what other processes saved since this one +/// loaded it (`merged_prefs`). fn save_prefs(app: &WordApp) { if let Err(e) = try_save_prefs(app) { log::warn!("preferences: {e}"); @@ -348,11 +366,79 @@ fn try_save_prefs(app: &WordApp) -> Result { if let Some(dir) = p.parent() { std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?; } - let bytes = serde_json::to_vec_pretty(&app.prefs()).map_err(|e| format!("cannot serialize: {e}"))?; - write_prefs(&p, &bytes).map_err(|e| format!("cannot save {}: {e}", p.display()))?; + let ours = serde_json::to_value(app.prefs()).map_err(|e| format!("cannot serialize: {e}"))?; + let mut base = LOADED_PREFS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + save_merged(&p, &mut base, ours)?; Ok(true) } +/// Writes `ours` to `path`, merged with what other WordCraft processes saved there since this one +/// loaded or saved `base` (`merged_prefs`), and makes `ours` the new `base`: a setting changed here +/// before this save and by another process after it then takes the other's value at the next save. +/// Holds `lock_prefs` from the read to the rename. +fn save_merged(path: &std::path::Path, base: &mut Option, ours: serde_json::Value) -> Result<(), String> { + let _lock = lock_prefs(path); + let merged = merged_prefs(path, base.as_ref(), ours.clone()); + let bytes = serde_json::to_vec_pretty(&merged).map_err(|e| format!("cannot serialize: {e}"))?; + write_prefs(path, &bytes).map_err(|e| format!("cannot save {}: {e}", path.display()))?; + *base = Some(ours); + Ok(()) +} + +/// `ours` with what other WordCraft processes saved to `path` since this one loaded or saved +/// `base`, for the settings this one left alone (#3773, see `prefs_merge`). `ours` as it is when +/// there's no `base`, or the file is missing or isn't preferences now. +fn merged_prefs(path: &std::path::Path, base: Option<&serde_json::Value>, ours: serde_json::Value) -> serde_json::Value { + let Some(base) = base else { return ours }; + let disk = match std::fs::read(path) { + Ok(bytes) => prefs_merge::as_read(&bytes), + Err(e) => { + if e.kind() != std::io::ErrorKind::NotFound { + log::debug!("preferences: cannot read {} to merge, saving this process's: {e}", path.display()); + } + return ours; + } + }; + match disk { + Some(disk) => prefs_merge::merge(base, ours, &disk), + None => { + log::debug!("preferences: {} isn't preferences, saving this process's", path.display()); + ours + } + } +} + +/// How long a save waits for another process's save to finish before going ahead anyway: a save +/// takes milliseconds, and a process stuck holding the lock mustn't stop this one from saving. +const PREFS_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2); + +/// An advisory lock beside `path` (`.ui.json.lock`), held while it is returned, so that two +/// processes saving at once (logging out closes every window together) take turns at reading, +/// merging and replacing `ui.json` instead of one losing the other's changes. `None` (save +/// unlocked) when the lock file can't be opened or the lock isn't free within [`PREFS_LOCK_WAIT`]. +fn lock_prefs(path: &std::path::Path) -> Option { + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "ui.json".into()); + let lock = path.with_file_name(format!(".{name}.lock")); + let file = match std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(&lock) { + Ok(f) => f, + Err(e) => { + log::debug!("preferences: cannot open {}, saving without it: {e}", lock.display()); + return None; + } + }; + let start = std::time::Instant::now(); + loop { + match file.try_lock() { + Ok(()) => return Some(file), + Err(std::fs::TryLockError::WouldBlock) if start.elapsed() < PREFS_LOCK_WAIT => std::thread::sleep(std::time::Duration::from_millis(10)), + Err(e) => { + log::warn!("preferences: {} is held, saving without it: {e}", lock.display()); + return None; + } + } + } +} + /// Writes `bytes` to a sibling temporary file and renames it over `path`, so a failed or /// interrupted write leaves the previous preferences in place. fn write_prefs(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { @@ -601,6 +687,13 @@ fn main() -> eframe::Result { })); } } + // egui-wgpu draws on the discrete GPU by default; on a laptop whose integrated GPU drives the + // panel, that wakes the discrete GPU whenever the window redraws. Draw on the GPU that drives + // the screen; `WGPU_ADAPTER_NAME` and `WGPU_POWER_PREF` still decide (see linux_gpu.rs). + #[cfg(target_os = "linux")] + if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup { + setup.native_adapter_selector = Some(std::sync::Arc::new(linux_gpu::pick_adapter)); + } // Registered before the event loop starts, so it catches the Finder event that launched us as // well as later ones. Lives until the event loop returns; the app creator only borrows it. #[cfg(target_os = "macos")] @@ -626,7 +719,6 @@ fn main() -> eframe::Result { if updates_unsafe { app.disable_self_update(); } - load_user_dictionary(&mut app); // Language packs from the suite's font store; an Install click is the person's own. wordcraft_engine::packs::use_font_store(true); // A region chosen in File › Options replaces the system's for the first blank @@ -636,6 +728,7 @@ fn main() -> eframe::Result { app.replace_startup_document(doc); } app.watch_desktop_theme(&cc.egui_ctx); + app.tell_about_font_downloads(); if prefs_enabled() && let Some(dir) = wordcraft_control_key::settings_dir() { @@ -839,7 +932,72 @@ mod launch_arg_tests { #[cfg(test)] mod prefs_tests { - use super::write_prefs; + use serde_json::{Value, json}; + use wordcraft_ui_egui::{UiState, theme::Appearance}; + + use super::{load_prefs_from, lock_prefs, prefs_merge, save_merged, write_prefs}; + + /// The preferences saved with `theme` (every other setting at its default). + fn with_theme(theme: &str) -> Value { + prefs_merge::as_read(&serde_json::to_vec(&json!({"theme": theme})).unwrap()).unwrap() + } + + /// The theme the next process loads from `path`. + fn saved_theme(path: &std::path::Path) -> Appearance { + UiState::from_json(&std::fs::read(path).unwrap()).unwrap().theme + } + + #[test] + fn a_setting_changed_by_another_process_after_a_save_here_keeps_its_value() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ui.json"); + std::fs::write(&path, serde_json::to_vec(&with_theme("light")).unwrap()).unwrap(); + // A loads Light, switches to Dark and saves before exiting (taking a document off the + // recent list does). + let mut a = Some(with_theme("light")); + save_merged(&path, &mut a, with_theme("dark")).unwrap(); + assert_eq!(saved_theme(&path), Appearance::Dark); + // B starts, loads Dark, switches to Light and exits. + save_merged(&path, &mut Some(with_theme("dark")), with_theme("light")).unwrap(); + // A exits without touching the theme since its save: B's choice, made later, stays. + save_merged(&path, &mut a, with_theme("dark")).unwrap(); + assert_eq!(saved_theme(&path), Appearance::Light); + } + + #[test] + fn the_loaded_preferences_include_the_words_of_the_dictionary_file() { + // A word only `custom-dictionary.txt` has is loaded, not added here: if another process + // removes it from `ui.json`, this one mustn't write it back. + let dir = tempfile::tempdir().unwrap(); + let (prefs, dict) = (dir.path().join("ui.json"), dir.path().join("custom-dictionary.txt")); + std::fs::write(&prefs, br#"{"dictionary": ["zqxinjson"]}"#).unwrap(); + std::fs::write(&dict, "zqxinfile\n").unwrap(); + let mut app = wordcraft_ui_egui::WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default()); + let loaded = load_prefs_from(&mut app, Some(&prefs), Some(dict)).unwrap(); + let words = loaded["dictionary"].as_array().unwrap(); + for word in ["zqxinjson", "zqxinfile"] { + assert!(words.contains(&json!(word)), "{word}: {words:?}"); + } + wordcraft_engine::proof::remove_word("zqxinjson"); + wordcraft_engine::proof::remove_word("zqxinfile"); + } + + #[test] + fn a_save_waits_for_another_process_saving_at_the_same_moment() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ui.json"); + // Another process is between reading and replacing `ui.json`. + let held = lock_prefs(&path).expect("the lock is free"); + let saver = { + let path = path.clone(); + std::thread::spawn(move || save_merged(&path, &mut None, with_theme("dark"))) + }; + std::thread::sleep(std::time::Duration::from_millis(200)); + assert!(!path.exists(), "saved while another process held the lock"); + drop(held); + saver.join().unwrap().unwrap(); + assert_eq!(saved_theme(&path), Appearance::Dark); + } #[test] fn failed_preferences_write_keeps_the_old_file_and_reports_the_error() { diff --git a/apps/wordcraft/src/prefs_merge.rs b/apps/wordcraft/src/prefs_merge.rs new file mode 100644 index 0000000000..b052737ccd --- /dev/null +++ b/apps/wordcraft/src/prefs_merge.rs @@ -0,0 +1,550 @@ +//! Several WordCraft processes share one `ui.json` (opening a file from the file manager starts +//! another). Each reads it at start-up and writes it at exit (and when a change must survive a +//! crash, like taking a document off the recent list), so without a merge the process that writes +//! last writes back what it loaded and loses the others' changes (#3773). +//! +//! The policy: when saving, read `ui.json` again as this version reads it ([`as_read`]: a setting +//! of the wrong type reads as its default, and keys it doesn't know or reads only to migrate are +//! left out), and write it with only what this process changed since it last loaded or saved its +//! preferences (`base`). Every other setting keeps what the file holds now, including the absence +//! of one another process removed (a shortcut, a task pane's place). +//! +//! - A setting both changed takes this process's value. +//! - Groups of settings (editing options, AutoCorrect's switches, keyboard shortcuts, the ribbon, +//! task pane places) merge entry by entry ([`rule`]). Any other object is one setting: the +//! window's size and place, or one task pane's place, are never mixed from two processes. +//! - Lists of user entries (AutoCorrect entries by the text they replace, its exceptions, removed +//! built-in shortcuts, ribbon tabs by name, Quick Access Toolbar commands, caption labels, pens, +//! custom dictionary words) merge entry by entry too ([`merge_entries`]): entries either process +//! added are kept, entries either process removed stay removed, and an entry both changed takes +//! this process's version. A ribbon or toolbar left as it comes counts as its default entries. +//! - Recent lists (documents, symbols, colours, fonts) take the entries this process added or used +//! again first, then the file's, without duplicates, without the entries this process removed, +//! and within each list's limit ([`merge_recent`]). +//! - Any other list (the task panes' order, a floating pane's rectangle) is one setting. +//! +//! What this process changed is found by comparing with `base`, not by recording each change: a +//! setting changed and then changed back counts as untouched, so the file's value stays, and a +//! recent entry used again without moving (it was already first) counts as not used. + +use std::collections::{HashMap, HashSet}; + +use serde_json::{Map, Value}; +use wordcraft_engine::ribbon::{DEFAULT_QAT, RibbonLayout}; +use wordcraft_ui_egui::{MAX_RECENT, MAX_RECENT_FONTS, UiState, colors, dialogs_insert}; + +/// Whether two entries of a recent list are the same entry. +type Same = fn(&Value, &Value) -> bool; + +/// What tells an entry of a list of user entries from the others. Entries with the same key are +/// told apart by their order ([`ids`]). +type Key = fn(&Value) -> String; + +/// How a setting this process changed merges with the file's. +#[derive(Clone, Copy)] +enum Rule { + /// A group of settings: each entry on its own. + Group, + /// A recent list, most recent first: how many entries it keeps, and when two are the same. + Recent(usize, Same), + /// A list of user entries: each entry on its own. + Entries(Key), + /// One setting: this process's value. + Whole, +} + +/// The rule for the setting at `path` (`ui.json`'s keys from the top). +fn rule(path: &[&str]) -> Rule { + match path { + [] | ["editing" | "keyboard" | "ribbon" | "panePlaces"] | ["editing", "markup" | "marks" | "autocorrect"] | ["keyboard", "assigned"] => { + Rule::Group + } + ["recent"] => Rule::Recent(MAX_RECENT, same_entry), + ["recentSymbols"] => Rule::Recent(dialogs_insert::RECENT_SYMBOLS, same_entry), + ["recentColors"] => Rule::Recent(colors::RECENT_MAX, same_entry), + ["recentFonts"] => Rule::Recent(MAX_RECENT_FONTS, same_font), + ["editing", "autocorrect", "entries"] => Rule::Entries(replaced_text), + ["ribbon", "tabs"] => Rule::Entries(tab_name), + ["editing", "autocorrect", "removed" | "exceptions" | "exceptionsRemoved" | "initialCapsExceptions"] + | ["keyboard", "removed"] + | ["ribbon", "qat"] + | ["captionLabels" | "inkPens" | "dictionary"] => Rule::Entries(whole_entry), + _ => Rule::Whole, + } +} + +/// What a setting saved only when it isn't its default stands for when it is missing: the +/// default ribbon tabs and Quick Access Toolbar, so that two processes customizing them from the +/// default merge entry by entry. +fn when_missing(path: &[&str]) -> Option { + match path { + ["ribbon", "tabs"] => serde_json::to_value(RibbonLayout::default().tabs()).ok(), + ["ribbon", "qat"] => serde_json::to_value(DEFAULT_QAT).ok(), + _ => None, + } +} + +/// Entries saved alike (colours are saved normalised, `colors::push_recent`). +fn same_entry(a: &Value, b: &Value) -> bool { + a == b +} + +/// Font names ignoring case, as `push_recent_font` compares them. +fn same_font(a: &Value, b: &Value) -> bool { + match (a.as_str(), b.as_str()) { + (Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(), + _ => a == b, + } +} + +/// The entry as saved. +fn whole_entry(v: &Value) -> String { + v.to_string() +} + +/// An AutoCorrect entry `[from, to]` by the text it replaces. +fn replaced_text(v: &Value) -> String { + v.get(0).unwrap_or(v).to_string() +} + +/// A ribbon tab by its name, ignoring case as the ribbon does. +fn tab_name(v: &Value) -> String { + v.get("name").and_then(Value::as_str).map_or_else(|| v.to_string(), str::to_lowercase) +} + +/// `ui.json`'s bytes as this version reads them, saved again: `None` when they aren't +/// preferences at all. +pub fn as_read(bytes: &[u8]) -> Option { + serde_json::to_value(UiState::from_json(bytes)?).ok() +} + +/// The preferences to write: `ours` (this process's, now), with every value it left as it was in +/// `base` (what it last loaded or saved) taken from `disk` (what `ui.json` holds now, [`as_read`]). +pub fn merge(base: &Value, ours: Value, disk: &Value) -> Value { + let fallback = ours.clone(); + merge_setting(&mut Vec::new(), Some(base), Some(ours), Some(disk)).unwrap_or(fallback) +} + +/// One setting, at `path`. `None` for a setting left out (this process removed it, or it left it +/// alone and another process removed it). +fn merge_setting(path: &mut Vec, base: Option<&Value>, ours: Option, disk: Option<&Value>) -> Option { + if base == ours.as_ref() { + // Unchanged here: whatever the file holds now. + return disk.cloned(); + } + let ours = ours?; + let keys: Vec<&str> = path.iter().map(String::as_str).collect(); + Some(match (rule(&keys), ours, base, disk) { + (Rule::Group, Value::Object(ours), Some(Value::Object(base)), Some(Value::Object(disk))) => { + Value::Object(merge_group(path, base, ours, disk)) + } + (Rule::Recent(cap, same), Value::Array(ours), Some(Value::Array(base)), Some(Value::Array(disk))) => { + Value::Array(merge_recent(base, ours, disk, cap, same)) + } + (Rule::Entries(key), Value::Array(ours), Some(Value::Array(base)), Some(Value::Array(disk))) => { + Value::Array(merge_entries(base, &ours, disk, key)) + } + (_, ours, ..) => ours, + }) +} + +/// A group of settings, entry by entry: this process's entries in their order, then those only +/// the file or `base` has. +fn merge_group(path: &mut Vec, base: &Map, mut ours: Map, disk: &Map) -> Map { + let mut names: Vec = ours.keys().cloned().collect(); + let mut seen: HashSet = names.iter().cloned().collect(); + for k in disk.keys().chain(base.keys()) { + if seen.insert(k.clone()) { + names.push(k.clone()); + } + } + let mut merged = Map::new(); + for k in names { + path.push(k.clone()); + let keys: Vec<&str> = path.iter().map(String::as_str).collect(); + let missing = when_missing(&keys); + let base_v = base.get(&k).cloned().or_else(|| missing.clone()); + let disk_v = disk.get(&k).cloned().or_else(|| missing.clone()); + let ours_v = ours.remove(&k).or_else(|| missing.clone()); + let v = merge_setting(path, base_v.as_ref(), ours_v, disk_v.as_ref()); + path.pop(); + // A setting saved only when it isn't its default is left out when it is. + if let Some(v) = v.filter(|v| Some(v) != missing.as_ref()) { + merged.insert(k, v); + } + } + merged +} + +/// A list entry: its key, and how many entries before it have the same key. +type Id = (String, usize); + +/// The entries of `list` told apart by `key`, in order. +fn ids(list: &[Value], key: Key) -> Vec { + let mut seen: HashMap = HashMap::new(); + list.iter() + .map(|v| { + let k = key(v); + let n = seen.entry(k.clone()).or_default(); + *n += 1; + (k, *n - 1) + }) + .collect() +} + +/// A list of user entries, entry by entry. An entry either process added is kept, one either +/// removed stays removed, and one this process changed takes its version (else the file's). The +/// order is this process's if it reordered the entries it loaded, else the file's; an entry only +/// the other list has goes after the entry it follows there. +fn merge_entries(base: &[Value], ours: &[Value], disk: &[Value], key: Key) -> Vec { + let (base_ids, ours_ids, disk_ids) = (ids(base, key), ids(ours, key), ids(disk, key)); + let index = |ids: &[Id], list: &[Value]| -> HashMap { ids.iter().cloned().zip(list.iter().cloned()).collect() }; + let (b, o, d) = (index(&base_ids, base), index(&ours_ids, ours), index(&disk_ids, disk)); + let value = |id: &Id| -> Option<&Value> { + match (b.get(id), o.get(id), d.get(id)) { + // Left alone here: the file's, or gone if the other process removed it. + (Some(b), Some(o), d) if b == o => d, + // Added or changed here. + (_, Some(o), _) => Some(o), + // Removed here. + (Some(_), None, _) => None, + // Added there. + (None, None, d) => d, + } + }; + let common = |ids: &[Id], other: &HashMap| -> Vec { ids.iter().filter(|id| other.contains_key(*id)).cloned().collect() }; + let reordered = common(&ours_ids, &b) != common(&base_ids, &o); + let (first, second) = if reordered { (&ours_ids, &disk_ids) } else { (&disk_ids, &ours_ids) }; + let in_first: HashSet<&Id> = first.iter().collect(); + let kept: HashSet<&Id> = first.iter().filter(|id| value(id).is_some()).collect(); + // Entries only `second` has, by the kept entry they follow there (`None`: at the start). + let mut after: HashMap, Vec<&Id>> = HashMap::new(); + let mut anchor = None; + for id in second { + if kept.contains(id) { + anchor = Some(id); + } else if !in_first.contains(id) && value(id).is_some() { + after.entry(anchor).or_default().push(id); + } + } + let mut merged = Vec::new(); + let mut emit = |ids: &[&Id]| merged.extend(ids.iter().filter_map(|id| value(id).cloned())); + emit(after.get(&None).map_or(&[], Vec::as_slice)); + for id in first.iter().filter(|id| kept.contains(id)) { + emit(&[id]); + emit(after.get(&Some(id)).map_or(&[], Vec::as_slice)); + } + merged +} + +/// The entries this process put at the front of `ours` ([`touched_len`]), then `disk`'s, leaving +/// out what this process removed (in `base` but no longer in `ours`), without duplicates and at +/// most `cap` entries. Entries are told apart by `same`. +fn merge_recent(base: &[Value], ours: Vec, disk: &[Value], cap: usize, same: Same) -> Vec { + let has = |list: &[Value], v: &Value| list.iter().any(|x| same(x, v)); + let removed = |v: &Value| has(base, v) && !has(&ours, v); + let touched = &ours[..touched_len(base, &ours, same)]; + let mut merged: Vec = Vec::new(); + for v in touched.iter().cloned().chain(disk.iter().filter(|v| !removed(v)).cloned()) { + if merged.len() == cap { + break; + } + if !has(&merged, &v) { + merged.push(v); + } + } + merged +} + +/// How many of `ours`'s first entries this process added or used again. Each use moves an entry +/// to the front of a recent list, so what it left alone is a tail of `ours` in `base`'s order: the +/// longest such tail is untouched, and everything before it (new entries, and entries that moved +/// ahead of one loaded before them) was touched. A use that leaves the order as it was loaded +/// (the first entry used again) can't be told from no use, and merges as none. +fn touched_len(base: &[Value], ours: &[Value], same: Same) -> usize { + let mut end = base.len(); + for (i, v) in ours.iter().enumerate().rev() { + match base[..end].iter().rposition(|b| same(b, v)) { + Some(at) => end = at, + None => return i + 1, + } + } + 0 +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + use wordcraft_ui_egui::UiState; + + use super::{as_read, merge}; + + /// The preferences a process holds after loading a `ui.json` with `settings` (every other + /// setting at its default), as it saves them. + fn prefs(settings: Value) -> Value { + as_read(&serde_json::to_vec(&settings).unwrap()).unwrap() + } + + /// What the next process loads from the merged preferences. + fn reloaded(merged: &Value) -> UiState { + UiState::from_json(&serde_json::to_vec(merged).unwrap()).unwrap() + } + + /// `ui.json` after B and then A, which both loaded `loaded`, save `b` and `a`. + fn b_then_a(loaded: &Value, b: Value, a: Value) -> Value { + let after_b = merge(loaded, b, loaded); + merge(loaded, a, &after_b) + } + + #[test] + fn two_processes_keep_each_others_changes() { + // #3773: A and B both start from the same file. + let loaded = + json!({"theme": "light", "author": "Ann", "recent": ["a.docx", "b.docx"], "editing": {"smartQuotes": true, "autoCapitalize": true}}); + // B changes the theme and opens c.docx, then exits first. + let b = json!({"theme": "dark", "author": "Ann", "recent": ["c.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": false, "autoCapitalize": true}}); + // A changes the author name and opens d.docx, then exits. + let a = json!({"theme": "light", "author": "Bo", "recent": ["d.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": true, "autoCapitalize": false}}); + assert_eq!( + b_then_a(&loaded, b, a), + json!({"theme": "dark", "author": "Bo", "recent": ["d.docx", "c.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": false, "autoCapitalize": false}}) + ); + } + + #[test] + fn a_process_that_changed_nothing_writes_the_file_back_as_it_is() { + let loaded = json!({"theme": "light", "recent": ["a.docx"]}); + let disk = json!({"theme": "dark", "recent": ["b.docx", "a.docx"]}); + assert_eq!(merge(&loaded, loaded.clone(), &disk), disk); + } + + #[test] + fn this_process_wins_a_setting_both_changed() { + let loaded = json!({"theme": "light"}); + assert_eq!(merge(&loaded, json!({"theme": "system"}), &json!({"theme": "dark"})), json!({"theme": "system"})); + } + + #[test] + fn a_setting_changed_and_changed_back_counts_as_untouched() { + // Changes are found by comparing with what was loaded: A switched to dark and back. + let loaded = json!({"theme": "light"}); + assert_eq!(merge(&loaded, json!({"theme": "light"}), &json!({"theme": "dark"})), json!({"theme": "dark"})); + } + + #[test] + fn a_recent_entry_removed_here_stays_removed() { + let loaded = json!({"recent": ["a.docx", "b.docx"]}); + let ours = json!({"recent": ["b.docx"]}); + let disk = json!({"recent": ["c.docx", "a.docx", "b.docx"]}); + assert_eq!(merge(&loaded, ours, &disk), json!({"recent": ["c.docx", "b.docx"]})); + // Clear Recent clears what the other process had added too only if it was loaded here. + assert_eq!(merge(&loaded, json!({"recent": []}), &json!({"recent": ["c.docx", "a.docx", "b.docx"]})), json!({"recent": ["c.docx"]})); + } + + #[test] + fn a_recent_entry_used_again_here_moves_to_the_front() { + // Applying a font already in Recently Used Fonts moves it to the front without adding one. + let loaded = json!({"recentFonts": ["A", "B"]}); + assert_eq!(merge(&loaded, json!({"recentFonts": ["B", "A"]}), &loaded), json!({"recentFonts": ["B", "A"]})); + // Here C was used again, D opened and A removed; the other process used B again and added E. + let loaded = json!({"recent": ["a.docx", "b.docx", "c.docx"]}); + let ours = json!({"recent": ["d.docx", "c.docx", "b.docx"]}); + let disk = json!({"recent": ["e.docx", "b.docx", "a.docx", "c.docx"]}); + assert_eq!(merge(&loaded, ours, &disk), json!({"recent": ["d.docx", "c.docx", "e.docx", "b.docx"]})); + // Entries this process only kept, in the order it loaded them, don't override the file's order. + let loaded = json!({"recentSymbols": ["x", "y", "z"]}); + let ours = json!({"recentSymbols": ["w", "x", "z"]}); + let disk = json!({"recentSymbols": ["z", "x", "y"]}); + assert_eq!(merge(&loaded, ours, &disk), json!({"recentSymbols": ["w", "z", "x"]})); + } + + #[test] + fn recent_fonts_are_one_entry_whatever_their_case() { + // Recently Used Fonts ignores case (`push_recent_font`): Arial applied here as `arial` and + // there as `ARIAL` is one entry, and doesn't push a distinct font out of the ten. + let loaded = json!({"recentFonts": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "Arial"]}); + let ours = json!({"recentFonts": ["arial", "A", "B", "C", "D", "E", "F", "G", "H", "I"]}); + let disk = json!({"recentFonts": ["ARIAL", "A", "B", "C", "D", "E", "F", "G", "H", "I"]}); + assert_eq!(merge(&loaded, ours, &disk), json!({"recentFonts": ["arial", "A", "B", "C", "D", "E", "F", "G", "H", "I"]})); + // Other lists compare their entries as saved. + let loaded = json!({"recent": ["a.docx"]}); + assert_eq!(merge(&loaded, json!({"recent": ["A.docx", "a.docx"]}), &loaded), json!({"recent": ["A.docx", "a.docx"]})); + } + + #[test] + fn merged_recent_lists_keep_their_limit() { + // Recently Used Fonts keeps ten. + let loaded = json!({"recentFonts": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]}); + let ours = json!({"recentFonts": ["X", "A", "B", "C", "D", "E", "F", "G", "H", "I"]}); + let disk = json!({"recentFonts": ["Y", "A", "B", "C", "D", "E", "F", "G", "H", "I"]}); + assert_eq!(merge(&loaded, ours, &disk), json!({"recentFonts": ["X", "Y", "A", "B", "C", "D", "E", "F", "G", "H"]})); + } + + #[test] + fn a_bad_recent_entry_in_the_file_is_not_carried_forward() { + // A non-string entry makes the whole list read as empty (`options::lenient` falls back per + // setting). Merging it in would keep Recent empty in every later session; instead the + // list reads as this version reads it, and the next save heals it. + let loaded = prefs(json!({"recent": []})); + let ours = prefs(json!({"recent": ["x.docx"]})); + let disk = as_read(br#"{"recent": [{"path": "y.docx"}, "z.docx"]}"#).unwrap(); + let merged = merge(&loaded, ours, &disk); + assert_eq!(merged["recent"], json!(["x.docx"])); + assert_eq!(loaded_recent(&merged), ["x.docx"]); + // Same for recent symbols. + let ours = prefs(json!({"recentSymbols": [{"ch": "§", "font": "Arial"}]})); + let disk = as_read(r#"{"recentSymbols": [{"ch": "¶", "font": "Arial"}, 7]}"#.as_bytes()).unwrap(); + assert_eq!(reloaded(&merge(&prefs(json!({})), ours, &disk)).recent_symbols.len(), 1); + } + + /// The recent documents the next process loads. + fn loaded_recent(merged: &Value) -> Vec { + reloaded(merged).recent + } + + #[test] + fn only_keys_this_version_writes_are_kept() { + // A legacy key read once to migrate, and junk, are not written back, even from the file. + let loaded = prefs(json!({"theme": "light"})); + let disk = as_read(br#"{"theme": "light", "dark": true, "interfaceSize": 120, "junk": 1}"#).unwrap(); + let merged = merge(&loaded, loaded.clone(), &disk); + for gone in ["dark", "interfaceSize", "junk"] { + assert!(merged.get(gone).is_none(), "{gone}"); + } + assert_eq!(merged["theme"], "light"); + } + + #[test] + fn a_file_another_process_damaged_gives_way_to_ours() { + let loaded = json!({"theme": "light", "recent": ["a.docx"]}); + let ours = json!({"theme": "dark", "recent": ["a.docx"]}); + // Not preferences at all: everything comes from this process. + assert_eq!(as_read(b"\"garbage\""), None); + assert_eq!(merge(&loaded, ours.clone(), &json!("garbage")), ours); + // A list replaced by something else keeps ours. + assert_eq!(merge(&loaded, json!({"recent": ["b.docx", "a.docx"]}), &json!({"recent": 3})), json!({"recent": ["b.docx", "a.docx"]})); + } + + #[test] + fn autocorrect_entries_and_exceptions_from_both_processes_are_kept() { + let loaded = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "the"]], "exceptions": ["approx."]}}})); + // B adds an entry and an exception; A adds another entry, changes `teh`'s replacement and + // removes `approx.`. Each added entry follows the entry it was added after. + let b = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "the"], ["teh2", "the"]], "exceptions": ["approx.", "fig."]}}})); + let a = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "THE"], ["adn", "and"]], "exceptions": []}}})); + let ac = reloaded(&b_then_a(&loaded, b, a)).editing.autocorrect; + let entries: Vec<(&str, &str)> = ac.entries.iter().map(|(f, t)| (f.as_str(), t.as_str())).collect(); + assert_eq!(entries, [("teh", "THE"), ("adn", "and"), ("teh2", "the")]); + assert_eq!(ac.exceptions, ["fig."]); + } + + #[test] + fn keyboard_customisations_merge_key_by_key() { + let loaded = prefs(json!({"keyboard": {"assigned": {"Mod+Shift+K": "format.bold"}, "removed": []}})); + // B takes Ctrl+B off Bold and deletes its own Mod+Shift+K; A takes Ctrl+I off Italic and + // assigns Mod+Shift+J. + let b = prefs(json!({"keyboard": {"assigned": {}, "removed": ["Mod+B"]}})); + let a = prefs(json!({"keyboard": {"assigned": {"Mod+Shift+K": "format.bold", "Mod+Shift+J": "format.italic"}, "removed": ["Mod+I"]}})); + let keys = reloaded(&b_then_a(&loaded, b, a)).keyboard; + assert_eq!(keys.assigned.into_iter().collect::>(), [("Mod+Shift+J".to_string(), "format.italic".to_string())]); + assert_eq!(keys.removed.into_iter().collect::>(), ["Mod+B", "Mod+I"]); + } + + #[test] + fn ribbon_changes_from_both_processes_are_kept() { + // Both start from the default ribbon. B hides Draw; A adds a custom tab after Home. + let loaded = prefs(json!({})); + let b = prefs(json!({"ribbon": {"tabs": hide(default_tabs(), "Draw")}})); + let mut a_tabs = default_tabs(); + a_tabs.insert(1, json!({"name": "Mine", "custom": true})); + let a = prefs(json!({"ribbon": {"tabs": a_tabs}})); + let mut want = hide(default_tabs(), "Draw"); + want.insert(1, json!({"name": "Mine", "custom": true})); + assert_eq!(serde_json::to_value(loaded_ribbon(&b_then_a(&loaded, b, a)).tabs).unwrap(), Value::Array(want)); + } + + #[test] + fn a_toolbar_reset_by_one_process_stays_reset() { + // B resets its custom Quick Access Toolbar to the default; A, which left it alone, adds a + // custom tab. The toolbar stays the default. + let loaded = prefs(json!({"ribbon": {"qat": ["file.save", "format.bold"]}})); + let b = prefs(json!({})); + let mut a_tabs = default_tabs(); + a_tabs.push(json!({"name": "Mine", "custom": true})); + let a = prefs(json!({"ribbon": {"tabs": a_tabs, "qat": ["file.save", "format.bold"]}})); + let merged = b_then_a(&loaded, b, a); + assert!(merged["ribbon"].get("qat").is_none(), "{}", merged["ribbon"]); + let ribbon = loaded_ribbon(&merged); + assert_eq!(ribbon.qat, None); + assert!(ribbon.tabs.iter().any(|t| t.name == "Mine")); + // Two processes customizing the default toolbar: both commands, Save removed by A gone. + let loaded = prefs(json!({})); + let b = prefs(json!({"ribbon": {"qat": ["file.save", "edit.undo", "edit.redo", "format.bold"]}})); + let a = prefs(json!({"ribbon": {"qat": ["edit.undo", "edit.redo", "format.italic"]}})); + assert_eq!(loaded_ribbon(&b_then_a(&loaded, b, a)).qat.unwrap(), ["edit.undo", "edit.redo", "format.italic", "format.bold"]); + } + + /// The default ribbon tabs, as saved once the ribbon is customized. + fn default_tabs() -> Vec { + serde_json::from_value(serde_json::to_value(wordcraft_engine::RibbonLayout::default().tabs()).unwrap()).unwrap() + } + + /// `tabs` with the tab `name` hidden. + fn hide(mut tabs: Vec, name: &str) -> Vec { + for t in &mut tabs { + if t["name"] == name { + t["hidden"] = json!(true); + } + } + tabs + } + + /// The ribbon the next process loads. + fn loaded_ribbon(merged: &Value) -> wordcraft_engine::RibbonLayout { + reloaded(merged).ribbon + } + + #[test] + fn a_pane_order_changed_by_the_other_process_is_kept() { + // `paneOrder` is saved only when it isn't the default. B reorders; A leaves it alone and + // switches to dark. + let loaded = prefs(json!({})); + let order = json!(["styles", "navigation"]); + let b = prefs(json!({"paneOrder": order})); + let merged = b_then_a(&loaded, b, prefs(json!({"theme": "dark"}))); + assert_eq!((&merged["paneOrder"], &merged["theme"]), (&order, &json!("dark"))); + // B goes back to the default order; A, which loaded B's order and left it, doesn't bring + // it back. + let loaded = prefs(json!({"paneOrder": order})); + let merged = b_then_a(&loaded, prefs(json!({})), prefs(json!({"paneOrder": order, "theme": "dark"}))); + assert!(merged.get("paneOrder").is_none(), "{merged}"); + assert_eq!(merged["theme"], "dark"); + } + + #[test] + fn the_window_and_a_pane_place_are_one_setting_each() { + // A moved its window and B resized its own: the window is A's, not A's place with B's size. + let window = |x: f32, width: f32| json!({"window": {"position": [x, 10.0], "width": width, "height": 600.0, "maximized": false}}); + let loaded = prefs(window(0.0, 800.0)); + let merged = b_then_a(&loaded, prefs(window(0.0, 1000.0)), prefs(window(300.0, 800.0))); + assert_eq!(merged["window"], prefs(window(300.0, 800.0))["window"]); + } + + #[test] + fn pens_labels_and_dictionary_words_from_both_processes_are_kept() { + let pen = |color: &str| json!({"kind": "pen", "color": color, "width": 1.0}); + let loaded = prefs(json!({"inkPens": [pen("FF0000"), pen("FF0000")], "captionLabels": ["Plate"], "dictionary": ["foo", "bar"]})); + // B adds a third red pen, a label and a word; A adds a blue pen, removes `bar` and adds a + // label of its own. Identical pens stay apart, by their order. + let b = prefs( + json!({"inkPens": [pen("FF0000"), pen("FF0000"), pen("FF0000")], "captionLabels": ["Plate", "Chart"], "dictionary": ["foo", "bar", "baz"]}), + ); + let a = prefs(json!({"inkPens": [pen("FF0000"), pen("FF0000"), pen("0000FF")], "captionLabels": ["Plate", "Map"], "dictionary": ["foo"]})); + let merged = b_then_a(&loaded, b, a); + let ui = reloaded(&merged); + let colors: Vec = ui.ink_pens.iter().map(|p| serde_json::to_value(p).unwrap()["color"].as_str().unwrap().to_string()).collect(); + assert_eq!(colors, ["FF0000", "FF0000", "0000FF", "FF0000"]); + assert_eq!(ui.caption_labels, ["Plate", "Map", "Chart"]); + assert_eq!(merged["dictionary"], json!(["foo", "baz"])); + } +} diff --git a/apps/wordcraft/src/print.rs b/apps/wordcraft/src/print.rs index 9465c4485c..7b8c98ca1c 100644 --- a/apps/wordcraft/src/print.rs +++ b/apps/wordcraft/src/print.rs @@ -89,9 +89,11 @@ pub fn submit() -> Submit { Duplex::Off => craft_print::Duplex::Off, }), grayscale: settings.grayscale, + grey_pages: false, scaling: craft_print::Scaling::ShrinkToFit, title: "WordCraft document".into(), options, + driver_settings: None, }; #[cfg(not(windows))] let sent = craft_print::submit_cancellable(&bytes, &job, &mut |_, _| {}, &token).map_err(|error| error.to_string()); diff --git a/apps/wordcraft/src/print/isolated.rs b/apps/wordcraft/src/print/isolated.rs index b2463b5d92..6d89b969fb 100644 --- a/apps/wordcraft/src/print/isolated.rs +++ b/apps/wordcraft/src/print/isolated.rs @@ -15,6 +15,8 @@ use serde::{Deserialize, Serialize}; const FLAG: &str = "--wordcraft-print-worker"; const PREFIX: &str = "WORDCRAFT_PRINT:"; const MAX_MESSAGE: u64 = 64 * 1024; +/// The job's options, and a driver's settings of up to 1 MiB written as hex. +const MAX_REQUEST: u64 = MAX_MESSAGE + 2 * 1024 * 1024; const MAX_PDF: u64 = 512 * 1024 * 1024; const CANCELLED: &str = "the print job was cancelled before anything was sent to the printer"; @@ -32,9 +34,12 @@ struct Request { collate: bool, duplex: Option, grayscale: bool, + grey_pages: bool, shrink: bool, title: String, options: Vec<(String, String)>, + /// The printer the driver's settings were chosen for, and their DEVMODE as hex. + driver_settings: Option<(String, String)>, } impl Request { @@ -50,15 +55,21 @@ impl Request { craft_print::Duplex::ShortEdge => Duplex::ShortEdge, }), grayscale: job.grayscale, + grey_pages: job.grey_pages, shrink: job.scaling == craft_print::Scaling::ShrinkToFit, title: job.title.clone(), options: job.options.clone(), + driver_settings: job.driver_settings.as_ref().map(|settings| (settings.printer().to_owned(), settings.dev_mode().to_hex())), } } /// Restore the job without substituting printer defaults or changing copy semantics. - fn job(self) -> craft_print::Job { - craft_print::Job { + fn job(self) -> Result { + let driver_settings = match self.driver_settings { + Some((printer, hex)) => Some(craft_print::DriverSettings::new(printer, craft_print::rgb::DevMode::from_hex(&hex).map_err(error)?)), + None => None, + }; + Ok(craft_print::Job { printer: self.printer, copies: self.copies, collate: self.collate, @@ -68,10 +79,12 @@ impl Request { Duplex::ShortEdge => craft_print::Duplex::ShortEdge, }), grayscale: self.grayscale, + grey_pages: self.grey_pages, scaling: if self.shrink { craft_print::Scaling::ShrinkToFit } else { craft_print::Scaling::Exact }, title: self.title, options: self.options, - } + driver_settings, + }) } } @@ -166,7 +179,7 @@ impl Submission { return Err("the print PDF exceeds the 512 MiB helper limit".into()); } let request = serde_json::to_vec(&Request::from_job(job)).map_err(error)?; - if request.len() as u64 > MAX_MESSAGE { + if request.len() as u64 > MAX_REQUEST { return Err("the print settings exceed the helper message limit".into()); } let directory = tempfile::tempdir().map_err(error)?; @@ -323,10 +336,10 @@ fn helper( }) .map_err(error)?; let request: Request = - serde_json::from_slice(&bounded(std::fs::File::open(directory.join("job.json")).map_err(error)?, MAX_MESSAGE)?).map_err(error)?; + serde_json::from_slice(&bounded(std::fs::File::open(directory.join("job.json")).map_err(error)?, MAX_REQUEST)?).map_err(error)?; let pdf = bounded(std::fs::File::open(directory.join("input.pdf")).map_err(error)?, MAX_PDF)?; remove_inputs(directory)?; - let result = submit(&pdf, &request.job(), &cancel); + let result = submit(&pdf, &request.job()?, &cancel); emit(&Event::Done(result)) } @@ -463,21 +476,40 @@ mod tests { } #[test] - /// Job transport preserves every explicit setting, including Unicode and duplex direction. + /// Job transport preserves every explicit setting, including Unicode, duplex direction and the + /// driver's own settings. fn job_options_survive_the_process_boundary() { + // A DEVMODEW header of 156 bytes (`dmSize` at 68) and a 4-byte private part (`dmDriverExtra` at 70). + let mut dev_mode = vec![0u8; 160]; + dev_mode[68..70].copy_from_slice(&156u16.to_le_bytes()); + dev_mode[70..72].copy_from_slice(&4u16.to_le_bytes()); + dev_mode[156..].copy_from_slice(&[1, 2, 3, 4]); + let dev_mode = craft_print::rgb::DevMode::from_bytes(dev_mode).unwrap(); let expected = craft_print::Job { printer: Some("Office λ".into()), copies: 3, collate: false, duplex: Some(craft_print::Duplex::ShortEdge), grayscale: true, + grey_pages: true, scaling: craft_print::Scaling::ShrinkToFit, title: "A document".into(), options: vec![("media".into(), "iso_a4_210x297mm".into())], + driver_settings: Some(craft_print::DriverSettings::new("Office λ", dev_mode)), }; let bytes = serde_json::to_vec(&Request::from_job(&expected)).unwrap(); let received: Request = serde_json::from_slice(&bytes).unwrap(); - assert_eq!(received.job(), expected); + assert_eq!(received.job(), Ok(expected)); + } + + #[test] + /// Damaged driver settings on the wire are an error, not a job printed with other settings. + fn damaged_driver_settings_are_refused() { + for hex in ["", "0", "zz", "00"] { + let mut request = Request::from_job(&job()); + request.driver_settings = Some(("Office".into(), hex.into())); + assert!(request.job().is_err(), "{hex:?}"); + } } #[test] diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index e6c7f41c0c..11aeb4df7a 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -13,10 +13,12 @@ workspace = true # `zip_guard::zip64_entry_count_sample`) and the step count of # `work::count`; turned on only as a dev-dependency, so never built into # the app. -test-support = [] +test-support = ["craft-zip/test-support"] [dependencies] +craft-codepage = { workspace = true } wordcraft-geom = { workspace = true } +craft-zip = { workspace = true } base64 = { workspace = true } log = { workspace = true } serde = { workspace = true } @@ -25,4 +27,5 @@ thiserror = { workspace = true } unicode-segmentation = { workspace = true } [dev-dependencies] +craft-zip = { workspace = true, features = ["test-support"] } proptest = { workspace = true } diff --git a/crates/doc/src/chart.rs b/crates/doc/src/chart.rs index 6bbfeb8849..4132252af1 100644 --- a/crates/doc/src/chart.rs +++ b/crates/doc/src/chart.rs @@ -11,6 +11,8 @@ use serde::{Deserialize, Serialize}; +use crate::props::Rgb; + /// Most series in a chart. pub const MAX_SERIES: usize = 255; /// Most categories (points per series) in a chart. @@ -123,17 +125,119 @@ impl LegendPos { } } -/// One series: its name and a value per category (`None` = no value, a gap). +/// One series: its name, a value per category (`None` = no value, a gap) and how it is drawn: +/// fill, line, markers, smooth lines, its own data labels and number format. Unset fields follow +/// the chart's defaults. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ChartSeries { pub name: String, #[serde(default)] pub values: Vec>, + /// Fill color; `None`: the chart's accent color for the series. + #[serde(default)] + pub fill: Option, + /// "None" fill: the series draws no fill. + #[serde(default)] + pub no_fill: bool, + /// Line width in points; `None`: the chart's default. + #[serde(default)] + pub line_w: Option, + /// "None" line: the series draws no line. + #[serde(default)] + pub no_line: bool, + /// Markers on points; `None`: unset (scatter charts draw them; a saved scatter series then has + /// no `c:marker`). + #[serde(default)] + pub markers: Option, + /// Draw the line as a smooth curve. + #[serde(default)] + pub smooth: bool, + /// Data labels for this series; `None`: follow the chart's setting. + #[serde(default)] + pub labels: Option, + /// Number format of this series's labels and values; `None`: linked to the source. + #[serde(default)] + pub fmt: Option, +} + +impl ChartSeries { + /// A new series of a `kind` chart: a scatter series is drawn as markers without a line. + pub fn new(kind: ChartType, name: String, values: Vec>) -> ChartSeries { + ChartSeries { name, values, no_line: kind == ChartType::Scatter, ..Default::default() } + } +} + +/// One chart axis: title, scale bounds, tick-label number format, gridlines, tick labels and the +/// axis line. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ChartAxis { + /// `None`: no axis title; text cut to [`MAX_TEXT`] characters. + #[serde(default)] + pub title: Option, + /// Fixed lower bound; `None`: automatic. + #[serde(default)] + pub min: Option, + /// Fixed upper bound; `None`: automatic. + #[serde(default)] + pub max: Option, + /// Tick-label number format (`#,##0`, `0.00`, `0%`…); `None`: linked to the source data. + #[serde(default)] + pub fmt: Option, + /// Major gridlines drawn along this axis. + #[serde(default)] + pub gridlines: bool, + /// Tick labels; `false` hides them. + #[serde(default = "the_true")] + pub labels: bool, + /// The axis line. + #[serde(default = "the_true")] + pub line: bool, +} + +fn the_true() -> bool { + true +} + +impl Default for ChartAxis { + fn default() -> Self { + ChartAxis { title: None, min: None, max: None, fmt: None, gridlines: false, labels: true, line: true } + } +} + +/// The value axis as a new chart has it: gridlines, labels, no axis line. +pub fn value_axis() -> ChartAxis { + ChartAxis { gridlines: true, line: false, ..ChartAxis::default() } +} + +impl ChartAxis { + /// Make the axis safe to store: texts cleaned, bounds finite, `min` under `max` (an + /// impossible pair drops both), the format code cut to [`MAX_FMT`] characters. + pub fn sanitize(&mut self) { + self.title = self.title.as_deref().map(clean_text).filter(|t| !t.is_empty()); + self.min = self.min.filter(|v| v.is_finite()); + self.max = self.max.filter(|v| v.is_finite()); + if matches!((self.min, self.max), (Some(lo), Some(hi)) if lo >= hi) { + self.min = None; + self.max = None; + } + self.fmt = self.fmt.as_deref().map(clean_fmt).filter(|f| !f.is_empty()); + } +} + +/// Longest axis number format kept, characters. +pub const MAX_FMT: usize = 128; + +/// A number format code: control characters as spaces, ends trimmed, at most [`MAX_FMT`] +/// characters. +pub fn clean_fmt(s: &str) -> String { + 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::().trim_end().to_string() } /// A chart WordCraft can edit. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct ChartSpec { #[serde(rename = "type")] @@ -151,6 +255,78 @@ pub struct ChartSpec { /// Show each point's value next to it. #[serde(default)] pub data_labels: bool, + /// The category axis (scatter charts: the x axis). + #[serde(default)] + pub cat_axis: ChartAxis, + /// The value axis (scatter charts: the y axis); gridlines on and no axis line in a new chart. + #[serde(default = "value_axis")] + pub val_axis: ChartAxis, +} + +/// A [`ChartSpec`] as stored. A scatter series saved without `noLine` (by a version without +/// series formatting) is drawn as markers without a line, as that version drew it. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct StoredSpec { + #[serde(rename = "type")] + kind: ChartType, + #[serde(default)] + categories: Vec, + #[serde(default)] + series: Vec, + #[serde(default)] + title: Option, + #[serde(default)] + legend: Option, + #[serde(default)] + data_labels: bool, + #[serde(default)] + cat_axis: ChartAxis, + #[serde(default = "value_axis")] + val_axis: ChartAxis, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct StoredSeries { + #[serde(default)] + no_line: Option, + #[serde(flatten)] + series: ChartSeries, +} + +impl<'de> Deserialize<'de> for ChartSpec { + fn deserialize>(deserializer: D) -> Result { + let s = StoredSpec::deserialize(deserializer)?; + let scatter = s.kind == ChartType::Scatter; + Ok(ChartSpec { + kind: s.kind, + categories: s.categories, + series: s.series.into_iter().map(|x| ChartSeries { no_line: x.no_line.unwrap_or(scatter), ..x.series }).collect(), + title: s.title, + legend: s.legend, + data_labels: s.data_labels, + cat_axis: s.cat_axis, + val_axis: s.val_axis, + }) + } +} + +impl Default for ChartSpec { + /// An empty chart whose value axis is the one a new chart (and a missing JSON field) has: + /// gridlines on, no axis line. + fn default() -> Self { + ChartSpec { + kind: ChartType::default(), + categories: Vec::new(), + series: Vec::new(), + title: None, + legend: None, + data_labels: false, + cat_axis: ChartAxis::default(), + val_axis: value_axis(), + } + } } impl ChartSpec { @@ -168,10 +344,14 @@ impl ChartSpec { ChartSpec { kind, categories: categories.into_iter().map(str::to_string).collect(), - series: series.into_iter().map(|(n, v)| ChartSeries { name: n.to_string(), values: v.into_iter().map(Some).collect() }).collect(), + series: series.into_iter().map(|(n, v)| ChartSeries::new(kind, n.to_string(), v.into_iter().map(Some).collect())).collect(), title: None, legend: Some(LegendPos::Bottom), data_labels: false, + cat_axis: ChartAxis::default(), + // Pie and doughnut charts have no axes: their axes stay plain, so the chart reads back + // as the same model. + val_axis: if kind.is_round() { ChartAxis::default() } else { value_axis() }, } } @@ -203,8 +383,12 @@ impl ChartSpec { *v = v.filter(|x| x.is_finite()); } s.values.resize(n, None); + s.fmt = s.fmt.as_deref().map(clean_fmt).filter(|f| !f.is_empty()); + s.line_w = s.line_w.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 20.0)); } self.title = self.title.as_deref().map(clean_text).filter(|t| !t.is_empty()); + self.cat_axis.sanitize(); + self.val_axis.sanitize(); } /// The chart after `sanitize`. @@ -229,7 +413,11 @@ mod tests { let mut c = ChartSpec { categories: vec!["a".into(); MAX_POINTS + 10], series: (0..MAX_SERIES + 5) - .map(|i| ChartSeries { name: format!("{}\n{}", "x".repeat(400), i), values: vec![Some(f64::NAN), Some(f64::INFINITY), Some(1.0)] }) + .map(|i| ChartSeries { + name: format!("{}\n{}", "x".repeat(400), i), + values: vec![Some(f64::NAN), Some(f64::INFINITY), Some(1.0)], + ..Default::default() + }) .collect(), title: Some(" ".into()), ..Default::default() @@ -250,7 +438,7 @@ mod tests { fn short_categories_are_padded_to_the_longest_series() { let c = ChartSpec { categories: vec!["a".into()], - series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0), Some(2.0)] }], + series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0), Some(2.0)], ..Default::default() }], ..Default::default() } .sanitized(); @@ -258,4 +446,70 @@ mod tests { assert_eq!(ChartType::from_id("BARSTACKED"), Some(ChartType::BarStacked)); assert_eq!(LegendPos::from_id("top"), Some(LegendPos::Top)); } + + /// A scatter series stored without `noLine` reads as markers without a line; a stored value + /// and the other chart types keep theirs. + #[test] + fn stored_scatter_series_without_a_line_setting_draw_no_line() { + let read = |json: &str| -> Vec { serde_json::from_str::(json).unwrap().series.iter().map(|s| s.no_line).collect() }; + let series = r#"[{"name":"a","values":[1,null,2.5]},{"name":"b","values":[3],"noLine":false}]"#; + assert_eq!(read(&format!(r#"{{"type":"scatter","series":{series}}}"#)), [true, false]); + assert_eq!(read(&format!(r#"{{"type":"line","series":{series}}}"#)), [false, false]); + let c: ChartSpec = serde_json::from_str(&format!(r#"{{"type":"scatter","series":{series}}}"#)).unwrap(); + assert_eq!(c.series[0].values, [Some(1.0), None, Some(2.5)]); + // What this version writes reads back as itself. + for kind in ChartType::ALL { + let spec = ChartSpec::sample(kind); + assert_eq!(serde_json::from_str::(&serde_json::to_string(&spec).unwrap()).unwrap(), spec, "{kind:?}"); + } + } + + #[test] + fn default_and_missing_json_axis_fields_agree() { + let from_json: ChartSpec = serde_json::from_str(r#"{"type":"column"}"#).unwrap(); + let d = ChartSpec::default(); + assert_eq!((d.cat_axis.clone(), d.val_axis.clone()), (from_json.cat_axis, from_json.val_axis)); + assert!(d.val_axis.gridlines && !d.val_axis.line); + } + + #[test] + fn axis_bounds_and_formats_are_cleaned() { + let mut a = ChartAxis { + title: Some(" Sales\n".into()), + min: Some(f64::NAN), + max: Some(50.0), + fmt: Some("x".repeat(MAX_FMT + 40)), + gridlines: true, + labels: false, + line: true, + }; + a.sanitize(); + assert_eq!(a.title.as_deref(), Some("Sales")); + assert_eq!(a.min, None); + assert_eq!(a.max, Some(50.0)); + assert_eq!(a.fmt.as_deref().map(|f| f.chars().count()), Some(MAX_FMT)); + + // min not under max drops the pair; a format of only spaces is no format. + let mut b = ChartAxis { min: Some(50.0), max: Some(50.0), fmt: Some(" ".into()), ..Default::default() }; + b.sanitize(); + assert_eq!((b.min, b.max), (None, None)); + assert_eq!(b.fmt, None); + + let mut spec = ChartSpec { + series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0)], ..Default::default() }], + categories: vec!["a".into()], + ..Default::default() + }; + spec.series[0].line_w = Some(f32::NAN); + spec.series[0].fmt = Some("0.00".into()); + spec.sanitize(); + assert_eq!(spec.series[0].line_w, None); + assert_eq!(spec.series[0].fmt.as_deref(), Some("0.00")); + let mut spec = ChartSpec { + series: vec![ChartSeries { name: "s".into(), values: vec![], line_w: Some(100.0), ..Default::default() }], + ..Default::default() + }; + spec.sanitize(); + assert_eq!(spec.series[0].line_w, Some(20.0), "a wild width clamps to 20 pt"); + } } diff --git a/crates/doc/src/connector.rs b/crates/doc/src/connector.rs index 68602fff15..1978098d69 100644 --- a/crates/doc/src/connector.rs +++ b/crates/doc/src/connector.rs @@ -270,8 +270,11 @@ impl ShapeExtra { /// The largest rounded-rectangle corner: half the shorter side, which makes its ends round. pub const MAX_CORNER: u32 = 50_000; -/// A rounded rectangle's corner radius without its own: 16% of the shorter side. -pub const DEFAULT_CORNER: f32 = 0.16; +/// A rounded rectangle's corner radius without its own: a sixth of the shorter side, the preset's +/// default `adj` of 16667 (ECMA-376 §20.1.10.56). Measured in Word for Windows: a 300 × 100 pt +/// rounded rectangle without `adj` is drawn with corners of 16.67 pt, a 300 × 40 pt one of 6.67 +/// pt and a 60 × 150 pt one of 10 pt. +pub const DEFAULT_CORNER: f32 = 16_667.0 / 100_000.0; /// The corner radius, in points, of a `w` × `h` rounded rectangle with `corner` (see /// [`ShapeExtra::corner`]). @@ -521,7 +524,10 @@ mod tests { #[test] fn corner_radius_follows_the_shorter_side() { let near = |a: f32, b: f32| (a - b).abs() < 1e-4; - assert!(near(corner_radius(None, 200.0, 100.0), 16.0)); + assert!(near(corner_radius(None, 200.0, 100.0), 16.667)); + assert!(near(corner_radius(None, 300.0, 40.0), 6.6668)); + assert!(near(corner_radius(None, 60.0, 150.0), 10.0002)); + assert!(near(corner_radius(None, 200.0, 100.0), corner_radius(Some(16_667), 200.0, 100.0)), "the preset's default"); assert!(near(corner_radius(Some(0), 200.0, 100.0), 0.0)); assert!(near(corner_radius(Some(3_565), 100.0, 200.0), 3.565)); assert!(near(corner_radius(Some(MAX_CORNER), 200.0, 100.0), 50.0)); diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rs index 175210e031..14081425e1 100644 --- a/crates/doc/src/edit.rs +++ b/crates/doc/src/edit.rs @@ -727,9 +727,16 @@ impl Document { } /// Split the paragraph at `pos`; returns the start of the new (second) paragraph. + /// + /// A split after the first letters leaves the drop cap on the first paragraph only: the new + /// one is plain (Word: Enter makes a normal paragraph). A split at offset 0 is unchanged. + /// A drop cap that comes from a paragraph style, not the paragraph, is not cleared. pub fn split_paragraph(&mut self, pos: &Pos) -> Result { let i = pos.path.last(); - let tail = self.para_mut(pos.story, &pos.path)?.split_off(pos.off)?; + let mut tail = self.para_mut(pos.story, &pos.path)?.split_off(pos.off)?; + if pos.off > 0 { + clear_drop_cap(&mut tail.props); + } let bl = self.container_mut(pos.story, &pos.path)?; bl.insert((i + 1).min(bl.len()), para_block(tail)); Ok(Pos { story: pos.story, path: pos.path.with_last(i + 1), off: 0 }) @@ -1599,5 +1606,13 @@ impl Document { } } +/// Take the drop cap (and its options) off a paragraph's properties. +fn clear_drop_cap(props: &mut crate::props::ParaProps) { + props.drop_cap = None; + props.drop_cap_margin = None; + props.drop_cap_distance = None; + props.drop_cap_font = None; +} + #[cfg(test)] mod tests; diff --git a/crates/doc/src/edit/tests.rs b/crates/doc/src/edit/tests.rs index 0278396824..7b85dcc694 100644 --- a/crates/doc/src/edit/tests.rs +++ b/crates/doc/src/edit/tests.rs @@ -988,3 +988,38 @@ fn insert_fragment_remaps_conflicting_media_keys() { let remapped = para.objects.iter().find_map(|o| if let InlineObject::Image { media, .. } = o { Some(media.as_str()) } else { None }).unwrap(); assert_eq!(remapped, other_key); } + +/// #6788: splitting a paragraph after its first letters leaves the drop cap on the first +/// paragraph only; the new one (also when it is empty) is plain. A split at offset 0 is unchanged. +#[test] +fn split_paragraph_keeps_the_drop_cap_on_the_first_paragraph_only() { + let drop_cap = |d: &Document, i: usize| { + let p = d.body.get(i).and_then(|b| b.as_para()).map(|p| p.props.clone()).unwrap_or_default(); + (p.drop_cap, p.drop_cap_margin, p.drop_cap_distance, p.drop_cap_font) + }; + let capped = |text: &str| { + let mut d = doc(&[text]); + if let Ok(p) = d.para_mut(StoryRef::Body, &Path::top(0)) { + p.props.drop_cap = Some(3); + p.props.drop_cap_margin = Some(true); + p.props.drop_cap_distance = Some(4.0); + p.props.drop_cap_font = Some("Serif".into()); + } + d + }; + let cap = (Some(3), Some(true), Some(4.0), Some("Serif".to_string())); + let plain = (None, None, None, None); + + let mut d = capped("Sugar and knowledge"); + d.split_paragraph(&Pos::body(0, 10)).unwrap(); + assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), plain.clone())); + + let mut d = capped("Sugar"); + d.split_paragraph(&Pos::body(0, 5)).unwrap(); + assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), plain.clone())); + + // At offset 0 nothing changes: both paragraphs keep the properties, as before. + let mut d = capped("Sugar"); + d.split_paragraph(&Pos::body(0, 0)).unwrap(); + assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), cap)); +} diff --git a/crates/doc/src/encoding.rs b/crates/doc/src/encoding.rs index d6c7edda8a..658b5d51c5 100644 --- a/crates/doc/src/encoding.rs +++ b/crates/doc/src/encoding.rs @@ -1,345 +1,52 @@ -//! Windows-1252 (the byte encoding legacy Word text pieces use) and the other single-byte Windows -//! code pages RTF files name with `\ansicpg` or a font's `\fcharset` (Cyrillic 1251, Central -//! European 1250, Greek, Turkish, Hebrew, Arabic, Baltic, Vietnamese, Thai), Mac OS Roman -//! (10000, RTF `\mac`), and the East Asian multibyte code pages (932 Shift-JIS, 936 GBK, 949 UHC, -//! 950 Big5), whose bytes decode as runs rather than one at a time. +//! Legacy character decoding delegates to craft-codepage; document fallback policy stays here. +pub use craft_codepage::{ + MAC_ROMAN_CODE_PAGE, MULTIBYTE_CODE_PAGES, OEM_CODE_PAGES, SINGLE_BYTE_CODE_PAGES, cp1252, is_multibyte_code_page, multibyte_encoding_name, + oem_byte, windows_byte, +}; -/// Windows-1252 code points for 0x80..=0x9F. -const CP1252: [u16; 32] = [ - 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F, 0x0090, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178, -]; - -/// One Windows-1252 byte as a char. -pub fn cp1252(b: u8) -> char { - if (0x80..0xA0).contains(&b) { - CP1252.get((b - 0x80) as usize).and_then(|u| char::from_u32(u32::from(*u))).unwrap_or('\u{FFFD}') - } else { - b as char - } +/// Word's supported single-byte document code pages (symbol-font policy is separate). +pub fn is_byte_code_page(cp: u16) -> bool { + SINGLE_BYTE_CODE_PAGES.contains(&cp) || OEM_CODE_PAGES.contains(&cp) || cp == MAC_ROMAN_CODE_PAGE } - -/// Windows-874 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP874: [u16; 128] = [ - 0x20AC, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2026, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x0E01, 0x0E02, 0x0E03, - 0x0E04, 0x0E05, 0x0E06, 0x0E07, 0x0E08, 0x0E09, 0x0E0A, 0x0E0B, 0x0E0C, 0x0E0D, 0x0E0E, 0x0E0F, 0x0E10, 0x0E11, 0x0E12, 0x0E13, 0x0E14, 0x0E15, - 0x0E16, 0x0E17, 0x0E18, 0x0E19, 0x0E1A, 0x0E1B, 0x0E1C, 0x0E1D, 0x0E1E, 0x0E1F, 0x0E20, 0x0E21, 0x0E22, 0x0E23, 0x0E24, 0x0E25, 0x0E26, 0x0E27, - 0x0E28, 0x0E29, 0x0E2A, 0x0E2B, 0x0E2C, 0x0E2D, 0x0E2E, 0x0E2F, 0x0E30, 0x0E31, 0x0E32, 0x0E33, 0x0E34, 0x0E35, 0x0E36, 0x0E37, 0x0E38, 0x0E39, - 0x0E3A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x0E3F, 0x0E40, 0x0E41, 0x0E42, 0x0E43, 0x0E44, 0x0E45, 0x0E46, 0x0E47, 0x0E48, 0x0E49, 0x0E4A, 0x0E4B, - 0x0E4C, 0x0E4D, 0x0E4E, 0x0E4F, 0x0E50, 0x0E51, 0x0E52, 0x0E53, 0x0E54, 0x0E55, 0x0E56, 0x0E57, 0x0E58, 0x0E59, 0x0E5A, 0x0E5B, 0xFFFD, 0xFFFD, - 0xFFFD, 0xFFFD, -]; - -/// Windows-1250 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1250: [u16; 128] = [ - 0x20AC, 0xFFFD, 0x201A, 0xFFFD, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0x0160, 0x2039, 0x015A, 0x0164, 0x017D, 0x0179, 0xFFFD, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0x0161, 0x203A, 0x015B, 0x0165, 0x017E, 0x017A, 0x00A0, 0x02C7, 0x02D8, 0x0141, - 0x00A4, 0x0104, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x015E, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x017B, 0x00B0, 0x00B1, 0x02DB, 0x0142, 0x00B4, 0x00B5, - 0x00B6, 0x00B7, 0x00B8, 0x0105, 0x015F, 0x00BB, 0x013D, 0x02DD, 0x013E, 0x017C, 0x0154, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x0139, 0x0106, 0x00C7, - 0x010C, 0x00C9, 0x0118, 0x00CB, 0x011A, 0x00CD, 0x00CE, 0x010E, 0x0110, 0x0143, 0x0147, 0x00D3, 0x00D4, 0x0150, 0x00D6, 0x00D7, 0x0158, 0x016E, - 0x00DA, 0x0170, 0x00DC, 0x00DD, 0x0162, 0x00DF, 0x0155, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x013A, 0x0107, 0x00E7, 0x010D, 0x00E9, 0x0119, 0x00EB, - 0x011B, 0x00ED, 0x00EE, 0x010F, 0x0111, 0x0144, 0x0148, 0x00F3, 0x00F4, 0x0151, 0x00F6, 0x00F7, 0x0159, 0x016F, 0x00FA, 0x0171, 0x00FC, 0x00FD, - 0x0163, 0x02D9, -]; - -/// Windows-1251 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1251: [u16; 128] = [ - 0x0402, 0x0403, 0x201A, 0x0453, 0x201E, 0x2026, 0x2020, 0x2021, 0x20AC, 0x2030, 0x0409, 0x2039, 0x040A, 0x040C, 0x040B, 0x040F, 0x0452, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0x0459, 0x203A, 0x045A, 0x045C, 0x045B, 0x045F, 0x00A0, 0x040E, 0x045E, 0x0408, - 0x00A4, 0x0490, 0x00A6, 0x00A7, 0x0401, 0x00A9, 0x0404, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x0407, 0x00B0, 0x00B1, 0x0406, 0x0456, 0x0491, 0x00B5, - 0x00B6, 0x00B7, 0x0451, 0x2116, 0x0454, 0x00BB, 0x0458, 0x0405, 0x0455, 0x0457, 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, - 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, - 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B, - 0x043C, 0x043D, 0x043E, 0x043F, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, - 0x044E, 0x044F, -]; - -/// Windows-1253 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1253: [u16; 128] = [ - 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x0385, 0x0386, 0x00A3, - 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0xFFFD, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x2015, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x0384, 0x00B5, - 0x00B6, 0x00B7, 0x0388, 0x0389, 0x038A, 0x00BB, 0x038C, 0x00BD, 0x038E, 0x038F, 0x0390, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, - 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0, 0x03A1, 0xFFFD, 0x03A3, 0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9, - 0x03AA, 0x03AB, 0x03AC, 0x03AD, 0x03AE, 0x03AF, 0x03B0, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB, - 0x03BC, 0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C2, 0x03C3, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8, 0x03C9, 0x03CA, 0x03CB, 0x03CC, 0x03CD, - 0x03CE, 0xFFFD, -]; - -/// Windows-1254 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1254: [u16; 128] = [ - 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0xFFFD, 0xFFFD, 0x0178, 0x00A0, 0x00A1, 0x00A2, 0x00A3, - 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, - 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7, - 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, 0x011E, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7, 0x00D8, 0x00D9, - 0x00DA, 0x00DB, 0x00DC, 0x0130, 0x015E, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, - 0x00EC, 0x00ED, 0x00EE, 0x00EF, 0x011F, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x0131, - 0x015F, 0x00FF, -]; - -/// Windows-1255 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1255: [u16; 128] = [ - 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x00A1, 0x00A2, 0x00A3, - 0x20AA, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00D7, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, - 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00F7, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x05B0, 0x05B1, 0x05B2, 0x05B3, 0x05B4, 0x05B5, 0x05B6, 0x05B7, - 0x05B8, 0x05B9, 0x05BA, 0x05BB, 0x05BC, 0x05BD, 0x05BE, 0x05BF, 0x05C0, 0x05C1, 0x05C2, 0x05C3, 0x05F0, 0x05F1, 0x05F2, 0x05F3, 0x05F4, 0xFFFD, - 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA, 0x05DB, - 0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0xFFFD, 0xFFFD, 0x200E, - 0x200F, 0xFFFD, -]; - -/// Windows-1256 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1256: [u16; 128] = [ - 0x20AC, 0x067E, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0679, 0x2039, 0x0152, 0x0686, 0x0698, 0x0688, 0x06AF, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x06A9, 0x2122, 0x0691, 0x203A, 0x0153, 0x200C, 0x200D, 0x06BA, 0x00A0, 0x060C, 0x00A2, 0x00A3, - 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x06BE, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, - 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x061B, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x061F, 0x06C1, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, - 0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x00D7, 0x0637, 0x0638, - 0x0639, 0x063A, 0x0640, 0x0641, 0x0642, 0x0643, 0x00E0, 0x0644, 0x00E2, 0x0645, 0x0646, 0x0647, 0x0648, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, - 0x0649, 0x064A, 0x00EE, 0x00EF, 0x064B, 0x064C, 0x064D, 0x064E, 0x00F4, 0x064F, 0x0650, 0x00F7, 0x0651, 0x00F9, 0x0652, 0x00FB, 0x00FC, 0x200E, - 0x200F, 0x06D2, -]; - -/// Windows-1257 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1257: [u16; 128] = [ - 0x20AC, 0xFFFD, 0x201A, 0xFFFD, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0x00A8, 0x02C7, 0x00B8, 0xFFFD, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0x00AF, 0x02DB, 0xFFFD, 0x00A0, 0xFFFD, 0x00A2, 0x00A3, - 0x00A4, 0xFFFD, 0x00A6, 0x00A7, 0x00D8, 0x00A9, 0x0156, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00C6, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, - 0x00B6, 0x00B7, 0x00F8, 0x00B9, 0x0157, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00E6, 0x0104, 0x012E, 0x0100, 0x0106, 0x00C4, 0x00C5, 0x0118, 0x0112, - 0x010C, 0x00C9, 0x0179, 0x0116, 0x0122, 0x0136, 0x012A, 0x013B, 0x0160, 0x0143, 0x0145, 0x00D3, 0x014C, 0x00D5, 0x00D6, 0x00D7, 0x0172, 0x0141, - 0x015A, 0x016A, 0x00DC, 0x017B, 0x017D, 0x00DF, 0x0105, 0x012F, 0x0101, 0x0107, 0x00E4, 0x00E5, 0x0119, 0x0113, 0x010D, 0x00E9, 0x017A, 0x0117, - 0x0123, 0x0137, 0x012B, 0x013C, 0x0161, 0x0144, 0x0146, 0x00F3, 0x014D, 0x00F5, 0x00F6, 0x00F7, 0x0173, 0x0142, 0x015B, 0x016B, 0x00FC, 0x017C, - 0x017E, 0x02D9, -]; - -/// Windows-1258 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1258: [u16; 128] = [ - 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0xFFFD, 0x2039, 0x0152, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0xFFFD, 0x203A, 0x0153, 0xFFFD, 0xFFFD, 0x0178, 0x00A0, 0x00A1, 0x00A2, 0x00A3, - 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, - 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x00C5, 0x00C6, 0x00C7, - 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x0300, 0x00CD, 0x00CE, 0x00CF, 0x0110, 0x00D1, 0x0309, 0x00D3, 0x00D4, 0x01A0, 0x00D6, 0x00D7, 0x00D8, 0x00D9, - 0x00DA, 0x00DB, 0x00DC, 0x01AF, 0x0303, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, - 0x0301, 0x00ED, 0x00EE, 0x00EF, 0x0111, 0x00F1, 0x0323, 0x00F3, 0x00F4, 0x01A1, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x01B0, - 0x20AB, 0x00FF, -]; - -/// Mac OS Roman (code page 10000, RTF `\mac`) code points for 0x80..=0xFF, with the euro sign at -/// 0xDB (Mac OS 8.5 and later). -const MAC_ROMAN: [u16; 128] = [ - 0x00C4, 0x00C5, 0x00C7, 0x00C9, 0x00D1, 0x00D6, 0x00DC, 0x00E1, 0x00E0, 0x00E2, 0x00E4, 0x00E3, 0x00E5, 0x00E7, 0x00E9, 0x00E8, 0x00EA, 0x00EB, - 0x00ED, 0x00EC, 0x00EE, 0x00EF, 0x00F1, 0x00F3, 0x00F2, 0x00F4, 0x00F6, 0x00F5, 0x00FA, 0x00F9, 0x00FB, 0x00FC, 0x2020, 0x00B0, 0x00A2, 0x00A3, - 0x00A7, 0x2022, 0x00B6, 0x00DF, 0x00AE, 0x00A9, 0x2122, 0x00B4, 0x00A8, 0x2260, 0x00C6, 0x00D8, 0x221E, 0x00B1, 0x2264, 0x2265, 0x00A5, 0x00B5, - 0x2202, 0x2211, 0x220F, 0x03C0, 0x222B, 0x00AA, 0x00BA, 0x03A9, 0x00E6, 0x00F8, 0x00BF, 0x00A1, 0x00AC, 0x221A, 0x0192, 0x2248, 0x2206, 0x00AB, - 0x00BB, 0x2026, 0x00A0, 0x00C0, 0x00C3, 0x00D5, 0x0152, 0x0153, 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0x00F7, 0x25CA, 0x00FF, 0x0178, - 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, 0x2021, 0x00B7, 0x201A, 0x201E, 0x2030, 0x00C2, 0x00CA, 0x00C1, 0x00CB, 0x00C8, 0x00CD, 0x00CE, - 0x00CF, 0x00CC, 0x00D3, 0x00D4, 0xF8FF, 0x00D2, 0x00DA, 0x00DB, 0x00D9, 0x0131, 0x02C6, 0x02DC, 0x00AF, 0x02D8, 0x02D9, 0x02DA, 0x00B8, 0x02DD, - 0x02DB, 0x02C7, -]; -/// IBM PC (OEM) code page 437 code points for 0x80..=0xFF (the Unicode Consortium's CP437 -/// mapping file). -const CP437: [u16; 128] = [ - 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6, - 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA, - 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, - 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, - 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, - 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, - 0x221E, 0x03C6, 0x03B5, 0x2229, 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, - 0x25A0, 0x00A0, -]; - -/// OEM code page 850 (DOS Latin-1, Western European) code points for 0x80..=0xFF (the Unicode -/// Consortium's CP850 mapping file). -const CP850: [u16; 128] = [ - 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6, - 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x00D7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA, - 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, - 0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3, - 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x00F0, 0x00D0, 0x00CA, 0x00CB, 0x00C8, 0x0131, 0x00CD, 0x00CE, 0x00CF, 0x2518, - 0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0x00FE, 0x00DE, 0x00DA, 0x00DB, 0x00D9, - 0x00FD, 0x00DD, 0x00AF, 0x00B4, 0x00AD, 0x00B1, 0x2017, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, - 0x25A0, 0x00A0, -]; - -/// OEM code page 852 (DOS Latin-2, Central European) code points for 0x80..=0xFF (the Unicode Consortium's CP852 -/// mapping file). -const CP852: [u16; 128] = [ - 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x016F, 0x0107, 0x00E7, 0x0142, 0x00EB, 0x0150, 0x0151, 0x00EE, 0x0179, 0x00C4, 0x0106, 0x00C9, 0x0139, - 0x013A, 0x00F4, 0x00F6, 0x013D, 0x013E, 0x015A, 0x015B, 0x00D6, 0x00DC, 0x0164, 0x0165, 0x0141, 0x00D7, 0x010D, 0x00E1, 0x00ED, 0x00F3, 0x00FA, - 0x0104, 0x0105, 0x017D, 0x017E, 0x0118, 0x0119, 0x00AC, 0x017A, 0x010C, 0x015F, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, - 0x00C2, 0x011A, 0x015E, 0x2563, 0x2551, 0x2557, 0x255D, 0x017B, 0x017C, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x0102, 0x0103, - 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x0111, 0x0110, 0x010E, 0x00CB, 0x010F, 0x0147, 0x00CD, 0x00CE, 0x011B, 0x2518, - 0x250C, 0x2588, 0x2584, 0x0162, 0x016E, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x0143, 0x0144, 0x0148, 0x0160, 0x0161, 0x0154, 0x00DA, 0x0155, 0x0170, - 0x00FD, 0x00DD, 0x0163, 0x00B4, 0x00AD, 0x02DD, 0x02DB, 0x02C7, 0x02D8, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x02D9, 0x0171, 0x0158, 0x0159, - 0x25A0, 0x00A0, -]; - -/// OEM code page 866 (DOS Cyrillic) code points for 0x80..=0xFF (the Unicode Consortium's CP866 -/// mapping file). -const CP866: [u16; 128] = [ - 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, 0x0420, 0x0421, - 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, 0x0430, 0x0431, 0x0432, 0x0433, - 0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, - 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, - 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, - 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B, - 0x044C, 0x044D, 0x044E, 0x044F, 0x0401, 0x0451, 0x0404, 0x0454, 0x0407, 0x0457, 0x040E, 0x045E, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x2116, 0x00A4, - 0x25A0, 0x00A0, -]; - -/// OEM code page 737 (DOS Greek) code points for 0x80..=0xFF (the Unicode Consortium's CP737 -/// mapping file). -const CP737: [u16; 128] = [ - 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0, 0x03A1, 0x03A3, - 0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB, 0x03BC, - 0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C3, 0x03C2, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, - 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, - 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, - 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03C9, 0x03AC, 0x03AD, 0x03AE, 0x03CA, 0x03AF, 0x03CC, 0x03CD, 0x03CB, 0x03CE, 0x0386, 0x0388, - 0x0389, 0x038A, 0x038C, 0x038E, 0x038F, 0x00B1, 0x2265, 0x2264, 0x03AA, 0x03AB, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, - 0x25A0, 0x00A0, -]; - -/// OEM code page 857 (DOS Turkish; U+FFFD where the byte is unassigned) code points for 0x80..=0xFF (the Unicode Consortium's CP857 -/// mapping file). -const CP857: [u16; 128] = [ - 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x0131, 0x00C4, 0x00C5, 0x00C9, 0x00E6, - 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x0130, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x015E, 0x015F, 0x00E1, 0x00ED, 0x00F3, 0x00FA, - 0x00F1, 0x00D1, 0x011E, 0x011F, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, - 0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3, - 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x00BA, 0x00AA, 0x00CA, 0x00CB, 0x00C8, 0xFFFD, 0x00CD, 0x00CE, 0x00CF, 0x2518, - 0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0xFFFD, 0x00D7, 0x00DA, 0x00DB, 0x00D9, - 0x00EC, 0x00FF, 0x00AF, 0x00B4, 0x00AD, 0x00B1, 0xFFFD, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, - 0x25A0, 0x00A0, -]; - -/// The glyphs the OEM code pages show for 0x01..=0x1F (smileys, card suits, arrows), as -/// Windows' Alt+numpad entry produces them rather than the control characters. -const OEM_GLYPHS: [u16; 31] = [ - 0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C, 0x25BA, 0x25C4, 0x2195, - 0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC, -]; - -/// The OEM code pages [`oem_byte`] decodes. -pub const OEM_CODE_PAGES: [u16; 6] = [437, 737, 850, 852, 857, 866]; - -/// One byte of an OEM code page in [`OEM_CODE_PAGES`] (any other code page reads as 437) as a -/// char, with the graphic glyphs for 0x01..=0x1F and 0x7F (⌂); 0x00 stays NUL. -pub fn oem_byte(code_page: u16, b: u8) -> char { - let table: &[u16; 128] = match code_page { - 737 => &CP737, - 850 => &CP850, - 852 => &CP852, - 857 => &CP857, - 866 => &CP866, - _ => &CP437, - }; - let u = match b { - 0x01..=0x1F => OEM_GLYPHS.get(usize::from(b - 1)).copied(), - 0x7F => Some(0x2302), - 0x80..=0xFF => table.get(usize::from(b - 0x80)).copied(), - _ => Some(u16::from(b)), - }; - u.and_then(|u| char::from_u32(u32::from(u))).unwrap_or('\u{FFFD}') +/// Decode document text without applying OEM control glyphs or symbol-font remapping. +pub fn code_page_byte(cp: u16, b: u8) -> char { + if b >= 0x80 && OEM_CODE_PAGES.contains(&cp) { oem_byte(cp, b) } else { windows_byte(cp, b) } } - -/// The single-byte Windows code pages [`windows_byte`] decodes (1252 included). -pub const SINGLE_BYTE_CODE_PAGES: [u16; 10] = [874, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258]; - -/// Mac OS Roman, RTF's `\mac` character set. -pub const MAC_ROMAN_CODE_PAGE: u16 = 10000; - -/// One byte of a single-byte code page as a char: a Windows one in [`SINGLE_BYTE_CODE_PAGES`] or -/// Mac OS Roman ([`MAC_ROMAN_CODE_PAGE`]); any other code page reads as Windows-1252. -pub fn windows_byte(code_page: u16, b: u8) -> char { - let table: &[u16; 128] = match code_page { - 874 => &CP874, - 1250 => &CP1250, - 1251 => &CP1251, - 1253 => &CP1253, - 1254 => &CP1254, - 1255 => &CP1255, - 1256 => &CP1256, - 1257 => &CP1257, - 1258 => &CP1258, - MAC_ROMAN_CODE_PAGE => &MAC_ROMAN, - _ => return cp1252(b), - }; - if b < 0x80 { - return b as char; - } - table.get(usize::from(b - 0x80)).and_then(|u| char::from_u32(u32::from(*u))).unwrap_or('\u{FFFD}') +/// Whether Word's document import accepts this encoding. +pub fn is_text_code_page(cp: u16) -> bool { + is_byte_code_page(cp) || is_multibyte_code_page(cp) } - -/// Whether [`code_page_byte`] decodes `code_page`: a Windows one ([`SINGLE_BYTE_CODE_PAGES`]), an -/// OEM (DOS) one ([`OEM_CODE_PAGES`]) or Mac OS Roman. Document formats (RTF) name all three. -pub fn is_byte_code_page(code_page: u16) -> bool { - SINGLE_BYTE_CODE_PAGES.contains(&code_page) || OEM_CODE_PAGES.contains(&code_page) || code_page == MAC_ROMAN_CODE_PAGE -} - -/// A byte of 8-bit document text in `code_page` (see [`is_byte_code_page`]) as a char. Below 0x80 -/// it is ASCII in every code page (text, so an OEM page's glyphs for control codes don't apply). -pub fn code_page_byte(code_page: u16, b: u8) -> char { - if b >= 0x80 && OEM_CODE_PAGES.contains(&code_page) { oem_byte(code_page, b) } else { windows_byte(code_page, b) } -} - -/// The East Asian multibyte code pages a document format names with `\ansicpg` or a font's `\cpg`: -/// 932 Shift-JIS (Japanese), 936 GBK (Simplified Chinese), 949 UHC (Korean) and 950 Big5 -/// (Traditional Chinese). -pub const MULTIBYTE_CODE_PAGES: [u16; 4] = [932, 936, 949, 950]; - -/// Whether `code_page` is one of the East Asian multibyte code pages ([`MULTIBYTE_CODE_PAGES`]): -/// its bytes decode as a run, a lead byte together with its trail byte. -pub fn is_multibyte_code_page(code_page: u16) -> bool { - multibyte_encoding_name(code_page).is_some() -} - -/// The WHATWG encoding name of an East Asian multibyte code page (see [`MULTIBYTE_CODE_PAGES`]), -/// for `encoding_rs::Encoding::for_label`; `None` for the single-byte code pages, whose bytes -/// decode one at a time, and anything else. -pub fn multibyte_encoding_name(code_page: u16) -> Option<&'static str> { - Some(match code_page { - 932 => "shift_jis", - 936 => "gbk", - 949 => "euc-kr", - 950 => "big5", - _ => return None, - }) -} - -/// Whether a document format can name `code_page` for its text: a single-byte Windows, DOS or Mac -/// one ([`is_byte_code_page`]) or an East Asian multibyte one ([`is_multibyte_code_page`]). -pub fn is_text_code_page(code_page: u16) -> bool { - is_byte_code_page(code_page) || is_multibyte_code_page(code_page) -} - -/// The code page of an RTF or Word font charset (`\fcharset`): 204 Russian → 1251, 238 Eastern -/// European → 1250, 77 Mac → 10000, 254 PC / 255 OEM → 437, 128 Japanese → 932, 129 Korean → 949, -/// 134 Simplified Chinese → 936, 136 Traditional Chinese → 950… `None` for the ANSI and default -/// charsets (the document's code page applies) and symbol fonts. +/// Preserve Word's existing symbol-font selection policy, not the shared symbol extension. pub fn charset_code_page(charset: i32) -> Option { - Some(match charset { - 77 => MAC_ROMAN_CODE_PAGE, - 128 => 932, - 129 => 949, - 134 => 936, - 136 => 950, - 161 => 1253, - 162 => 1254, - 163 => 1258, - 177 => 1255, - 178 => 1256, - 186 => 1257, - 204 => 1251, - 222 => 874, - 238 => 1250, - 254 | 255 => 437, - _ => return None, - }) + if charset == 2 { None } else { craft_codepage::charset_code_page(charset) } +} +#[cfg(test)] +#[allow(dead_code)] +#[path = "encoding_legacy_tests.rs"] +mod legacy; +#[cfg(test)] +mod parity { + use super::*; + #[test] + fn every_supported_byte_and_fallback_matches_original() { + let pages = [0, 42, 437, 737, 850, 852, 857, 866, 874, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 10000, 9999, u16::MAX]; + for cp in pages { + for b in 0..=u8::MAX { + assert_eq!(windows_byte(cp, b), legacy::windows_byte(cp, b), "windows {cp}/{b}"); + assert_eq!(oem_byte(cp, b), legacy::oem_byte(cp, b), "oem {cp}/{b}"); + assert_eq!(code_page_byte(cp, b), legacy::code_page_byte(cp, b), "text {cp}/{b}"); + assert_eq!(cp1252(b), legacy::cp1252(b)); + } + } + for cp in 0..=u16::MAX { + assert_eq!(is_byte_code_page(cp), legacy::is_byte_code_page(cp)); + assert_eq!(is_text_code_page(cp), legacy::is_text_code_page(cp)); + assert_eq!(multibyte_encoding_name(cp), legacy::multibyte_encoding_name(cp)); + } + for charset in -1..=256 { + assert_eq!(charset_code_page(charset), legacy::charset_code_page(charset)); + } + } } #[cfg(test)] diff --git a/crates/doc/src/encoding_legacy_tests.rs b/crates/doc/src/encoding_legacy_tests.rs new file mode 100644 index 0000000000..30bef4d745 --- /dev/null +++ b/crates/doc/src/encoding_legacy_tests.rs @@ -0,0 +1,428 @@ +// Frozen pre-cutover implementation, test-only parity oracle. Original authors retained in file history. +//! Windows-1252 (the byte encoding legacy Word text pieces use) and the other single-byte Windows +//! code pages RTF files name with `\ansicpg` or a font's `\fcharset` (Cyrillic 1251, Central +//! European 1250, Greek, Turkish, Hebrew, Arabic, Baltic, Vietnamese, Thai), Mac OS Roman +//! (10000, RTF `\mac`), and the East Asian multibyte code pages (932 Shift-JIS, 936 GBK, 949 UHC, +//! 950 Big5), whose bytes decode as runs rather than one at a time. + +/// Windows-1252 code points for 0x80..=0x9F. +const CP1252: [u16; 32] = [ + 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F, 0x0090, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178, +]; + +/// One Windows-1252 byte as a char. +pub fn cp1252(b: u8) -> char { + if (0x80..0xA0).contains(&b) { + CP1252.get((b - 0x80) as usize).and_then(|u| char::from_u32(u32::from(*u))).unwrap_or('\u{FFFD}') + } else { + b as char + } +} + +/// Windows-874 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP874: [u16; 128] = [ + 0x20AC, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2026, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x0E01, 0x0E02, 0x0E03, + 0x0E04, 0x0E05, 0x0E06, 0x0E07, 0x0E08, 0x0E09, 0x0E0A, 0x0E0B, 0x0E0C, 0x0E0D, 0x0E0E, 0x0E0F, 0x0E10, 0x0E11, 0x0E12, 0x0E13, 0x0E14, 0x0E15, + 0x0E16, 0x0E17, 0x0E18, 0x0E19, 0x0E1A, 0x0E1B, 0x0E1C, 0x0E1D, 0x0E1E, 0x0E1F, 0x0E20, 0x0E21, 0x0E22, 0x0E23, 0x0E24, 0x0E25, 0x0E26, 0x0E27, + 0x0E28, 0x0E29, 0x0E2A, 0x0E2B, 0x0E2C, 0x0E2D, 0x0E2E, 0x0E2F, 0x0E30, 0x0E31, 0x0E32, 0x0E33, 0x0E34, 0x0E35, 0x0E36, 0x0E37, 0x0E38, 0x0E39, + 0x0E3A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x0E3F, 0x0E40, 0x0E41, 0x0E42, 0x0E43, 0x0E44, 0x0E45, 0x0E46, 0x0E47, 0x0E48, 0x0E49, 0x0E4A, 0x0E4B, + 0x0E4C, 0x0E4D, 0x0E4E, 0x0E4F, 0x0E50, 0x0E51, 0x0E52, 0x0E53, 0x0E54, 0x0E55, 0x0E56, 0x0E57, 0x0E58, 0x0E59, 0x0E5A, 0x0E5B, 0xFFFD, 0xFFFD, + 0xFFFD, 0xFFFD, +]; + +/// Windows-1250 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1250: [u16; 128] = [ + 0x20AC, 0xFFFD, 0x201A, 0xFFFD, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0x0160, 0x2039, 0x015A, 0x0164, 0x017D, 0x0179, 0xFFFD, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0x0161, 0x203A, 0x015B, 0x0165, 0x017E, 0x017A, 0x00A0, 0x02C7, 0x02D8, 0x0141, + 0x00A4, 0x0104, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x015E, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x017B, 0x00B0, 0x00B1, 0x02DB, 0x0142, 0x00B4, 0x00B5, + 0x00B6, 0x00B7, 0x00B8, 0x0105, 0x015F, 0x00BB, 0x013D, 0x02DD, 0x013E, 0x017C, 0x0154, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x0139, 0x0106, 0x00C7, + 0x010C, 0x00C9, 0x0118, 0x00CB, 0x011A, 0x00CD, 0x00CE, 0x010E, 0x0110, 0x0143, 0x0147, 0x00D3, 0x00D4, 0x0150, 0x00D6, 0x00D7, 0x0158, 0x016E, + 0x00DA, 0x0170, 0x00DC, 0x00DD, 0x0162, 0x00DF, 0x0155, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x013A, 0x0107, 0x00E7, 0x010D, 0x00E9, 0x0119, 0x00EB, + 0x011B, 0x00ED, 0x00EE, 0x010F, 0x0111, 0x0144, 0x0148, 0x00F3, 0x00F4, 0x0151, 0x00F6, 0x00F7, 0x0159, 0x016F, 0x00FA, 0x0171, 0x00FC, 0x00FD, + 0x0163, 0x02D9, +]; + +/// Windows-1251 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1251: [u16; 128] = [ + 0x0402, 0x0403, 0x201A, 0x0453, 0x201E, 0x2026, 0x2020, 0x2021, 0x20AC, 0x2030, 0x0409, 0x2039, 0x040A, 0x040C, 0x040B, 0x040F, 0x0452, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0x0459, 0x203A, 0x045A, 0x045C, 0x045B, 0x045F, 0x00A0, 0x040E, 0x045E, 0x0408, + 0x00A4, 0x0490, 0x00A6, 0x00A7, 0x0401, 0x00A9, 0x0404, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x0407, 0x00B0, 0x00B1, 0x0406, 0x0456, 0x0491, 0x00B5, + 0x00B6, 0x00B7, 0x0451, 0x2116, 0x0454, 0x00BB, 0x0458, 0x0405, 0x0455, 0x0457, 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, + 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, + 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B, + 0x043C, 0x043D, 0x043E, 0x043F, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, + 0x044E, 0x044F, +]; + +/// Windows-1253 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1253: [u16; 128] = [ + 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x0385, 0x0386, 0x00A3, + 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0xFFFD, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x2015, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x0384, 0x00B5, + 0x00B6, 0x00B7, 0x0388, 0x0389, 0x038A, 0x00BB, 0x038C, 0x00BD, 0x038E, 0x038F, 0x0390, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, + 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0, 0x03A1, 0xFFFD, 0x03A3, 0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9, + 0x03AA, 0x03AB, 0x03AC, 0x03AD, 0x03AE, 0x03AF, 0x03B0, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB, + 0x03BC, 0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C2, 0x03C3, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8, 0x03C9, 0x03CA, 0x03CB, 0x03CC, 0x03CD, + 0x03CE, 0xFFFD, +]; + +/// Windows-1254 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1254: [u16; 128] = [ + 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0xFFFD, 0xFFFD, 0x0178, 0x00A0, 0x00A1, 0x00A2, 0x00A3, + 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, + 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7, + 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, 0x011E, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7, 0x00D8, 0x00D9, + 0x00DA, 0x00DB, 0x00DC, 0x0130, 0x015E, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, + 0x00EC, 0x00ED, 0x00EE, 0x00EF, 0x011F, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x0131, + 0x015F, 0x00FF, +]; + +/// Windows-1255 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1255: [u16; 128] = [ + 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x00A1, 0x00A2, 0x00A3, + 0x20AA, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00D7, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, + 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00F7, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x05B0, 0x05B1, 0x05B2, 0x05B3, 0x05B4, 0x05B5, 0x05B6, 0x05B7, + 0x05B8, 0x05B9, 0x05BA, 0x05BB, 0x05BC, 0x05BD, 0x05BE, 0x05BF, 0x05C0, 0x05C1, 0x05C2, 0x05C3, 0x05F0, 0x05F1, 0x05F2, 0x05F3, 0x05F4, 0xFFFD, + 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA, 0x05DB, + 0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0xFFFD, 0xFFFD, 0x200E, + 0x200F, 0xFFFD, +]; + +/// Windows-1256 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1256: [u16; 128] = [ + 0x20AC, 0x067E, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0679, 0x2039, 0x0152, 0x0686, 0x0698, 0x0688, 0x06AF, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x06A9, 0x2122, 0x0691, 0x203A, 0x0153, 0x200C, 0x200D, 0x06BA, 0x00A0, 0x060C, 0x00A2, 0x00A3, + 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x06BE, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, + 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x061B, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x061F, 0x06C1, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, + 0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x00D7, 0x0637, 0x0638, + 0x0639, 0x063A, 0x0640, 0x0641, 0x0642, 0x0643, 0x00E0, 0x0644, 0x00E2, 0x0645, 0x0646, 0x0647, 0x0648, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, + 0x0649, 0x064A, 0x00EE, 0x00EF, 0x064B, 0x064C, 0x064D, 0x064E, 0x00F4, 0x064F, 0x0650, 0x00F7, 0x0651, 0x00F9, 0x0652, 0x00FB, 0x00FC, 0x200E, + 0x200F, 0x06D2, +]; + +/// Windows-1257 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1257: [u16; 128] = [ + 0x20AC, 0xFFFD, 0x201A, 0xFFFD, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0x00A8, 0x02C7, 0x00B8, 0xFFFD, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0x00AF, 0x02DB, 0xFFFD, 0x00A0, 0xFFFD, 0x00A2, 0x00A3, + 0x00A4, 0xFFFD, 0x00A6, 0x00A7, 0x00D8, 0x00A9, 0x0156, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00C6, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, + 0x00B6, 0x00B7, 0x00F8, 0x00B9, 0x0157, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00E6, 0x0104, 0x012E, 0x0100, 0x0106, 0x00C4, 0x00C5, 0x0118, 0x0112, + 0x010C, 0x00C9, 0x0179, 0x0116, 0x0122, 0x0136, 0x012A, 0x013B, 0x0160, 0x0143, 0x0145, 0x00D3, 0x014C, 0x00D5, 0x00D6, 0x00D7, 0x0172, 0x0141, + 0x015A, 0x016A, 0x00DC, 0x017B, 0x017D, 0x00DF, 0x0105, 0x012F, 0x0101, 0x0107, 0x00E4, 0x00E5, 0x0119, 0x0113, 0x010D, 0x00E9, 0x017A, 0x0117, + 0x0123, 0x0137, 0x012B, 0x013C, 0x0161, 0x0144, 0x0146, 0x00F3, 0x014D, 0x00F5, 0x00F6, 0x00F7, 0x0173, 0x0142, 0x015B, 0x016B, 0x00FC, 0x017C, + 0x017E, 0x02D9, +]; + +/// Windows-1258 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1258: [u16; 128] = [ + 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0xFFFD, 0x2039, 0x0152, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0xFFFD, 0x203A, 0x0153, 0xFFFD, 0xFFFD, 0x0178, 0x00A0, 0x00A1, 0x00A2, 0x00A3, + 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, + 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x00C5, 0x00C6, 0x00C7, + 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x0300, 0x00CD, 0x00CE, 0x00CF, 0x0110, 0x00D1, 0x0309, 0x00D3, 0x00D4, 0x01A0, 0x00D6, 0x00D7, 0x00D8, 0x00D9, + 0x00DA, 0x00DB, 0x00DC, 0x01AF, 0x0303, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, + 0x0301, 0x00ED, 0x00EE, 0x00EF, 0x0111, 0x00F1, 0x0323, 0x00F3, 0x00F4, 0x01A1, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x01B0, + 0x20AB, 0x00FF, +]; + +/// Mac OS Roman (code page 10000, RTF `\mac`) code points for 0x80..=0xFF, with the euro sign at +/// 0xDB (Mac OS 8.5 and later). +const MAC_ROMAN: [u16; 128] = [ + 0x00C4, 0x00C5, 0x00C7, 0x00C9, 0x00D1, 0x00D6, 0x00DC, 0x00E1, 0x00E0, 0x00E2, 0x00E4, 0x00E3, 0x00E5, 0x00E7, 0x00E9, 0x00E8, 0x00EA, 0x00EB, + 0x00ED, 0x00EC, 0x00EE, 0x00EF, 0x00F1, 0x00F3, 0x00F2, 0x00F4, 0x00F6, 0x00F5, 0x00FA, 0x00F9, 0x00FB, 0x00FC, 0x2020, 0x00B0, 0x00A2, 0x00A3, + 0x00A7, 0x2022, 0x00B6, 0x00DF, 0x00AE, 0x00A9, 0x2122, 0x00B4, 0x00A8, 0x2260, 0x00C6, 0x00D8, 0x221E, 0x00B1, 0x2264, 0x2265, 0x00A5, 0x00B5, + 0x2202, 0x2211, 0x220F, 0x03C0, 0x222B, 0x00AA, 0x00BA, 0x03A9, 0x00E6, 0x00F8, 0x00BF, 0x00A1, 0x00AC, 0x221A, 0x0192, 0x2248, 0x2206, 0x00AB, + 0x00BB, 0x2026, 0x00A0, 0x00C0, 0x00C3, 0x00D5, 0x0152, 0x0153, 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0x00F7, 0x25CA, 0x00FF, 0x0178, + 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, 0x2021, 0x00B7, 0x201A, 0x201E, 0x2030, 0x00C2, 0x00CA, 0x00C1, 0x00CB, 0x00C8, 0x00CD, 0x00CE, + 0x00CF, 0x00CC, 0x00D3, 0x00D4, 0xF8FF, 0x00D2, 0x00DA, 0x00DB, 0x00D9, 0x0131, 0x02C6, 0x02DC, 0x00AF, 0x02D8, 0x02D9, 0x02DA, 0x00B8, 0x02DD, + 0x02DB, 0x02C7, +]; +/// IBM PC (OEM) code page 437 code points for 0x80..=0xFF (the Unicode Consortium's CP437 +/// mapping file). +const CP437: [u16; 128] = [ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6, + 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA, + 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, + 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, + 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, + 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, + 0x221E, 0x03C6, 0x03B5, 0x2229, 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, + 0x25A0, 0x00A0, +]; + +/// OEM code page 850 (DOS Latin-1, Western European) code points for 0x80..=0xFF (the Unicode +/// Consortium's CP850 mapping file). +const CP850: [u16; 128] = [ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6, + 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x00D7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA, + 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, + 0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3, + 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x00F0, 0x00D0, 0x00CA, 0x00CB, 0x00C8, 0x0131, 0x00CD, 0x00CE, 0x00CF, 0x2518, + 0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0x00FE, 0x00DE, 0x00DA, 0x00DB, 0x00D9, + 0x00FD, 0x00DD, 0x00AF, 0x00B4, 0x00AD, 0x00B1, 0x2017, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, + 0x25A0, 0x00A0, +]; + +/// OEM code page 852 (DOS Latin-2, Central European) code points for 0x80..=0xFF (the Unicode Consortium's CP852 +/// mapping file). +const CP852: [u16; 128] = [ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x016F, 0x0107, 0x00E7, 0x0142, 0x00EB, 0x0150, 0x0151, 0x00EE, 0x0179, 0x00C4, 0x0106, 0x00C9, 0x0139, + 0x013A, 0x00F4, 0x00F6, 0x013D, 0x013E, 0x015A, 0x015B, 0x00D6, 0x00DC, 0x0164, 0x0165, 0x0141, 0x00D7, 0x010D, 0x00E1, 0x00ED, 0x00F3, 0x00FA, + 0x0104, 0x0105, 0x017D, 0x017E, 0x0118, 0x0119, 0x00AC, 0x017A, 0x010C, 0x015F, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, + 0x00C2, 0x011A, 0x015E, 0x2563, 0x2551, 0x2557, 0x255D, 0x017B, 0x017C, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x0102, 0x0103, + 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x0111, 0x0110, 0x010E, 0x00CB, 0x010F, 0x0147, 0x00CD, 0x00CE, 0x011B, 0x2518, + 0x250C, 0x2588, 0x2584, 0x0162, 0x016E, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x0143, 0x0144, 0x0148, 0x0160, 0x0161, 0x0154, 0x00DA, 0x0155, 0x0170, + 0x00FD, 0x00DD, 0x0163, 0x00B4, 0x00AD, 0x02DD, 0x02DB, 0x02C7, 0x02D8, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x02D9, 0x0171, 0x0158, 0x0159, + 0x25A0, 0x00A0, +]; + +/// OEM code page 866 (DOS Cyrillic) code points for 0x80..=0xFF (the Unicode Consortium's CP866 +/// mapping file). +const CP866: [u16; 128] = [ + 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, 0x0420, 0x0421, + 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, 0x0430, 0x0431, 0x0432, 0x0433, + 0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, + 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, + 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, + 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B, + 0x044C, 0x044D, 0x044E, 0x044F, 0x0401, 0x0451, 0x0404, 0x0454, 0x0407, 0x0457, 0x040E, 0x045E, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x2116, 0x00A4, + 0x25A0, 0x00A0, +]; + +/// OEM code page 737 (DOS Greek) code points for 0x80..=0xFF (the Unicode Consortium's CP737 +/// mapping file). +const CP737: [u16; 128] = [ + 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0, 0x03A1, 0x03A3, + 0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB, 0x03BC, + 0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C3, 0x03C2, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, + 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, + 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, + 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03C9, 0x03AC, 0x03AD, 0x03AE, 0x03CA, 0x03AF, 0x03CC, 0x03CD, 0x03CB, 0x03CE, 0x0386, 0x0388, + 0x0389, 0x038A, 0x038C, 0x038E, 0x038F, 0x00B1, 0x2265, 0x2264, 0x03AA, 0x03AB, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, + 0x25A0, 0x00A0, +]; + +/// OEM code page 857 (DOS Turkish; U+FFFD where the byte is unassigned) code points for 0x80..=0xFF (the Unicode Consortium's CP857 +/// mapping file). +const CP857: [u16; 128] = [ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x0131, 0x00C4, 0x00C5, 0x00C9, 0x00E6, + 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x0130, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x015E, 0x015F, 0x00E1, 0x00ED, 0x00F3, 0x00FA, + 0x00F1, 0x00D1, 0x011E, 0x011F, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, + 0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3, + 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x00BA, 0x00AA, 0x00CA, 0x00CB, 0x00C8, 0xFFFD, 0x00CD, 0x00CE, 0x00CF, 0x2518, + 0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0xFFFD, 0x00D7, 0x00DA, 0x00DB, 0x00D9, + 0x00EC, 0x00FF, 0x00AF, 0x00B4, 0x00AD, 0x00B1, 0xFFFD, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, + 0x25A0, 0x00A0, +]; + +/// The glyphs the OEM code pages show for 0x01..=0x1F (smileys, card suits, arrows), as +/// Windows' Alt+numpad entry produces them rather than the control characters. +const OEM_GLYPHS: [u16; 31] = [ + 0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C, 0x25BA, 0x25C4, 0x2195, + 0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC, +]; + +/// The OEM code pages [`oem_byte`] decodes. +pub const OEM_CODE_PAGES: [u16; 6] = [437, 737, 850, 852, 857, 866]; + +/// One byte of an OEM code page in [`OEM_CODE_PAGES`] (any other code page reads as 437) as a +/// char, with the graphic glyphs for 0x01..=0x1F and 0x7F (⌂); 0x00 stays NUL. +pub fn oem_byte(code_page: u16, b: u8) -> char { + let table: &[u16; 128] = match code_page { + 737 => &CP737, + 850 => &CP850, + 852 => &CP852, + 857 => &CP857, + 866 => &CP866, + _ => &CP437, + }; + let u = match b { + 0x01..=0x1F => OEM_GLYPHS.get(usize::from(b - 1)).copied(), + 0x7F => Some(0x2302), + 0x80..=0xFF => table.get(usize::from(b - 0x80)).copied(), + _ => Some(u16::from(b)), + }; + u.and_then(|u| char::from_u32(u32::from(u))).unwrap_or('\u{FFFD}') +} + +/// The single-byte Windows code pages [`windows_byte`] decodes (1252 included). +pub const SINGLE_BYTE_CODE_PAGES: [u16; 10] = [874, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258]; + +/// Mac OS Roman, RTF's `\mac` character set. +pub const MAC_ROMAN_CODE_PAGE: u16 = 10000; + +/// One byte of a single-byte code page as a char: a Windows one in [`SINGLE_BYTE_CODE_PAGES`] or +/// Mac OS Roman ([`MAC_ROMAN_CODE_PAGE`]); any other code page reads as Windows-1252. +pub fn windows_byte(code_page: u16, b: u8) -> char { + let table: &[u16; 128] = match code_page { + 874 => &CP874, + 1250 => &CP1250, + 1251 => &CP1251, + 1253 => &CP1253, + 1254 => &CP1254, + 1255 => &CP1255, + 1256 => &CP1256, + 1257 => &CP1257, + 1258 => &CP1258, + MAC_ROMAN_CODE_PAGE => &MAC_ROMAN, + _ => return cp1252(b), + }; + if b < 0x80 { + return b as char; + } + table.get(usize::from(b - 0x80)).and_then(|u| char::from_u32(u32::from(*u))).unwrap_or('\u{FFFD}') +} + +/// Whether [`code_page_byte`] decodes `code_page`: a Windows one ([`SINGLE_BYTE_CODE_PAGES`]), an +/// OEM (DOS) one ([`OEM_CODE_PAGES`]) or Mac OS Roman. Document formats (RTF) name all three. +pub fn is_byte_code_page(code_page: u16) -> bool { + SINGLE_BYTE_CODE_PAGES.contains(&code_page) || OEM_CODE_PAGES.contains(&code_page) || code_page == MAC_ROMAN_CODE_PAGE +} + +/// A byte of 8-bit document text in `code_page` (see [`is_byte_code_page`]) as a char. Below 0x80 +/// it is ASCII in every code page (text, so an OEM page's glyphs for control codes don't apply). +pub fn code_page_byte(code_page: u16, b: u8) -> char { + if b >= 0x80 && OEM_CODE_PAGES.contains(&code_page) { oem_byte(code_page, b) } else { windows_byte(code_page, b) } +} + +/// The East Asian multibyte code pages a document format names with `\ansicpg` or a font's `\cpg`: +/// 932 Shift-JIS (Japanese), 936 GBK (Simplified Chinese), 949 UHC (Korean) and 950 Big5 +/// (Traditional Chinese). +pub const MULTIBYTE_CODE_PAGES: [u16; 4] = [932, 936, 949, 950]; + +/// Whether `code_page` is one of the East Asian multibyte code pages ([`MULTIBYTE_CODE_PAGES`]): +/// its bytes decode as a run, a lead byte together with its trail byte. +pub fn is_multibyte_code_page(code_page: u16) -> bool { + multibyte_encoding_name(code_page).is_some() +} + +/// The WHATWG encoding name of an East Asian multibyte code page (see [`MULTIBYTE_CODE_PAGES`]), +/// for `encoding_rs::Encoding::for_label`; `None` for the single-byte code pages, whose bytes +/// decode one at a time, and anything else. +pub fn multibyte_encoding_name(code_page: u16) -> Option<&'static str> { + Some(match code_page { + 932 => "shift_jis", + 936 => "gbk", + 949 => "euc-kr", + 950 => "big5", + _ => return None, + }) +} + +/// Whether a document format can name `code_page` for its text: a single-byte Windows, DOS or Mac +/// one ([`is_byte_code_page`]) or an East Asian multibyte one ([`is_multibyte_code_page`]). +pub fn is_text_code_page(code_page: u16) -> bool { + is_byte_code_page(code_page) || is_multibyte_code_page(code_page) +} + +/// The code page of an RTF or Word font charset (`\fcharset`): 204 Russian → 1251, 238 Eastern +/// European → 1250, 77 Mac → 10000, 254 PC / 255 OEM → 437, 128 Japanese → 932, 129 Korean → 949, +/// 134 Simplified Chinese → 936, 136 Traditional Chinese → 950… `None` for the ANSI and default +/// charsets (the document's code page applies) and symbol fonts. +pub fn charset_code_page(charset: i32) -> Option { + Some(match charset { + 77 => MAC_ROMAN_CODE_PAGE, + 128 => 932, + 129 => 949, + 134 => 936, + 136 => 950, + 161 => 1253, + 162 => 1254, + 163 => 1258, + 177 => 1255, + 178 => 1256, + 186 => 1257, + 204 => 1251, + 222 => 874, + 238 => 1250, + 254 | 255 => 437, + _ => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn single_byte_code_pages() { + let decode = |cp: u16, bytes: &[u8]| bytes.iter().map(|&b| windows_byte(cp, b)).collect::(); + assert_eq!(decode(1251, &[0xD1, 0xF7, 0xE5, 0xF2, 0x20, 0xB9]), "Счет №"); + assert_eq!(decode(1251, &[0xA8, 0xB8]), "Ёё"); + assert_eq!(decode(1250, &[0xA3, 0xF3, 0x9F]), "Łóź"); + assert_eq!(decode(1253, &[0xC1, 0xE2]), "Αβ"); + assert_eq!(decode(1252, &[0x80, 0xE9]), "€é"); + assert_eq!(decode(9999, &[0xE9]), "é"); + // Mac OS Roman (#1653): accents, the euro sign at 0xDB, typographic quotes. + assert_eq!(decode(10000, &[0x80, 0x8E, 0xDB, 0xF1, 0xF2, 0xF3, 0xD2, 0xD3, 0x41]), "Äé€ÒÚÛ“”A"); + assert_eq!(charset_code_page(77), Some(10000)); + assert_eq!(charset_code_page(254), Some(437)); + assert_eq!(charset_code_page(255), Some(437)); + assert_eq!(charset_code_page(204), Some(1251)); + assert_eq!(charset_code_page(0), None); + for cp in SINGLE_BYTE_CODE_PAGES { + for b in 0..=255u8 { + let _ = windows_byte(cp, b); + } + } + } + + #[test] + fn windows_1255_holam_haser_for_vav() { + assert_eq!(windows_byte(1255, 0xCA), '\u{05BA}'); + } + + /// #1653: one decoder for document text in any code page RTF names: Windows, DOS or Mac. + #[test] + fn document_text_in_windows_dos_and_mac_code_pages() { + let decode = |cp: u16, bytes: &[u8]| bytes.iter().map(|&b| code_page_byte(cp, b)).collect::(); + assert_eq!(decode(437, &[0x82, 0xA0, 0x41, 0x01]), "éáA\u{1}", "DOS text; ASCII stays ASCII"); + assert_eq!(decode(850, &[0x9D, 0xE9]), "ØÚ"); + assert_eq!(decode(10000, &[0x8E]), "é"); + assert_eq!(decode(1251, &[0xC4]), "Д"); + for cp in [437, 850, 866, 1250, 1252, 10000] { + assert!(is_byte_code_page(cp), "{cp}"); + } + assert!(!is_byte_code_page(932) && !is_byte_code_page(0) && !SINGLE_BYTE_CODE_PAGES.contains(&10000)); + } + + /// #1653: the East Asian charsets and code pages RTF names are multibyte: their bytes decode + /// as runs (a lead byte and its trail byte together), not one at a time. + #[test] + fn east_asian_code_pages_are_multibyte() { + assert_eq!(charset_code_page(128), Some(932), "Japanese"); + assert_eq!(charset_code_page(129), Some(949), "Korean"); + assert_eq!(charset_code_page(134), Some(936), "Simplified Chinese"); + assert_eq!(charset_code_page(136), Some(950), "Traditional Chinese"); + assert_eq!(charset_code_page(255), Some(437), "OEM is single-byte"); + assert_eq!(MULTIBYTE_CODE_PAGES, [932, 936, 949, 950]); + for cp in MULTIBYTE_CODE_PAGES { + assert!(is_multibyte_code_page(cp) && is_text_code_page(cp), "{cp}"); + assert!(!is_byte_code_page(cp) && !SINGLE_BYTE_CODE_PAGES.contains(&cp), "{cp}"); + assert!(multibyte_encoding_name(cp).is_some(), "{cp}"); + } + assert!(is_text_code_page(1251) && is_text_code_page(437) && is_text_code_page(10000)); + assert!(!is_text_code_page(0) && !is_text_code_page(9999)); + } + + #[test] + fn oem_code_pages() { + let decode = |cp: u16, bytes: &[u8]| bytes.iter().map(|&b| oem_byte(cp, b)).collect::(); + assert_eq!(decode(437, &[0x82, 0xE9, 0x01, 0x7F]), "éΘ☺⌂"); + assert_eq!(decode(850, &[0x9B, 0xE9]), "øÚ"); + assert_eq!(decode(852, &[0xA5, 0x88, 0xBE, 0xA9]), "ąłżę"); + assert_eq!(decode(866, &[0x8F, 0xE0, 0xA8, 0xA2, 0xA5, 0xE2, 0xF0, 0xFC]), "ПриветЁ№"); + assert_eq!(decode(737, &[0x80, 0x99, 0xE0]), "Αβω"); + assert_eq!(decode(857, &[0x8D, 0x98, 0xA6, 0x9F]), "ıİĞş"); + assert_eq!(oem_byte(857, 0xD5), '\u{FFFD}', "unassigned in 857"); + assert_eq!(decode(9999, &[0xE9]), "Θ", "unknown pages read as 437"); + for cp in OEM_CODE_PAGES { + for b in 0..=255u8 { + let _ = oem_byte(cp, b); + } + } + } +} diff --git a/crates/doc/src/graphic.rs b/crates/doc/src/graphic.rs index f0e87b52de..8efa0abc16 100644 --- a/crates/doc/src/graphic.rs +++ b/crates/doc/src/graphic.rs @@ -127,6 +127,10 @@ pub enum GraphicItem { align: TextAlign, #[serde(default)] font: Option, + /// Degrees clockwise the text turns about `rect`'s center as it is drawn (a chart's vertical + /// axis title is turned -90°). + #[serde(default)] + angle: f32, }, /// A picture (`Document::media` key) stretched into `rect`. Image { rect: [f32; 4], media: String }, diff --git a/crates/doc/src/math.rs b/crates/doc/src/math.rs index adf66a6236..568bd1c668 100644 --- a/crates/doc/src/math.rs +++ b/crates/doc/src/math.rs @@ -610,11 +610,12 @@ fn lin_node(n: &MNode, s: &mut String, depth: usize) { } MNode::Nary { chr, sub_hide, sup_hide, sub, sup, e, .. } => { s.push(*chr); - if !sub_hide && !sub.is_empty() { + // A shown limit is written even when empty (`_()`): left out, it reads back hidden (#6076). + if !sub_hide { s.push('_'); lin_script(sub, s, depth); } - if !sup_hide && !sup.is_empty() { + if !sup_hide { s.push('^'); lin_script(sup, s, depth); } diff --git a/crates/doc/src/settings.rs b/crates/doc/src/settings.rs index 3dd38116c7..1fd4e598dd 100644 --- a/crates/doc/src/settings.rs +++ b/crates/doc/src/settings.rs @@ -80,6 +80,8 @@ pub struct Settings { pub default_tab: f32, pub even_odd_headers: bool, pub mirror_margins: bool, + /// The gutter is added to the top margin instead of the left one (`w:gutterAtTop`). + pub gutter_at_top: bool, pub auto_hyphenation: bool, /// Hyphenation zone (`w:hyphenationZone`), points: a line is hyphenated only when breaking /// it at a word boundary would leave more than this empty at its end. @@ -126,6 +128,15 @@ pub struct Settings { /// draws one that isn't installed in a serif face. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub roman_fonts: Vec, + /// Fonts the font table classes as modern (fixed pitch, `w:family w:val="modern"`): Word draws + /// one that isn't installed, and whose alternate isn't either, in a serif face (#2702). Not + /// the East Asian ones (`w:charset` 80, 81, 86, 88: MS Gothic, SimHei…). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub modern_fonts: Vec, + /// Alternate names the document's font table gives its fonts (`w:font/w:altName`), as (font, + /// alternate): Word draws a font that isn't installed in its alternate when that one is. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub font_alt_names: Vec<(String, String)>, /// `w:doNotUseHTMLParagraphAutoSpacing`: the space between two paragraphs is the first's space /// after plus the second's space before, not the larger of the two. #[serde(default, skip_serializing_if = "std::ops::Not::not")] @@ -137,6 +148,12 @@ pub struct Settings { /// Keep contextual paragraph spacing inside legacy table cells (`allowSpaceOfSameStyleInTable`). /// Word ignores the layout override in compatibility mode 15, but the flag still round-trips. pub allow_space_of_same_style_in_table: bool, + /// `w:doNotSuppressIndentation` (a `.doc`'s `Copts.fWW11IndentRules`): Word 2003's indent + /// rules beside floating objects. An unnumbered paragraph's line starts right after a floating + /// object before it on the line, its own indent ignored (ECMA-376 Part 4 §14.8.3.12). Word 2013's + /// layout (compatibility mode 15) does not use it. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub do_not_suppress_indentation: bool, /// Drawing grid spacing in points, across and down (View › Gridlines); ECMA-376's default is 1/8 inch. pub grid_h: f32, pub grid_v: f32, @@ -296,6 +313,7 @@ impl Default for Settings { default_tab: 36.0, even_odd_headers: false, mirror_margins: false, + gutter_at_top: false, auto_hyphenation: false, hyphenation_zone: DEFAULT_HYPHENATION_ZONE, hyphenate_caps: true, @@ -316,9 +334,12 @@ impl Default for Settings { protect_hash: Vec::new(), compat_mode: COMPAT_MODE_CURRENT, roman_fonts: Vec::new(), + modern_fonts: Vec::new(), + font_alt_names: Vec::new(), sum_paragraph_spacing: false, do_not_expand_shift_return: false, allow_space_of_same_style_in_table: false, + do_not_suppress_indentation: false, grid_h: DEFAULT_GRID, grid_v: DEFAULT_GRID, math: None, diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 088bd3bd2c..43cdedcb44 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -144,6 +144,7 @@ fn parts_and_media() { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn many_distinct_media_add_in_linear_time() { // An import with tens of thousands of small distinct images (same length, differing only at // the end) used to compare each against every earlier one. @@ -645,6 +646,7 @@ fn para_of_objects(objs: Vec) -> Paragraph { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn object_walks_are_linear_in_the_paragraph() { // #3614: loops of object_offsets + object_at recounted the objects before each one, so a // paragraph of 40,000 markers took seconds per walk. @@ -691,6 +693,7 @@ fn object_walks_are_linear_in_the_paragraph() { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn deleting_across_many_lone_control_markers_is_not_quadratic() { // A millisecond now; the old delete took 18 s at 1,500 markers and 114 s at 3,000. let n = 3_000; @@ -725,6 +728,7 @@ fn control_markers_kept_are_sorted() { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn lone_table_open_markers_linear_time() { let mut d = Document::new(); let mut t = Table::new(1, 1, 100.0); diff --git a/crates/doc/src/wrap.rs b/crates/doc/src/wrap.rs index 1c235d73e4..ef4b0d9a86 100644 --- a/crates/doc/src/wrap.rs +++ b/crates/doc/src/wrap.rs @@ -265,10 +265,10 @@ mod tests { } assert!(shape_outline(ShapeKind::Rectangle, 10.0, 10.0, None).is_none()); // The end of the bottom-right corner: in the frame's corner when the corner is square, - // 16% of the height (8 of 100 wide) in from it by default. + // a sixth of the height (8.33 of 100 wide) in from it by default. let corner_pt = |corner| shape_outline(ShapeKind::RoundedRectangle, 100.0, 50.0, corner).unwrap()[6]; assert!(corner_pt(Some(0)).0 > 0.999 && corner_pt(Some(0)).1 > 0.999, "{:?}", corner_pt(Some(0))); - assert!((corner_pt(None).0 - 0.92).abs() < 0.001, "{:?}", corner_pt(None)); + assert!((corner_pt(None).0 - 0.916_67).abs() < 0.0001, "{:?}", corner_pt(None)); } #[test] diff --git a/crates/doc/src/zip_guard.rs b/crates/doc/src/zip_guard.rs index 0610cac1e3..b6364c5bac 100644 --- a/crates/doc/src/zip_guard.rs +++ b/crates/doc/src/zip_guard.rs @@ -1,131 +1,21 @@ -//! A bytes-only check of a ZIP package's declared entry count before the `zip` crate opens it -//! (#3660). Every reader of `.docx`, `.odt` and spreadsheet packages calls [`check`] first. -//! -//! `zip::ZipArchive::new` reserves room for, and parses, as many central directory headers as the -//! end record declares before its caller can look at `len()`. A ZIP64 end record can declare -//! millions of entries for a file of a few hundred megabytes (only 46 bytes each have to fit), and -//! each parsed entry costs several times that in memory. Here the end records are found the way -//! `zip` finds them (APPNOTE.TXT §4.3.14 to §4.3.16), and a package declaring more than the -//! reader's limit is refused before `zip` parses anything. Anything else that is wrong is left for -//! `zip` to report. - -const EOCD: &[u8; 4] = b"PK\x05\x06"; -const EOCD64_LOCATOR: &[u8; 4] = b"PK\x06\x07"; -const EOCD64: &[u8; 4] = b"PK\x06\x06"; -const CENTRAL_HEADER: &[u8; 4] = b"PK\x01\x02"; - -/// End records looked at, at most. A package has one; a few more can turn up inside stored data. -const MAX_END_RECORDS: usize = 16; +//! A bytes-only check of a ZIP package's declared entry count, run before anything opens the ZIP +//! (#3660). The logic lives in `craft-zip`; this wraps its error as a `String`. /// Refuse `bytes` when the end record `zip` would use declares more than `max_entries` entries. -/// -/// `zip` searches the file backwards for an end of central directory record. A ZIP64 one points -/// through its locator at the ZIP64 end record, which `zip` looks for from the locator's offset -/// on: every such record there is checked, and as `zip` may fall back to an earlier end record -/// when one doesn't parse, the search goes on. A plain one is used when it declares no entries, or -/// a central directory header lies between its directory offset and itself: it is the last one -/// looked at. pub fn check(bytes: &[u8], max_entries: u64) -> Result<(), String> { - let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); - let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); - let u64_at = |at: usize| bytes.get(at..at.checked_add(8)?).and_then(|b| <[u8; 8]>::try_from(b).ok()).map(u64::from_le_bytes); - let refuse = |n: u64| -> Result<(), String> { - if n > max_entries { Err(format!("the package declares {n} entries, more than {max_entries}")) } else { Ok(()) } - }; - let mut end = bytes.len(); - let mut seen = 0; - while let Some(at) = bytes.get(..end).and_then(|b| b.windows(4).rposition(|w| w == EOCD)) { - end = at; - seen += 1; - if seen > MAX_END_RECORDS { - return Err(format!("more than {MAX_END_RECORDS} end of central directory records")); - } - // `zip` skips a record whose comment runs past the end of the file. - let Some(comment) = u16_at(at + 20) else { continue }; - if at + 22 + usize::from(comment) > bytes.len() { - continue; - } - let (Some(on_disk), Some(total), Some(cd_offset)) = (u16_at(at + 8), u16_at(at + 10), u32_at(at + 16)) else { continue }; - let zip64 = total == u16::MAX || cd_offset == u32::MAX; - if zip64 - && let Some(locator) = at.checked_sub(20) - && bytes.get(locator..locator + 4) == Some(EOCD64_LOCATOR.as_slice()) - { - let (Some(eocd64), Some(disks)) = (u64_at(locator + 8), u32_at(locator + 16)) else { continue }; - let Some(from) = usize::try_from(eocd64).ok().filter(|&f| f < locator) else { continue }; - if disks > 1 { - continue; - } - let records = bytes.get(from..locator).unwrap_or_default().windows(4).enumerate().filter(|(_, w)| *w == EOCD64); - for (i, _) in records { - let p = from + i; - refuse(u64_at(p + 24).unwrap_or(0).max(u64_at(p + 32).unwrap_or(0)))?; - } - continue; - } - if total == 0 { - return Ok(()); - } - let cd = cd_offset as usize; - if cd < at && bytes.get(cd..at).is_some_and(|b| b.windows(4).any(|w| w == CENTRAL_HEADER)) { - return refuse(u64::from(on_disk.max(total))); - } - } - Ok(()) + craft_zip::check_entry_count(bytes, max_entries).map_err(|e| e.to_string()) } -/// A package of one empty stored file, `a`, whose central directory lists it `entries` times (at -/// most as many as fit in 64 MiB) under a ZIP64 end record that declares them all: `zip` 3.0.0 -/// parses and keeps every one of them before its caller can count them. Regression input for the -/// readers' tests: built only for tests, this crate's and (through the `test-support` feature, -/// which they turn on as a dev-dependency) the readers', never into the app. +/// A ZIP64 package declaring `entries` entries: regression input for the readers' tests. #[cfg(any(test, feature = "test-support"))] -pub fn zip64_entry_count_sample(entries: u64) -> Vec { - // Local file header (APPNOTE.TXT §4.3.7): version 10, stored, no data, name "a". - let mut f = b"PK\x03\x04".to_vec(); - f.extend_from_slice(&[10, 0, 0, 0, 0, 0, 0, 0, 0x21, 0]); // version, flags, method, time, date - f.extend_from_slice(&[0; 12]); // crc, sizes - f.extend_from_slice(&[1, 0, 0, 0]); // name and extra lengths - f.push(b'a'); - let cd_at = f.len() as u64; - // Its central header (§4.3.12), 47 bytes. - let mut header = CENTRAL_HEADER.to_vec(); - header.extend_from_slice(&[10, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0x21, 0]); // versions, flags, method, time, date - header.extend_from_slice(&[0; 12]); // crc, sizes - header.extend_from_slice(&[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // name, extra, comment, disk, attributes - header.extend_from_slice(&[0; 4]); // local header offset - header.push(b'a'); - let count = entries.min((64 << 20) / header.len() as u64); - for _ in 0..count { - f.extend_from_slice(&header); - } - let cd_len = f.len() as u64 - cd_at; - let eocd64_at = f.len() as u64; - // ZIP64 end of central directory record (§4.3.14), 56 bytes. - f.extend_from_slice(EOCD64); - f.extend_from_slice(&44u64.to_le_bytes()); // size of the rest of the record - f.extend_from_slice(&[45, 0, 45, 0]); // versions - f.extend_from_slice(&[0; 8]); // this disk, disk with the central directory - f.extend_from_slice(&entries.to_le_bytes()); // entries on this disk - f.extend_from_slice(&entries.to_le_bytes()); // entries - f.extend_from_slice(&cd_len.to_le_bytes()); - f.extend_from_slice(&cd_at.to_le_bytes()); - // Its locator (§4.3.15), 20 bytes. - f.extend_from_slice(EOCD64_LOCATOR); - f.extend_from_slice(&0u32.to_le_bytes()); - f.extend_from_slice(&eocd64_at.to_le_bytes()); - f.extend_from_slice(&1u32.to_le_bytes()); - // End of central directory record (§4.3.16), 22 bytes, each count and offset "see ZIP64". - f.extend_from_slice(EOCD); - f.extend_from_slice(&[0; 4]); - f.extend_from_slice(&[0xFF; 12]); - f.extend_from_slice(&[0; 2]); - f -} +pub use craft_zip::zip64_entry_count_sample; #[cfg(test)] mod tests { - use super::{CENTRAL_HEADER, EOCD, check, zip64_entry_count_sample}; + use super::{check, zip64_entry_count_sample}; + + const EOCD: &[u8; 4] = b"PK\x05\x06"; + const CENTRAL_HEADER: &[u8; 4] = b"PK\x01\x02"; /// A plain package's tail: one central header at 0, then an end record declaring `entries`. fn plain(entries: u16, comment: &[u8]) -> Vec { @@ -188,4 +78,140 @@ mod tests { let f: Vec = (0..20).flat_map(|_| EOCD.iter().copied().chain(record)).collect(); assert!(check(&f, 20_000).is_err_and(|e| e.contains("end of central directory records"))); } + + /// The pre-cutover implementation, kept as a differential oracle. + mod old { + const EOCD: &[u8; 4] = b"PK\x05\x06"; + const EOCD64_LOCATOR: &[u8; 4] = b"PK\x06\x07"; + const EOCD64: &[u8; 4] = b"PK\x06\x06"; + const CENTRAL_HEADER: &[u8; 4] = b"PK\x01\x02"; + /// End records looked at, at most. A package has one; a few more can turn up inside stored data. + const MAX_END_RECORDS: usize = 16; + + /// Refuse `bytes` when the end record `zip` would use declares more than `max_entries` entries. + /// + /// `zip` searches the file backwards for an end of central directory record. A ZIP64 one points + /// through its locator at the ZIP64 end record, which `zip` looks for from the locator's offset + /// on: every such record there is checked, and as `zip` may fall back to an earlier end record + /// when one doesn't parse, the search goes on. A plain one is used when it declares no entries, or + /// a central directory header lies between its directory offset and itself: it is the last one + /// looked at. + pub fn check(bytes: &[u8], max_entries: u64) -> Result<(), String> { + let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); + let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let u64_at = |at: usize| bytes.get(at..at.checked_add(8)?).and_then(|b| <[u8; 8]>::try_from(b).ok()).map(u64::from_le_bytes); + let refuse = |n: u64| -> Result<(), String> { + if n > max_entries { Err(format!("the package declares {n} entries, more than {max_entries}")) } else { Ok(()) } + }; + let mut end = bytes.len(); + let mut seen = 0; + while let Some(at) = bytes.get(..end).and_then(|b| b.windows(4).rposition(|w| w == EOCD)) { + end = at; + seen += 1; + if seen > MAX_END_RECORDS { + return Err(format!("more than {MAX_END_RECORDS} end of central directory records")); + } + // `zip` skips a record whose comment runs past the end of the file. + let Some(comment) = u16_at(at + 20) else { continue }; + if at + 22 + usize::from(comment) > bytes.len() { + continue; + } + let (Some(on_disk), Some(total), Some(cd_offset)) = (u16_at(at + 8), u16_at(at + 10), u32_at(at + 16)) else { continue }; + let zip64 = total == u16::MAX || cd_offset == u32::MAX; + if zip64 + && let Some(locator) = at.checked_sub(20) + && bytes.get(locator..locator + 4) == Some(EOCD64_LOCATOR.as_slice()) + { + let (Some(eocd64), Some(disks)) = (u64_at(locator + 8), u32_at(locator + 16)) else { continue }; + let Some(from) = usize::try_from(eocd64).ok().filter(|&f| f < locator) else { continue }; + if disks > 1 { + continue; + } + let records = bytes.get(from..locator).unwrap_or_default().windows(4).enumerate().filter(|(_, w)| *w == EOCD64); + for (i, _) in records { + let p = from + i; + refuse(u64_at(p + 24).unwrap_or(0).max(u64_at(p + 32).unwrap_or(0)))?; + } + continue; + } + if total == 0 { + return Ok(()); + } + let cd = cd_offset as usize; + if cd < at && bytes.get(cd..at).is_some_and(|b| b.windows(4).any(|w| w == CENTRAL_HEADER)) { + return refuse(u64::from(on_disk.max(total))); + } + } + Ok(()) + } + } + + fn sentinel_sample() -> Vec { + // ZIP64 sample whose plain end record claims one entry and a real directory offset but + // sets the directory size to u32::MAX, the ZIP64 marker `zip` honours. + let mut f = zip64_entry_count_sample(30_000); + let n = f.len(); + f[n - 14..n - 12].copy_from_slice(&1u16.to_le_bytes()); + f[n - 12..n - 10].copy_from_slice(&1u16.to_le_bytes()); + f[n - 10..n - 6].copy_from_slice(&u32::MAX.to_le_bytes()); + f[n - 6..n - 2].copy_from_slice(&31u32.to_le_bytes()); + f + } + + fn corpus() -> Vec> { + let mut seed = 0x2545_F491_4F6C_DD1Du64; + let mut rnd = |n: usize| -> Vec { + (0..n) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 24) as u8 + }) + .collect() + }; + let mut truncated = zip64_entry_count_sample(10); + truncated.truncate(truncated.len() - 5); + vec![ + vec![], + plain(3, b""), + plain(30_000, b"c"), + zip64_entry_count_sample(1), + zip64_entry_count_sample(10), + zip64_entry_count_sample(30_000), + zip64_entry_count_sample(5_000_000), + truncated, + rnd(1), + rnd(100), + rnd(5000), + ] + } + + #[test] + fn agrees_with_the_old_implementation_except_for_the_sentinel() { + for (i, input) in corpus().iter().enumerate() { + for max in [0u64, 9, 10, 20_000] { + assert_eq!(check(input, max).is_ok(), old::check(input, max).is_ok(), "input {i}, max {max}"); + } + } + } + + #[test] + fn a_directory_size_sentinel_alone_cannot_bypass_the_count_limit() { + let f = sentinel_sample(); + assert!(old::check(&f, 20_000).is_ok(), "the old check missed it"); + assert!(check(&f, 20_000).is_err_and(|e| e.contains("30000 entries"))); + } + + #[test] + fn no_truncation_of_a_zip64_package_panics() { + for f in [zip64_entry_count_sample(10), sentinel_sample()] { + for end in 0..=f.len().min(4096) { + let _ = check(&f[..end], 5); + } + for start in f.len().saturating_sub(300)..f.len() { + let _ = check(&f[start..], 5); + } + } + } } diff --git a/crates/doc/tests/linear_empty_limits.rs b/crates/doc/tests/linear_empty_limits.rs new file mode 100644 index 0000000000..208e22849a --- /dev/null +++ b/crates/doc/tests/linear_empty_limits.rs @@ -0,0 +1,24 @@ +//! An n-ary operator's empty but shown limit survives linear text (#6076): half-typed `∑_` has an +//! empty lower limit that is shown, and `to_linear` writes it as `_()`. Left out, it reads back as a +//! hidden limit. + +use wordcraft_doc::math::{MNode, MRun, parse_linear, to_linear}; + +#[test] +fn an_empty_shown_limit_prints_back_the_same() { + for s in ["∑_", "∑^", "∫_0^▒x", "∑_()^n▒i"] { + let n = parse_linear(s); + assert_eq!(parse_linear(&to_linear(&n)), n, "{s} → {}", to_linear(&n)); + } +} + +#[test] +fn hidden_and_filled_limits_print_as_before() { + let nary = |sub_hide, sup_hide, sub: &str, sup: &str| { + let arg = |t: &str| if t.is_empty() { Vec::new() } else { vec![MNode::Run(MRun::new(t))] }; + vec![MNode::Nary { chr: '∑', lim_loc: None, grow: false, sub_hide, sup_hide, sub: arg(sub), sup: arg(sup), e: arg("x") }] + }; + assert_eq!(to_linear(&nary(true, true, "", "")), "∑▒x"); + assert_eq!(to_linear(&nary(false, false, "i", "n")), "∑_i^n▒x"); + assert_eq!(to_linear(&nary(false, true, "", "")), "∑_()▒x"); +} diff --git a/crates/docx/src/model_bridge.rs b/crates/docx/src/model_bridge.rs index 68931e75a5..b3e07601d0 100644 --- a/crates/docx/src/model_bridge.rs +++ b/crates/docx/src/model_bridge.rs @@ -94,6 +94,15 @@ fn object_value_from_shared( }; Ok(Target::Graphic { w, h, alt, float: convert(float)?, graphic }) } + // This model has no picture frame shape: DrawingML's `frame` preset is read as a + // rectangle, without the frame's border width. + mut shape @ Source::Shape { kind: craft_wordmodel::para::ShapeKind::Frame, .. } => { + if let Source::Shape { kind, extra, .. } = &mut shape { + *kind = craft_wordmodel::para::ShapeKind::Rectangle; + extra.corner = None; + } + convert(shape) + } Source::Group { w, h, float, ch_w, ch_h, children, canvas } => Ok(Target::Group { w, h, @@ -442,6 +451,110 @@ pub fn to_shared_model(source: &wordcraft_doc::Document) -> Result) -> craft_wordmodel::Document { + let mut source = craft_wordmodel::Document::new(); + let mut para = craft_wordmodel::para::Paragraph::new(); + para.objects = objects; + source.body = vec![Arc::new(craft_wordmodel::Block::Para(para))]; + source + } + + fn objects(doc: &wordcraft_doc::Document) -> Vec { + doc.body.first().and_then(|b| b.as_para()).map(|p| p.objects.clone()).unwrap_or_default() + } + + fn chart_object(spec: craft_wordmodel::chart::ChartSpec) -> craft_wordmodel::para::InlineObject { + let graphic = craft_wordmodel::graphic::Graphic { chart: Some(Arc::new(spec)), ..Default::default() }; + craft_wordmodel::para::InlineObject::Graphic { w: 100.0, h: 60.0, alt: String::new(), float: Default::default(), graphic: Arc::new(graphic) } + } + + fn charts(doc: &wordcraft_doc::Document) -> Vec> { + objects(doc) + .iter() + .filter_map(|o| match o { + wordcraft_doc::para::InlineObject::Graphic { graphic, .. } => Some(graphic.chart.as_deref().cloned()), + _ => None, + }) + .collect() + } + + /// A picture frame shape opens as a rectangle instead of failing the whole document. + #[test] + fn a_frame_shape_reads_as_a_rectangle() { + let shape = |kind| craft_wordmodel::para::InlineObject::Shape { + kind, + w: 40.0, + h: 30.0, + fill: None, + stroke: None, + stroke_width: 1.0, + float: Default::default(), + story: None, + freeform: None, + effects: Default::default(), + extra: craft_wordmodel::connector::ShapeExtra { corner: Some(2604), ..Default::default() }, + }; + let doc = from_shared_model(doc_with(vec![shape(craft_wordmodel::para::ShapeKind::Frame)])).expect("from_shared_model"); + let found = objects(&doc); + let [wordcraft_doc::para::InlineObject::Shape { kind, w, extra, .. }] = found.as_slice() else { panic!("{found:?}") }; + assert_eq!((*kind, *w, extra.corner), (wordcraft_doc::para::ShapeKind::Rectangle, 40.0, None)); + } + + /// A chart's series formatting and axis settings survive the trip through this model, so + /// saving writes the chart part the reader read. + #[test] + fn chart_formatting_survives_the_bridge() { + use craft_wordmodel::chart::{ChartSpec, ChartType}; + let mut formatted = ChartSpec::sample(ChartType::Line); + formatted.series[0].fill = Some(craft_wordmodel::props::Rgb(0x12, 0x34, 0x56)); + formatted.series[0].line_w = Some(2.5); + formatted.series[1].smooth = true; + formatted.series[1].markers = Some(true); + formatted.series[2].labels = Some(true); + formatted.series[2].fmt = Some("0.0".into()); + formatted.val_axis.title = Some("Sales".into()); + formatted.val_axis.min = Some(0.0); + formatted.cat_axis.gridlines = true; + let mut scatter_lines = ChartSpec::sample(ChartType::Scatter); + scatter_lines.series[0].no_line = false; + let all = [formatted, ChartSpec::sample(ChartType::Scatter), ChartSpec::sample(ChartType::Pie), scatter_lines]; + let doc = from_shared_model(doc_with(all.iter().cloned().map(chart_object).collect())).expect("from_shared_model"); + assert!(charts(&doc).iter().all(Option::is_some)); + let back = to_shared_model(&doc).expect("to_shared_model"); + let back: Vec = back + .body + .first() + .and_then(|b| b.as_para()) + .map(|p| { + p.objects + .iter() + .filter_map(|o| match o { + craft_wordmodel::para::InlineObject::Graphic { graphic, .. } => graphic.chart.as_deref().cloned(), + _ => None, + }) + .collect() + }) + .unwrap_or_default(); + assert_eq!(back, all); + } + + /// A scatter chart this model makes is written as markers without lines, the same part the + /// shared model writes for its own new scatter chart. + #[test] + fn a_new_scatter_chart_is_written_without_lines() { + let local = wordcraft_doc::chart::ChartSpec::sample(wordcraft_doc::chart::ChartType::Scatter); + assert!(!local.series.is_empty() && local.series.iter().all(|s| s.no_line)); + assert_eq!( + crate::chart_xml(&local), + craft_docx::chart_xml(&craft_wordmodel::chart::ChartSpec::sample(craft_wordmodel::chart::ChartType::Scatter)).into_bytes() + ); + for kind in wordcraft_doc::chart::ChartType::ALL { + let local = wordcraft_doc::chart::ChartSpec::sample(kind); + let shared: craft_wordmodel::chart::ChartSpec = convert_ref(&local).expect("convert"); + assert_eq!(shared, craft_wordmodel::chart::ChartSpec::sample(shared.kind), "{kind:?}"); + } + } + #[test] fn bridges_nested_stories_and_moves_media_both_directions() { let mut source = craft_wordmodel::Document::new(); diff --git a/crates/docx/tests/it/comment_save_cost.rs b/crates/docx/tests/it/comment_save_cost.rs index 2716578b29..e6858e5785 100644 --- a/crates/docx/tests/it/comment_save_cost.rs +++ b/crates/docx/tests/it/comment_save_cost.rs @@ -27,6 +27,7 @@ fn cpu_cost(mut f: impl FnMut()) -> f64 { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn many_comments_save_without_quadratic_id_searches() { for imported in [true, false] { let small = comments(4_000, imported); diff --git a/crates/docx/tests/it/content_control_save_cost.rs b/crates/docx/tests/it/content_control_save_cost.rs index 0859ad1a4d..0ed92b64d6 100644 --- a/crates/docx/tests/it/content_control_save_cost.rs +++ b/crates/docx/tests/it/content_control_save_cost.rs @@ -74,6 +74,7 @@ fn cost_ratio(scale: usize, mut small: impl FnMut(), mut big: impl FnMut()) -> ( /// looked for each paragraph's markers in the whole set of markers, once per paragraph, so a /// document with 32,000 controls took four seconds to save where it takes a tenth of one now. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn a_document_with_many_inline_content_controls_saves_in_linear_time() { let scale = 4; let small = inline_controls(8_000); @@ -94,6 +95,7 @@ fn a_document_with_many_inline_content_controls_saves_in_linear_time() { /// The same for the controls written around whole paragraphs: the writer compared every control /// with every other one to find the ones that clash, so the save was quadratic in their number. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn a_document_with_many_block_content_controls_saves_in_linear_time() { let scale = 4; let small = block_controls(8_000); @@ -217,6 +219,8 @@ const PINNED_PARTS: &[&str] = &[ "word/styles.xml", "word/settings.xml", "word/theme/theme1.xml", + // The fonts the document uses, with their families: it brings no font table of its own. + "word/fontTable.xml", "docProps/core.xml", "docProps/app.xml", ]; diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 7f6cddb6e7..ec1852b797 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -1280,10 +1280,12 @@ fn anchor_stacking_order_is_read_and_kept() { paras(d)[0].objects.iter().filter_map(|o| if let InlineObject::Shape { float, .. } = o { Some(float.z) } else { None }).collect() }; let d = read_body(&body); - assert_eq!(zs(&d), [251660288, 251657214, 0]); + // The shared reader keeps one more than the file's `relativeHeight` (so a file's 0 is the + // lowest order, not "none") and the writer writes one less. + assert_eq!(zs(&d), [251660289, 251657215, 0]); let again = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap(); let z = zs(&again); - assert_eq!(&z[..2], &[251660288, 251657214]); + assert_eq!(&z[..2], &[251660289, 251657215]); assert!(z[2] > 0, "an object without one gets an order on saving: {z:?}"); } diff --git a/crates/docx/tests/it/malformed.rs b/crates/docx/tests/it/malformed.rs index e5e06407ae..304b9fcf38 100644 --- a/crates/docx/tests/it/malformed.rs +++ b/crates/docx/tests/it/malformed.rs @@ -152,6 +152,7 @@ fn many_fields_and_huge_attribute_values() { /// A paragraph with 2,000,000 attributes deflates to ~15 KB. Opening it is refused with a /// limit error, or the extras are dropped and the text survives (#3702, WC-06). #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn millions_of_attributes_on_one_paragraph_are_capped() { let attrs: String = (0..2_000_000).map(|i| format!(" a{i}=\"\"")).collect(); let x = format!("kept"); @@ -222,6 +223,7 @@ fn malformed_or_hostile_bibliography_never_panics() { /// A file with a huge number of bibliography sources (duplicates and distinct ones) reads in /// linear time and keeps at most 10,000 of them. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn hostile_bibliography_source_count_is_capped() { let doc = format!("body"); let mut sources = String::from(r#""#); diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 970804d4cd..649d70e66f 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -989,7 +989,8 @@ fn toc_field_skips_nested_stories() { let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap(); let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap(); let boxes: Vec<(usize, usize)> = xml.match_indices("").map(|(a, _)| (a, a + xml[a..].find("").unwrap())).collect(); - assert_eq!(boxes.len(), 2, "{xml}"); + // Each text box is written twice: in the drawing and in its VML fallback. + assert_eq!(boxes.len(), 4, "{xml}"); let in_box = |i: usize| boxes.iter().any(|(a, b)| (*a..*b).contains(&i)); for kind in ["begin", "separate", "end"] { let at: Vec = xml.match_indices(&format!(r#"fldCharType="{kind}""#)).map(|(i, _)| i).collect(); @@ -997,7 +998,7 @@ fn toc_field_skips_nested_stories() { assert!(!in_box(at[0]), "field {kind} written inside a text box: {xml}"); } let (begin, end) = (xml.find(r#"fldCharType="begin""#).unwrap(), xml.find(r#"fldCharType="end""#).unwrap()); - assert!(begin > boxes[0].1 && end > boxes[1].1 && end < xml.find("").unwrap(), "{xml}"); + assert!(begin > boxes[1].1 && end > boxes[3].1 && end < xml.find("").unwrap(), "{xml}"); } #[test] @@ -1567,6 +1568,29 @@ fn attached_template_and_link_styles_round_trip() { assert!(!plain.settings.link_styles); } +/// Gutter position Top (`w:gutterAtTop`) is kept when a document is opened and saved again, and +/// is not written when it is off. +#[test] +fn gutter_at_top_survives_open_and_save() { + let settings_xml = |bytes: &[u8]| { + let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap(); + String::from_utf8(zip.read("word/settings.xml", 16 << 20).unwrap().unwrap()).unwrap() + }; + let mut d = Document::new(); + d.settings.gutter_at_top = true; + let first = wordcraft_docx::write(&d).expect("write"); + assert_eq!(settings_xml(&first).matches("").count(), 1); + + let opened = wordcraft_docx::read(&first).expect("read"); + assert!(opened.settings.gutter_at_top); + let saved = wordcraft_docx::write(&opened).expect("write again"); + assert_eq!(settings_xml(&saved).matches("").count(), 1); + assert!(wordcraft_docx::read(&saved).expect("read again").settings.gutter_at_top); + + let plain = wordcraft_docx::write(&Document::new()).expect("write plain"); + assert!(!settings_xml(&plain).contains("gutterAtTop")); +} + /// #995: the zoom a document was saved at (`w:zoom`), One Page (`fullPage`) included, is read /// and written back. #[test] @@ -1922,8 +1946,21 @@ fn flat_opc_round_trip_equals_docx() { assert!(text.starts_with("")); assert!(text.contains("pkg:name=\"/word/document.xml\"") && text.contains("")); assert_eq!(wordcraft_docx::sniff_xml(&xml), wordcraft_docx::XmlKind::FlatOpc); - let back = wordcraft_docx::read_xml(&xml).expect("read flat"); - assert_eq!(back, rt(&d)); + let mut back = wordcraft_docx::read_xml(&xml).expect("read flat"); + // `pkg:xmlData` inlines a part without its XML declaration, so a kept XML part (the font + // table) comes back without one; the markup is the same. + let mut want = rt(&d); + for doc in [&mut back, &mut want] { + for v in doc.passthrough.values_mut() { + if let Some(rest) = + v.strip_prefix(b"').map(|e| r[e + 1..].trim_ascii_start().to_vec())) + { + *v = Arc::new(rest); + } + } + } + assert!(back.passthrough.contains_key("word/fontTable.xml")); + assert_eq!(back, want); assert_eq!(back.media.len(), 1); } @@ -2398,6 +2435,10 @@ fn bibliography_sources_round_trip() { assert_bibliography_parts(&bytes); assert_bibliography_sources_round_trip(&bytes); + // Saved again after reading, the store keeps one relationship, from the main part. + let again = wordcraft_docx::write(&wordcraft_docx::read(&bytes).expect("read")).expect("write again"); + assert_bibliography_parts(&again); + assert_eq!(wordcraft_docx::read(&again).expect("read again").sources.len(), d.sources.len()); } /// #4848: a corporate author saves as Word's `b:Corporate`, in place of a name list (a role holds @@ -2438,9 +2479,12 @@ fn assert_bibliography_parts(bytes: &[u8]) { assert!(zip.contains("customXml/itemProps1.xml")); assert!(zip.contains("customXml/_rels/item1.xml.rels")); - let rels_xml = String::from_utf8(zip.read("_rels/.rels", 16 << 20).unwrap().unwrap()).unwrap(); - assert!(rels_xml.contains("relationships/customXml"), "{rels_xml}"); - assert!(rels_xml.contains("Target=\"customXml/item1.xml\""), "{rels_xml}"); + // The sources' data store is related from the main part's relationships only. + let rels_xml = String::from_utf8(zip.read("word/_rels/document.xml.rels", 16 << 20).unwrap().unwrap()).unwrap(); + assert_eq!(rels_xml.matches("relationships/customXml\"").count(), 1, "{rels_xml}"); + assert!(rels_xml.contains("Target=\"../customXml/item1.xml\""), "{rels_xml}"); + let root_xml = String::from_utf8(zip.read("_rels/.rels", 16 << 20).unwrap().unwrap()).unwrap(); + assert!(!root_xml.contains("relationships/customXml\""), "{root_xml}"); let ct_xml = String::from_utf8(zip.read("[Content_Types].xml", 16 << 20).unwrap().unwrap()).unwrap(); assert!(ct_xml.contains("PartName=\"/customXml/item1.xml\""), "{ct_xml}"); diff --git a/crates/docx/tests/it/section_page_number_type.rs b/crates/docx/tests/it/section_page_number_type.rs index 461f1581f7..a11e965fc8 100644 --- a/crates/docx/tests/it/section_page_number_type.rs +++ b/crates/docx/tests/it/section_page_number_type.rs @@ -30,10 +30,16 @@ fn page_number_type_is_kept_even_when_it_only_repeats_the_defaults() { #[test] fn page_number_type_with_a_start_and_format_still_round_trips() { - let body = r#"One"#; - let d = wordcraft_docx::read(&docx(body)).unwrap(); - let xml = document_xml(&wordcraft_docx::write(&d).unwrap()); - assert!(xml.contains(r#"w:fmt="upperRoman""#) && xml.contains(r#"w:start="3""#), "{xml}"); + for (format, start) in [("decimal", 0), ("upperRoman", 3)] { + let page_number_type = format!(r#""#); + let body = format!(r#"One{page_number_type}"#); + let d = wordcraft_docx::read(&docx(&body)).unwrap(); + assert_eq!(d.last_section.page_num_start, Some(start)); + let saved = wordcraft_docx::write(&d).unwrap(); + let xml = document_xml(&saved); + assert!(xml.contains(&page_number_type), "{xml}"); + assert_eq!(wordcraft_docx::read(&saved).unwrap().last_section.page_num_start, Some(start)); + } } #[test] diff --git a/crates/docx/tests/it/text_boxes.rs b/crates/docx/tests/it/text_boxes.rs index 30b752cda3..32b8d0e386 100644 --- a/crates/docx/tests/it/text_boxes.rs +++ b/crates/docx/tests/it/text_boxes.rs @@ -261,5 +261,7 @@ fn story_shared_by_many_shapes_is_written_once() { } let xml = document_xml(&wordcraft_docx::write(&d).unwrap()); assert!(xml.len() < 2_000_000, "document.xml is {} bytes", xml.len()); - assert_eq!(xml.matches(text.as_str()).count(), 1); + // The story is written for the first shape only: in its drawing and in that drawing's VML + // fallback. The other shapes do not repeat it. + assert_eq!(xml.matches(text.as_str()).count(), 2); } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index ad546f0b86..a4f11931e9 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -48,6 +48,10 @@ craft-font-catalog = { workspace = true } # The local time zone's offset for Insert ▸ Date & Time and date fields (#1707); the web asks the browser's Date. chrono = { workspace = true, features = ["clock"] } +[target.'cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))'.dependencies] +# Speech Dispatcher's wire framing for Read Aloud (speech/ssip.rs). +craft-ssip = { workspace = true } + [target.'cfg(unix)'.dependencies] # O_NONBLOCK, so a path swapped for a named pipe can't block `open` (#3666). libc = { workspace = true } @@ -59,6 +63,7 @@ rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } [dev-dependencies] wordcraft-doc = { workspace = true, features = ["test-support"] } +wordcraft-formats = { workspace = true, features = ["test-support"] } encoding_rs = { workspace = true } craft-zip = { workspace = true } cfb = { workspace = true } diff --git a/crates/engine/examples/typing_bench.rs b/crates/engine/examples/typing_bench.rs new file mode 100644 index 0000000000..fff1cbd7bf --- /dev/null +++ b/crates/engine/examples/typing_bench.rs @@ -0,0 +1,32 @@ +//! Typing timing: opens a document, types at the middle of it, and prints the layout time of +//! each keystroke (the pagination every edit pays for). +//! +//! `cargo run --release -p wordcraft-engine --example typing_bench -- doc.docx [keys]` + +use serde_json::json; +use wordcraft_engine::Session; + +fn main() -> Result<(), String> { + let args: Vec = std::env::args().skip(1).collect(); + let path = args.first().ok_or("usage: typing_bench doc.docx [keys]")?; + let keys: usize = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(40); + let mut s = Session::new(wordcraft_engine::doc::Document::new()); + s.run("file.open", &json!({"path": path})).map_err(|e| e.to_string())?; + let first = s.layout().ms; + let mid = s.doc.body.len() / 2; + let block = (mid..s.doc.body.len()).chain((0..mid).rev()).find(|&i| s.doc.body.get(i).and_then(|b| b.as_para()).is_some()).unwrap_or(mid); + s.run("caret.set", &json!({"pos": {"story": "body", "path": [block], "off": 0}})).map_err(|e| e.to_string())?; + let mut ms = Vec::with_capacity(keys); + for _ in 0..keys { + s.run("text.insert", &json!({"text": "a"})).map_err(|e| e.to_string())?; + ms.push(s.layout().ms); + } + ms.sort_by(f64::total_cmp); + let med = ms.get(ms.len() / 2).copied().unwrap_or(0.0); + println!( + "blocks {}, first layout {first:.1} ms, per key: median {med:.1} ms, min {:.1} ms", + s.doc.body.len(), + ms.first().copied().unwrap_or(0.0) + ); + Ok(()) +} diff --git a/crates/engine/src/cmd/canvas.rs b/crates/engine/src/cmd/canvas.rs index 3e62cdd7f2..021fe9b9dc 100644 --- a/crates/engine/src/cmd/canvas.rs +++ b/crates/engine/src/cmd/canvas.rs @@ -79,7 +79,7 @@ pub fn specs() -> Vec { .when(has_canvas) .pure(), CommandSpec::new("canvas.member", "Canvas Member", "Shape Format › Drawing Canvas", member) - .params(r#"{"index": n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; with no change, returns the members)"#) + .params(r#"{"index"?: n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; without index, returns the members)"#) .when(has_canvas), ] } @@ -211,7 +211,7 @@ fn scale(s: &mut Session, v: &Value) -> CmdResult { result(&o) } -/// `canvas.member`: move, resize or remove one member; with no change, list the members. +/// `canvas.member`: move, resize or remove one member; without index, list the members. fn member(s: &mut Session, v: &Value) -> CmdResult { let pos = canvas_pos(s)?; let Some(i) = p::u64(v, "index").and_then(|i| usize::try_from(i).ok()) else { diff --git a/crates/engine/src/cmd/caret.rs b/crates/engine/src/cmd/caret.rs index 23b83e7084..c519c9e060 100644 --- a/crates/engine/src/cmd/caret.rs +++ b/crates/engine/src/cmd/caret.rs @@ -68,6 +68,7 @@ pub fn specs() -> Vec { sel_result(s) }) .key("Escape") + .params(r#"{"end"?: bool (default false: collapse to the start; true: to the end)}"#) .pure(), ] } diff --git a/crates/engine/src/cmd/chart.rs b/crates/engine/src/cmd/chart.rs index 79a16560e7..83a02368c5 100644 --- a/crates/engine/src/cmd/chart.rs +++ b/crates/engine/src/cmd/chart.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use serde_json::{Value, json}; -use wordcraft_doc::chart::{ChartSeries, ChartSpec, ChartType, LegendPos, MAX_POINTS, MAX_SERIES}; +use wordcraft_doc::chart::{ChartAxis, ChartSeries, ChartSpec, ChartType, LegendPos, MAX_POINTS, MAX_SERIES, value_axis}; use wordcraft_doc::graphic::{Graphic, GraphicKind}; use wordcraft_doc::para::{Float, InlineObject}; use wordcraft_doc::props::Rgb; @@ -33,6 +33,23 @@ pub fn specs() -> Vec { CommandSpec::new("chart.type", "Change Chart Type", "Chart Design › Type", |s, v| { let kind = chart_type(v)?.ok_or_else(|| CmdError::Params(format!("`type` is required: {TYPES}")))?; edit(s, |c| { + // A scatter series is drawn as markers without a line; the other types draw it. + if (c.kind == ChartType::Scatter) != (kind == ChartType::Scatter) { + for series in &mut c.series { + series.no_line = kind == ChartType::Scatter; + if series.no_line && series.markers == Some(false) { + series.markers = None; + } + } + } + // Pie and doughnut charts have a plain value axis and the other types a new + // chart's value axis; an axis left as the old type had it takes the new type's. + if c.kind.is_round() != kind.is_round() { + let (from, to) = if kind.is_round() { (value_axis(), ChartAxis::default()) } else { (ChartAxis::default(), value_axis()) }; + if c.val_axis == from { + c.val_axis = to; + } + } c.kind = kind; Ok(()) }) @@ -52,7 +69,15 @@ pub fn specs() -> Vec { c.categories = cats.clone(); } if let Some(series) = &series { - c.series = series.clone(); + // Each series keeps the formatting of the one it replaces. + c.series = series + .iter() + .enumerate() + .map(|(i, (name, values))| match c.series.get(i) { + Some(old) => ChartSeries { name: name.clone(), values: values.clone(), ..old.clone() }, + None => ChartSeries::new(c.kind, name.clone(), values.clone()), + }) + .collect(); } Ok(()) }) @@ -99,6 +124,10 @@ pub fn specs() -> Vec { let on = p::bool(v, "on").or_else(|| p::bool(v, "value")); edit(s, move |c| { c.data_labels = on.unwrap_or(!c.data_labels); + // The chart's setting replaces each series' own. + for series in &mut c.series { + series.labels = None; + } Ok(()) }) }) @@ -152,7 +181,14 @@ fn insert(s: &mut Session, v: &Value) -> CmdResult { let mut spec = ChartSpec::sample(kind); if let Some(d) = v.get("data") { spec.categories = d.get("categories").map(categories).transpose()?.unwrap_or_default(); - spec.series = d.get("series").map(series_list).transpose()?.unwrap_or_default(); + spec.series = d + .get("series") + .map(series_list) + .transpose()? + .unwrap_or_default() + .into_iter() + .map(|(name, values)| ChartSeries::new(kind, name, values)) + .collect(); if spec.series.is_empty() { return Err(CmdError::Params(format!("`data.series` needs at least one series: {DATA}"))); } @@ -220,8 +256,8 @@ fn cell_text(v: &Value) -> String { } } -/// Series from JSON: `[{"name", "values": [number|null|numeric string]}]`. -fn series_list(v: &Value) -> Result, CmdError> { +/// Series names and values from JSON: `[{"name", "values": [number|null|numeric string]}]`. +fn series_list(v: &Value) -> Result>)>, CmdError> { let a = v.as_array().ok_or_else(|| CmdError::Params(format!("`series`: {DATA}")))?; a.iter() .take(MAX_SERIES) @@ -232,7 +268,7 @@ fn series_list(v: &Value) -> Result, CmdError> { None | Some(Value::Null) => Vec::new(), Some(_) => return Err(CmdError::Params("`values`: an array of numbers (null for none)".into())), }; - Ok(ChartSeries { name, values }) + Ok((name, values)) }) .collect() } diff --git a/crates/engine/src/cmd/citations.rs b/crates/engine/src/cmd/citations.rs index 87e83fac77..f889790a56 100644 --- a/crates/engine/src/cmd/citations.rs +++ b/crates/engine/src/cmd/citations.rs @@ -19,6 +19,7 @@ mod sources; mod styles; use cross_refs::cross_ref; +pub(crate) use cross_refs::leading_breaks; pub use cross_refs::{caption_labels, ref_targets}; #[cfg(test)] use generated::ENTRY_STYLE; diff --git a/crates/engine/src/cmd/citations/cross_refs.rs b/crates/engine/src/cmd/citations/cross_refs.rs index 265a73fabc..6c35c27797 100644 --- a/crates/engine/src/cmd/citations/cross_refs.rs +++ b/crates/engine/src/cmd/citations/cross_refs.rs @@ -1,5 +1,5 @@ -use super::generated::page_of; use super::{CharProps, CmdError, CmdResult, Document, InlineObject, Paragraph, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p}; +use crate::cmd::references::page_label; pub(super) fn cross_ref(s: &mut Session, v: &Value) -> CmdResult { let to = p::str(v, "to").unwrap_or("heading"); @@ -10,9 +10,10 @@ pub(super) fn cross_ref(s: &mut Session, v: &Value) -> CmdResult { let find = |ts: Vec<(String, Pos)>| ts.into_iter().find(|(t, _)| t == target || t.starts_with(target)); let (text, pos) = find(targets).ok_or_else(|| CmdError::Params(format!("no {to} `{target}`")))?; let show = p::str(v, "show").unwrap_or("text"); - let page = page_of(s, &pos); let result = match show { - "page" => page.to_string(), + // The page the target's text starts on (after its leading page breaks), as its footer + // shows it. + "page" => page_label(s, &Pos { off: leading_breaks(&s.doc, &pos), ..pos.clone() }), "number" => text.split(':').next().unwrap_or(&text).trim().to_string(), "aboveBelow" => { if pos < s.sel.focus { @@ -152,6 +153,23 @@ pub fn ref_targets(s: &Session, to: &str) -> Vec<(String, Pos)> { targets } +/// The offset just past the page breaks at the start of the paragraph at `pos`, skipping bookmark +/// marks among them (a `_Ref` bookmark may start before the breaks): its text starts there. +pub(crate) fn leading_breaks(doc: &Document, pos: &Pos) -> usize { + let Some(p) = doc.para(pos.story, &pos.path) else { return 0 }; + let mut after = 0; + for (i, c) in p.text.char_indices() { + if c == '\u{0C}' { + after = i.saturating_add(c.len_utf8()); + } else if c != wordcraft_doc::para::OBJ + || !matches!(p.object_at(i), Some(InlineObject::BookmarkStart { .. } | InlineObject::BookmarkEnd { .. })) + { + break; + } + } + after +} + /// The hidden `_Ref` bookmark around the target paragraph at `pos` (its label and number only /// when `number_only`), reusing one already there. Returns its name and `at` moved past the /// bookmark marks inserted before it. @@ -159,16 +177,22 @@ fn ref_bookmark(s: &mut Session, pos: &Pos, number_only: bool, mut at: Pos) -> R const MARK: usize = wordcraft_doc::para::OBJ.len_utf8(); let para = s.doc.para(pos.story, &pos.path).ok_or_else(|| CmdError::Params("cross-reference target is gone".into()))?; let end = if number_only { para.text.find(':').unwrap_or(para.len()) } else { para.len() }; - if let Some(InlineObject::BookmarkStart { name }) = para.object_at(0) - && name.starts_with("_Ref") - { - // Reuse it when it covers the same extent: up to the colon, or the whole paragraph. - let same = para.object_offsets().into_iter().any(|o| { - matches!(para.object_at(o), Some(InlineObject::BookmarkEnd { name: n }) if n == name) - && para.text.get(o.saturating_add(MARK)..).is_some_and(|rest| if number_only { rest.starts_with(':') } else { rest.is_empty() }) - }); - if same { - return Ok((name.clone(), at)); + // The bookmark starts after the leading page breaks, so `PAGEREF` reads the page the text is on. + let start = leading_breaks(&s.doc, pos).min(end); + // Reuse one that starts there or at the paragraph's start (before the breaks): the field's + // result still reads the page the text is on. + for from in [start, 0] { + if let Some(InlineObject::BookmarkStart { name }) = para.object_at(from) + && name.starts_with("_Ref") + { + // Reuse it when it covers the same extent: up to the colon, or the whole paragraph. + let same = para.object_offsets().into_iter().any(|o| { + matches!(para.object_at(o), Some(InlineObject::BookmarkEnd { name: n }) if n == name) + && para.text.get(o.saturating_add(MARK)..).is_some_and(|rest| if number_only { rest.starts_with(':') } else { rest.is_empty() }) + }); + if same { + return Ok((name.clone(), at)); + } } } let next = @@ -176,11 +200,11 @@ fn ref_bookmark(s: &mut Session, pos: &Pos, number_only: bool, mut at: Pos) -> R let name = format!("_Ref{next:09}"); let props = CharProps::default(); s.doc.insert_object(&Pos { off: end, ..pos.clone() }, InlineObject::BookmarkEnd { name: name.clone() }, &props)?; - s.doc.insert_object(&Pos { off: 0, ..pos.clone() }, InlineObject::BookmarkStart { name: name.clone() }, &props)?; + s.doc.insert_object(&Pos { off: start, ..pos.clone() }, InlineObject::BookmarkStart { name: name.clone() }, &props)?; if at.story == pos.story && at.path == pos.path { if at.off >= end { at.off = at.off.saturating_add(2 * MARK); - } else if at.off > 0 { + } else if at.off > start { at.off = at.off.saturating_add(MARK); } } diff --git a/crates/engine/src/cmd/citations/generated.rs b/crates/engine/src/cmd/citations/generated.rs index 60b0b89882..b234948c68 100644 --- a/crates/engine/src/cmd/citations/generated.rs +++ b/crates/engine/src/cmd/citations/generated.rs @@ -6,7 +6,9 @@ use super::{ Block, CharProps, CmdError, CmdResult, Document, FieldCode, InlineObject, Paragraph, Path, Pos, Session, SortKey, StoryRef, TabAlign, TabLeader, TabStop, Value, delete_selection, heading_letter, p, sel_result, sort_key, }; +use crate::cmd::references::{page_at, page_formats, page_text}; use std::sync::Arc; +use wordcraft_doc::section::NumFormat; /// The TOC field for `references.tableOfFigures` (ECMA-376 §17.16.5.68): `\c "