mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-30 02:04:32 +01:00
Reconcile egui 0.37 with current shared libraries
Preserve the reviewed shared UI tree and the frozen app dependency commit while bringing in current main. Port the new keymap UI APIs and use verified central fonts in its strict UI tests and snapshots.
This commit is contained in:
commit
0f46902e32
143 files changed
+29310
-210
No files matched your search
@@ -25,5 +25,5 @@ jobs:
|
||||
with:
|
||||
components: rustfmt, clippy
|
||||
- run: cargo fmt --check
|
||||
- run: cargo clippy -p craft-i18n --all-targets --locked -- -D warnings
|
||||
- run: cargo test -p craft-i18n --locked -- --nocapture
|
||||
- run: cargo clippy -p craft-i18n --all-targets --features collate --locked -- -D warnings
|
||||
- run: cargo test -p craft-i18n --features collate --locked -- --nocapture
|
||||
@@ -0,0 +1,92 @@
|
||||
name: Keymap
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"]
|
||||
pull_request:
|
||||
paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: keymap-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
timeout-minutes: 15
|
||||
name: Keymap (Linux)
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/.test-inputs/craft-fonts
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Checkout test fonts
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: storytold/craft-fonts
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
path: .test-inputs/craft-fonts
|
||||
persist-credentials: false
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
with:
|
||||
components: rustfmt, clippy
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
key: craft-keymap-linux
|
||||
- run: cargo fmt -p craft-keymap --check
|
||||
- run: cargo clippy -p craft-keymap --all-targets --no-default-features --locked -- -D warnings
|
||||
# `snapshot` covers `ui` and `egui` and compiles the dialog screenshots, which need a GPU
|
||||
# to run, so the test steps leave them out.
|
||||
- run: cargo clippy -p craft-keymap --all-targets --features snapshot --locked -- -D warnings
|
||||
# Doctests run once, in the `ui` step.
|
||||
- name: Test core
|
||||
run: cargo test -p craft-keymap --no-default-features --lib --tests --locked
|
||||
- name: Test egui dispatch and the shortcuts dialog
|
||||
run: cargo test -p craft-keymap --features ui --locked
|
||||
native:
|
||||
timeout-minutes: 15
|
||||
name: Keymap (${{ matrix.os }})
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [macos-latest, windows-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
env:
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/.test-inputs/craft-fonts
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Checkout test fonts
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: storytold/craft-fonts
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
path: .test-inputs/craft-fonts
|
||||
persist-credentials: false
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
key: craft-keymap-${{ matrix.os }}
|
||||
- run: cargo test -p craft-keymap --features ui --locked
|
||||
wasm:
|
||||
timeout-minutes: 10
|
||||
name: Keymap WASM
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
with:
|
||||
targets: wasm32-unknown-unknown
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
key: craft-keymap-wasm
|
||||
- run: cargo check -p craft-keymap --features ui --locked --target wasm32-unknown-unknown
|
||||
+6
-4
@@ -9,6 +9,7 @@ author, source and license. Library code and original assets are under the repos
|
||||
| `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 |
|
||||
| `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 |
|
||||
| `crates/cms/tests/data/FOGRA39.txt` (unmodified) | Fogra | [Fogra characterisation data](https://fogra.org/en/downloads/work-tools/characterisation-data), `FOGRA39_to_FOGRA60_v2.zip` | Fogra terms: free use and redistribution, unmodified, with Fogra identified as the source; "FOGRA39" identifies the reference data only and implies no certification, approval or endorsement by Fogra (full text in [NOTICE](NOTICE)) |
|
||||
| `crates/i18n/data/collation.postcard` | Unicode, Inc. (ICU 78.1 collation data, CLDR 48.2.1); generated by `crates/i18n/data/generate-collation.sh` | [ICU](https://github.com/unicode-org/icu/releases/tag/release-78.1rc) | Unicode-3.0 |
|
||||
|
||||
Original assets are covered by the repository licence.
|
||||
|
||||
@@ -32,10 +33,11 @@ The vendored source patch and per-file hashes are recorded in `vendor/krilla/REA
|
||||
|
||||
## Assets retained with the optional PDF reader
|
||||
|
||||
The shared reader centralizes the four existing patched Hayro source trees from PdfCraft.
|
||||
The shared reader centralizes the five patched Hayro source trees from PdfCraft and the
|
||||
patched crates.io `hayro-postscript` 0.1.0 scanner, which bundles no assets.
|
||||
The standard-14 fonts, CMYK profile and generated metrics listed below remain byte-identical
|
||||
in `vendor/hayro-interpret`; no application document fonts are added. CMaps remain a pinned
|
||||
registry dependency. The removed upstream LAB.icc profile is not restored. Source hashes
|
||||
in `vendor/hayro-interpret`, and the CMaps in `vendor/hayro-cmap/assets`; no application
|
||||
document fonts are added. The removed upstream LAB.icc profile is not restored. Source hashes
|
||||
and the exact transfer revision are recorded in each vendored crate's SOURCE.json.
|
||||
|
||||
| Crate / file | Author | Source | Licence | SHA-256 | Use |
|
||||
@@ -55,5 +57,5 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) |
|
||||
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://crates.io/crates/hayro-cmap/0.1.0 | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
|
||||
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/pdfcraft/blob/a2ec27b4775f53c40cad3456936d9406611e3a8d/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
|
||||
| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged |
|
||||
Generated
+303
-39
@@ -8,6 +8,8 @@ version = "0.25.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932"
|
||||
dependencies = [
|
||||
"enumn",
|
||||
"serde",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
@@ -35,6 +37,7 @@ checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"once_cell",
|
||||
"serde",
|
||||
"version_check",
|
||||
"zerocopy",
|
||||
]
|
||||
@@ -571,6 +574,15 @@ dependencies = [
|
||||
"x509-cert",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cobs"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codespan-reporting"
|
||||
version = "0.13.1"
|
||||
@@ -733,14 +745,59 @@ dependencies = [
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-fonts-build-consumer",
|
||||
"skera",
|
||||
"skrifa 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build-consumer"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"intl_pluralrules",
|
||||
"fixed_decimal",
|
||||
"icu_collator",
|
||||
"icu_decimal",
|
||||
"icu_locale_core",
|
||||
"icu_locale_fallback",
|
||||
"icu_normalizer",
|
||||
"icu_plurals",
|
||||
"icu_properties",
|
||||
"icu_provider",
|
||||
"icu_provider_adapters",
|
||||
"icu_provider_blob",
|
||||
"log",
|
||||
"objc2-foundation 0.3.2",
|
||||
"sys-locale",
|
||||
"unic-langid",
|
||||
"unicode-bidi",
|
||||
"windows-registry",
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-i18n",
|
||||
"craft-settings",
|
||||
"craft-ui",
|
||||
"egui",
|
||||
"egui_kittest",
|
||||
"image",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1055,6 +1112,7 @@ source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d09
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1103,6 +1161,7 @@ dependencies = [
|
||||
"log",
|
||||
"nohash-hasher",
|
||||
"profiling",
|
||||
"serde",
|
||||
"smallvec",
|
||||
"unicode-segmentation",
|
||||
"web-sys",
|
||||
@@ -1189,8 +1248,21 @@ version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "embedded-io"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced"
|
||||
|
||||
[[package]]
|
||||
name = "embedded-io"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"
|
||||
|
||||
[[package]]
|
||||
name = "encoding_rs"
|
||||
version = "0.8.42"
|
||||
@@ -1252,6 +1324,17 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "enumn"
|
||||
version = "0.1.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "epaint"
|
||||
version = "0.37.0"
|
||||
@@ -1262,13 +1345,14 @@ dependencies = [
|
||||
"ecolor",
|
||||
"emath",
|
||||
"epaint_default_fonts",
|
||||
"font-types 0.12.6",
|
||||
"font-types 0.12.7",
|
||||
"harfrust",
|
||||
"log",
|
||||
"nohash-hasher",
|
||||
"parking_lot",
|
||||
"profiling",
|
||||
"self_cell",
|
||||
"serde",
|
||||
"skrifa 0.44.0",
|
||||
"smallvec",
|
||||
"unicode-bidi",
|
||||
@@ -1365,6 +1449,17 @@ version = "0.1.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
|
||||
|
||||
[[package]]
|
||||
name = "fixed_decimal"
|
||||
version = "0.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "79c3c892f121fff406e5dd6b28c1b30096b95111c30701a899d4f2b18da6d1bd"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"smallvec",
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flagset"
|
||||
version = "0.4.7"
|
||||
@@ -1436,11 +1531,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "font-types"
|
||||
version = "0.12.6"
|
||||
version = "0.12.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c92d9081c7ab3bd83ef1eecdfad090f3d966e3ce74106779664114cfe1a6274"
|
||||
checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1767,8 +1863,6 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "24d285dc30731c8485de5fa732fbdf2b3affdf01e4da7c2135022ca6fa664bf6"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
@@ -1811,8 +1905,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
@@ -1983,6 +2075,24 @@ dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_collator"
|
||||
version = "2.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08984ed58ac439ebf3e13d2cf26b0c46a60afcd21721c1d14087c0b240344dda"
|
||||
dependencies = [
|
||||
"icu_collections",
|
||||
"icu_locale_core",
|
||||
"icu_normalizer",
|
||||
"icu_properties",
|
||||
"icu_provider",
|
||||
"serde",
|
||||
"smallvec",
|
||||
"utf16_iter",
|
||||
"utf8_iter",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_collections"
|
||||
version = "2.3.0"
|
||||
@@ -1991,12 +2101,30 @@ checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"potential_utf",
|
||||
"serde",
|
||||
"utf8_iter",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_decimal"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9eb8f655bba2d0c0459e43a5b0e6cd3cd388109898fb3d85d048165e8b0abd08"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"fixed_decimal",
|
||||
"icu_locale_core",
|
||||
"icu_pattern",
|
||||
"icu_plurals",
|
||||
"icu_provider",
|
||||
"serde",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_core"
|
||||
version = "2.3.0"
|
||||
@@ -2005,11 +2133,32 @@ checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"litemap",
|
||||
"serde",
|
||||
"tinystr",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_fallback"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9"
|
||||
dependencies = [
|
||||
"icu_locale_core",
|
||||
"icu_locale_fallback_data",
|
||||
"icu_provider",
|
||||
"potential_utf",
|
||||
"tinystr",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_fallback_data"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8"
|
||||
|
||||
[[package]]
|
||||
name = "icu_normalizer"
|
||||
version = "2.3.0"
|
||||
@@ -2020,7 +2169,11 @@ dependencies = [
|
||||
"icu_normalizer_data",
|
||||
"icu_properties",
|
||||
"icu_provider",
|
||||
"serde",
|
||||
"smallvec",
|
||||
"utf16_iter",
|
||||
"utf8_iter",
|
||||
"write16",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
@@ -2030,6 +2183,32 @@ version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
|
||||
|
||||
[[package]]
|
||||
name = "icu_pattern"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b3db611446bd92c246b03e4aa0bafa71ddb194af431ddbb42b9d70e4bfce1a0"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"either",
|
||||
"serde",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_plurals"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e475e6766ef87b1d3c1f97be6363995b0bfaeddbc789671615df598a97ff0593"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"fixed_decimal",
|
||||
"icu_provider",
|
||||
"serde",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_properties"
|
||||
version = "2.3.0"
|
||||
@@ -2041,6 +2220,7 @@ dependencies = [
|
||||
"icu_locale_core",
|
||||
"icu_properties_data",
|
||||
"icu_provider",
|
||||
"serde",
|
||||
"zerotrie",
|
||||
"zerovec",
|
||||
]
|
||||
@@ -2059,6 +2239,9 @@ checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"icu_locale_core",
|
||||
"postcard",
|
||||
"serde",
|
||||
"stable_deref_trait",
|
||||
"writeable",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
@@ -2066,6 +2249,30 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_provider_adapters"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df887bc4f55dbc773c7c45a0c7dfa75be886f7b7812830a71ab7271cc1801820"
|
||||
dependencies = [
|
||||
"icu_locale_fallback",
|
||||
"icu_provider",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_provider_blob"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5916b44fac319d3f58e4d8d805a627df19e27937b582cd99fcde3bb6b7ce1b0e"
|
||||
dependencies = [
|
||||
"icu_provider",
|
||||
"postcard",
|
||||
"serde",
|
||||
"writeable",
|
||||
"zerotrie",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "idna"
|
||||
version = "1.1.0"
|
||||
@@ -2132,15 +2339,6 @@ dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "intl_pluralrules"
|
||||
version = "7.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "078ea7b7c29a2b4df841a7f6ac8775ff6074020c6776d48491ce2268e068f972"
|
||||
dependencies = [
|
||||
"unic-langid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ipnet"
|
||||
version = "2.12.2"
|
||||
@@ -2385,6 +2583,9 @@ name = "litemap"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "litrs"
|
||||
@@ -3242,12 +3443,26 @@ dependencies = [
|
||||
"portable-atomic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "postcard"
|
||||
version = "1.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24"
|
||||
dependencies = [
|
||||
"cobs",
|
||||
"embedded-io 0.4.0",
|
||||
"embedded-io 0.6.1",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "potential_utf"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
@@ -3526,7 +3741,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types 0.12.6",
|
||||
"font-types 0.12.7",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
@@ -3537,10 +3752,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types 0.12.6",
|
||||
"font-types 0.12.7",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.45.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4edc8db0d972de88e53a085b1f01fb3fbdae7bb0cb7a0ce2b2f8285a412fe3ef"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"foldhash",
|
||||
"font-types 0.12.7",
|
||||
"once_cell",
|
||||
"yoke",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.4.1"
|
||||
@@ -4241,6 +4469,18 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
|
||||
|
||||
[[package]]
|
||||
name = "skera"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "531045338e36ad05b9652912a47ba38a935d0eaa0293c3e33d8112cfa414c14b"
|
||||
dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
"skrifa 0.48.0",
|
||||
"thiserror 2.0.21",
|
||||
"write-fonts 0.54.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.42.1"
|
||||
@@ -4271,6 +4511,16 @@ dependencies = [
|
||||
"read-fonts 0.44.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.48.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a5213b4825bac3587046330052d61bfac7bd3bd0d203c758d7c2ef726fcea034"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.45.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
@@ -4291,6 +4541,9 @@ name = "smallvec"
|
||||
version = "1.16.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smol_str"
|
||||
@@ -4392,7 +4645,7 @@ dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"rustc-hash 2.1.3",
|
||||
"skrifa 0.42.1",
|
||||
"write-fonts",
|
||||
"write-fonts 0.48.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4857,24 +5110,6 @@ version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
|
||||
|
||||
[[package]]
|
||||
name = "unic-langid"
|
||||
version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a28ba52c9b05311f4f6e62d5d9d46f094bd6e84cb8df7b3ef952748d752a7d05"
|
||||
dependencies = [
|
||||
"unic-langid-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unic-langid-impl"
|
||||
version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dce1bf08044d4b7a94028c93786f8566047edc11110595914de93362559bc658"
|
||||
dependencies = [
|
||||
"tinystr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-bidi"
|
||||
version = "0.3.18"
|
||||
@@ -4984,6 +5219,12 @@ dependencies = [
|
||||
"xmlwriter",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf16_iter"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246"
|
||||
|
||||
[[package]]
|
||||
name = "utf8_iter"
|
||||
version = "1.0.4"
|
||||
@@ -5785,11 +6026,31 @@ dependencies = [
|
||||
"read-fonts 0.39.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "write-fonts"
|
||||
version = "0.54.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "55716cfa7e8bcdb90289e07dfac478ccb2e3ec0f9a604fe682c7a03a7984d705"
|
||||
dependencies = [
|
||||
"font-types 0.12.7",
|
||||
"log",
|
||||
"read-fonts 0.45.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "write16"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936"
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x509-cert"
|
||||
@@ -6030,8 +6291,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"litemap",
|
||||
"serde_core",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
+5
-1
@@ -1,7 +1,7 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/*"]
|
||||
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2"]
|
||||
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
@@ -24,7 +24,9 @@ thiserror = "2"
|
||||
craft-atomic = { path = "crates/atomic" }
|
||||
craft-cms = { path = "crates/cms" }
|
||||
craft-docpath = { path = "crates/docpath" }
|
||||
craft-fonts-build = { path = "crates/fonts-build" }
|
||||
craft-i18n = { path = "crates/i18n" }
|
||||
craft-keymap = { path = "crates/keymap" }
|
||||
craft-media = { path = "crates/media" }
|
||||
craft-print = { path = "crates/print" }
|
||||
craft-quit = { path = "crates/quit" }
|
||||
@@ -54,6 +56,8 @@ hayro = { path = "vendor/hayro" }
|
||||
hayro-interpret = { path = "vendor/hayro-interpret" }
|
||||
hayro-syntax = { path = "vendor/hayro-syntax" }
|
||||
hayro-jbig2 = { path = "vendor/hayro-jbig2" }
|
||||
hayro-cmap = { path = "vendor/hayro-cmap" }
|
||||
hayro-postscript = { path = "vendor/hayro-postscript" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }
|
||||
|
||||
@@ -96,15 +96,18 @@ and vendor/krilla/SOURCE.json. Its upstream MIT/Apache-2.0 licences and CC0 prof
|
||||
|
||||
Optional PDF reader
|
||||
|
||||
Hayro 0.7.1, hayro-interpret 0.7.0, hayro-syntax 0.7.2 and hayro-jbig2 0.3.0
|
||||
(https://github.com/LaurenzV/hayro), MIT OR Apache-2.0, retain their upstream licence files.
|
||||
These patched sources are transferred from PdfCraft revision
|
||||
7437bde378f43856eada40af25b983812e615e8a (https://github.com/storytold/pdfcraft).
|
||||
Hayro 0.7.1, hayro-interpret 0.7.0, hayro-syntax 0.7.2, hayro-jbig2 0.3.0, hayro-cmap 0.1.0
|
||||
and hayro-postscript 0.1.0 (https://github.com/LaurenzV/hayro), MIT OR Apache-2.0, retain their
|
||||
upstream licence files. The first five are patched sources transferred from PdfCraft
|
||||
(https://github.com/storytold/pdfcraft): hayro-cmap from revision
|
||||
a2ec27b4775f53c40cad3456936d9406611e3a8d, the others from revision
|
||||
7437bde378f43856eada40af25b983812e615e8a. hayro-postscript is the crates.io 0.1.0 package
|
||||
(upstream revision a2354aebaf86f5ab13e5fd6b6b0521306488bf9d) with one local patch.
|
||||
See vendor/README.craft-reader.md and each crate's SOURCE.json for provenance and local changes.
|
||||
The reader retains the existing Foxit/PDFium standard-14 font assets (BSD-3-Clause),
|
||||
Compact ICC Profiles by Clinton Ingram (CC0-1.0), and dependency CMaps (BSD-3-Clause).
|
||||
Their licences and per-file hashes are retained in vendor/hayro-interpret/assets,
|
||||
licenses/pdf-backend and ATTRIBUTION.md. These are existing reader dependency assets;
|
||||
vendor/hayro-cmap/assets, licenses/pdf-backend and ATTRIBUTION.md. These are existing reader dependency assets;
|
||||
applications retain their own document-font selection and licensing policy.
|
||||
|
||||
Platform lifecycle source provenance
|
||||
|
||||
@@ -37,10 +37,17 @@ craft-<name> = { git = "https://github.com/storytold/craft-libs", rev = "<commit
|
||||
- [`craft-docpath`](crates/docpath/src/lib.rs): decides whether a path or `file:` URL stored in a
|
||||
document may be opened. Paths stored in documents are followed only when they are local or on the
|
||||
document's own network share; other network paths, device paths and non-file URLs are refused.
|
||||
- [`craft-fonts-build`](crates/fonts-build/README.md): embeds the optional craft-fonts faces
|
||||
from an app's `build.rs` (`CRAFT_FONTS_DIR`, `CRAFT_FONTS_REQUIRED`, script filters) as a table
|
||||
of `EmbeddedFace`s. No dependencies; the app picks the faces.
|
||||
- [`craft-i18n`](crates/i18n/README.md): translations over the embedded craft-i18n catalogs:
|
||||
lookup with fallback (`pt-br` → `pt` → English), plurals, language names, the system locale and
|
||||
a pseudo locale. The catalogs stay a fully optional build input; apps keep `tl!` and their
|
||||
language setting.
|
||||
- [`craft-keymap`](crates/keymap/README.md): keyboard bindings: chords and their text forms,
|
||||
scopes, conflicts, user overrides stored through craft-settings and import of other
|
||||
applications' shortcut sets. Command catalogs, file readers and the shortcut editor UI stay
|
||||
in each app.
|
||||
- [`craft-media`](crates/media/README.md): bit-level I/O (`bitstream`), clean-room MP4/MOV
|
||||
(`isobmff`) and Matroska/WebM (`matroska`) demuxers and muxers, from FilmCraft, and an ISO BMFF
|
||||
box reader. Containers only; codecs stay in each app.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "craft-fonts-build"
|
||||
description = "Embeds the optional craft-fonts faces from an app's build.rs, plus the EmbeddedFace type the generated table uses."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[features]
|
||||
# Cut the `role ui` faces to the catalogs' characters (`Embed::subset_to`). Enable it only in an
|
||||
# app's `[build-dependencies]`, so the subsetter stays out of the app itself.
|
||||
subset = ["dep:skera", "dep:skrifa"]
|
||||
|
||||
[dependencies]
|
||||
skera = { version = "0.8", optional = true }
|
||||
skrifa = { version = "0.48", default-features = false, features = ["std"], optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-fonts-build-consumer = { path = "tests/consumer" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,168 @@
|
||||
# craft-fonts-build
|
||||
|
||||
Embeds the optional [craft-fonts](https://github.com/storytold/craft-fonts) faces from an app's
|
||||
`build.rs`, and defines `EmbeddedFace`, the plain data type of the generated table. No
|
||||
dependencies without the `subset` feature, and no egui, so crates below the UI layer (text engines,
|
||||
exporters) can use it.
|
||||
|
||||
Apps never list craft-fonts in `Cargo.toml`: Cargo would fetch the font repository for every
|
||||
build. The build reads a local checkout named by `CRAFT_FONTS_DIR` instead.
|
||||
|
||||
| Environment | Result |
|
||||
|---|---|
|
||||
| `CRAFT_FONTS_DIR` unset or empty | Empty table. |
|
||||
| `CRAFT_FONTS_DIR` = a craft-fonts checkout | Every selected face of `fonts/manifest.txt`, embedded with `include_bytes!`. |
|
||||
| `CRAFT_FONTS_DIR` set, but no manifest or a missing font file | `cargo::warning`, empty table. |
|
||||
| `CRAFT_FONTS_REQUIRED=1` (exactly `1`; other values are ignored) | Error instead when the directory is unset, unreadable, has no selected face, or has no face for a script passed to `scripts`. |
|
||||
|
||||
Give `CRAFT_FONTS_DIR` as an absolute path: Cargo runs build scripts in the package's directory.
|
||||
|
||||
## Using it
|
||||
|
||||
`Cargo.toml` (same `rev` as the app's other craft-libs crates). The `subset` feature goes on the
|
||||
build-dependency only: it brings in the subsetter ([skera](https://crates.io/crates/skera) and the
|
||||
fontations crates), which the app itself never needs. Cargo's resolver 2 and later (edition 2021
|
||||
and later) keep build-dependency features apart from the app's, so the dependency stays without
|
||||
it.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "…" }
|
||||
|
||||
[build-dependencies]
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "…", features = ["subset"] }
|
||||
```
|
||||
|
||||
`build.rs` (FilmCraft's `crates/text/build.rs`, in full):
|
||||
|
||||
```rust
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() {
|
||||
println!("cargo::rerun-if-changed=build.rs");
|
||||
let wasm = craft_fonts_build::target_is_wasm();
|
||||
let embedded = craft_fonts_build::Embed::new()
|
||||
// CJK faces only as the interface faces, cut to the characters FilmCraft's catalogs use.
|
||||
.subset_to(catalogs("filmcraft"))
|
||||
// Web builds have a size budget: embed only the Japanese interface face there.
|
||||
.filter(move |face| !wasm || face.has_script("Jpan"))
|
||||
.write("craft_fonts.rs");
|
||||
if let Err(e) = embedded {
|
||||
println!("cargo::error={e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every locale's shared and app catalog in the craft-i18n checkout `CRAFT_I18N_DIR` names, the
|
||||
/// files the app's translations embed; none when it is unset.
|
||||
fn catalogs(app: &str) -> Vec<PathBuf> {
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_I18N_DIR");
|
||||
let Some(dir) = std::env::var_os("CRAFT_I18N_DIR").filter(|dir| !dir.is_empty()) else { return Vec::new() };
|
||||
let locales = PathBuf::from(dir).join("locales");
|
||||
println!("cargo::rerun-if-changed={}", locales.display());
|
||||
let mut paths: Vec<PathBuf> = std::fs::read_dir(&locales)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.flat_map(|locale| ["common.tsv".to_owned(), format!("{app}.tsv")].map(|file| locale.path().join(file)))
|
||||
.filter(|path| path.is_file())
|
||||
.collect();
|
||||
paths.sort();
|
||||
paths
|
||||
}
|
||||
```
|
||||
|
||||
The crate:
|
||||
|
||||
```rust
|
||||
use craft_fonts_build::EmbeddedFace;
|
||||
|
||||
/// craft-fonts faces; empty unless built with `CRAFT_FONTS_DIR`.
|
||||
pub static CRAFT_FONTS: &[EmbeddedFace] = include!(concat!(env!("OUT_DIR"), "/craft_fonts.rs"));
|
||||
```
|
||||
|
||||
`Embed::new()` selects every face except the sources of the interface faces (`role` `ui`, see
|
||||
below), and `Embed::documents(&["Noto Sans", …])` only the families it names (see
|
||||
[Document fonts](#document-fonts)). The builder narrows the set:
|
||||
|
||||
- `scripts(&["Jpan", "Arab", "Hant"])` keeps faces with any of these script tags. A tag matches
|
||||
itself and its region forms (`Hant` matches `Hant-HK`). With `CRAFT_FONTS_REQUIRED=1`, each tag
|
||||
must match at least one face.
|
||||
- `filter(|entry| …)` keeps faces by any manifest field (family, style, licence, index).
|
||||
- `for_ui()` keeps CJK faces only as the interface faces (see below).
|
||||
- `subset_to(catalogs)` (feature `subset`) cuts the interface faces to the catalogs' characters;
|
||||
it implies `for_ui()`.
|
||||
- `check_text(paths)` warns about characters in these files that no embedded face covers.
|
||||
- `embedded_elsewhere(&["Noto Sans Math", …])` names families another table of the app embeds,
|
||||
so `check_text` and the catalog check count their characters as covered.
|
||||
- `dir(path)` and `required(bool)` override the two environment variables.
|
||||
|
||||
`write` returns the embedded `ManifestEntry`s, for build-time checks such as "the interface face
|
||||
is present". The generated file is a slice expression of `EmbeddedFace { family, style, scripts,
|
||||
index, bytes }` literals; any struct with those fields and that name in scope works too.
|
||||
`EmbeddedFace` itself has `name()`, `has_script(tag)`, `is_cjk()` and `weight()`.
|
||||
|
||||
## Document fonts
|
||||
|
||||
An app that draws document text (titles, layouts, vector text) embeds the families its documents
|
||||
use, and only those, in a table of its own:
|
||||
|
||||
```rust
|
||||
let embedded = craft_fonts_build::Embed::documents(&["Noto Sans", "Shippori Mincho"])
|
||||
// The interface table holds the CJK cuts and the symbol faces.
|
||||
.embedded_elsewhere(&["Noto Sans Math", "Noto Sans Symbols 2"])
|
||||
.write("document_fonts.rs");
|
||||
```
|
||||
|
||||
Each named family brings all its styles, as whole files: a CJK document face takes 5–17 MB, so a
|
||||
release embeds exactly the faces the app's documents need. A family named here is embedded even
|
||||
when it is also an interface face's source (`BIZ UDPGothic` brings its Regular too). A name the
|
||||
manifest lacks is an `Error::UnknownFamilies` listing the manifest's families: a build error with
|
||||
`CRAFT_FONTS_REQUIRED=1`, and a `cargo::warning` with an empty table otherwise, as for any
|
||||
checkout that can't be used. `scripts` and `filter` narrow the families further, for example to
|
||||
their Regular faces.
|
||||
|
||||
## Interface faces
|
||||
|
||||
The full CJK faces take 5–17 MB each. For the interface, craft-fonts marks one Regular TrueType
|
||||
face per CJK script with the role `ui`: `Noto Sans SC UI` (`Hans`), `Noto Sans TC UI` (`Hant`),
|
||||
`Noto Sans HK UI` (`Hant-HK`), `Noto Sans KR UI` (`Kore`) and BIZ UDPGothic Regular (`Jpan`). The
|
||||
app's build cuts them to the characters its translation catalogs use; for FilmCraft's catalogs
|
||||
the five cuts take about 3 MB together.
|
||||
|
||||
- `for_ui()` drops every face with a CJK script tag (`Hans`, `Hant`, `Hant-HK`, `Jpan`, `Kore`,
|
||||
`Hani`) that is not an interface face, and keeps the rest. Document text embeds the full faces
|
||||
it names with `Embed::documents` instead. Without `for_ui()` or `subset_to`, the interface
|
||||
faces' sources are left out unless `Embed::documents` names their family.
|
||||
- `subset_to(catalogs)` cuts each interface face to the characters the catalogs use from U+2E80 up
|
||||
(CJK and later blocks, without emoji, variation selectors and tags), plus CJK punctuation
|
||||
(U+3000–303F), kana (U+3040–30FF, U+31F0–31FF) and full-width forms (U+FF00–FFEF), and keeps
|
||||
every layout feature, so vertical forms (`vert`) still work. Every face gets the characters of
|
||||
every catalog, so a Japanese label in a Chinese catalog still draws. The cuts are written to
|
||||
`OUT_DIR/craft-fonts-ui/` and embedded from there; the same inputs give the same bytes, for
|
||||
reproducible releases. Cutting all five faces takes well under a second.
|
||||
- Without `subset_to`, or with an empty catalog list, `for_ui()` leaves the interface faces out
|
||||
with a `cargo::warning`: a full CJK face is never embedded for the interface by accident. A
|
||||
checkout whose manifest has no interface face is a `cargo::warning` too. With `CRAFT_FONTS_REQUIRED=1` that
|
||||
makes `scripts(&["Hant"])` an error; with catalogs, an interface face satisfies it.
|
||||
- An interface face with CFF outlines is an error (`Error::NotTrueType`), even when not required:
|
||||
the subsetter cuts TrueType (`glyf`) faces correctly, but not CFF ones.
|
||||
|
||||
The catalogs come from craft-i18n. An app's build reads them from the checkout `CRAFT_I18N_DIR`
|
||||
names (craft-i18n's `docs/integration.md`); the fonts build script reads the same variable, as in
|
||||
the example above. Catalogs kept in the app's own repository are passed by path, relative to the
|
||||
package directory.
|
||||
|
||||
A character the faces lack still shows: craft-ui's system font provider draws it with an installed
|
||||
font. The build says so: for each catalog, and each file passed to `check_text`, it prints one
|
||||
`cargo::warning` with the count and the first few characters from U+2E80 up that no embedded face
|
||||
covers. Since the cuts hold every catalog character their sources have, these are the characters
|
||||
the sources lack. Faces the app embeds in another table count as covering their characters when
|
||||
named with `embedded_elsewhere`; they are read whole from the checkout, so a face cut elsewhere is
|
||||
exact only for the catalogs it was cut to. It also reruns the build script when a file changes.
|
||||
|
||||
## The manifest
|
||||
|
||||
One face per line, eight or nine fields separated by `" | "`; craft-fonts' `docs/integration.md`
|
||||
defines them. Lines starting with `#` are comments. A file field ending in `#<n>` names face `n` of
|
||||
a font collection (`fonts/noto-sans-cjk/NotoSansCJK.ttc#2`); without it the index is 0. The ninth
|
||||
field, `role`, is `ui` on interface faces and absent elsewhere. Fields after the ninth are ignored.
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Just enough of an OpenType reader to ask which characters a face maps: the `cmap` table's
|
||||
//! Unicode subtables in formats 4 and 12, in a single font or one face of a collection.
|
||||
|
||||
/// The Unicode character maps of one face.
|
||||
pub(crate) struct Cmap<'a> {
|
||||
subtables: Vec<&'a [u8]>,
|
||||
}
|
||||
|
||||
impl<'a> Cmap<'a> {
|
||||
/// The cmap of face `index` of `font` (a `.ttf`/`.otf`, or a `.ttc` collection); `None` when the
|
||||
/// file isn't a font or has no Unicode subtable in format 4 or 12.
|
||||
pub(crate) fn read(font: &'a [u8], index: u32) -> Option<Self> {
|
||||
let face = if font.get(0..4)? == b"ttcf" {
|
||||
if index >= u32_at(font, 8)? {
|
||||
return None;
|
||||
}
|
||||
usize::try_from(u32_at(font, 12 + 4 * usize::try_from(index).ok()?)?).ok()?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let tables = usize::from(u16_at(font, face + 4)?);
|
||||
let record = (0..tables).map(|i| face + 12 + 16 * i).find(|&r| font.get(r..r + 4) == Some(b"cmap"))?;
|
||||
let cmap = slice(font, u32_at(font, record + 8)?, u32_at(font, record + 12)?)?;
|
||||
let mut subtables = Vec::new();
|
||||
for i in 0..usize::from(u16_at(cmap, 2)?) {
|
||||
let (platform, encoding) = (u16_at(cmap, 4 + 8 * i)?, u16_at(cmap, 6 + 8 * i)?);
|
||||
// Unicode platform, or Windows Unicode BMP (1) and full repertoire (10).
|
||||
if platform != 0 && !(platform == 3 && matches!(encoding, 1 | 10)) {
|
||||
continue;
|
||||
}
|
||||
let start = usize::try_from(u32_at(cmap, 8 + 8 * i)?).ok()?;
|
||||
let rest = cmap.get(start..)?;
|
||||
// Bound each subtable by its own length so that reads can't stray into the next one.
|
||||
// Some large CJK fonts declare a format 4 length past the end of the table, so that
|
||||
// one is clamped; a format 12 length that doesn't fit is skipped.
|
||||
let len = match u16_at(rest, 0) {
|
||||
Some(4) => u16_at(rest, 2).map(|len| usize::from(len).min(rest.len())),
|
||||
Some(12) => u32_at(rest, 4).and_then(|len| usize::try_from(len).ok()),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(subtable) = len.and_then(|len| rest.get(..len)) {
|
||||
subtables.push(subtable);
|
||||
}
|
||||
}
|
||||
(!subtables.is_empty()).then_some(Self { subtables })
|
||||
}
|
||||
|
||||
/// Whether any Unicode subtable maps `c` to a glyph other than `.notdef`.
|
||||
pub(crate) fn covers(&self, c: char) -> bool {
|
||||
self.subtables.iter().any(|t| glyph(t, u32::from(c)).is_some_and(|g| g != 0))
|
||||
}
|
||||
}
|
||||
|
||||
fn glyph(subtable: &[u8], c: u32) -> Option<u32> {
|
||||
match u16_at(subtable, 0)? {
|
||||
4 => format4(subtable, u16::try_from(c).ok()?),
|
||||
12 => format12(subtable, c),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn format4(t: &[u8], c: u16) -> Option<u32> {
|
||||
let seg_x2 = usize::from(u16_at(t, 6)?);
|
||||
let (ends, starts, deltas, range_offsets) = (14, 16 + seg_x2, 16 + 2 * seg_x2, 16 + 3 * seg_x2);
|
||||
// End codes are sorted: the first segment ending at or after `c` is the only candidate.
|
||||
let segments = seg_x2 / 2;
|
||||
let i = partition_point(segments, |i| u16_at(t, ends + 2 * i).is_some_and(|end| end < c));
|
||||
if i == segments {
|
||||
return None;
|
||||
}
|
||||
let start = u16_at(t, starts + 2 * i)?;
|
||||
if c < start {
|
||||
return None;
|
||||
}
|
||||
let delta = u16_at(t, deltas + 2 * i)?;
|
||||
let range_offset_at = range_offsets + 2 * i;
|
||||
let range_offset = usize::from(u16_at(t, range_offset_at)?);
|
||||
if range_offset == 0 {
|
||||
return Some(u32::from(c.wrapping_add(delta)));
|
||||
}
|
||||
let g = u16_at(t, range_offset_at + range_offset + 2 * usize::from(c - start))?;
|
||||
Some(if g == 0 { 0 } else { u32::from(g.wrapping_add(delta)) })
|
||||
}
|
||||
|
||||
fn format12(t: &[u8], c: u32) -> Option<u32> {
|
||||
let groups = usize::try_from(u32_at(t, 12)?).ok()?;
|
||||
// Groups are sorted by start code and don't overlap.
|
||||
let i = partition_point(groups, |i| u32_at(t, 16 + 12 * i + 4).is_some_and(|end| end < c));
|
||||
if i == groups {
|
||||
return None;
|
||||
}
|
||||
let g = 16 + 12 * i;
|
||||
let (start, end, glyph) = (u32_at(t, g)?, u32_at(t, g + 4)?, u32_at(t, g + 8)?);
|
||||
(start..=end).contains(&c).then(|| glyph.wrapping_add(c - start))
|
||||
}
|
||||
|
||||
/// The first index in `0..len` for which `before` is false, given that it is true for a prefix.
|
||||
fn partition_point(len: usize, before: impl Fn(usize) -> bool) -> usize {
|
||||
let (mut lo, mut hi) = (0, len);
|
||||
while lo < hi {
|
||||
let mid = lo + (hi - lo) / 2;
|
||||
if before(mid) { lo = mid + 1 } else { hi = mid }
|
||||
}
|
||||
lo
|
||||
}
|
||||
|
||||
fn slice(data: &[u8], offset: u32, len: u32) -> Option<&[u8]> {
|
||||
let offset = usize::try_from(offset).ok()?;
|
||||
data.get(offset..offset.checked_add(usize::try_from(len).ok()?)?)
|
||||
}
|
||||
|
||||
fn u16_at(data: &[u8], at: usize) -> Option<u16> {
|
||||
Some(u16::from_be_bytes(data.get(at..at.checked_add(2)?)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
fn u32_at(data: &[u8], at: usize) -> Option<u32> {
|
||||
Some(u32::from_be_bytes(data.get(at..at.checked_add(4)?)?.try_into().ok()?))
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
//! The build-script side: read `CRAFT_FONTS_DIR`, select faces, write the generated table.
|
||||
|
||||
#[cfg(feature = "subset")]
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::OsString;
|
||||
use std::fmt::{self, Write as _};
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::cmap::Cmap;
|
||||
use crate::manifest::{ManifestEntry, ParseError, parse_manifest, script_matches};
|
||||
|
||||
const DIR_VAR: &str = "CRAFT_FONTS_DIR";
|
||||
const REQUIRED_VAR: &str = "CRAFT_FONTS_REQUIRED";
|
||||
const EMPTY_TABLE: &str = "&[]\n";
|
||||
|
||||
/// Whether the build script is building for wasm32 (web builds usually embed fewer faces).
|
||||
pub fn target_is_wasm() -> bool {
|
||||
std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|arch| arch == "wasm32")
|
||||
}
|
||||
|
||||
type Filter = Box<dyn Fn(&ManifestEntry) -> bool>;
|
||||
|
||||
/// Which faces to embed, and from where. [`Embed::write`] does the work.
|
||||
#[derive(Default)]
|
||||
pub struct Embed {
|
||||
scripts: Option<Vec<String>>,
|
||||
filter: Option<Filter>,
|
||||
dir: Option<PathBuf>,
|
||||
required: Option<bool>,
|
||||
ui: bool,
|
||||
catalogs: Option<Vec<PathBuf>>,
|
||||
texts: Vec<PathBuf>,
|
||||
families: Option<Vec<String>>,
|
||||
elsewhere: Vec<String>,
|
||||
}
|
||||
|
||||
/// A selected face and the file the table embeds it from.
|
||||
struct Face {
|
||||
entry: ManifestEntry,
|
||||
path: PathBuf,
|
||||
index: u32,
|
||||
/// An interface face to cut to the catalogs' characters before it is embedded.
|
||||
#[cfg_attr(not(feature = "subset"), expect(dead_code))]
|
||||
cut: bool,
|
||||
}
|
||||
|
||||
impl Embed {
|
||||
/// Every face except the interface faces' sources (`role` `ui`), from `CRAFT_FONTS_DIR`,
|
||||
/// required when `CRAFT_FONTS_REQUIRED=1`. Narrow it with [`Embed::scripts`] and
|
||||
/// [`Embed::filter`]; a table of document fonts starts from [`Embed::documents`] instead.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Every face of these families, whole, and nothing else: an app's document fonts. A family
|
||||
/// is named as the manifest spells it (`"Noto Sans"`, `"Shippori Mincho"`) and contributes all
|
||||
/// its styles, interface faces included (`"BIZ UDPGothic"` brings its Regular as well).
|
||||
/// A name the manifest lacks is an [`Error::UnknownFamilies`], so the build fails with
|
||||
/// `CRAFT_FONTS_REQUIRED=1` and warns and embeds nothing otherwise. Narrow it further with
|
||||
/// [`Embed::scripts`] and [`Embed::filter`].
|
||||
pub fn documents(families: &[&str]) -> Self {
|
||||
Self { families: Some(families.iter().map(|f| (*f).to_owned()).collect()), ..Self::default() }
|
||||
}
|
||||
|
||||
/// Embed only faces with at least one of these script tags (see
|
||||
/// [`ManifestEntry::has_script`]). With `CRAFT_FONTS_REQUIRED=1`, each tag must match a face.
|
||||
pub fn scripts(mut self, tags: &[&str]) -> Self {
|
||||
self.scripts = Some(tags.iter().map(|t| (*t).to_owned()).collect());
|
||||
self
|
||||
}
|
||||
|
||||
/// Embed only faces for which `keep` returns true (applied after [`Embed::scripts`]).
|
||||
pub fn filter(mut self, keep: impl Fn(&ManifestEntry) -> bool + 'static) -> Self {
|
||||
self.filter = Some(Box::new(keep));
|
||||
self
|
||||
}
|
||||
|
||||
/// Embed faces for an app's interface: CJK faces only as the interface faces (`role` `ui` in
|
||||
/// the manifest), cut to the characters of the catalogs given to `Embed::subset_to`. Other
|
||||
/// CJK faces are dropped and the rest are kept. Without catalogs the interface faces are left
|
||||
/// out too, with a `cargo::warning`, so a full CJK face is never embedded for the interface.
|
||||
/// A manifest with no interface face is also a `cargo::warning` when that drops a CJK face.
|
||||
/// Combines with [`Embed::scripts`] and [`Embed::filter`]; with `CRAFT_FONTS_REQUIRED=1`, an
|
||||
/// interface face satisfies its script tags.
|
||||
pub fn for_ui(mut self) -> Self {
|
||||
self.ui = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Cut the interface faces to the characters these translation catalogs use, and embed the
|
||||
/// cut faces, written to `OUT_DIR`. Implies [`Embed::for_ui`]. An empty list counts as no
|
||||
/// catalogs: the interface faces are left out, with a `cargo::warning`.
|
||||
///
|
||||
/// The cut keeps the catalogs' characters from U+2E80 up (CJK and later blocks, without emoji,
|
||||
/// variation selectors and tags), plus CJK punctuation (U+3000–303F), kana (U+3040–30FF,
|
||||
/// U+31F0–31FF) and full-width forms (U+FF00–FFEF), with every layout feature. The same inputs
|
||||
/// give the same bytes. A face with CFF outlines is an [`Error::NotTrueType`].
|
||||
///
|
||||
/// The catalogs are also checked as by [`Embed::check_text`]. Relative paths are under the
|
||||
/// package directory; an unreadable catalog is a `cargo::warning`.
|
||||
#[cfg(feature = "subset")]
|
||||
pub fn subset_to<P: Into<PathBuf>>(mut self, catalogs: impl IntoIterator<Item = P>) -> Self {
|
||||
self.ui = true;
|
||||
self.catalogs.get_or_insert_default().extend(catalogs.into_iter().map(Into::into));
|
||||
self
|
||||
}
|
||||
|
||||
/// Check that the embedded faces cover these text files, such as translation catalogs: one
|
||||
/// `cargo::warning` per file that has characters from U+2E80 up (CJK and later blocks, without
|
||||
/// emoji and variation selectors) that no embedded face maps. Those characters fall back to
|
||||
/// system fonts at run time. Relative paths are under the package directory. The check runs
|
||||
/// only when a checkout was read.
|
||||
pub fn check_text<P: Into<PathBuf>>(mut self, paths: impl IntoIterator<Item = P>) -> Self {
|
||||
self.texts.extend(paths.into_iter().map(Into::into));
|
||||
self
|
||||
}
|
||||
|
||||
/// Families the app embeds in another table, such as its interface faces next to its document
|
||||
/// fonts: [`Embed::check_text`] and the catalog check count their characters as covered. Each
|
||||
/// is read from the checkout whole, so for a face cut elsewhere this is exact only for the
|
||||
/// catalogs it was cut to. A name the manifest lacks is a `cargo::warning`.
|
||||
pub fn embedded_elsewhere(mut self, families: &[&str]) -> Self {
|
||||
self.elsewhere.extend(families.iter().map(|f| (*f).to_owned()));
|
||||
self
|
||||
}
|
||||
|
||||
/// Read this checkout instead of `CRAFT_FONTS_DIR`.
|
||||
pub fn dir(mut self, dir: impl Into<PathBuf>) -> Self {
|
||||
self.dir = Some(dir.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Override `CRAFT_FONTS_REQUIRED` (required only when it is exactly `1`).
|
||||
pub fn required(mut self, required: bool) -> Self {
|
||||
self.required = Some(required);
|
||||
self
|
||||
}
|
||||
|
||||
/// Write the face table to `out_file` and print the `cargo::` lines; returns the faces
|
||||
/// embedded.
|
||||
///
|
||||
/// Without a checkout the table is empty. A checkout that can't be read is a
|
||||
/// `cargo::warning` and an empty table, or an [`Error`] when required. The table is written
|
||||
/// in every case, so on an error the build fails only on the message the caller prints.
|
||||
pub fn write(&self, out_file: impl AsRef<Path>) -> Result<Vec<ManifestEntry>, Error> {
|
||||
let env = Env { dir: std::env::var_os(DIR_VAR), required: std::env::var_os(REQUIRED_VAR), out_dir: std::env::var_os("OUT_DIR") };
|
||||
let mut cargo = Vec::new();
|
||||
let result = self.run(&env, out_file.as_ref(), &mut cargo);
|
||||
for line in cargo {
|
||||
println!("{line}");
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) fn run(&self, env: &Env, out_file: &Path, cargo: &mut Vec<String>) -> Result<Vec<ManifestEntry>, Error> {
|
||||
cargo.push(format!("cargo::rerun-if-env-changed={DIR_VAR}"));
|
||||
cargo.push(format!("cargo::rerun-if-env-changed={REQUIRED_VAR}"));
|
||||
for text in self.checked_files() {
|
||||
cargo.push(format!("cargo::rerun-if-changed={}", text.display()));
|
||||
}
|
||||
let out = match (out_file.is_absolute(), &env.out_dir) {
|
||||
(true, _) => out_file.to_path_buf(),
|
||||
(false, Some(out_dir)) => Path::new(out_dir).join(out_file),
|
||||
(false, None) => return Err(Error::NoOutDir),
|
||||
};
|
||||
let required = self.required.unwrap_or_else(|| env.required.as_ref().is_some_and(|v| v == "1"));
|
||||
let dir = self.dir.clone().or_else(|| env.dir.clone().filter(|d| !d.is_empty()).map(PathBuf::from));
|
||||
|
||||
let selected = match &dir {
|
||||
None => Err(Error::NotSet),
|
||||
Some(dir) => self.select(dir, cargo).and_then(|faces| if required { self.check_required(dir, faces) } else { Ok(faces) }),
|
||||
};
|
||||
let mut selected = selected;
|
||||
if let Ok(faces) = &mut selected {
|
||||
// A face that can't be cut is a broken manifest line: an error even when not required.
|
||||
if let Err(e) = self.cut(faces, out.parent().unwrap_or(Path::new(""))) {
|
||||
write(&out, EMPTY_TABLE)?;
|
||||
return Err(e);
|
||||
}
|
||||
if let Some(dir) = &dir {
|
||||
self.check_coverage(faces, dir, cargo);
|
||||
}
|
||||
}
|
||||
let tabled = selected.and_then(|faces| Ok((table(&faces)?, faces.into_iter().map(|face| face.entry).collect())));
|
||||
let (table, faces) = match tabled {
|
||||
Ok(tabled) => tabled,
|
||||
Err(e) if required => {
|
||||
write(&out, EMPTY_TABLE)?;
|
||||
return Err(e);
|
||||
}
|
||||
Err(Error::NotSet) => (EMPTY_TABLE.to_owned(), Vec::new()),
|
||||
Err(e) => {
|
||||
cargo.push(format!("cargo::warning=building without craft-fonts: {e}"));
|
||||
(EMPTY_TABLE.to_owned(), Vec::new())
|
||||
}
|
||||
};
|
||||
write(&out, &table)?;
|
||||
Ok(faces)
|
||||
}
|
||||
|
||||
/// The wanted manifest entries with their canonical file paths.
|
||||
fn select(&self, dir: &Path, cargo: &mut Vec<String>) -> Result<Vec<Face>, Error> {
|
||||
let manifest = dir.join("fonts/manifest.txt");
|
||||
let text = std::fs::read_to_string(&manifest).map_err(|source| Error::Read { path: manifest.clone(), source })?;
|
||||
// Cargo treats a missing watched file as changed, which would rerun the build every time.
|
||||
cargo.push(format!("cargo::rerun-if-changed={}", manifest.display()));
|
||||
let entries = parse_manifest(&text).map_err(|error| Error::Parse { manifest: manifest.clone(), error })?;
|
||||
if let Some(families) = &self.families {
|
||||
let unknown: Vec<String> = families.iter().filter(|f| !entries.iter().any(|e| &e.family == *f)).cloned().collect();
|
||||
if !unknown.is_empty() {
|
||||
let mut known: Vec<String> = Vec::new();
|
||||
for entry in &entries {
|
||||
if !known.contains(&entry.family) {
|
||||
known.push(entry.family.clone());
|
||||
}
|
||||
}
|
||||
return Err(Error::UnknownFamilies { manifest, families: unknown, known });
|
||||
}
|
||||
}
|
||||
let has_ui = entries.iter().any(ManifestEntry::is_ui);
|
||||
let no_catalogs = self.catalogs.as_ref().is_none_or(Vec::is_empty);
|
||||
let mut faces = Vec::new();
|
||||
let mut uncut = Vec::new();
|
||||
let mut dropped_cjk = false;
|
||||
for entry in entries {
|
||||
// Interface faces are the sources of the cuts: embedded whole only when named.
|
||||
let named = match &self.families {
|
||||
Some(families) => families.contains(&entry.family),
|
||||
None => self.ui || !entry.is_ui(),
|
||||
};
|
||||
if !named {
|
||||
continue;
|
||||
}
|
||||
let wanted = self.scripts.as_ref().is_none_or(|tags| tags.iter().any(|t| entry.has_script(t)));
|
||||
let ui_dropped = self.ui && entry.is_cjk() && !entry.is_ui();
|
||||
if !wanted || ui_dropped || self.filter.as_ref().is_some_and(|keep| !keep(&entry)) {
|
||||
dropped_cjk |= wanted && ui_dropped;
|
||||
continue;
|
||||
}
|
||||
let cut = self.ui && entry.is_ui();
|
||||
// An empty list would cut the faces to kana and punctuation, so it counts as none.
|
||||
if cut && no_catalogs {
|
||||
uncut.push(format!("{} {}", entry.family, entry.style));
|
||||
continue;
|
||||
}
|
||||
let file = dir.join(&entry.file);
|
||||
// `include_bytes!` resolves relative paths from the including source file.
|
||||
let path = file.canonicalize().map_err(|source| Error::Read { path: file, source })?;
|
||||
cargo.push(format!("cargo::rerun-if-changed={}", path.display()));
|
||||
let index = entry.index;
|
||||
faces.push(Face { entry, path, index, cut });
|
||||
}
|
||||
if !uncut.is_empty() {
|
||||
let why = if self.catalogs.is_some() { "Embed::subset_to was given no translation catalogs" } else { "no translation catalogs" };
|
||||
cargo.push(format!(
|
||||
"cargo::warning=craft-fonts: not embedding the interface faces {}: {why}; pass the catalogs to \
|
||||
Embed::subset_to (feature `subset`) to embed them cut to the catalogs' characters",
|
||||
uncut.join(", ")
|
||||
));
|
||||
}
|
||||
if dropped_cjk && !has_ui {
|
||||
cargo.push(format!(
|
||||
"cargo::warning=craft-fonts: not embedding any CJK face for the interface: {} has no interface face \
|
||||
(role `ui`); use a craft-fonts checkout that has them",
|
||||
manifest.display()
|
||||
));
|
||||
}
|
||||
Ok(faces)
|
||||
}
|
||||
|
||||
/// Replace each interface face with its cut, written to `out_dir`.
|
||||
#[cfg(feature = "subset")]
|
||||
fn cut(&self, faces: &mut [Face], out_dir: &Path) -> Result<(), Error> {
|
||||
let Some(catalogs) = &self.catalogs else { return Ok(()) };
|
||||
// `select` leaves the faces to cut out when there are no catalogs.
|
||||
if !faces.iter().any(|face| face.cut) {
|
||||
return Ok(());
|
||||
}
|
||||
let mut chars = BTreeSet::new();
|
||||
// An unreadable catalog adds nothing here; `check_coverage` reports it.
|
||||
for text in catalogs.iter().filter_map(|path| std::fs::read_to_string(path).ok()) {
|
||||
chars.extend(text.chars().filter(|&c| needs_glyph(c)));
|
||||
}
|
||||
for (start, end) in UI_RANGES {
|
||||
chars.extend(start..=end);
|
||||
}
|
||||
let dir = out_dir.join("craft-fonts-ui");
|
||||
std::fs::create_dir_all(&dir).map_err(|source| Error::Write { path: dir.clone(), source })?;
|
||||
for face in faces.iter_mut().filter(|face| face.cut) {
|
||||
let source = std::fs::read(&face.path).map_err(|source| Error::Read { path: face.path.clone(), source })?;
|
||||
let bytes = crate::subset::subset(&source, face.index, &chars).map_err(|failure| match failure {
|
||||
crate::subset::Failure::NotTrueType => Error::NotTrueType { path: face.path.clone() },
|
||||
crate::subset::Failure::Other(reason) => Error::Subset { path: face.path.clone(), reason },
|
||||
})?;
|
||||
let name: String =
|
||||
format!("{}-{}", face.entry.family, face.entry.style).chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();
|
||||
let out = dir.join(format!("{name}.ttf"));
|
||||
// Rewriting identical bytes would make Cargo rebuild the crate that embeds them.
|
||||
if std::fs::read(&out).ok().as_deref() != Some(&bytes[..]) {
|
||||
std::fs::write(&out, &bytes).map_err(|source| Error::Write { path: out.clone(), source })?;
|
||||
}
|
||||
face.path = out;
|
||||
face.index = 0;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Without the subsetter there are no catalogs, so [`Embed::select`] left out every face to cut.
|
||||
#[cfg(not(feature = "subset"))]
|
||||
fn cut(&self, _faces: &mut [Face], _out_dir: &Path) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The catalogs, then the other [`Embed::check_text`] files.
|
||||
fn checked_files(&self) -> Vec<&PathBuf> {
|
||||
let mut files: Vec<&PathBuf> = self.catalogs.iter().flatten().collect();
|
||||
for text in &self.texts {
|
||||
if !files.contains(&text) {
|
||||
files.push(text);
|
||||
}
|
||||
}
|
||||
files
|
||||
}
|
||||
|
||||
/// The manifest entries of the [`Embed::embedded_elsewhere`] families, with a
|
||||
/// `cargo::warning` for a family the manifest lacks.
|
||||
fn elsewhere(&self, dir: &Path, cargo: &mut Vec<String>) -> Vec<ManifestEntry> {
|
||||
if self.elsewhere.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let manifest = dir.join("fonts/manifest.txt");
|
||||
// `select` read and parsed this manifest already.
|
||||
let entries = std::fs::read_to_string(&manifest).ok().and_then(|text| parse_manifest(&text).ok()).unwrap_or_default();
|
||||
for family in self.elsewhere.iter().filter(|f| !entries.iter().any(|e| &e.family == *f)) {
|
||||
cargo.push(format!("cargo::warning=craft-fonts: embedded_elsewhere names {family}, which {} lacks", manifest.display()));
|
||||
}
|
||||
entries.into_iter().filter(|e| self.elsewhere.contains(&e.family)).collect()
|
||||
}
|
||||
|
||||
/// Warn about each catalog's and [`Embed::check_text`] file's characters that neither an
|
||||
/// embedded face nor an [`Embed::embedded_elsewhere`] face covers.
|
||||
fn check_coverage(&self, faces: &[Face], dir: &Path, cargo: &mut Vec<String>) {
|
||||
let files = self.checked_files();
|
||||
if files.is_empty() {
|
||||
return;
|
||||
}
|
||||
let elsewhere = self.elsewhere(dir, cargo);
|
||||
let fonts: Vec<(&ManifestEntry, u32, Option<Vec<u8>>)> = faces
|
||||
.iter()
|
||||
.map(|face| (&face.entry, face.index, std::fs::read(&face.path).ok()))
|
||||
.chain(elsewhere.iter().map(|entry| (entry, entry.index, std::fs::read(dir.join(&entry.file)).ok())))
|
||||
.collect();
|
||||
let mut cmaps = Vec::new();
|
||||
for (entry, index, bytes) in &fonts {
|
||||
match bytes.as_deref().and_then(|bytes| Cmap::read(bytes, *index)) {
|
||||
Some(cmap) => cmaps.push(cmap),
|
||||
None => cargo
|
||||
.push(format!("cargo::warning=craft-fonts: cannot read the character map of {} {} ({})", entry.family, entry.style, entry.file)),
|
||||
}
|
||||
}
|
||||
for path in files {
|
||||
let text = match std::fs::read_to_string(path) {
|
||||
Ok(text) => text,
|
||||
Err(e) => {
|
||||
cargo.push(format!("cargo::warning=craft-fonts: cannot check {}: {e}", path.display()));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut seen = HashSet::new();
|
||||
let missing: Vec<char> = text.chars().filter(|&c| needs_glyph(c) && seen.insert(c) && !cmaps.iter().any(|cmap| cmap.covers(c))).collect();
|
||||
if missing.is_empty() {
|
||||
continue;
|
||||
}
|
||||
const SHOWN: usize = 8;
|
||||
let shown: String = missing.iter().take(SHOWN).collect();
|
||||
let more = if missing.len() > SHOWN { " …" } else { "" };
|
||||
cargo.push(format!(
|
||||
"cargo::warning=craft-fonts: {} has {} character{} no embedded face covers ({shown}{more}); system fonts will draw them.",
|
||||
path.display(),
|
||||
missing.len(),
|
||||
if missing.len() == 1 { "" } else { "s" },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn check_required(&self, dir: &Path, faces: Vec<Face>) -> Result<Vec<Face>, Error> {
|
||||
let manifest = dir.join("fonts/manifest.txt");
|
||||
if faces.is_empty() {
|
||||
return Err(Error::NoFaces { manifest });
|
||||
}
|
||||
let missing: Vec<String> = self
|
||||
.scripts
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|tag| !faces.iter().any(|face| face.entry.scripts.iter().any(|s| script_matches(s, tag))))
|
||||
.cloned()
|
||||
.collect();
|
||||
if missing.is_empty() { Ok(faces) } else { Err(Error::MissingScripts { manifest, scripts: missing }) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the interface faces need `c`: CJK and later blocks, except emoji and other pictographs
|
||||
/// (the emoji faces draw them), variation selectors, tags and a byte order mark.
|
||||
fn needs_glyph(c: char) -> bool {
|
||||
c >= '\u{2E80}' && !matches!(c, '\u{FE00}'..='\u{FE0F}' | '\u{FEFF}' | '\u{1F000}'..='\u{1FFFF}' | '\u{E0000}'..)
|
||||
}
|
||||
|
||||
/// Kept in every cut, whatever the catalogs use: CJK punctuation, kana and full-width forms.
|
||||
#[cfg(feature = "subset")]
|
||||
const UI_RANGES: [(char, char); 4] = [('\u{3000}', '\u{303F}'), ('\u{3040}', '\u{30FF}'), ('\u{31F0}', '\u{31FF}'), ('\u{FF00}', '\u{FFEF}')];
|
||||
|
||||
/// The environment a build script sees, separated out for tests.
|
||||
pub(crate) struct Env {
|
||||
pub dir: Option<OsString>,
|
||||
pub required: Option<OsString>,
|
||||
pub out_dir: Option<OsString>,
|
||||
}
|
||||
|
||||
/// The generated source; `include_bytes!` takes a string, so a face under a path that isn't UTF-8
|
||||
/// is an error rather than a lossy path the consumer's build can't find.
|
||||
fn table(faces: &[Face]) -> Result<String, Error> {
|
||||
let mut src = String::from("// Generated by craft-fonts-build. Do not edit.\n&[\n");
|
||||
for Face { entry, path, index, .. } in faces {
|
||||
let file = path.to_str().ok_or_else(|| Error::NonUtf8Path { path: path.clone() })?;
|
||||
let scripts: Vec<String> = entry.scripts.iter().map(|s| format!("{s:?}")).collect();
|
||||
let _ = writeln!(
|
||||
src,
|
||||
" EmbeddedFace {{ family: {:?}, style: {:?}, scripts: &[{}], index: {}, bytes: include_bytes!({:?}) }},",
|
||||
entry.family,
|
||||
entry.style,
|
||||
scripts.join(", "),
|
||||
index,
|
||||
file,
|
||||
);
|
||||
}
|
||||
src.push_str("]\n");
|
||||
Ok(src)
|
||||
}
|
||||
|
||||
fn write(path: &Path, contents: &str) -> Result<(), Error> {
|
||||
std::fs::write(path, contents).map_err(|source| Error::Write { path: path.to_path_buf(), source })
|
||||
}
|
||||
|
||||
/// Why the faces could not be embedded. Print it as `cargo::error={error}`.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
/// `CRAFT_FONTS_REQUIRED=1` but `CRAFT_FONTS_DIR` is unset or empty.
|
||||
NotSet,
|
||||
/// The manifest or a font file it lists can't be read.
|
||||
Read { path: PathBuf, source: io::Error },
|
||||
/// The manifest has a malformed line.
|
||||
Parse { manifest: PathBuf, error: ParseError },
|
||||
/// Required, but no face in the manifest was selected.
|
||||
NoFaces { manifest: PathBuf },
|
||||
/// Required, but no face in the manifest has these requested script tags.
|
||||
MissingScripts { manifest: PathBuf, scripts: Vec<String> },
|
||||
/// The generated table can't be written.
|
||||
Write { path: PathBuf, source: io::Error },
|
||||
/// `out_file` is relative and `OUT_DIR` is unset (not running as a build script).
|
||||
NoOutDir,
|
||||
/// An interface face has CFF outlines, which can't be cut correctly; it must be TrueType.
|
||||
NotTrueType { path: PathBuf },
|
||||
/// An interface face can't be cut.
|
||||
Subset { path: PathBuf, reason: String },
|
||||
/// [`Embed::documents`] names families the manifest lacks; `known` lists the manifest's.
|
||||
UnknownFamilies { manifest: PathBuf, families: Vec<String>, known: Vec<String> },
|
||||
/// A face to embed has a path that isn't UTF-8, which `include_bytes!` can't name.
|
||||
NonUtf8Path { path: PathBuf },
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::NotSet => {
|
||||
write!(f, "{REQUIRED_VAR}=1 but {DIR_VAR} is not: set {DIR_VAR} to the absolute path of a storytold/craft-fonts checkout")
|
||||
}
|
||||
Self::Read { path, source } => {
|
||||
write!(f, "cannot read {} ({DIR_VAR} must be the absolute path of a storytold/craft-fonts checkout): {source}", path.display())
|
||||
}
|
||||
Self::Parse { manifest, error } => write!(f, "{}: {error}", manifest.display()),
|
||||
Self::NoFaces { manifest } => write!(f, "{REQUIRED_VAR}=1 but no face in {} was selected", manifest.display()),
|
||||
Self::MissingScripts { manifest, scripts } => {
|
||||
write!(f, "{REQUIRED_VAR}=1 but {} has no face for {}", manifest.display(), scripts.join(", "))
|
||||
}
|
||||
Self::Write { path, source } => write!(f, "cannot write {}: {source}", path.display()),
|
||||
Self::NoOutDir => write!(f, "OUT_DIR is not set: call craft-fonts-build from a build script, or pass an absolute out_file"),
|
||||
Self::NotTrueType { path } => write!(
|
||||
f,
|
||||
"{} has CFF outlines, which craft-fonts-build can't subset correctly: an interface face (role ui) must be a TrueType (glyf) font",
|
||||
path.display()
|
||||
),
|
||||
Self::Subset { path, reason } => write!(f, "cannot subset {}: {reason}", path.display()),
|
||||
Self::UnknownFamilies { manifest, families, known } => write!(
|
||||
f,
|
||||
"{} has no family {}; Embed::documents names families as the manifest spells them: {}",
|
||||
manifest.display(),
|
||||
families.join(", "),
|
||||
known.join(", ")
|
||||
),
|
||||
Self::NonUtf8Path { path } => write!(f, "cannot embed {}: include_bytes! needs a UTF-8 path", path.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
Self::Read { source, .. } | Self::Write { source, .. } => Some(source),
|
||||
Self::Parse { error, .. } => Some(error),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
//! Embed the optional [craft-fonts](https://github.com/storytold/craft-fonts) faces from an app's
|
||||
//! `build.rs`.
|
||||
//!
|
||||
//! Apps never depend on craft-fonts in `Cargo.toml` (Cargo would fetch the font repository for
|
||||
//! every build). The build reads a local checkout named by `CRAFT_FONTS_DIR` instead:
|
||||
//!
|
||||
//! - **Unset or empty:** the table is empty and the app uses its own and system fonts.
|
||||
//! - **Set:** every selected face in `fonts/manifest.txt` is embedded with `include_bytes!`.
|
||||
//! - **Set, but not readable as a checkout:** a `cargo::warning` and an empty table.
|
||||
//! - **`CRAFT_FONTS_REQUIRED=1`** (release builds; any other value is ignored): a missing or
|
||||
//! unreadable checkout, no selected face, or a requested script without a face is an [`Error`].
|
||||
//!
|
||||
//! Add this crate both as a build-dependency (for [`Embed`]) and as a dependency (for
|
||||
//! [`EmbeddedFace`]). The build-dependency enables the `subset` feature for `Embed::subset_to`,
|
||||
//! which cuts the CJK interface faces to the translation catalogs' characters; the dependency
|
||||
//! leaves it off, so the subsetter is not part of the app. In `build.rs`'s `main`:
|
||||
//!
|
||||
//! ```ignore
|
||||
//! println!("cargo::rerun-if-changed=build.rs");
|
||||
//! let wasm = craft_fonts_build::target_is_wasm();
|
||||
//! let catalogs: Vec<std::path::PathBuf> = /* the app's translation catalogs */;
|
||||
//! let embedded = craft_fonts_build::Embed::new()
|
||||
//! // CJK faces only as the interface faces, cut to the characters the catalogs use.
|
||||
//! .subset_to(catalogs)
|
||||
//! // Web builds have a size budget: embed only the Japanese interface face there.
|
||||
//! .filter(move |face| !wasm || face.has_script("Jpan"))
|
||||
//! .write("craft_fonts.rs");
|
||||
//! if let Err(e) = embedded {
|
||||
//! println!("cargo::error={e}");
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! and in the crate:
|
||||
//!
|
||||
//! ```ignore
|
||||
//! use craft_fonts_build::EmbeddedFace;
|
||||
//!
|
||||
//! pub static CRAFT_FONTS: &[EmbeddedFace] = include!(concat!(env!("OUT_DIR"), "/craft_fonts.rs"));
|
||||
//! ```
|
||||
//!
|
||||
//! The generated file is a slice expression of `EmbeddedFace { .. }` literals, so any struct with
|
||||
//! the same fields and that name in scope works too.
|
||||
//!
|
||||
//! An app's document fonts go in a table of their own that names its families,
|
||||
//! `Embed::documents(&["Noto Sans", "Shippori Mincho"])`: nothing is embedded for documents
|
||||
//! unless the app names it.
|
||||
|
||||
mod cmap;
|
||||
mod embed;
|
||||
mod manifest;
|
||||
#[cfg(feature = "subset")]
|
||||
mod subset;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use embed::{Embed, Error, target_is_wasm};
|
||||
pub use manifest::{CJK_SCRIPTS, ManifestEntry, ParseError, UI_ROLE, parse_manifest};
|
||||
|
||||
/// A craft-fonts face embedded by [`Embed`]: one line of `fonts/manifest.txt`.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct EmbeddedFace {
|
||||
/// Family name, e.g. `"Noto Sans Arabic"`.
|
||||
pub family: &'static str,
|
||||
/// Style, e.g. `"Regular"` or `"Bold"`.
|
||||
pub style: &'static str,
|
||||
/// Script tags: ISO 15924 codes such as `Arab`, `Jpan`, `Hans`, `Hant`, optionally with a
|
||||
/// region subtag (`Hant-HK` for Hong Kong forms, which have no ISO 15924 code).
|
||||
pub scripts: &'static [&'static str],
|
||||
/// Face index in a font collection (`.ttc`); `0` for a single font.
|
||||
pub index: u32,
|
||||
pub bytes: &'static [u8],
|
||||
}
|
||||
|
||||
impl EmbeddedFace {
|
||||
/// `"<family> <style>"`, e.g. `"Noto Sans Arabic Regular"`.
|
||||
pub fn name(&self) -> String {
|
||||
format!("{} {}", self.family, self.style)
|
||||
}
|
||||
|
||||
/// Whether any script tag matches `tag`: `Hant` matches `Hant` and `Hant-HK`.
|
||||
pub fn has_script(&self, tag: &str) -> bool {
|
||||
self.scripts.iter().any(|s| manifest::script_matches(s, tag))
|
||||
}
|
||||
|
||||
/// Whether the face has a CJK script tag ([`CJK_SCRIPTS`]).
|
||||
pub fn is_cjk(&self) -> bool {
|
||||
CJK_SCRIPTS.iter().any(|tag| self.has_script(tag))
|
||||
}
|
||||
|
||||
/// CSS/OpenType weight implied by the style name (`Bold` → 700); 400 when it names none.
|
||||
pub fn weight(&self) -> u16 {
|
||||
let style = self.style.to_ascii_lowercase().replace([' ', '-'], "");
|
||||
const WEIGHTS: [(&str, u16); 14] = [
|
||||
("extralight", 200),
|
||||
("ultralight", 200),
|
||||
("semibold", 600),
|
||||
("demibold", 600),
|
||||
("extrabold", 800),
|
||||
("ultrabold", 800),
|
||||
("thin", 100),
|
||||
("light", 300),
|
||||
("medium", 500),
|
||||
("bold", 700),
|
||||
("black", 900),
|
||||
("heavy", 900),
|
||||
("regular", 400),
|
||||
("book", 400),
|
||||
];
|
||||
WEIGHTS.iter().find(|(name, _)| style.contains(name)).map_or(400, |(_, weight)| *weight)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for EmbeddedFace {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("EmbeddedFace")
|
||||
.field("family", &self.family)
|
||||
.field("style", &self.style)
|
||||
.field("scripts", &self.scripts)
|
||||
.field("index", &self.index)
|
||||
.field("bytes", &format_args!("[{} bytes]", self.bytes.len()))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! craft-fonts' `fonts/manifest.txt`: one font face per line, eight or nine fields separated by
|
||||
//! `" | "`:
|
||||
//!
|
||||
//! ```text
|
||||
//! family | style | file | scripts | licence | licence file | sha256 | source [| role]
|
||||
//! ```
|
||||
//!
|
||||
//! Blank lines and lines starting with `#` are skipped. `file` is relative to the checkout and may
|
||||
//! end in `#<index>` to pick one face of a font collection (`.ttc`). The optional `role` is `ui` for
|
||||
//! an interface face: a full Regular TrueType face that an app's build cuts to the characters of its
|
||||
//! translation catalogs. Fields after the ninth are ignored, so a manifest that gains a field still
|
||||
//! embeds.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// One face listed in the manifest.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ManifestEntry {
|
||||
/// Family name, as the font's `name` table spells it (e.g. `Noto Sans Arabic`).
|
||||
pub family: String,
|
||||
/// Style within the family (e.g. `Regular`, `Bold`).
|
||||
pub style: String,
|
||||
/// Font file, relative to the checkout, without the `#<index>` suffix.
|
||||
pub file: String,
|
||||
/// Face index in a font collection; `0` when the file field has no `#<index>`.
|
||||
pub index: u32,
|
||||
/// Script tags: ISO 15924 codes (`Jpan`, `Arab`), optionally with a region (`Hant-HK`).
|
||||
pub scripts: Vec<String>,
|
||||
/// SPDX licence identifier.
|
||||
pub licence: String,
|
||||
/// Licence text, relative to the checkout.
|
||||
pub licence_file: String,
|
||||
/// Hex SHA-256 of the font file.
|
||||
pub sha256: String,
|
||||
/// Where the file came from.
|
||||
pub source: String,
|
||||
/// The optional ninth field: `Some("ui")` for an interface face, `None` when the line has no
|
||||
/// role.
|
||||
pub role: Option<String>,
|
||||
}
|
||||
|
||||
impl ManifestEntry {
|
||||
/// Whether any of the face's script tags matches `tag`. `Hant` matches `Hant` and `Hant-HK`;
|
||||
/// `Hant-HK` matches only `Hant-HK`.
|
||||
pub fn has_script(&self, tag: &str) -> bool {
|
||||
self.scripts.iter().any(|s| script_matches(s, tag))
|
||||
}
|
||||
|
||||
/// Whether the face is an interface face (`role` is `ui`).
|
||||
pub fn is_ui(&self) -> bool {
|
||||
self.role.as_deref() == Some(UI_ROLE)
|
||||
}
|
||||
|
||||
/// Whether the face has a CJK script tag ([`CJK_SCRIPTS`]).
|
||||
pub fn is_cjk(&self) -> bool {
|
||||
CJK_SCRIPTS.iter().any(|tag| self.has_script(tag))
|
||||
}
|
||||
}
|
||||
|
||||
/// The `role` of an interface face.
|
||||
pub const UI_ROLE: &str = "ui";
|
||||
|
||||
/// Script tags of the CJK faces, which craft-fonts also ships as interface faces. `Hant` covers
|
||||
/// `Hant-HK`.
|
||||
pub const CJK_SCRIPTS: &[&str] = &["Hans", "Hant", "Jpan", "Kore", "Hani"];
|
||||
|
||||
/// `face_tag` is `wanted` or `wanted` plus a `-` subtag.
|
||||
pub(crate) fn script_matches(face_tag: &str, wanted: &str) -> bool {
|
||||
face_tag.strip_prefix(wanted).is_some_and(|rest| rest.is_empty() || rest.starts_with('-'))
|
||||
}
|
||||
|
||||
/// A manifest line that could not be read.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ParseError {
|
||||
/// 1-based line number.
|
||||
pub line: usize,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
impl fmt::Display for ParseError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "manifest line {}: {}", self.line, self.reason)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ParseError {}
|
||||
|
||||
/// Parse a whole manifest.
|
||||
pub fn parse_manifest(text: &str) -> Result<Vec<ManifestEntry>, ParseError> {
|
||||
let mut entries = Vec::new();
|
||||
for (i, raw) in text.lines().enumerate() {
|
||||
let line = i + 1;
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.is_empty() || trimmed.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let fields: Vec<&str> = trimmed.split(" | ").map(str::trim).collect();
|
||||
let [family, style, file, scripts, licence, licence_file, sha256, source, rest @ ..] = fields.as_slice() else {
|
||||
return Err(ParseError { line, reason: format!("expected 8 fields separated by \" | \", found {}", fields.len()) });
|
||||
};
|
||||
for (name, value) in [("family", family), ("style", style), ("file", file), ("scripts", scripts)] {
|
||||
if value.is_empty() {
|
||||
return Err(ParseError { line, reason: format!("the {name} field is empty") });
|
||||
}
|
||||
}
|
||||
let (file, index) = match file.rsplit_once('#') {
|
||||
Some((path, index)) => {
|
||||
let index = index.parse().map_err(|_| ParseError { line, reason: format!("bad face index in {file:?}") })?;
|
||||
(path, index)
|
||||
}
|
||||
None => (*file, 0),
|
||||
};
|
||||
entries.push(ManifestEntry {
|
||||
family: (*family).to_owned(),
|
||||
style: (*style).to_owned(),
|
||||
file: file.to_owned(),
|
||||
index,
|
||||
scripts: scripts.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect(),
|
||||
licence: (*licence).to_owned(),
|
||||
licence_file: (*licence_file).to_owned(),
|
||||
sha256: (*sha256).to_owned(),
|
||||
source: (*source).to_owned(),
|
||||
role: rest.first().filter(|role| !role.is_empty()).map(|role| (*role).to_owned()),
|
||||
});
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//! Cutting an interface face down to the characters the translation catalogs use, with skera.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use skera::{Plan, SubsetFlags, subset_font};
|
||||
use skrifa::raw::collections::IntSet;
|
||||
use skrifa::raw::types::NameId;
|
||||
use skrifa::{FontRef, GlyphId, Tag};
|
||||
|
||||
/// Why a face could not be cut.
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum Failure {
|
||||
/// The face has CFF outlines: skera's CFF output draws the wrong glyphs.
|
||||
NotTrueType,
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// Face `index` of `font` with the glyphs of those `chars` it maps and the glyphs its layout tables
|
||||
/// reach from them (vertical forms, ligatures). Every layout feature and script is kept; the name
|
||||
/// table keeps IDs 0–6 in US English, as fonttools' subsetter does. The same input gives the same
|
||||
/// bytes.
|
||||
pub(crate) fn subset(font: &[u8], index: u32, chars: &BTreeSet<char>) -> Result<Vec<u8>, Failure> {
|
||||
let font = FontRef::from_index(font, index).map_err(|e| Failure::Other(e.to_string()))?;
|
||||
if font.table_data(Tag::new(b"glyf")).is_none() {
|
||||
return Err(Failure::NotTrueType);
|
||||
}
|
||||
let mut unicodes = IntSet::<u32>::empty();
|
||||
unicodes.extend(chars.iter().map(|&c| u32::from(c)));
|
||||
let mut name_ids = IntSet::<NameId>::empty();
|
||||
name_ids.insert_range(NameId::new(0)..=NameId::new(6));
|
||||
let mut languages = IntSet::<u16>::empty();
|
||||
languages.insert(0x0409);
|
||||
let plan = Plan::new(
|
||||
&IntSet::<GlyphId>::empty(),
|
||||
&unicodes,
|
||||
&font,
|
||||
SubsetFlags::default(),
|
||||
&IntSet::<Tag>::empty(),
|
||||
&IntSet::<Tag>::all(),
|
||||
&IntSet::<Tag>::all(),
|
||||
&name_ids,
|
||||
&languages,
|
||||
);
|
||||
subset_font(&font, &plan).map_err(|e| Failure::Other(e.to_string()))
|
||||
}
|
||||
@@ -0,0 +1,562 @@
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use crate::cmap::Cmap;
|
||||
use crate::embed::Env;
|
||||
use crate::{Embed, EmbeddedFace, Error, parse_manifest};
|
||||
|
||||
fn fixture() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixture/craft-fonts")
|
||||
}
|
||||
|
||||
/// A fresh scratch directory under the system temp dir.
|
||||
struct Scratch(PathBuf);
|
||||
|
||||
impl Scratch {
|
||||
fn new(name: &str) -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("craft-fonts-build-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
struct Run {
|
||||
result: Result<Vec<String>, Error>,
|
||||
cargo: Vec<String>,
|
||||
table: String,
|
||||
/// `OUT_DIR`, which holds the table and the cut faces.
|
||||
#[cfg_attr(not(feature = "subset"), expect(dead_code))]
|
||||
out: Scratch,
|
||||
}
|
||||
|
||||
/// Run `embed` with `CRAFT_FONTS_DIR` and `CRAFT_FONTS_REQUIRED` as given; returns the embedded
|
||||
/// face names, the cargo lines and the generated table.
|
||||
fn run(embed: Embed, dir: Option<&Path>, required: Option<&str>) -> Run {
|
||||
static RUNS: AtomicUsize = AtomicUsize::new(0);
|
||||
let scratch = Scratch::new(&format!("run-{}", RUNS.fetch_add(1, Ordering::Relaxed)));
|
||||
let env = Env { dir: dir.map(OsString::from), required: required.map(OsString::from), out_dir: Some(scratch.0.clone().into()) };
|
||||
let mut cargo = Vec::new();
|
||||
let result = embed.run(&env, Path::new("craft_fonts.rs"), &mut cargo);
|
||||
let table = std::fs::read_to_string(scratch.0.join("craft_fonts.rs")).unwrap();
|
||||
Run { result: result.map(|faces| faces.iter().map(|f| format!("{} {}", f.family, f.style)).collect()), cargo, table, out: scratch }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_the_manifest_with_collection_indices() {
|
||||
let text = std::fs::read_to_string(fixture().join("fonts/manifest.txt")).unwrap();
|
||||
let entries = parse_manifest(&text).unwrap();
|
||||
assert_eq!(entries.len(), 6);
|
||||
assert_eq!((entries[0].family.as_str(), entries[0].style.as_str()), ("Sans JP", "Regular"));
|
||||
assert_eq!(entries[0].scripts, ["Jpan", "Latn"]);
|
||||
assert_eq!((entries[0].file.as_str(), entries[0].index), ("fonts/sans-jp/SansJP-Regular.ttf", 0));
|
||||
assert_eq!((entries[4].file.as_str(), entries[4].index), ("fonts/sans-cjk/SansCJK.ttc", 3));
|
||||
assert_eq!(entries[4].scripts, ["Hant-HK", "Latn"]);
|
||||
assert_eq!(entries[4].licence, "OFL-1.1");
|
||||
|
||||
let short = "# comment\n\nA | Regular | a.ttf | Latn\n";
|
||||
let err = parse_manifest(short).unwrap_err();
|
||||
assert_eq!(err.line, 3);
|
||||
assert!(err.to_string().contains("expected 8 fields"), "{err}");
|
||||
let bad_index = "A | Regular | a.ttc#x | Latn | OFL-1.1 | OFL.txt | 00 | src\n";
|
||||
assert!(parse_manifest(bad_index).unwrap_err().to_string().contains("face index"));
|
||||
let ui = "A UI | Regular | a.ttf | Hant | OFL-1.1 | OFL.txt | 00 | src | ui | future field\nA | Regular | a.ttf | Hant | OFL-1.1 | OFL.txt | 00 | src |\n";
|
||||
let entries = parse_manifest(ui).unwrap();
|
||||
assert_eq!(entries[0].role.as_deref(), Some("ui"));
|
||||
assert!(entries[0].is_ui() && entries[0].is_cjk());
|
||||
assert_eq!(entries[1].role, None);
|
||||
assert!(!entries[1].is_ui());
|
||||
assert!(entries.iter().all(|e| e.role.is_none() || e.is_ui()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unset_dir_writes_an_empty_table() {
|
||||
let r = run(Embed::new(), None, None);
|
||||
assert_eq!(r.result.unwrap(), Vec::<String>::new());
|
||||
assert_eq!(r.table.trim(), "&[]");
|
||||
assert!(r.cargo.contains(&"cargo::rerun-if-env-changed=CRAFT_FONTS_DIR".to_owned()));
|
||||
assert!(r.cargo.contains(&"cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED".to_owned()));
|
||||
assert!(!r.cargo.iter().any(|l| l.starts_with("cargo::warning")));
|
||||
// Only `1` means required.
|
||||
for value in ["0", "true", "yes", " 1"] {
|
||||
assert!(run(Embed::new(), None, Some(value)).result.is_ok(), "{value:?}");
|
||||
}
|
||||
assert!(run(Embed::new(), Some(Path::new("")), Some("")).result.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn required_fails_without_a_usable_checkout() {
|
||||
for dir in [None, Some(Path::new(""))] {
|
||||
let r = run(Embed::new(), dir, Some("1"));
|
||||
assert!(matches!(r.result, Err(Error::NotSet)), "{dir:?}");
|
||||
assert_eq!(r.table.trim(), "&[]");
|
||||
}
|
||||
let err = run(Embed::new(), None, Some("1")).result.unwrap_err().to_string();
|
||||
assert!(err.contains("CRAFT_FONTS_DIR") && err.contains("CRAFT_FONTS_REQUIRED"), "{err}");
|
||||
|
||||
let missing = Path::new("/nonexistent/craft-fonts");
|
||||
assert!(matches!(run(Embed::new(), Some(missing), Some("1")).result, Err(Error::Read { .. })));
|
||||
let r = run(Embed::new(), Some(missing), None);
|
||||
assert!(r.result.unwrap().is_empty());
|
||||
// Watching a missing manifest would rerun the build script on every build.
|
||||
assert!(!r.cargo.iter().any(|l| l.starts_with("cargo::rerun-if-changed")), "{:?}", r.cargo);
|
||||
assert!(r.cargo.iter().any(|l| l.starts_with("cargo::warning=building without craft-fonts")), "{:?}", r.cargo);
|
||||
|
||||
let scratch = Scratch::new("missing-file");
|
||||
std::fs::create_dir_all(scratch.0.join("fonts")).unwrap();
|
||||
std::fs::write(scratch.0.join("fonts/manifest.txt"), "A | Regular | fonts/a.ttf | Latn | OFL-1.1 | OFL.txt | 00 | src\n").unwrap();
|
||||
assert!(matches!(run(Embed::new(), Some(&scratch.0), Some("1")).result, Err(Error::Read { .. })));
|
||||
std::fs::write(scratch.0.join("fonts/manifest.txt"), "# no faces\n").unwrap();
|
||||
assert!(matches!(run(Embed::new(), Some(&scratch.0), Some("1")).result, Err(Error::NoFaces { .. })));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn rejects_a_checkout_under_a_non_utf8_path() {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let scratch = Scratch::new("non-utf8");
|
||||
let dir = scratch.0.join(std::ffi::OsStr::from_bytes(b"craft-fonts-\xff"));
|
||||
std::fs::create_dir_all(dir.join("fonts")).unwrap();
|
||||
std::fs::copy(fixture().join("fonts/sans-arabic/SansArabic.ttf"), dir.join("fonts/a.ttf")).unwrap();
|
||||
std::fs::write(dir.join("fonts/manifest.txt"), "A | Regular | fonts/a.ttf | Arab | OFL-1.1 | OFL.txt | 00 | src\n").unwrap();
|
||||
let r = run(Embed::new(), Some(&dir), Some("1"));
|
||||
assert!(matches!(r.result, Err(Error::NonUtf8Path { .. })), "{:?}", r.result);
|
||||
assert_eq!(r.table.trim(), "&[]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embeds_the_selected_scripts() {
|
||||
let r = run(Embed::new(), Some(&fixture()), Some("1"));
|
||||
assert_eq!(r.result.unwrap().len(), 6);
|
||||
|
||||
let r = run(Embed::new().scripts(&["Jpan", "Hant"]), Some(&fixture()), Some("1"));
|
||||
assert_eq!(r.result.unwrap(), ["Sans JP Regular", "Sans JP Bold", "Sans CJK TC Regular", "Sans CJK HK Regular"]);
|
||||
let manifest = fixture().join("fonts/manifest.txt");
|
||||
assert!(r.cargo.contains(&format!("cargo::rerun-if-changed={}", manifest.display())));
|
||||
let jp = fixture().join("fonts/sans-jp/SansJP-Regular.ttf").canonicalize().unwrap();
|
||||
assert!(r.cargo.contains(&format!("cargo::rerun-if-changed={}", jp.display())));
|
||||
assert!(r.table.contains(&format!("include_bytes!({:?})", jp.display().to_string())), "{}", r.table);
|
||||
assert!(r.table.contains("family: \"Sans CJK HK\", style: \"Regular\", scripts: &[\"Hant-HK\", \"Latn\"], index: 3"), "{}", r.table);
|
||||
|
||||
let r = run(Embed::new().scripts(&["Hant-HK"]).filter(|f| f.index != 0), Some(&fixture()), None);
|
||||
assert_eq!(r.result.unwrap(), ["Sans CJK HK Regular"]);
|
||||
|
||||
let r = run(Embed::new().scripts(&["Arab", "Kore", "Geor"]), Some(&fixture()), Some("1"));
|
||||
let Err(Error::MissingScripts { scripts, .. }) = r.result else { panic!("{:?}", r.result) };
|
||||
assert_eq!(scripts, ["Kore", "Geor"]);
|
||||
// Not required: whatever matched is embedded.
|
||||
let r = run(Embed::new().scripts(&["Arab", "Kore"]), Some(&fixture()), None);
|
||||
assert_eq!(r.result.unwrap(), ["Sans Arabic Regular"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_face_helpers() {
|
||||
let face = |style: &'static str| EmbeddedFace { family: "Sans", style, scripts: &["Hant-HK", "Latn"], index: 0, bytes: b"" };
|
||||
assert_eq!(face("Regular").name(), "Sans Regular");
|
||||
assert!(face("Regular").has_script("Hant") && face("Regular").has_script("Hant-HK") && !face("Regular").has_script("Han"));
|
||||
let weights: Vec<u16> = ["Regular", "Bold", "SemiBold", "Extra Light", "Black Italic", "Italic"].map(|s| face(s).weight()).into();
|
||||
assert_eq!(weights, [400, 700, 600, 200, 900, 400]);
|
||||
assert!(face("Regular").is_cjk());
|
||||
assert!(!EmbeddedFace { scripts: &["Arab"], ..face("Regular") }.is_cjk());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documents_embeds_only_the_named_families() {
|
||||
let r = run(Embed::documents(&["Sans JP", "Sans Thai"]), Some(&fixture()), Some("1"));
|
||||
assert_eq!(r.result.unwrap(), ["Sans JP Regular", "Sans JP Bold", "Sans Thai Regular"]);
|
||||
let r = run(Embed::documents(&["Sans JP", "Sans Thai"]).filter(|f| f.style == "Bold"), Some(&fixture()), Some("1"));
|
||||
assert_eq!(r.result.unwrap(), ["Sans JP Bold"]);
|
||||
let r = run(Embed::documents(&[]), Some(&fixture()), None);
|
||||
assert_eq!(r.result.unwrap(), Vec::<String>::new());
|
||||
|
||||
let r = run(Embed::documents(&["Sans JP", "Sans Jp", "Serif"]), Some(&fixture()), Some("1"));
|
||||
let Err(Error::UnknownFamilies { families, .. }) = &r.result else { panic!("{:?}", r.result) };
|
||||
assert_eq!(families, &["Sans Jp", "Serif"]);
|
||||
let message = r.result.unwrap_err().to_string();
|
||||
assert!(
|
||||
message.contains("has no family Sans Jp, Serif") && message.ends_with("Sans JP, Sans Arabic, Sans CJK TC, Sans CJK HK, Sans Thai"),
|
||||
"{message}"
|
||||
);
|
||||
assert_eq!(r.table.trim(), "&[]");
|
||||
// Not required: a warning and an empty table, as for any checkout that can't be used.
|
||||
let r = run(Embed::documents(&["Serif"]), Some(&fixture()), None);
|
||||
assert!(r.result.as_ref().unwrap().is_empty());
|
||||
assert!(warnings(&r).iter().any(|w| w.contains("building without craft-fonts") && w.contains("no family Serif")), "{:?}", r.cargo);
|
||||
}
|
||||
|
||||
/// A font with only a `cmap` table: a Windows format 4 subtable with `bmp` segments `(first,
|
||||
/// last, glyphs)`, mapped to glyphs 1.. when `glyphs` is `None` and through the glyph array
|
||||
/// otherwise, and a format 12 subtable with `groups` `(first, last)` when there are any.
|
||||
fn tiny_font(bmp: &[(u16, u16, Option<&[u16]>)], groups: &[(u32, u32)]) -> Vec<u8> {
|
||||
let be16 = |v: &mut Vec<u8>, x: u16| v.extend_from_slice(&x.to_be_bytes());
|
||||
let be32 = |v: &mut Vec<u8>, x: u32| v.extend_from_slice(&x.to_be_bytes());
|
||||
|
||||
let mut segments = bmp.to_vec();
|
||||
segments.push((0xFFFF, 0xFFFF, None));
|
||||
let n = u16::try_from(segments.len()).unwrap();
|
||||
let (mut ends, mut starts, mut deltas, mut offsets, mut glyphs) = (vec![], vec![], vec![], vec![], vec![]);
|
||||
for (i, &(first, last, ids)) in segments.iter().enumerate() {
|
||||
be16(&mut ends, last);
|
||||
be16(&mut starts, first);
|
||||
match ids {
|
||||
None => {
|
||||
// The last segment maps 0xFFFF to glyph 0, as fonts do.
|
||||
be16(&mut deltas, 1u16.wrapping_sub(if first == 0xFFFF { 0 } else { first }));
|
||||
be16(&mut offsets, 0);
|
||||
}
|
||||
Some(ids) => {
|
||||
be16(&mut deltas, 0);
|
||||
be16(&mut offsets, 2 * (n - u16::try_from(i).unwrap()) + u16::try_from(glyphs.len()).unwrap());
|
||||
ids.iter().for_each(|&g| be16(&mut glyphs, g));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut format4 = vec![];
|
||||
for x in [4, 0, 0, 2 * n, 0, 0, 0] {
|
||||
be16(&mut format4, x);
|
||||
}
|
||||
format4.extend(ends.iter().chain(&[0, 0]).chain(&starts).chain(&deltas).chain(&offsets).chain(&glyphs));
|
||||
let len = u16::try_from(format4.len()).unwrap();
|
||||
format4[2..4].copy_from_slice(&len.to_be_bytes());
|
||||
|
||||
let mut format12 = vec![];
|
||||
be16(&mut format12, 12);
|
||||
be16(&mut format12, 0);
|
||||
be32(&mut format12, 16 + 12 * u32::try_from(groups.len()).unwrap());
|
||||
be32(&mut format12, 0);
|
||||
be32(&mut format12, u32::try_from(groups.len()).unwrap());
|
||||
for &(first, last) in groups {
|
||||
[first, last, 1].into_iter().for_each(|x| be32(&mut format12, x));
|
||||
}
|
||||
|
||||
let subtables: Vec<(u16, Vec<u8>)> = [(1, format4), (10, format12)].into_iter().filter(|(enc, _)| *enc == 1 || !groups.is_empty()).collect();
|
||||
let mut cmap = vec![];
|
||||
be16(&mut cmap, 0);
|
||||
be16(&mut cmap, u16::try_from(subtables.len()).unwrap());
|
||||
let mut at = 4 + 8 * u32::try_from(subtables.len()).unwrap();
|
||||
for (encoding, table) in &subtables {
|
||||
[3, *encoding].into_iter().for_each(|x| be16(&mut cmap, x));
|
||||
be32(&mut cmap, at);
|
||||
at += u32::try_from(table.len()).unwrap();
|
||||
}
|
||||
subtables.iter().for_each(|(_, table)| cmap.extend(table));
|
||||
|
||||
let mut font = vec![];
|
||||
be32(&mut font, 0x0001_0000);
|
||||
for x in [1, 0, 0, 0] {
|
||||
be16(&mut font, x);
|
||||
}
|
||||
font.extend_from_slice(b"cmap");
|
||||
for x in [0, 28, u32::try_from(cmap.len()).unwrap()] {
|
||||
be32(&mut font, x);
|
||||
}
|
||||
font.extend(cmap);
|
||||
font
|
||||
}
|
||||
|
||||
/// A `.ttc` of fonts made by [`tiny_font`].
|
||||
fn tiny_collection(fonts: &[Vec<u8>]) -> Vec<u8> {
|
||||
let header = 12 + 4 * fonts.len();
|
||||
let mut ttc = b"ttcf\0\x01\0\0".to_vec();
|
||||
ttc.extend_from_slice(&u32::try_from(fonts.len()).unwrap().to_be_bytes());
|
||||
let mut body = vec![];
|
||||
for font in fonts {
|
||||
let start = u32::try_from(header + body.len()).unwrap();
|
||||
ttc.extend_from_slice(&start.to_be_bytes());
|
||||
let mut font = font.clone();
|
||||
// The table offsets of a collection's faces count from the start of the file.
|
||||
let offset = u32::from_be_bytes(font[20..24].try_into().unwrap()) + start;
|
||||
font[20..24].copy_from_slice(&offset.to_be_bytes());
|
||||
body.extend(font);
|
||||
}
|
||||
ttc.extend(body);
|
||||
ttc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmap_reads_formats_4_and_12_and_collections() {
|
||||
let font = tiny_font(&[(0x41, 0x5A, None), (0x4E00, 0x4E02, Some(&[5, 0, 7]))], &[(0x2_0000, 0x2_0001)]);
|
||||
let cmap = Cmap::read(&font, 0).unwrap();
|
||||
let covered: Vec<char> = "AZa一丁丂七\u{FFFF}\u{20000}\u{20001}\u{20002}".chars().filter(|&c| cmap.covers(c)).collect();
|
||||
assert_eq!(covered, ['A', 'Z', '一', '丂', '\u{20000}', '\u{20001}']);
|
||||
|
||||
let bmp_in_format12 = tiny_font(&[], &[(0x4E00, 0x4E0F)]);
|
||||
assert!(Cmap::read(&bmp_in_format12, 0).unwrap().covers('丁'));
|
||||
|
||||
let ttc = tiny_collection(&[tiny_font(&[(0x41, 0x41, None)], &[]), tiny_font(&[(0x4E00, 0x4E00, None)], &[])]);
|
||||
let second = Cmap::read(&ttc, 1).unwrap();
|
||||
assert!(second.covers('一') && !second.covers('A'));
|
||||
assert!(Cmap::read(&ttc, 0).unwrap().covers('A'));
|
||||
assert!(Cmap::read(&ttc, 2).is_none());
|
||||
assert!(Cmap::read(b"fixture: Sans JP Regular", 0).is_none());
|
||||
assert!(Cmap::read(&font[..40], 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmap_reads_each_subtable_within_its_declared_length() {
|
||||
// 'A' takes its glyph from an empty glyph array, so the read lands on the format 12 subtable
|
||||
// that follows the format 4 one.
|
||||
let font = tiny_font(&[(0x41, 0x41, Some(&[]))], &[(0x2_0000, 0x2_0000)]);
|
||||
let cmap = Cmap::read(&font, 0).unwrap();
|
||||
assert!(!cmap.covers('A') && cmap.covers('\u{20000}'));
|
||||
|
||||
// A format 4 length past the end of the table is clamped rather than rejected. The format 4
|
||||
// subtable starts after the 28-byte font header, the 4-byte cmap header and two 8-byte encoding
|
||||
// records.
|
||||
let mut font = tiny_font(&[(0x41, 0x5A, None)], &[(0x2_0000, 0x2_0000)]);
|
||||
let format4 = 28 + 4 + 2 * 8;
|
||||
let format12 = format4 + usize::from(u16::from_be_bytes(font[format4 + 2..format4 + 4].try_into().unwrap()));
|
||||
font[format4 + 2..format4 + 4].copy_from_slice(&u16::MAX.to_be_bytes());
|
||||
assert!(Cmap::read(&font, 0).unwrap().covers('A'));
|
||||
|
||||
// A format 12 group past the declared length doesn't count.
|
||||
font[format12 + 4..format12 + 8].copy_from_slice(&16u32.to_be_bytes());
|
||||
let cmap = Cmap::read(&font, 0).unwrap();
|
||||
assert!(cmap.covers('A') && !cmap.covers('\u{20000}'));
|
||||
}
|
||||
|
||||
/// A craft-fonts checkout in `scratch` with these `(family, scripts, role, font)` faces, all
|
||||
/// Regular.
|
||||
fn checkout(scratch: &Scratch, faces: &[(&str, &str, &str, Vec<u8>)]) -> PathBuf {
|
||||
let dir = scratch.0.join("craft-fonts");
|
||||
std::fs::create_dir_all(dir.join("fonts")).unwrap();
|
||||
let mut manifest = String::new();
|
||||
for (i, (family, scripts, role, font)) in faces.iter().enumerate() {
|
||||
std::fs::write(dir.join(format!("fonts/{i}.ttf")), font).unwrap();
|
||||
manifest += &format!("{family} | Regular | fonts/{i}.ttf | {scripts} | OFL-1.1 | fonts/OFL.txt | 00 | src | {role}\n");
|
||||
}
|
||||
std::fs::write(dir.join("fonts/manifest.txt"), manifest).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn warnings(r: &Run) -> Vec<String> {
|
||||
r.cargo.iter().filter(|l| l.starts_with("cargo::warning")).cloned().collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_ui_embeds_cjk_faces_only_as_cut_interface_faces() {
|
||||
let scratch = Scratch::new("for-ui");
|
||||
let latin = || tiny_font(&[(0x20, 0x7E, None)], &[]);
|
||||
let dir = checkout(
|
||||
&scratch,
|
||||
&[
|
||||
("Noto Sans TC", "Hant,Latn", "", latin()),
|
||||
("Noto Sans TC UI", "Hant,Latn", "ui", latin()),
|
||||
("Noto Sans HK UI", "Hant-HK,Latn", "ui", latin()),
|
||||
("Noto Sans Arabic", "Arab", "", latin()),
|
||||
],
|
||||
);
|
||||
// Without catalogs to cut them to, the interface faces are left out too.
|
||||
let r = run(Embed::new().for_ui(), Some(&dir), None);
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
|
||||
let w = warnings(&r);
|
||||
assert_eq!(w.len(), 1, "{w:#?}");
|
||||
assert!(w[0].contains("not embedding the interface faces Noto Sans TC UI Regular, Noto Sans HK UI Regular"), "{}", w[0]);
|
||||
assert!(w[0].contains("Embed::subset_to"), "{}", w[0]);
|
||||
// A manifest without interface faces loses every CJK face, which is worth a warning.
|
||||
let r = run(Embed::new().for_ui(), Some(&fixture()), None);
|
||||
assert!(r.cargo.contains(&format!("cargo::rerun-if-changed={}", fixture().join("fonts/manifest.txt").display())), "{:?}", r.cargo);
|
||||
let w = warnings(&r);
|
||||
assert_eq!(w.len(), 1, "{w:#?}");
|
||||
assert!(w[0].contains("not embedding any CJK face for the interface") && w[0].contains("role `ui`"), "{}", w[0]);
|
||||
let r = run(Embed::new().for_ui().scripts(&["Hant", "Arab"]), Some(&dir), Some("1"));
|
||||
let Err(Error::MissingScripts { scripts, .. }) = r.result else { panic!("{:?}", r.result) };
|
||||
assert_eq!(scripts, ["Hant"]);
|
||||
assert_eq!(r.table.trim(), "&[]");
|
||||
// Without `for_ui` the interface faces' sources are left out, unless a document table names them.
|
||||
let r = run(Embed::new().scripts(&["Hant"]), Some(&dir), Some("1"));
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans TC Regular"]);
|
||||
assert_eq!(warnings(&r), Vec::<String>::new());
|
||||
let r = run(Embed::documents(&["Noto Sans TC UI", "Noto Sans TC"]), Some(&dir), Some("1"));
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans TC Regular", "Noto Sans TC UI Regular"]);
|
||||
assert!(r.table.contains("fonts/1.ttf"), "{}", r.table);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_text_warns_about_characters_no_face_covers() {
|
||||
let scratch = Scratch::new("check-text");
|
||||
let dir = checkout(
|
||||
&scratch,
|
||||
&[
|
||||
("Noto Sans TC", "Hant,Latn", "", tiny_font(&[(0x20, 0x7E, None), (0x4E00, 0x4E03, None)], &[])),
|
||||
("Noto Sans Arabic", "Arab", "", tiny_font(&[(0x600, 0x6FF, None)], &[])),
|
||||
("Noto Sans SC", "Hans,Latn", "", tiny_font(&[(0x20, 0x7E, None), (0x3000, 0x9FFF, None)], &[])),
|
||||
],
|
||||
);
|
||||
let catalogs = scratch.0.join("i18n");
|
||||
std::fs::create_dir_all(&catalogs).unwrap();
|
||||
std::fs::write(catalogs.join("zh-TW.ftl"), "\u{FEFF}open = 一丁万。\nclose = 丁万\u{FE0F} \u{1F600}\n").unwrap();
|
||||
std::fs::write(catalogs.join("ar.ftl"), "open = فتح\nok = 一\n").unwrap();
|
||||
let long: String = (0x4E10..0x4E20).filter_map(char::from_u32).collect();
|
||||
std::fs::write(catalogs.join("long.ftl"), format!("x = {long}\n")).unwrap();
|
||||
let paths = ["zh-TW.ftl", "ar.ftl", "long.ftl", "missing.ftl"].map(|f| catalogs.join(f));
|
||||
|
||||
let r = run(Embed::new().scripts(&["Hant", "Arab"]).check_text(paths.clone()), Some(&dir), None);
|
||||
assert_eq!(r.result.as_ref().unwrap().len(), 2);
|
||||
for path in &paths {
|
||||
assert!(r.cargo.contains(&format!("cargo::rerun-if-changed={}", path.display())), "{:?}", r.cargo);
|
||||
}
|
||||
let w = warnings(&r);
|
||||
assert_eq!(w.len(), 3, "{w:#?}");
|
||||
assert!(w[0].contains("zh-TW.ftl has 2 characters no embedded face covers (万。); system fonts"), "{}", w[0]);
|
||||
assert!(w[1].contains("long.ftl has 16 characters") && w[1].contains("(丐丑丒专且丕世丗 …)"), "{}", w[1]);
|
||||
assert!(w[2].contains("cannot check") && w[2].contains("missing.ftl"), "{}", w[2]);
|
||||
|
||||
// The full face covers everything; without a checkout there is nothing to check.
|
||||
let r = run(Embed::new().check_text(paths[..3].to_vec()), Some(&dir), None);
|
||||
assert_eq!(warnings(&r), Vec::<String>::new());
|
||||
let r = run(Embed::new().check_text(paths.clone()), None, None);
|
||||
assert_eq!(warnings(&r), Vec::<String>::new());
|
||||
assert!(r.cargo.contains(&format!("cargo::rerun-if-changed={}", paths[0].display())));
|
||||
|
||||
// Faces another table embeds count as covering their characters.
|
||||
let r = run(Embed::new().scripts(&["Arab"]).embedded_elsewhere(&["Noto Sans SC"]).check_text(paths[..3].to_vec()), Some(&dir), None);
|
||||
assert_eq!(warnings(&r), Vec::<String>::new());
|
||||
let r = run(
|
||||
Embed::new().scripts(&["Arab"]).embedded_elsewhere(&["Noto Sans TC", "Noto Sans Math"]).check_text(paths[..2].to_vec()),
|
||||
Some(&dir),
|
||||
None,
|
||||
);
|
||||
let w = warnings(&r);
|
||||
assert_eq!(w.len(), 2, "{w:#?}");
|
||||
assert!(w[0].contains("embedded_elsewhere names Noto Sans Math, which") && w[0].ends_with("manifest.txt lacks"), "{}", w[0]);
|
||||
assert!(w[1].contains("zh-TW.ftl has 2 characters no embedded face covers (万。)"), "{}", w[1]);
|
||||
|
||||
// The fixture's "fonts" are text, so they cover nothing.
|
||||
let r = run(Embed::new().scripts(&["Arab"]).check_text([&paths[1]]), Some(&fixture()), None);
|
||||
let w = warnings(&r);
|
||||
assert!(w[0].contains("cannot read the character map of Sans Arabic Regular"), "{w:#?}");
|
||||
assert!(w[1].contains("ar.ftl has 1 character no embedded face covers (一)"), "{w:#?}");
|
||||
}
|
||||
|
||||
#[cfg(feature = "subset")]
|
||||
mod subset {
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::{Run, Scratch, checkout, run, tiny_font, warnings};
|
||||
use crate::cmap::Cmap;
|
||||
use crate::{Embed, Error};
|
||||
|
||||
/// `fixture/subset/make-fonts.py` writes these.
|
||||
fn tiny(file: &str) -> Vec<u8> {
|
||||
std::fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixture/subset").join(file)).unwrap()
|
||||
}
|
||||
|
||||
/// The BMP characters `font` maps.
|
||||
fn mapped(font: &[u8]) -> Vec<u32> {
|
||||
let cmap = Cmap::read(font, 0).unwrap();
|
||||
('\0'..='\u{FFFF}').filter(|&c| cmap.covers(c)).map(u32::from).collect()
|
||||
}
|
||||
|
||||
fn table<'a>(font: &'a [u8], tag: &[u8; 4]) -> Option<&'a [u8]> {
|
||||
let u16_at = |at: usize| usize::from(u16::from_be_bytes([font[at], font[at + 1]]));
|
||||
let u32_at = |at: usize| usize::try_from(u32::from_be_bytes(font[at..at + 4].try_into().unwrap())).unwrap();
|
||||
let record = (0..u16_at(4)).map(|i| 12 + 16 * i).find(|&r| &font[r..r + 4] == tag)?;
|
||||
Some(&font[u32_at(record + 8)..][..u32_at(record + 12)])
|
||||
}
|
||||
|
||||
/// The feature tags of a GSUB or GPOS table.
|
||||
fn features(table: &[u8]) -> BTreeSet<String> {
|
||||
let list = usize::from(u16::from_be_bytes([table[6], table[7]]));
|
||||
let count = usize::from(u16::from_be_bytes([table[list], table[list + 1]]));
|
||||
(0..count).map(|i| String::from_utf8_lossy(&table[list + 2 + 6 * i..][..4]).into_owned()).collect()
|
||||
}
|
||||
|
||||
fn glyph_count(font: &[u8]) -> u16 {
|
||||
let maxp = table(font, b"maxp").unwrap();
|
||||
u16::from_be_bytes([maxp[4], maxp[5]])
|
||||
}
|
||||
|
||||
fn cut_file(r: &Run, family: &str) -> PathBuf {
|
||||
r.out.0.join("craft-fonts-ui").join(format!("{}-Regular.ttf", family.replace(' ', "-")))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subset_to_cuts_interface_faces_to_the_catalogs() {
|
||||
let scratch = Scratch::new("subset");
|
||||
let latin = || tiny_font(&[(0x20, 0x7E, None)], &[]);
|
||||
let dir = checkout(
|
||||
&scratch,
|
||||
&[
|
||||
("Noto Sans TC", "Hant,Latn", "", latin()),
|
||||
("Noto Sans TC UI", "Hant,Latn", "ui", tiny("Tiny-glyf.ttf")),
|
||||
("Noto Sans HK UI", "Hant-HK,Latn", "ui", tiny("Tiny-glyf.ttf")),
|
||||
("Noto Sans Arabic", "Arab", "", latin()),
|
||||
],
|
||||
);
|
||||
let tw = scratch.0.join("zh-TW.tsv");
|
||||
std::fs::write(&tw, "Open\t一万\n").unwrap();
|
||||
let ko = scratch.0.join("ko.tsv");
|
||||
std::fs::write(&ko, "Open\t丁\u{FE0F} \u{1F600}\n").unwrap();
|
||||
|
||||
let r = run(Embed::new().subset_to([&tw]).scripts(&["Hant"]), Some(&dir), Some("1"));
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans TC UI Regular", "Noto Sans HK UI Regular"]);
|
||||
let tc = cut_file(&r, "Noto Sans TC UI");
|
||||
assert!(r.table.contains(&format!("index: 0, bytes: include_bytes!({:?})", tc.display().to_string())), "{}", r.table);
|
||||
assert!(r.cargo.contains(&format!("cargo::rerun-if-changed={}", tw.display())), "{:?}", r.cargo);
|
||||
let cut = std::fs::read(&tc).unwrap();
|
||||
// The catalog's 一, plus the punctuation, kana and full-width forms the source has; not
|
||||
// its Latin, nor the 丁 and 七 no catalog uses.
|
||||
assert_eq!(mapped(&cut), [0x3001, 0x300C, 0x3042, 0x4E00, 0xFF01]);
|
||||
assert!(table(&cut, b"glyf").is_some());
|
||||
assert_eq!(features(table(&cut, b"GSUB").unwrap()), BTreeSet::from(["vert".to_owned()]));
|
||||
// .notdef, five characters and the vertical form of U+300C.
|
||||
assert_eq!(glyph_count(&cut), 7);
|
||||
// The source lacks 万, so system fonts draw it.
|
||||
let w = warnings(&r);
|
||||
assert_eq!(w.len(), 1, "{w:#?}");
|
||||
assert!(w[0].contains("zh-TW.tsv has 1 character no embedded face covers (万)"), "{}", w[0]);
|
||||
|
||||
// The same bytes on every run. Another catalog adds its characters, but no emoji or
|
||||
// variation selector, and a `check_text` file is only checked.
|
||||
let again = run(Embed::new().for_ui().subset_to([&tw]), Some(&dir), None);
|
||||
assert_eq!(std::fs::read(cut_file(&again, "Noto Sans TC UI")).unwrap(), cut);
|
||||
let r = run(Embed::new().subset_to([&tw, &ko]).check_text([scratch.0.join("zh-TW.tsv")]), Some(&dir), None);
|
||||
assert_eq!(mapped(&std::fs::read(cut_file(&r, "Noto Sans TC UI")).unwrap()), [0x3001, 0x300C, 0x3042, 0x4E00, 0x4E01, 0xFF01]);
|
||||
assert_eq!(warnings(&r).len(), 1, "{:#?}", warnings(&r));
|
||||
|
||||
// No catalogs (an app whose CRAFT_I18N_DIR is unset) leaves the faces out, not cut to kana.
|
||||
let r = run(Embed::new().subset_to(Vec::<PathBuf>::new()), Some(&dir), None);
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
|
||||
let w = warnings(&r);
|
||||
assert_eq!(w.len(), 1, "{w:#?}");
|
||||
assert!(w[0].contains("Noto Sans TC UI Regular") && w[0].contains("given no translation catalogs"), "{}", w[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subset_to_rejects_cff_interface_faces() {
|
||||
let scratch = Scratch::new("subset-cff");
|
||||
let dir = checkout(&scratch, &[("Noto Sans SC UI", "Hans", "ui", tiny("Tiny-cff.otf"))]);
|
||||
let catalog = scratch.0.join("zh-CN.tsv");
|
||||
std::fs::write(&catalog, "Open\t一\n").unwrap();
|
||||
for required in [None, Some("1")] {
|
||||
let r = run(Embed::new().subset_to([&catalog]), Some(&dir), required);
|
||||
let Err(e @ Error::NotTrueType { .. }) = r.result else { panic!("{:?}", r.result) };
|
||||
assert!(e.to_string().contains("0.ttf has CFF outlines"), "{e}");
|
||||
assert_eq!(r.table.trim(), "&[]");
|
||||
}
|
||||
}
|
||||
|
||||
/// With `CRAFT_FONTS_DIR` set to a craft-fonts checkout, cut its BIZ UDPGothic Regular.
|
||||
#[test]
|
||||
fn cuts_biz_udpgothic() {
|
||||
let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").filter(|dir| !dir.is_empty()) else { return };
|
||||
let Ok(source) = std::fs::read(Path::new(&dir).join("fonts/biz-ud-pgothic/BIZUDPGothic-Regular.ttf")) else { return };
|
||||
let chars: BTreeSet<char> = "ファイルを開く「新規」、保存。編集表示".chars().collect();
|
||||
let cut = crate::subset::subset(&source, 0, &chars).unwrap();
|
||||
let (source_cmap, cmap) = (Cmap::read(&source, 0).unwrap(), Cmap::read(&cut, 0).unwrap());
|
||||
assert!(chars.iter().all(|&c| cmap.covers(c) == source_cmap.covers(c)));
|
||||
assert!(!cmap.covers('A') && !cmap.covers('漢'));
|
||||
assert!(features(table(&cut, b"GSUB").unwrap()).contains("vert"));
|
||||
assert!(cut.len() < source.len() / 20, "{} of {} bytes", cut.len(), source.len());
|
||||
assert_eq!(crate::subset::subset(&source, 0, &chars).unwrap(), cut);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "craft-fonts-build-consumer"
|
||||
description = "Test crate: a build.rs that embeds the craft-fonts-build fixture the way an app does."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
craft-fonts-build = { path = "../.." }
|
||||
|
||||
[build-dependencies]
|
||||
craft-fonts-build = { path = "../.." }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Embeds the fixture checkout in `../fixture/craft-fonts` the way an app's build.rs embeds
|
||||
//! `CRAFT_FONTS_DIR`, so the generated table is compiled by a real `include!`.
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() {
|
||||
let root = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default());
|
||||
let embedded = craft_fonts_build::Embed::new()
|
||||
.dir(root.join("../fixture/craft-fonts"))
|
||||
.required(true)
|
||||
.scripts(&["Jpan", "Hant"])
|
||||
.filter(|face| face.style == "Regular")
|
||||
.write("craft_fonts.rs");
|
||||
if let Err(e) = embedded {
|
||||
println!("cargo::error={e}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
//! The fixture faces as an app's crate sees them; read by `craft-fonts-build`'s tests.
|
||||
|
||||
use craft_fonts_build::EmbeddedFace;
|
||||
|
||||
pub static CRAFT_FONTS: &[EmbeddedFace] = include!(concat!(env!("OUT_DIR"), "/craft_fonts.rs"));
|
||||
@@ -0,0 +1,10 @@
|
||||
# Test fixture in the craft-fonts manifest format. The "font files" are short text files:
|
||||
# embedding copies bytes and never parses them.
|
||||
# family | style | file | scripts | licence | licence file | sha256 | source
|
||||
|
||||
Sans JP | Regular | fonts/sans-jp/SansJP-Regular.ttf | Jpan,Latn | OFL-1.1 | fonts/sans-jp/OFL.txt | c9d08ef1fc69f15e87ce52bda8a9c24714e4125daf7e50a40edb1aa2be10dff1 | https://example.invalid/sans-jp
|
||||
Sans JP | Bold | fonts/sans-jp/SansJP-Bold.ttf | Jpan,Latn | OFL-1.1 | fonts/sans-jp/OFL.txt | a135adabc1facd7a49fa4ef04771f74ffe69e67418e0e0f0b81a4cebba776e48 | https://example.invalid/sans-jp
|
||||
Sans Arabic | Regular | fonts/sans-arabic/SansArabic.ttf | Arab | OFL-1.1 | fonts/sans-arabic/OFL.txt | 318d7469dd372ff3ad458d46ea714c0ea969696675794d6100396f8a11103514 | https://example.invalid/sans-arabic
|
||||
Sans CJK TC | Regular | fonts/sans-cjk/SansCJK.ttc#2 | Hant,Latn | OFL-1.1 | fonts/sans-cjk/OFL.txt | 2fecde232d5dcda26a2299664dae1a2c50ad92b694575c5cfa70207010b339be | https://example.invalid/sans-cjk
|
||||
Sans CJK HK | Regular | fonts/sans-cjk/SansCJK.ttc#3 | Hant-HK,Latn | OFL-1.1 | fonts/sans-cjk/OFL.txt | 2fecde232d5dcda26a2299664dae1a2c50ad92b694575c5cfa70207010b339be | https://example.invalid/sans-cjk
|
||||
Sans Thai | Regular | fonts/sans-thai/SansThai.ttf | Thai | OFL-1.1 | fonts/sans-thai/OFL.txt | 5960276bcbad8e7949804d35651ebf42e17648f4d128c71ccdb76167a5337944 | https://example.invalid/sans-thai
|
||||
@@ -0,0 +1 @@
|
||||
Fixture licence text.
|
||||
@@ -0,0 +1 @@
|
||||
fixture: Sans Arabic
|
||||
@@ -0,0 +1 @@
|
||||
Fixture licence text.
|
||||
@@ -0,0 +1 @@
|
||||
fixture: Sans CJK collection
|
||||
@@ -0,0 +1 @@
|
||||
Fixture licence text.
|
||||
@@ -0,0 +1 @@
|
||||
fixture: Sans JP Bold
|
||||
@@ -0,0 +1 @@
|
||||
fixture: Sans JP Regular
|
||||
@@ -0,0 +1 @@
|
||||
Fixture licence text.
|
||||
@@ -0,0 +1 @@
|
||||
fixture: Sans Thai
|
||||
Binary file not shown.
Binary file not shown.
+80
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env -S uv run --script
|
||||
# /// script
|
||||
# requires-python = ">=3.10"
|
||||
# dependencies = ["fonttools==4.67.0"]
|
||||
# ///
|
||||
"""Write the subsetting fixtures next to this script: Tiny-glyf.ttf (TrueType outlines) and
|
||||
Tiny-cff.otf (CFF outlines). Both map the same characters, have a `vert` feature that swaps
|
||||
U+300C for a vertical form, and draw every glyph as a square.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from fontTools.feaLib.builder import addOpenTypeFeaturesFromString
|
||||
from fontTools.fontBuilder import FontBuilder
|
||||
from fontTools.pens.t2CharStringPen import T2CharStringPen
|
||||
from fontTools.pens.ttGlyphPen import TTGlyphPen
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
CMAP = {
|
||||
0x20: "space",
|
||||
0x41: "A",
|
||||
0x3001: "uni3001",
|
||||
0x300C: "uni300C",
|
||||
0x3042: "uni3042",
|
||||
0x4E00: "uni4E00",
|
||||
0x4E01: "uni4E01",
|
||||
0x4E03: "uni4E03",
|
||||
0xFF01: "uniFF01",
|
||||
}
|
||||
GLYPHS = [".notdef", *CMAP.values(), "uni300C.vert"]
|
||||
FEATURES = "languagesystem DFLT dflt;\nfeature vert { sub uni300C by uni300C.vert; } vert;\n"
|
||||
# 2026-01-01, so the files are the same on every run.
|
||||
TIMESTAMP = 3_850_000_000
|
||||
|
||||
|
||||
def square(pen, size):
|
||||
pen.moveTo((100, 0))
|
||||
pen.lineTo((100, size))
|
||||
pen.lineTo((100 + size, size))
|
||||
pen.lineTo((100 + size, 0))
|
||||
pen.closePath()
|
||||
|
||||
|
||||
def build(cff: bool) -> FontBuilder:
|
||||
fb = FontBuilder(1000, isTTF=not cff)
|
||||
fb.setupGlyphOrder(GLYPHS)
|
||||
fb.setupCharacterMap(CMAP)
|
||||
if cff:
|
||||
charstrings = {}
|
||||
for i, name in enumerate(GLYPHS):
|
||||
pen = T2CharStringPen(1000, None)
|
||||
square(pen, 100 + 10 * i)
|
||||
charstrings[name] = pen.getCharString()
|
||||
fb.setupCFF("Tiny-Regular", {"FullName": "Tiny Regular"}, charstrings, {})
|
||||
else:
|
||||
glyphs = {}
|
||||
for i, name in enumerate(GLYPHS):
|
||||
pen = TTGlyphPen(None)
|
||||
square(pen, 100 + 10 * i)
|
||||
glyphs[name] = pen.glyph()
|
||||
fb.setupGlyf(glyphs)
|
||||
fb.setupHorizontalMetrics({name: (1000, 100) for name in GLYPHS})
|
||||
fb.setupHorizontalHeader(ascent=880, descent=-120)
|
||||
fb.setupNameTable({"familyName": "Tiny", "styleName": "Regular"})
|
||||
fb.setupOS2(sTypoAscender=880, sTypoDescender=-120, usWinAscent=880, usWinDescent=120)
|
||||
fb.setupPost()
|
||||
addOpenTypeFeaturesFromString(fb.font, FEATURES)
|
||||
fb.font["head"].created = TIMESTAMP
|
||||
fb.font["head"].modified = TIMESTAMP
|
||||
fb.font.recalcTimestamp = False
|
||||
return fb
|
||||
|
||||
|
||||
def main() -> None:
|
||||
build(cff=False).save(HERE / "Tiny-glyf.ttf")
|
||||
build(cff=True).save(HERE / "Tiny-cff.otf")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,16 @@
|
||||
//! The table `craft-fonts-build-consumer`'s build.rs generated from the fixture compiles and holds
|
||||
//! the selected faces' bytes.
|
||||
|
||||
use craft_fonts_build_consumer::CRAFT_FONTS;
|
||||
|
||||
#[test]
|
||||
fn generated_table_embeds_the_selected_faces() {
|
||||
let names: Vec<String> = CRAFT_FONTS.iter().map(|f| f.name()).collect();
|
||||
assert_eq!(names, ["Sans JP Regular", "Sans CJK TC Regular", "Sans CJK HK Regular"]);
|
||||
assert_eq!(CRAFT_FONTS[0].bytes, include_bytes!("fixture/craft-fonts/fonts/sans-jp/SansJP-Regular.ttf"));
|
||||
assert_eq!(CRAFT_FONTS[0].scripts, ["Jpan", "Latn"]);
|
||||
let indices: Vec<u32> = CRAFT_FONTS.iter().map(|f| f.index).collect();
|
||||
assert_eq!(indices, [0, 2, 3]);
|
||||
assert_eq!(CRAFT_FONTS[2].bytes, include_bytes!("fixture/craft-fonts/fonts/sans-cjk/SansCJK.ttc"));
|
||||
assert!(CRAFT_FONTS[2].has_script("Hant"));
|
||||
}
|
||||
+29
-3
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "craft-i18n"
|
||||
description = "Translations for the Craft apps: the embedded craft-i18n catalogs, lookup with fallback, plurals, language names and the system locale."
|
||||
description = "Translations for the Craft apps: the embedded craft-i18n catalogs, lookup with fallback, plurals, numbers for a region, language names, the system locale, search folding and locale sorting."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -8,13 +8,39 @@ rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
intl_pluralrules = "=7.0.2"
|
||||
unic-langid = "0.9"
|
||||
# Numbers and plural rules, on CLDR data (data/numbers.postcard) generated for one ICU4X minor
|
||||
# version, hence `~2.3`.
|
||||
fixed_decimal = { version = "0.7.2", default-features = false }
|
||||
icu_decimal = { version = "~2.3", default-features = false, features = ["serde"] }
|
||||
icu_locale_core = { version = "~2.3", default-features = false }
|
||||
icu_locale_fallback = { version = "~2.3", default-features = false, features = ["compiled_data"] }
|
||||
icu_plurals = { version = "~2.3", default-features = false, features = ["serde"] }
|
||||
icu_provider = { version = "~2.3", default-features = false, features = ["sync"] }
|
||||
icu_provider_adapters = { version = "~2.3", default-features = false }
|
||||
icu_provider_blob = { version = "~2.3", default-features = false }
|
||||
writeable = "0.6"
|
||||
log = "0.4"
|
||||
sys-locale = "0.3"
|
||||
icu_normalizer = "~2.3"
|
||||
icu_properties = "~2.3"
|
||||
# Generated data fits one ICU4X minor version; data/generate-collation.sh names its datagen.
|
||||
icu_collator = { version = "~2.3.1", default-features = false, features = ["serde"], optional = true }
|
||||
unicode-bidi = "0.3"
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
sys-locale = { version = "0.3", features = ["js"] }
|
||||
|
||||
# The regional format (Region::system); safe registry reads, MIT OR Apache-2.0.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-registry = "0.6"
|
||||
|
||||
# The current locale (Region::system); already in the apps' Cargo.lock through eframe.
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies]
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSDateFormatter", "NSFormatter", "NSLocale", "NSString"] }
|
||||
|
||||
[features]
|
||||
# Locale sorting (`collate`), with ICU4X collation data for the suite's locales embedded.
|
||||
collate = ["dep:icu_collator", "icu_provider/serde", "icu_provider_blob/alloc"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+88
-12
@@ -45,10 +45,21 @@ The app keeps its `tl!` macro, its language setting (`"auto"` → `I18N.system_l
|
||||
→ `pt`, `zh-hant-hk` → `zh-hant`); `sr-latn` never falls back to Cyrillic `sr`. A missing
|
||||
translation never errors.
|
||||
- **Lookups:** `t` (plain), `tc` (with a context such as `menu` or `@msg`, else plain), `tid` (an
|
||||
`@id` command id, else the English label), `trn` (a count, `@plural` rows, `{n}` filled), `get`
|
||||
(one context along the locale chain, so `pt-br` can return a `pt` row, but never the plain row
|
||||
`@id` command id, else the English label), `trn` and `trn_decimal` (a count, `@plural` rows,
|
||||
`{n}` filled), `get` (one context along the locale chain, so `pt-br` can return a `pt` row, but never the plain row
|
||||
or English: a key cap's name under `key`, or "is there a translation?"), and `fmt` for `{name}`
|
||||
placeholders, filled in one pass.
|
||||
- **Isolation:** when a message or a value inserted into it has a right-to-left letter (bidi
|
||||
class R or AL), or a value has a bidi control (LRE, RLE, PDF, LRO, RLO, LRI, RLI, FSI, PDI,
|
||||
LRM, RLM, ALM), `fmt` wraps each inserted value in a first-strong isolate (FSI…PDI), and `trn`,
|
||||
`file_size` and `measure` wrap `{n}` in a left-to-right one (LRI…PDI), so a Latin file name in an Arabic sentence, a
|
||||
Hebrew name in an English one, or an ASCII file name with a right-to-left override can't
|
||||
reorder the words around it. Embeddings, overrides and isolates a value opens are closed inside
|
||||
its isolate, and a stray PDF or PDI in it is dropped. Wrap numbers, paths and codes in `ltr`
|
||||
before passing them; a value that already is one isolate keeps it. Other text comes out
|
||||
without marks, as if `fmt` didn't isolate at all. egui draws the marks as nothing. For text
|
||||
that leaves the interface (file names, logs, terminals, text parsed later), use `fmt_plain` or
|
||||
`strip_isolates`.
|
||||
- **Bad rows** (malformed, an unknown `@` context, a wrong plural form count, a row defined twice,
|
||||
of which the first is kept) and bad locales (`en`, `pseudo`, a code embedded twice in any case)
|
||||
are skipped; craft-i18n's CI rejects them before they ship. `I18n::new` parses nothing: it
|
||||
@@ -56,21 +67,86 @@ The app keeps its `tl!` macro, its language setting (`"auto"` → `I18N.system_l
|
||||
`log::warn!`) on the first lookup that reaches it, including as a fallback. `I18n::check_all()`
|
||||
parses every locale and returns all problems (`<locale>/<common|app>: line N: …`), for a test.
|
||||
- **Plurals:** forms are listed in CLDR order (zero, one, two, few, many, other) for the categories
|
||||
whole numbers 0 to 1000 reach, from `intl_pluralrules`; a count in any other category takes the
|
||||
last form. CLDR's `pt` is Brazilian, so `pt` uses `pt-PT`'s rules (0 is plural) and `pt-br`
|
||||
`pt`'s. `intl_pluralrules` is pinned to the version craft-i18n's checker uses, and
|
||||
`plural_form_counts` holds the same counts.
|
||||
whole numbers 0 to 1000 reach, from ICU4X's CLDR rules; `plural_form_counts` holds the counts
|
||||
craft-i18n's checker expects. `trn_decimal` picks the form from the digits shown (ICU4X plural
|
||||
operands), so English `1.0` is plural and French `1,5` singular. A count in a category integers
|
||||
never reach takes the `few` form if there is one (Russian and Ukrainian decimals, `1,5 файла`),
|
||||
else the last. Rules are per language, so `sr-latn` and `zh-hant` take `sr`'s and `zh`'s. CLDR's
|
||||
`pt` is Brazilian, so `pt` uses `pt-PT`'s rules (0 is plural) and `pt-br` `pt`'s. A language
|
||||
CLDR has no plural rules for shows English forms.
|
||||
- **Names:** a language's name comes from the app catalog's `@id language.name` row, else the
|
||||
shared catalog's, else its code; English is "English".
|
||||
- **Right to left:** `rtl` is true for `ar`, `ckb`, `dv`, `fa`, `he`, `ps`, `sd`, `ug`, `ur` and
|
||||
`yi`; putting text into display order is the app's job.
|
||||
- **Scripts and direction:** for any language tag, `scripts` lists the ISO 15924 scripts its
|
||||
interface text is written in (`ja` → Hani, Hira, Kana; `sr-latn` → Latn; `pa-PK` → Arab),
|
||||
`direction` is right to left when the main script is (Arabic, Hebrew, Syriac, Thaana), and `han`
|
||||
gives the regional forms of its Han characters for picking a CJK face: `zh-CN`/`zh-SG`/`zh-Hans` →
|
||||
SC, `zh-TW`/`zh-US`/`zh-Hant` → TC, `zh-HK`/`zh-MO` → HK, `ja` → JP, `ko` → KR. `I18n::rtl` is
|
||||
`direction` of the language's code; putting text into display order is the app's job.
|
||||
- **Reading numbers:** `Format::parse(text)` reads what the format writes (its digits, decimal
|
||||
and grouping separators, the system's included) and what people type or paste: any Unicode
|
||||
decimal digits (ASCII, Arabic-Indic, Persian, Devanagari, Bengali, Thai, full-width, …) from one
|
||||
set; `٫` as a decimal mark everywhere; grouping by the locale's other mark of `.` and `,`, spaces
|
||||
(NBSP, narrow NBSP), `'`, `’` or `٬`, in threes or the Indian 2-2-3; a leading `-`, `−` or `+`;
|
||||
bidi marks ignored. A lone `.` in a comma locale is decimal when it can't be grouping (`1.5`,
|
||||
`0.250`, `1234.5`), while `1.234` stays 1234 in German; the same holds for `,` in a point
|
||||
locale. Percent signs and units (`50 %`, `12 px`) are not read: strip them first. Other input
|
||||
that doesn't fit is an error, never a guess. `parse_number(text, locale)` is the same for
|
||||
`Format::from_tag(locale)`.
|
||||
- **System locale:** `system_lang` matches the system's list once and caches it: on desktop Unix
|
||||
`LANGUAGE`, `LC_ALL`, `LC_MESSAGES` and `LANG`, read raw; elsewhere `sys-locale`'s (macOS and
|
||||
Windows preferred languages, the browser's on the web). `fr_CA.UTF-8` → `fr`, `zh-TW` →
|
||||
`zh-hant`, `pt-PT` → `pt-br` when that is the only Portuguese, `C`/`POSIX` → English. A script
|
||||
is never crossed: `sr_RS@latin` and `sr-Latn-RS` pick `sr-latn`, never `sr`, while `sr-Cyrl-RS`
|
||||
picks `sr`.
|
||||
Windows preferred languages, the browser's on the web). `fr_CA.UTF-8` → `fr`, `zh-TW` → `zh-hant`,
|
||||
`pt-PT` → `pt-br` when that is the only Portuguese, `C`/`POSIX` → English. A script is never
|
||||
crossed: `sr_RS@latin` and `sr-Latn-RS` pick `sr-latn`, never `sr`, while `sr-Cyrl-RS` picks `sr`.
|
||||
A region that implies a script counts as that script: `pa-PK` picks `pa-arab`, not Gurmukhi `pa`.
|
||||
- **Sizes and units:** `file_size(lang, bytes, style)` writes `1.5 MB` or `512 bytes`; `FileSize`
|
||||
picks steps of 1024 named KB (`BINARY`), 1024 named KiB (`IEC`) or 1000 named KB (`DECIMAL`),
|
||||
the decimals per unit, no decimals from a given value up, the smallest and largest unit (below
|
||||
the smallest, sizes round up), and `B` or words for bytes. `measure(lang, value, decimals,
|
||||
"{n} px")` writes any other measure. Unit names are rows in context `unit`, keyed by the English
|
||||
template (`{n} MB` → `{n} Mo`, `{n}%` → `{n} %`) and read with `get`, so a plain `B` row (bold)
|
||||
is never used; bytes in words are the `@plural` row `{n} byte|{n} bytes`. Numbers are written
|
||||
by `I18n::format`.
|
||||
- **Numbers:** `Format` writes numbers for a `Region` on ICU4X's decimal formatter: `integer`
|
||||
(`1.234.567`, Indian `12,34,567`), `number(value, decimals)` and `percent(ratio, decimals)`
|
||||
(`50 %`, Turkish `%50`). It follows the region, not the interface language, with the locale's
|
||||
digits (`١٬٢٣٤٫٥` in Egypt, `۱٬۲۳۴` in Iran) or, with `Digits::Latin`, `0`–`9`. With Latin
|
||||
digits, a decimal or grouping separator the system sets (Windows' and macOS's own settings)
|
||||
replaces the locale's. `I18n::format` is the format `trn`, `file_size` and `measure` use: the
|
||||
system region's until `I18n::set_format` (the user's region setting or digit choice), and again
|
||||
after `I18n::reset_format`. A count in `trn` is therefore grouped and in the region's digits
|
||||
(`1.234 Dateien`, `١٬٢٣٤ ملفًا`); for names written into documents or files (`Copy 1234`), use
|
||||
`trn_plain`, which writes `0`–`9` without grouping or isolate marks.
|
||||
- **CLDR data:** decimal symbols, digits and plural rules (`data/numbers.postcard`, about 10 KB) and
|
||||
percent patterns (`data/locales.rs`) cover every CLDR locale; `data/generate.sh` rebuilds both
|
||||
from CLDR. The ICU4X crates are pinned to one minor version (`~2.3`), the one the data is
|
||||
generated for. The ICU4X code and data add about 90 KB to a stripped release build and 80 KB to
|
||||
wasm.
|
||||
- **Formatting region:** `Region` holds how numbers, times and measurements are written, apart
|
||||
from the interface language: the number and time locales (BCP 47), metric or US measurement, A4
|
||||
or Letter, and the decimal and grouping separators (or no grouping) and clock when the system
|
||||
sets them; otherwise the number locale's CLDR data decides. `Region::system()` reads it once:
|
||||
Windows' regional format with the user's changes (`HKCU\Control Panel\International`), Apple's
|
||||
current locale (`en_PL`, `en_GB@rg=uszzzz`), `LC_ALL` or else `LC_NUMERIC`, `LC_TIME`,
|
||||
`LC_MEASUREMENT` and `LC_PAPER` each on its own over `LANG` on Unix (`C` there is English on A4,
|
||||
metric, with a `.` decimal and no grouping; `LANG=C` gives way to the preferred language), the
|
||||
preferred language on the web and Android. `Region::from_setting` takes the app's saved choice
|
||||
(`auto` or a tag like `pl-PL`). Paper and measurement follow CLDR's territory lists; tags may
|
||||
carry `-u-ms-`, `-u-hc-`, `-u-rg-` and `-u-nu-` (Apple's `@numbers=`), and a chosen digit
|
||||
system stays in the number locale.
|
||||
Ported from WordCraft's `Region`.
|
||||
- **Pseudo locale** (`pseudo`, debug builds only, never in `languages()`): every lookup, `get`
|
||||
included, comes back as `⟦…⟧`, line by line, so text drawn without the marks never went through
|
||||
translation. `looked_up()` lists the source texts looked up so far, for an audit against a
|
||||
complete catalog.
|
||||
- **Search** (`Folder`): `Folder::new(locale).fold(text)` gives a key for case- and
|
||||
accent-insensitive matching (`keep_accents()` makes accents count) and a map back to the original
|
||||
text, so `Folded::find` returns the byte range to highlight. Compatibility forms fold to their
|
||||
plain letters (`fi`, full-width `A`), `ß` to `ss`, `ς` to `σ`, digits of every script to ASCII
|
||||
(`Layer ١٢` finds `layer 12`); ignoring accents, Persian and Arabic letter forms match (`ک` and
|
||||
`ك`, `ی` and `ي`, `ة` and `ه`, `أ` and `ا`); invisible format characters (soft hyphens, joiners,
|
||||
bidi isolates) are dropped. Turkish and Azerbaijani fold `I` to `ı` when accents count; ignoring
|
||||
accents, `I`, `i`, `İ` and `ı` all match.
|
||||
- **Sorting** (`Collator`, feature `collate`): ICU4X collation for the locales craft-i18n ships,
|
||||
Persian and Hindi, with digits compared by value (`Layer 2` before `Layer 10`) and `-u-co-pinyin`
|
||||
/ `-u-co-stroke` for Chinese. The data (754 KB) is regenerated by `data/generate-collation.sh`;
|
||||
the feature adds about 1 MB to a release binary or wasm module (320 KB gzipped).
|
||||
Binary file not shown.
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
# Regenerates the collation data `collate` embeds, a postcard blob for the locales craft-i18n
|
||||
# ships (its `locales/` directory) plus English, Persian and Hindi: each locale's default order,
|
||||
# and Chinese pinyin and stroke orders.
|
||||
# Needs icu4x-datagen at the version of the icu_collator dependency:
|
||||
# cargo install icu4x-datagen --version 2.3.0 --locked
|
||||
set -eu
|
||||
cd "$(dirname "$0")"
|
||||
icu4x-datagen --format blob --overwrite --out collation.postcard --deduplication maximal \
|
||||
--cldr-tag 48.2.1 --icuexport-tag release-78.1rc \
|
||||
--attribute-filter 'collator=/^(stroke|pinyin)?$/' \
|
||||
--markers CollationRootV1 CollationTailoringV1 CollationDiacriticsV1 CollationJamoV1 \
|
||||
CollationMetadataV1 CollationReorderingV1 CollationSpecialPrimariesV1 \
|
||||
--locales en ar bg cs da de el es et fa fi fr hi hr hu id it ja ka kk ko lt nl pl pt-BR ru sl \
|
||||
sr sr-Latn sv te tr uk vi zh-Hans zh-Hant
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates the number and plural data in this directory from Unicode CLDR, for every CLDR
|
||||
# locale: 10 KB, of which CLDR's modern-coverage locales alone would be 7 KB. Lookups fall back
|
||||
# at run time, so a locale whose data matches its parent's is left out.
|
||||
#
|
||||
# Needs `cargo install icu4x-datagen --version 2.3.0` (the ICU4X minor version in Cargo.toml)
|
||||
# and python3. Downloads CLDR's JSON release once into $CACHE.
|
||||
set -euo pipefail
|
||||
|
||||
CLDR=48.2.1
|
||||
HERE=$(cd "$(dirname "$0")" && pwd)
|
||||
CACHE=${CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/craft-i18n-data}
|
||||
mkdir -p "$CACHE"
|
||||
|
||||
TMPDIR=$CACHE icu4x-datagen --format blob --overwrite \
|
||||
--cldr-tag "$CLDR" \
|
||||
--markers DecimalSymbolsV1 DecimalDigitsV1 PluralsCardinalV1 \
|
||||
--locales full --deduplication maximal \
|
||||
--out "$HERE/numbers.postcard"
|
||||
|
||||
ZIP=$CACHE/icu4x-source-cache/github.com/unicode-org/cldr-json/releases/download/$CLDR/cldr-$CLDR-json-full.zip
|
||||
python3 -I "$HERE/locales.py" "$ZIP" "$CLDR" > "$HERE/locales.rs.tmp"
|
||||
mv "$HERE/locales.rs.tmp" "$HERE/locales.rs"
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Writes locales.rs from CLDR's JSON release: the languages with plural rules and every locale's
|
||||
percent affixes.
|
||||
|
||||
Usage: locales.py <cldr-json-full.zip> <cldr version>
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
|
||||
def rust(s):
|
||||
return '"' + "".join(c if " " <= c <= "~" and c not in '"\\' else f"\\u{{{ord(c):x}}}" for c in s) + '"'
|
||||
|
||||
|
||||
def affixes(numbers, numsys):
|
||||
pattern = numbers[f"percentFormats-numberSystem-{numsys}"]["standard"].split(";")[0].replace("'", "")
|
||||
sign = numbers[f"symbols-numberSystem-{numsys}"]["percentSign"]
|
||||
number = re.search(r"[#0,.]+", pattern)
|
||||
return pattern[: number.start()].replace("%", sign), pattern[number.end() :].replace("%", sign)
|
||||
|
||||
|
||||
def main():
|
||||
path, version = sys.argv[1], sys.argv[2]
|
||||
found = {}
|
||||
with zipfile.ZipFile(path) as z:
|
||||
plurals = json.loads(z.read("cldr-core/supplemental/plurals.json"))["supplemental"]["plurals-type-cardinal"]
|
||||
languages = sorted(l for l in plurals if l != "root" and "-" not in l)
|
||||
for name in z.namelist():
|
||||
m = re.fullmatch(r"cldr-numbers-full/main/([^/]+)/numbers\.json", name)
|
||||
if not m or m.group(1) == "root":
|
||||
continue
|
||||
locale = m.group(1)
|
||||
numbers = json.loads(z.read(name))["main"][locale]["numbers"]
|
||||
found[(locale, True)] = affixes(numbers, "latn")
|
||||
default = numbers["defaultNumberingSystem"]
|
||||
if default != "latn":
|
||||
found[(locale, False)] = affixes(numbers, default)
|
||||
|
||||
# Kept only where the lookup by dropping trailing subtags would find something else.
|
||||
kept = {}
|
||||
for (locale, latin), value in sorted(found.items(), key=lambda e: (e[0][0].count("-"), e[0])):
|
||||
parts = locale.split("-")
|
||||
inherited = ("", "%")
|
||||
for n in range(len(parts) - 1, 0, -1):
|
||||
if ("-".join(parts[:n]), latin) in kept:
|
||||
inherited = kept[("-".join(parts[:n]), latin)]
|
||||
break
|
||||
if value != inherited:
|
||||
kept[(locale, latin)] = value
|
||||
|
||||
print(f"// @generated by generate.sh from Unicode CLDR {version} (Unicode License).")
|
||||
print()
|
||||
print("/// The languages CLDR has plural rules for; the baked data has them all.")
|
||||
print("pub(crate) const PLURAL_LANGUAGES: &[&str] = &[")
|
||||
for i in range(0, len(languages), 16):
|
||||
print(" " + ", ".join(rust(l) for l in languages[i : i + 16]) + ",")
|
||||
print("];")
|
||||
print()
|
||||
print("/// Percent signs around the number (CLDR's standard percent pattern and sign): locale, Latin")
|
||||
print("/// digits or the locale's own, text before the number, text after it. A locale missing here")
|
||||
print("/// takes its parent's by dropping trailing subtags, then `{n}%`.")
|
||||
print("pub(crate) const PERCENT: &[(&str, bool, &str, &str)] = &[")
|
||||
for (locale, latin), (before, after) in sorted(kept.items()):
|
||||
print(f" ({rust(locale)}, {str(latin).lower()}, {rust(before)}, {rust(after)}),")
|
||||
print("];")
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,144 @@
|
||||
// @generated by generate.sh from Unicode CLDR 48.2.1 (Unicode License).
|
||||
|
||||
/// The languages CLDR has plural rules for; the baked data has them all.
|
||||
pub(crate) const PLURAL_LANGUAGES: &[&str] = &[
|
||||
"af", "ak", "am", "an", "ar", "ars", "as", "asa", "ast", "az", "bal", "be", "bem", "bez", "bg", "bho",
|
||||
"blo", "bm", "bn", "bo", "br", "brx", "bs", "ca", "ce", "ceb", "cgg", "chr", "ckb", "cs", "csw", "cv",
|
||||
"cy", "da", "de", "doi", "dsb", "dv", "dz", "ee", "el", "en", "eo", "es", "et", "eu", "fa", "ff",
|
||||
"fi", "fil", "fo", "fr", "fur", "fy", "ga", "gd", "gl", "gsw", "gu", "guw", "gv", "ha", "haw", "he",
|
||||
"hi", "hnj", "hr", "hsb", "hu", "hy", "ia", "id", "ie", "ig", "ii", "io", "is", "it", "iu", "ja",
|
||||
"jbo", "jgo", "jmc", "jv", "jw", "ka", "kab", "kaj", "kcg", "kde", "kea", "kk", "kkj", "kl", "km", "kn",
|
||||
"ko", "kok", "ks", "ksb", "ksh", "ku", "kw", "ky", "lag", "lb", "lg", "lij", "lkt", "lld", "ln", "lo",
|
||||
"lt", "lv", "mas", "mg", "mgo", "mk", "ml", "mn", "mo", "mr", "ms", "mt", "my", "nah", "naq", "nb",
|
||||
"nd", "ne", "nl", "nn", "nnh", "no", "nqo", "nr", "nso", "ny", "nyn", "om", "or", "os", "osa", "pa",
|
||||
"pap", "pcm", "pl", "prg", "ps", "pt", "rm", "ro", "rof", "ru", "rwk", "sah", "saq", "sat", "sc", "scn",
|
||||
"sd", "sdh", "se", "seh", "ses", "sg", "sgs", "sh", "shi", "si", "sk", "sl", "sma", "smi", "smj", "smn",
|
||||
"sms", "sn", "so", "sq", "sr", "ss", "ssy", "st", "su", "sv", "sw", "syr", "ta", "te", "teo", "th",
|
||||
"ti", "tig", "tk", "tl", "tn", "to", "tpi", "tr", "ts", "tzm", "ug", "uk", "und", "ur", "uz", "ve",
|
||||
"vec", "vi", "vo", "vun", "wa", "wae", "wo", "xh", "xog", "yi", "yo", "yue", "zh", "zu",
|
||||
];
|
||||
|
||||
/// Percent signs around the number (CLDR's standard percent pattern and sign): locale, Latin
|
||||
/// digits or the locale's own, text before the number, text after it. A locale missing here
|
||||
/// takes its parent's by dropping trailing subtags, then `{n}%`.
|
||||
pub(crate) const PERCENT: &[(&str, bool, &str, &str)] = &[
|
||||
("ar", true, "", "\u{200e}%\u{200e}"),
|
||||
("ar-BH", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-DJ", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-EG", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-ER", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-IL", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-IQ", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-JO", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-KM", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-KW", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-LB", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-MR", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-OM", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-PS", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-QA", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-SA", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-SA", true, "", "\u{66a}"),
|
||||
("ar-SD", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-SO", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-SO", true, "", "\u{66a}"),
|
||||
("ar-SS", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-SY", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-TD", false, "", "\u{66a}\u{61c}"),
|
||||
("ar-YE", false, "", "\u{66a}\u{61c}"),
|
||||
("az-Arab", false, "", "\u{66a}"),
|
||||
("bas", true, "", "\u{a0}%"),
|
||||
("be", true, "", "\u{a0}%"),
|
||||
("bgn", false, "", "\u{66a}"),
|
||||
("bgn", true, "", "\u{66a}"),
|
||||
("blo", true, "%\u{a0}", ""),
|
||||
("br", true, "", "\u{a0}%"),
|
||||
("bua", true, "", "\u{a0}%"),
|
||||
("ca", true, "", "\u{a0}%"),
|
||||
("ce", true, "", "\u{a0}%"),
|
||||
("ckb", false, "", "\u{a0}\u{66a}"),
|
||||
("cs", true, "", "\u{a0}%"),
|
||||
("cv", true, "", "\u{a0}%"),
|
||||
("da", true, "", "\u{a0}%"),
|
||||
("de", true, "", "\u{a0}%"),
|
||||
("de-CH", true, "", "%"),
|
||||
("de-LI", true, "", "%"),
|
||||
("dsb", true, "", "\u{a0}%"),
|
||||
("dua", true, "", "\u{a0}%"),
|
||||
("dz", false, "", "\u{a0}%"),
|
||||
("dz", true, "", "\u{a0}%"),
|
||||
("en-AT", true, "", "\u{a0}%"),
|
||||
("en-DE", true, "", "\u{a0}%"),
|
||||
("en-DK", true, "", "\u{a0}%"),
|
||||
("en-FI", true, "", "\u{a0}%"),
|
||||
("en-NO", true, "", "\u{a0}%"),
|
||||
("en-SE", true, "", "\u{a0}%"),
|
||||
("es", true, "", "\u{a0}%"),
|
||||
("es-419", true, "", "%"),
|
||||
("es-AR", true, "", "%"),
|
||||
("es-BO", true, "", "%"),
|
||||
("es-BR", true, "", "%"),
|
||||
("es-BZ", true, "", "%"),
|
||||
("es-CL", true, "", "%"),
|
||||
("es-CO", true, "", "%"),
|
||||
("es-CR", true, "", "%"),
|
||||
("es-CU", true, "", "%"),
|
||||
("es-DO", true, "", "%"),
|
||||
("es-EC", true, "", "%"),
|
||||
("es-GT", true, "", "%"),
|
||||
("es-HN", true, "", "%"),
|
||||
("es-MX", true, "", "%"),
|
||||
("es-NI", true, "", "%"),
|
||||
("es-PA", true, "", "%"),
|
||||
("es-PE", true, "", "%"),
|
||||
("es-PR", true, "", "%"),
|
||||
("es-PY", true, "", "%"),
|
||||
("es-SV", true, "", "%"),
|
||||
("es-US", true, "", "%"),
|
||||
("es-UY", true, "", "%"),
|
||||
("es-VE", true, "", "%"),
|
||||
("eu", true, "%\u{a0}", ""),
|
||||
("fa", false, "", "\u{66a}"),
|
||||
("fi", true, "", "\u{a0}%"),
|
||||
("fo", true, "", "\u{a0}%"),
|
||||
("fr", true, "", "\u{a0}%"),
|
||||
("fr-CH", true, "", "%"),
|
||||
("gl", true, "", "\u{a0}%"),
|
||||
("gsw", true, "", "\u{a0}%"),
|
||||
("hr", true, "", "\u{a0}%"),
|
||||
("hsb", true, "", "\u{a0}%"),
|
||||
("ht", true, "", "\u{a0}%"),
|
||||
("kl", true, "", "\u{a0}%"),
|
||||
("ks", false, "", "\u{66a}"),
|
||||
("ksh", true, "", "\u{a0}%"),
|
||||
("ku", true, "%", ""),
|
||||
("ku-Arab", true, "", "%"),
|
||||
("lb", true, "", "\u{a0}%"),
|
||||
("lrc", false, "", "\u{66a}"),
|
||||
("lt", true, "", "\u{a0}%"),
|
||||
("mk", true, "", "\u{a0}%"),
|
||||
("mzn", false, "", "\u{66a}"),
|
||||
("nb", true, "", "\u{a0}%"),
|
||||
("nds", true, "", "\u{a0}%"),
|
||||
("nn", true, "", "\u{a0}%"),
|
||||
("no", true, "", "\u{a0}%"),
|
||||
("oc", true, "", "\u{202f}%"),
|
||||
("pa-Arab", false, "", "\u{66a}"),
|
||||
("ps", false, "", "\u{66a}"),
|
||||
("qu", true, "", "\u{a0}%"),
|
||||
("rn", true, "", "\u{a0}%"),
|
||||
("ro", true, "", "\u{a0}%"),
|
||||
("ru", true, "", "\u{a0}%"),
|
||||
("sd", false, "", "\u{66a}\u{61c}"),
|
||||
("sdh", false, "", "\u{66a}\u{61c}"),
|
||||
("se", true, "", "\u{a0}%"),
|
||||
("sk", true, "", "\u{a0}%"),
|
||||
("sl", true, "", "\u{a0}%"),
|
||||
("smn", true, "", "\u{a0}%"),
|
||||
("sv", true, "", "\u{a0}%"),
|
||||
("tk", true, "", "\u{a0}%"),
|
||||
("tr", true, "%", ""),
|
||||
("tt", true, "", "\u{a0}%"),
|
||||
("uz-Arab", false, "", "\u{66a}"),
|
||||
("zgh", true, "", "\u{a0}%"),
|
||||
];
|
||||
Binary file not shown.
@@ -0,0 +1,234 @@
|
||||
//! Locale sorting for lists people see: fonts, layers, presets, files.
|
||||
//!
|
||||
//! ICU4X collation with data embedded for the locales craft-i18n ships (regenerated by
|
||||
//! `data/generate-collation.sh`). A locale without data of its own sorts in the Unicode root
|
||||
//! order, which suits most languages that have no tailoring.
|
||||
|
||||
use std::cmp::Ordering;
|
||||
|
||||
use icu_collator::CollatorPreferences;
|
||||
use icu_collator::options::CollatorOptions;
|
||||
use icu_collator::preferences::CollationNumericOrdering;
|
||||
use icu_collator::provider::{
|
||||
CollationDiacriticsV1, CollationJamoV1, CollationMetadataV1, CollationReorderingV1, CollationRootV1, CollationSpecialPrimariesV1,
|
||||
CollationTailoringV1,
|
||||
};
|
||||
use icu_locale_core::Locale;
|
||||
use icu_locale_fallback::LocaleFallbacker;
|
||||
use icu_normalizer::provider::{NormalizerNfdDataV1, NormalizerNfdTablesV1};
|
||||
use icu_provider::buf::AsDeserializingBufferProvider;
|
||||
use icu_provider::prelude::*;
|
||||
use icu_provider_adapters::fallback::LocaleFallbackProvider;
|
||||
use icu_provider_blob::BlobDataProvider;
|
||||
|
||||
/// Compares text in one locale's order, with runs of digits by their value: `Layer 2` before
|
||||
/// `Layer 10`.
|
||||
#[derive(Debug)]
|
||||
pub struct Collator(Option<icu_collator::Collator>);
|
||||
|
||||
impl Collator {
|
||||
/// Sorting for `locale`, a language code such as `sv`, `pt-br` or `zh-hant` (any case, `-`
|
||||
/// or `_`, glibc forms such as `sv_SE.UTF-8` and `sr_RS@latin`). A BCP 47 collation type
|
||||
/// picks another order where there is one: `zh-hant-u-co-pinyin`, `zh-hans-u-co-stroke`.
|
||||
pub fn new(locale: &str) -> Collator {
|
||||
let mut prefs: CollatorPreferences = Locale::try_from_str(&bcp47(locale)).unwrap_or(Locale::UNKNOWN).into();
|
||||
prefs.numeric_ordering = Some(CollationNumericOrdering::True);
|
||||
let options = CollatorOptions::default();
|
||||
let collator = Data::new().ok().and_then(|data| {
|
||||
icu_collator::Collator::try_new_unstable(&data, prefs, options)
|
||||
.or_else(|_| icu_collator::Collator::try_new_unstable(&data, CollatorPreferences::default(), options))
|
||||
.ok()
|
||||
});
|
||||
Collator(collator)
|
||||
}
|
||||
|
||||
/// `a` against `b`. Text that differs only in case or accents still has an order, and text
|
||||
/// the collation counts as equal (`Layer 2` and `Layer 02`) is in code point order, so a sort
|
||||
/// doesn't depend on the input order. Without collation data (never with the embedded data)
|
||||
/// this is code point order.
|
||||
pub fn compare(&self, a: &str, b: &str) -> Ordering {
|
||||
match &self.0 {
|
||||
Some(c) => c.as_borrowed().compare(a, b).then_with(|| a.cmp(b)),
|
||||
None => a.cmp(b),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sort `items` by the text `key` gives each one.
|
||||
pub fn sort_by_key<T>(&self, items: &mut [T], key: impl Fn(&T) -> &str) {
|
||||
items.sort_by(|a, b| self.compare(key(a), key(b)));
|
||||
}
|
||||
}
|
||||
|
||||
/// `locale` as a BCP 47 tag: `_` → `-`, a glibc codeset dropped and its script modifier made a
|
||||
/// subtag (`sr_RS.UTF-8@latin` → `sr-latn-RS`).
|
||||
fn bcp47(locale: &str) -> String {
|
||||
let locale = locale.trim();
|
||||
let mut parts: Vec<&str> = locale.split(['.', '@']).next().unwrap_or_default().split(['-', '_']).collect();
|
||||
let script = match locale.split_once('@').map(|(_, m)| m.to_ascii_lowercase()).as_deref() {
|
||||
Some("latin") => Some("latn"),
|
||||
Some("cyrillic") => Some("cyrl"),
|
||||
_ => None,
|
||||
};
|
||||
let has_script = parts.get(1).is_some_and(|p| p.len() == 4 && p.bytes().all(|b| b.is_ascii_alphabetic()));
|
||||
if let Some(script) = script
|
||||
&& !has_script
|
||||
{
|
||||
parts.insert(1.min(parts.len()), script);
|
||||
}
|
||||
parts.join("-")
|
||||
}
|
||||
|
||||
/// The embedded collation data, with locale fallback, and the decomposition tables the collator
|
||||
/// also needs taken from `icu_normalizer`'s compiled data rather than embedded a second time.
|
||||
struct Data(LocaleFallbackProvider<BlobDataProvider>);
|
||||
|
||||
impl Data {
|
||||
fn new() -> Result<Data, DataError> {
|
||||
let blob = BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/collation.postcard"))?;
|
||||
Ok(Data(LocaleFallbackProvider::new(blob, LocaleFallbacker::new().static_to_owned())))
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! from_blob {
|
||||
($($marker:ty),*) => {$(
|
||||
impl DataProvider<$marker> for Data {
|
||||
fn load(&self, req: DataRequest) -> Result<DataResponse<$marker>, DataError> {
|
||||
self.0.as_deserializing().load(req)
|
||||
}
|
||||
}
|
||||
)*};
|
||||
}
|
||||
|
||||
from_blob!(
|
||||
CollationRootV1,
|
||||
CollationTailoringV1,
|
||||
CollationDiacriticsV1,
|
||||
CollationJamoV1,
|
||||
CollationMetadataV1,
|
||||
CollationReorderingV1,
|
||||
CollationSpecialPrimariesV1
|
||||
);
|
||||
|
||||
impl DataProvider<NormalizerNfdDataV1> for Data {
|
||||
fn load(&self, req: DataRequest) -> Result<DataResponse<NormalizerNfdDataV1>, DataError> {
|
||||
icu_normalizer::provider::Baked.load(req)
|
||||
}
|
||||
}
|
||||
|
||||
impl DataProvider<NormalizerNfdTablesV1> for Data {
|
||||
fn load(&self, req: DataRequest) -> Result<DataResponse<NormalizerNfdTablesV1>, DataError> {
|
||||
icu_normalizer::provider::Baked.load(req)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sorted<'a>(locale: &str, items: &[&'a str]) -> Vec<&'a str> {
|
||||
let mut v = items.to_vec();
|
||||
Collator::new(locale).sort_by_key(&mut v, |s| s);
|
||||
v
|
||||
}
|
||||
|
||||
/// Each tailored locale puts a pair in another order than the root collation does, which a
|
||||
/// locale whose data is missing (it falls back to root) wouldn't.
|
||||
#[test]
|
||||
fn every_shipped_locale_has_its_data() {
|
||||
let root = Collator::new("und");
|
||||
for (locale, first, second) in [
|
||||
("ar", "ب", "a"),
|
||||
("bg", "б", "a"),
|
||||
("cs", "hrad", "chata"),
|
||||
("da", "zebra", "år"),
|
||||
("el", "β", "a"),
|
||||
("es", "nube", "ñu"),
|
||||
("et", "wc", "õun"),
|
||||
("fa", "ب", "a"),
|
||||
("fi", "zeta", "äiti"),
|
||||
("hi", "क", "a"),
|
||||
("hr", "cvijet", "čaj"),
|
||||
("hu", "cukor", "csak"),
|
||||
("ja", "亜", "一"),
|
||||
("ka", "ა", "a"),
|
||||
("kk", "б", "a"),
|
||||
("ko", "가", "a"),
|
||||
("lt", "yra", "jau"),
|
||||
("pl", "az", "ąb"),
|
||||
("ru", "б", "a"),
|
||||
("sl", "cvet", "čaj"),
|
||||
("sr", "б", "a"),
|
||||
("sr-latn", "cvijet", "čaj"),
|
||||
("sv", "zebra", "år"),
|
||||
("te", "క", "a"),
|
||||
("tr", "cz", "ça"),
|
||||
("uk", "б", "a"),
|
||||
("vi", "az", "ăn"),
|
||||
("zh-hans", "阿", "中"),
|
||||
("zh-hant", "人", "丈"),
|
||||
] {
|
||||
assert_eq!(Collator::new(locale).compare(first, second), Ordering::Less, "{locale}: {first} < {second}");
|
||||
assert_eq!(root.compare(first, second), Ordering::Greater, "root: {second} < {first}");
|
||||
}
|
||||
// CLDR doesn't tailor these: they sort in the root order.
|
||||
for locale in ["en", "de", "fr", "id", "it", "nl", "pt-br", "not a locale"] {
|
||||
let collator = Collator::new(locale);
|
||||
assert!(collator.0.is_some(), "{locale}");
|
||||
assert_eq!(collator.compare("čaj", "cvijet"), Ordering::Less, "{locale}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digits_sort_by_value() {
|
||||
let layers = ["Layer 10", "Layer 2", "layer 1", "Layer 1", "Layer 2b", "Layer 02"];
|
||||
assert_eq!(sorted("en", &layers), ["layer 1", "Layer 1", "Layer 02", "Layer 2", "Layer 2b", "Layer 10"]);
|
||||
let reversed: Vec<&str> = layers.iter().rev().copied().collect();
|
||||
assert_eq!(sorted("en", &reversed), sorted("en", &layers));
|
||||
assert_eq!(sorted("de", &["Ebene ٣", "Ebene 10", "Ebene 2"]), ["Ebene 2", "Ebene ٣", "Ebene 10"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locales_sort_their_own_letters() {
|
||||
let words = ["öl", "zebra", "år", "äpple", "apa", "oxe"];
|
||||
assert_eq!(sorted("sv", &words), ["apa", "oxe", "zebra", "år", "äpple", "öl"]);
|
||||
assert_eq!(sorted("de", &words), ["apa", "äpple", "år", "öl", "oxe", "zebra"]);
|
||||
assert_eq!(sorted("de", &["Muller", "Müller", "Mueller", "Mahler"]), ["Mahler", "Mueller", "Muller", "Müller"]);
|
||||
assert_eq!(
|
||||
sorted("tr", &["şeker", "sabun", "ılık", "iğne", "çay", "cam", "uzun", "üzüm"]),
|
||||
["cam", "çay", "ılık", "iğne", "sabun", "şeker", "uzun", "üzüm"]
|
||||
);
|
||||
assert_eq!(sorted("en", &["ılık", "iğne", "cam", "çay"]), ["cam", "çay", "iğne", "ılık"]);
|
||||
assert_eq!(sorted("es", &["ñu", "nube", "oso"]), ["nube", "ñu", "oso"]);
|
||||
// Japanese: Latin, then kana in gojūon order (hiragana and katakana together), then kanji.
|
||||
assert_eq!(sorted("ja", &["漢字", "カメラ", "あめ", "いぬ", "Zoom"]), ["Zoom", "あめ", "いぬ", "カメラ", "漢字"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glibc_locale_names() {
|
||||
let words = ["öl", "zebra", "år", "äpple", "apa", "oxe"];
|
||||
assert_eq!(sorted("sv_SE.UTF-8", &words), sorted("sv", &words));
|
||||
assert_ne!(sorted("sv_SE.UTF-8", &words), sorted("en", &words));
|
||||
let cities = ["天津", "北京", "上海"];
|
||||
assert_eq!(sorted("zh_TW.UTF-8", &cities), sorted("zh-hant", &cities));
|
||||
assert_eq!(sorted("zh_CN.UTF-8", &cities), sorted("zh-hans", &cities));
|
||||
// Serbian Cyrillic sorts Cyrillic first; Latin Serbian sorts Latin first, `lj` after `lu`.
|
||||
let mixed = ["ljubav", "lula", "абв"];
|
||||
assert_eq!(sorted("sr_RS.UTF-8", &mixed), ["абв", "ljubav", "lula"]);
|
||||
assert_eq!(sorted("sr_RS.UTF-8@latin", &mixed), ["lula", "ljubav", "абв"]);
|
||||
assert_eq!(bcp47("sr_RS.UTF-8@latin"), "sr-latn-RS");
|
||||
assert_eq!(bcp47("sr_Latn_RS@latin"), "sr-Latn-RS");
|
||||
assert_eq!(bcp47("de_DE@euro"), "de-DE");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chinese_sorts_by_pinyin_or_stroke() {
|
||||
// 北 běi (5 strokes), 上 shàng (3), 天 tiān (4).
|
||||
let cities = ["天津", "北京", "上海"];
|
||||
let pinyin = ["北京", "上海", "天津"];
|
||||
let stroke = ["上海", "天津", "北京"];
|
||||
assert_eq!(sorted("zh-hans", &cities), pinyin);
|
||||
assert_eq!(sorted("zh-hant", &cities), stroke);
|
||||
assert_eq!(sorted("zh-hans-u-co-stroke", &cities), stroke);
|
||||
assert_eq!(sorted("zh-hant-u-co-pinyin", &cities), pinyin);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
//! Case- and accent-insensitive matching for search fields, with a map back to the original text
|
||||
//! for highlighting.
|
||||
//!
|
||||
//! [`Folder::fold`] turns text into a search key: compatibility forms decomposed (`fi` → `fi`,
|
||||
//! full-width `A` → `a`, `㎏` → `kg`), lower case, `ß` → `ss`, final `ς` → `σ`, and with accents
|
||||
//! ignored (the default) combining accents, Hebrew points and Arabic vowel marks dropped and the
|
||||
//! few letters with built-in strokes mapped to their base (`ø`, `ł`, `đ`, `ı`, `æ` → `ae`), and
|
||||
//! Persian letter forms mapped to the Arabic ones (`ک` → `ك`, `ی` → `ي`, `ة` → `ه`). Decimal
|
||||
//! digits of every script fold to ASCII (`١٢` → `12`). Invisible format characters (soft
|
||||
//! hyphens, zero-width joiners, bidi isolates) are dropped too.
|
||||
//!
|
||||
//! Dotted and dotless i follow the locale when accents count. In Turkish and Azerbaijani, `I`
|
||||
//! folds to `ı` and `İ` to `i`; elsewhere both fold to `i` and `ı` stays a letter of its own.
|
||||
//! Ignoring accents, all four fold to `i`, so `istanbul` finds `İSTANBUL` and `irmak` finds
|
||||
//! `IRMAK` and `ırmak`. Plain `str::to_lowercase` follows no locale and turns `İ` into `i` plus a
|
||||
//! combining dot, which nothing typed would match.
|
||||
//!
|
||||
//! The Turkish i handling and sigma folding come from PdfCraft's `fold_case` (snipeTR,
|
||||
//! nevicia2010-hub).
|
||||
|
||||
use std::ops::Range;
|
||||
|
||||
use icu_normalizer::DecomposingNormalizerBorrowed;
|
||||
use icu_properties::props::{GraphemeExtend, HangulSyllableType};
|
||||
use icu_properties::{CodePointMapData, CodePointSetData};
|
||||
|
||||
/// Folds text for one locale. Cheap to build and copy.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Folder {
|
||||
turkic: bool,
|
||||
accents: bool,
|
||||
}
|
||||
|
||||
impl Folder {
|
||||
/// Case- and accent-insensitive folding for `locale`, a language code such as `tr`, `pt-br`
|
||||
/// or `zh-hant` (any case, `-` or `_`).
|
||||
pub fn new(locale: &str) -> Folder {
|
||||
let language = locale.split(['-', '_', '.', '@']).next().unwrap_or_default();
|
||||
Folder { turkic: language.eq_ignore_ascii_case("tr") || language.eq_ignore_ascii_case("az"), accents: false }
|
||||
}
|
||||
|
||||
/// Accents count: `é` no longer matches `e`, and a match can't end on a letter whose accent it
|
||||
/// leaves out.
|
||||
pub fn keep_accents(self) -> Folder {
|
||||
Folder { accents: true, ..self }
|
||||
}
|
||||
|
||||
/// `s` folded, with the map back to `s`.
|
||||
pub fn fold(&self, s: &str) -> Folded {
|
||||
let nfkd = DecomposingNormalizerBorrowed::new_nfkd();
|
||||
let extend = CodePointSetData::new::<GraphemeExtend>();
|
||||
let hangul = CodePointMapData::<HangulSyllableType>::new();
|
||||
let mut text = String::with_capacity(s.len());
|
||||
let mut starts = Vec::new();
|
||||
// A cluster is a character and the combining marks after it, folded and mapped as one;
|
||||
// conjoining jamo that spell one syllable are one cluster too.
|
||||
let mut cluster_start = 0;
|
||||
let mut chars = s.char_indices();
|
||||
let mut prev = chars.next().map(|(_, c)| hangul.get(c));
|
||||
for (i, c) in chars {
|
||||
let kind = hangul.get(c);
|
||||
if !extend.contains(c) && !prev.is_some_and(|p| continues_syllable(p, kind)) {
|
||||
starts.push((text.len(), cluster_start));
|
||||
self.fold_cluster(&nfkd.normalize(&s[cluster_start..i]), &mut text);
|
||||
cluster_start = i;
|
||||
}
|
||||
prev = Some(kind);
|
||||
}
|
||||
if !s.is_empty() {
|
||||
starts.push((text.len(), cluster_start));
|
||||
self.fold_cluster(&nfkd.normalize(&s[cluster_start..]), &mut text);
|
||||
}
|
||||
starts.push((text.len(), s.len()));
|
||||
Folded { text, starts }
|
||||
}
|
||||
|
||||
/// `s` folded, without the map: a key to compare or store.
|
||||
pub fn key(&self, s: &str) -> String {
|
||||
self.fold(s).text
|
||||
}
|
||||
|
||||
/// Whether `haystack` contains `needle`, both folded.
|
||||
pub fn contains(&self, haystack: &str, needle: &str) -> bool {
|
||||
self.fold(haystack).find(&self.fold(needle)).is_some()
|
||||
}
|
||||
|
||||
/// One cluster, already in NFKD.
|
||||
fn fold_cluster(&self, cluster: &str, out: &mut String) {
|
||||
let mut chars = cluster.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
// `İ` decomposes to `I` and a combining dot above: the dot of a lower-case `i`.
|
||||
'I' if chars.peek() == Some(&'\u{307}') => {
|
||||
chars.next();
|
||||
out.push('i');
|
||||
}
|
||||
'I' if self.turkic && self.accents => out.push('ı'),
|
||||
// Persian heh with hamza above (ۀ) decomposes to ae (ە) and hamza.
|
||||
'\u{6D5}' if !self.accents && chars.peek() == Some(&'\u{654}') => {
|
||||
chars.next();
|
||||
out.push('ه');
|
||||
}
|
||||
'ß' | 'ẞ' => out.push_str("ss"),
|
||||
c if let Some(d) = ascii_digit(c) => out.push(d),
|
||||
'Σ' | 'σ' | 'ς' => out.push('σ'),
|
||||
c if ignorable(c) || (!self.accents && accent(c)) => {}
|
||||
c => {
|
||||
for l in c.to_lowercase() {
|
||||
match base_letter(l) {
|
||||
Some(base) if !self.accents => out.push_str(base),
|
||||
_ => out.push(l),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The base of a lower-case letter whose diacritic is built in rather than combining, and the
|
||||
/// Arabic form of a letter that Persian and Urdu write differently: keheh (ک) is kaf (ك), Farsi
|
||||
/// yeh (ی) and alef maksura (ى) are yeh (ي), teh marbuta (ة) is heh (ه), alef wasla (ٱ) is alef.
|
||||
fn base_letter(c: char) -> Option<&'static str> {
|
||||
Some(match c {
|
||||
'ک' => "ك",
|
||||
'ی' | 'ى' => "ي",
|
||||
'ة' => "ه",
|
||||
'ٱ' => "ا",
|
||||
'ı' => "i",
|
||||
'ø' => "o",
|
||||
'ł' => "l",
|
||||
'đ' => "d",
|
||||
'ħ' => "h",
|
||||
'ŧ' => "t",
|
||||
'æ' => "ae",
|
||||
'œ' => "oe",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Invisible characters that only steer layout: soft hyphen, Arabic letter mark, the kashida
|
||||
/// that stretches Arabic words, Mongolian variation selectors, zero-width space and joiners, direction marks, embeddings and isolates,
|
||||
/// word joiner, variation selectors, byte order mark and tags.
|
||||
fn ignorable(c: char) -> bool {
|
||||
matches!(c,
|
||||
'\u{AD}' | '\u{61C}' | '\u{640}' | '\u{180B}'..='\u{180F}' | '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}'
|
||||
| '\u{2060}'..='\u{206F}' | '\u{FE00}'..='\u{FE0F}' | '\u{FEFF}' | '\u{E0000}'..='\u{E0FFF}')
|
||||
}
|
||||
|
||||
/// Marks that searching without accents ignores: Latin, Greek and Cyrillic combining diacritics,
|
||||
/// Hebrew points and cantillation, Arabic vowel marks.
|
||||
/// Kana voicing marks, Indic and Thai vowel signs are letters' parts, not accents, and stay.
|
||||
fn accent(c: char) -> bool {
|
||||
matches!(c,
|
||||
'\u{300}'..='\u{36F}' | '\u{1AB0}'..='\u{1AFF}' | '\u{1DC0}'..='\u{1DFF}' | '\u{20D0}'..='\u{20FF}'
|
||||
| '\u{FE20}'..='\u{FE2F}'
|
||||
| '\u{591}'..='\u{5BD}' | '\u{5BF}' | '\u{5C1}' | '\u{5C2}' | '\u{5C4}' | '\u{5C5}' | '\u{5C7}'
|
||||
| '\u{610}'..='\u{61A}' | '\u{64B}'..='\u{65F}' | '\u{670}' | '\u{6D6}'..='\u{6DC}'
|
||||
| '\u{6DF}'..='\u{6E4}' | '\u{6E7}' | '\u{6E8}' | '\u{6EA}'..='\u{6ED}')
|
||||
}
|
||||
|
||||
/// The first code point of each run of ten Unicode decimal digits (general category Nd), Unicode
|
||||
/// 16.0.
|
||||
const ZEROS: [u32; 76] = [
|
||||
0x30, 0x660, 0x6F0, 0x7C0, 0x966, 0x9E6, 0xA66, 0xAE6, 0xB66, 0xBE6, 0xC66, 0xCE6, 0xD66, 0xDE6, 0xE50, 0xED0, 0xF20, 0x1040, 0x1090, 0x17E0,
|
||||
0x1810, 0x1946, 0x19D0, 0x1A80, 0x1A90, 0x1B50, 0x1BB0, 0x1C40, 0x1C50, 0xA620, 0xA8D0, 0xA900, 0xA9D0, 0xA9F0, 0xAA50, 0xABF0, 0xFF10, 0x104A0,
|
||||
0x10D30, 0x10D40, 0x11066, 0x110F0, 0x11136, 0x111D0, 0x112F0, 0x11450, 0x114D0, 0x11650, 0x116C0, 0x116D0, 0x116DA, 0x11730, 0x118E0, 0x11950,
|
||||
0x11BF0, 0x11C50, 0x11D50, 0x11DA0, 0x11F50, 0x16130, 0x16A60, 0x16AC0, 0x16B50, 0x16D70, 0x1CCF0, 0x1D7CE, 0x1D7D8, 0x1D7E2, 0x1D7EC, 0x1D7F6,
|
||||
0x1E140, 0x1E2F0, 0x1E4F0, 0x1E5F1, 0x1E950, 0x1FBF0,
|
||||
];
|
||||
|
||||
/// A decimal digit of any script as its ASCII digit: `١٢` and `१२` search as `12`.
|
||||
fn ascii_digit(c: char) -> Option<char> {
|
||||
let c = u32::from(c);
|
||||
let zero = match ZEROS.binary_search(&c) {
|
||||
Ok(i) => ZEROS.get(i),
|
||||
Err(i) => ZEROS.get(i.checked_sub(1)?),
|
||||
}?;
|
||||
let value = c - zero;
|
||||
if value < 10 { char::from_digit(value, 10) } else { None }
|
||||
}
|
||||
|
||||
/// Whether a conjoining jamo of kind `next` continues the syllable a character of kind `prev`
|
||||
/// ends: a vowel after a leading consonant, a final consonant after a vowel or an open syllable
|
||||
/// (`가` and `ᆨ` spell `각`).
|
||||
fn continues_syllable(prev: HangulSyllableType, next: HangulSyllableType) -> bool {
|
||||
matches!(
|
||||
(prev, next),
|
||||
(HangulSyllableType::LeadingJamo, HangulSyllableType::VowelJamo)
|
||||
| (HangulSyllableType::VowelJamo | HangulSyllableType::LVSyllable, HangulSyllableType::TrailingJamo)
|
||||
)
|
||||
}
|
||||
|
||||
/// Folded text and where each part came from.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Folded {
|
||||
text: String,
|
||||
/// One (folded offset, source offset) per source cluster, in order, then both lengths. A
|
||||
/// cluster folds to the text up to the next entry's folded offset, possibly none.
|
||||
starts: Vec<(usize, usize)>,
|
||||
}
|
||||
|
||||
impl Folded {
|
||||
/// The folded text.
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.text
|
||||
}
|
||||
|
||||
/// The source byte range that folded bytes `range` came from, widened to whole source
|
||||
/// characters with their accents: `ss` in the folding of `Straße` maps back to `ß`, `e` in
|
||||
/// that of `é` to the whole `é`. An empty range maps to an empty one.
|
||||
pub fn source_range(&self, range: Range<usize>) -> Range<usize> {
|
||||
// The last cluster starting at or before `at` is the one holding it: clusters that fold to
|
||||
// nothing share their offset with the next one.
|
||||
let cluster = |at: usize| self.starts.partition_point(|&(f, _)| f <= at).saturating_sub(1);
|
||||
if range.is_empty() {
|
||||
let s = self.starts[cluster(range.start)].1;
|
||||
return s..s;
|
||||
}
|
||||
let first = cluster(range.start);
|
||||
let last = cluster(range.end - 1);
|
||||
self.starts[first].1..self.starts[(last + 1).min(self.starts.len() - 1)].1
|
||||
}
|
||||
|
||||
/// The first match of `needle` (folded the same way), as a byte range of the source text.
|
||||
/// An empty needle matches at the start.
|
||||
pub fn find(&self, needle: &Folded) -> Option<Range<usize>> {
|
||||
self.matches(needle).next()
|
||||
}
|
||||
|
||||
/// Every non-overlapping match of `needle` (folded the same way), as byte ranges of the
|
||||
/// source text. A match may start or end inside an expansion (`ss` of `ß`, `fi` of `fi`) but
|
||||
/// not leave out a mark that follows a letter, so `re` doesn't match `ré` when accents count.
|
||||
pub fn matches<'a>(&'a self, needle: &'a Folded) -> impl Iterator<Item = Range<usize>> + 'a {
|
||||
let extend = CodePointSetData::new::<GraphemeExtend>();
|
||||
let hangul = CodePointMapData::<HangulSyllableType>::new();
|
||||
// The vowel and final consonant of a decomposed Hangul syllable continue it, like a mark,
|
||||
// but only inside one source cluster: standalone jamo (`ㅋㅠ`, `ㅠㅠ`) are letters.
|
||||
let starts_mark = move |at: usize| {
|
||||
let Some(c) = self.text[at..].chars().next() else { return false };
|
||||
if extend.contains(c) {
|
||||
return true;
|
||||
}
|
||||
let inside = self.starts.binary_search_by_key(&at, |&(f, _)| f).is_err();
|
||||
inside && self.text[..at].chars().next_back().is_some_and(|p| continues_syllable(hangul.get(p), hangul.get(c)))
|
||||
};
|
||||
let n = needle.text.as_str();
|
||||
let mut from = 0;
|
||||
let mut done = false;
|
||||
std::iter::from_fn(move || {
|
||||
if done {
|
||||
return None;
|
||||
}
|
||||
if n.is_empty() {
|
||||
done = true;
|
||||
return Some(0..0);
|
||||
}
|
||||
while let Some(i) = self.text.get(from..).and_then(|t| t.find(n)) {
|
||||
let start = from + i;
|
||||
let end = start + n.len();
|
||||
if !starts_mark(start) && !starts_mark(end) {
|
||||
from = end;
|
||||
return Some(self.source_range(start..end));
|
||||
}
|
||||
from = start + self.text[start..].chars().next().map_or(1, char::len_utf8);
|
||||
}
|
||||
done = true;
|
||||
None
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn key(locale: &str, s: &str) -> String {
|
||||
Folder::new(locale).key(s)
|
||||
}
|
||||
|
||||
fn key_accents(locale: &str, s: &str) -> String {
|
||||
Folder::new(locale).keep_accents().key(s)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_table() {
|
||||
let nfd = |s: &str| DecomposingNormalizerBorrowed::new_nfd().normalize(s).into_owned();
|
||||
// (locale, input, ignoring accents, keeping accents)
|
||||
let table = [
|
||||
("en", "Hello WORLD", "hello world".to_owned(), "hello world".to_owned()),
|
||||
("en", "İSTANBUL", "istanbul".into(), "istanbul".into()),
|
||||
("tr", "İSTANBUL", "istanbul".into(), "istanbul".into()),
|
||||
("en", "IRMAK ırmak", "irmak irmak".into(), "irmak ırmak".into()),
|
||||
("tr", "IRMAK ırmak", "irmak irmak".into(), "ırmak ırmak".into()),
|
||||
("az", "İIıi", "iiii".into(), "iııi".into()),
|
||||
("tr-TR", "Şişli", "sisli".into(), nfd("şişli")),
|
||||
("de", "Straße STRAẞE", "strasse strasse".into(), "strasse strasse".into()),
|
||||
("el", "ΟΔΥΣΣΕΥΣ οδυσσευς", "οδυσσευσ οδυσσευσ".into(), "οδυσσευσ οδυσσευσ".into()),
|
||||
("el", "Ἀθῆναι", "αθηναι".into(), nfd("ἀθῆναι")),
|
||||
("fr", "Œuvre ÉTÉ", "oeuvre ete".into(), nfd("œuvre été")),
|
||||
("da", "Ærø", "aero".into(), nfd("ærø")),
|
||||
("pl", "Łódź", "lodz".into(), nfd("łódź")),
|
||||
("vi", "Đà Nẵng", "da nang".into(), nfd("đà nẵng")),
|
||||
("en", "final ff", "final ff".into(), "final ff".into()),
|
||||
("ja", "ABC123 ガ", nfd("abc123 ガ"), nfd("abc123 ガ")),
|
||||
("ar", "مُحَمَّد أحمـــد", nfd("محمد احمد"), nfd("مُحَمَّد أحمد")),
|
||||
("he", "שָׁלוֹם", "שלום".into(), nfd("שָׁלוֹם")),
|
||||
("en", "soft\u{AD}ware \u{2068}name\u{2069}", "software name".into(), "software name".into()),
|
||||
("ru", "Ёлка", "елка".into(), nfd("ёлка")),
|
||||
("ar", "Layer ١٢ ۳۴ १२", "layer 12 34 12".into(), "layer 12 34 12".into()),
|
||||
("fa", "کتاب یک", "كتاب يك".into(), "کتاب یک".into()),
|
||||
("fa", "خانۀ", "خانه".into(), nfd("خانۀ")),
|
||||
("ar", "مدرسة على إسلام آمن", "مدرسه علي اسلام امن".into(), nfd("مدرسة على إسلام آمن")),
|
||||
];
|
||||
for (locale, input, ignoring, keeping) in table {
|
||||
assert_eq!(key(locale, input), ignoring, "{locale} {input}");
|
||||
assert_eq!(key_accents(locale, input), keeping, "{locale} {input}, accents kept");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turkish_i_depends_on_locale_when_accents_count() {
|
||||
let tr = Folder::new("tr").keep_accents();
|
||||
let en = Folder::new("en").keep_accents();
|
||||
assert!(tr.contains("IRMAK", "ırmak") && !tr.contains("IRMAK", "irmak"));
|
||||
assert!(en.contains("IRMAK", "irmak") && !en.contains("IRMAK", "ırmak"));
|
||||
assert!(tr.contains("İSTANBUL", "istanbul") && en.contains("İSTANBUL", "istanbul"));
|
||||
for locale in ["tr", "en"] {
|
||||
let f = Folder::new(locale);
|
||||
assert!(f.contains("IRMAK", "ırmak") && f.contains("ırmak", "IRMAK") && f.contains("İzmir", "izmir"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_map_back_to_the_source() {
|
||||
let f = Folder::new("en");
|
||||
fn find<'a>(f: Folder, haystack: &'a str, needle: &str) -> Option<&'a str> {
|
||||
f.fold(haystack).find(&f.fold(needle)).map(|r| &haystack[r])
|
||||
}
|
||||
let find = |haystack, needle| find(f, haystack, needle);
|
||||
assert_eq!(find("Große Straße", "strasse"), Some("Straße"));
|
||||
assert_eq!(find("Große Straße", "SS"), Some("ß"));
|
||||
assert_eq!(find("Große Straße", "sse"), Some("ße"));
|
||||
assert_eq!(find("Café crème", "creme"), Some("crème"));
|
||||
assert_eq!(find("Cafe\u{301} noir", "cafe"), Some("Cafe\u{301}"));
|
||||
assert_eq!(find("File 2", "file 2"), Some("File 2"));
|
||||
assert_eq!(find("the final cut", "fin"), Some("fin"));
|
||||
assert_eq!(find("Layer \u{2068}İSTANBUL\u{2069}", "istanbul"), Some("İSTANBUL"));
|
||||
assert_eq!(find("abc", "x"), None);
|
||||
assert_eq!(find("abc", ""), Some(""));
|
||||
|
||||
let all: Vec<_> = f.fold("Ab ab AB").matches(&f.fold("ab")).collect();
|
||||
assert_eq!(all, [0..2, 3..5, 6..8]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persian_and_arabic_letters_match() {
|
||||
let f = Folder::new("fa");
|
||||
// Persian keheh and Farsi yeh against Arabic kaf and yeh, and hamza forms of alef.
|
||||
assert!(f.contains("كتاب عربي", "کتاب عربی"));
|
||||
assert!(f.contains("کتاب عربی", "كتاب عربي"));
|
||||
assert!(f.contains("أحمد إبراهيم", "احمد ابراهیم"));
|
||||
assert!(f.contains("مدرسة", "مدرسه"));
|
||||
assert_eq!(f.fold("Layer ١٢").find(&f.fold("layer 12")), Some(0.."Layer ١٢".len()));
|
||||
assert!(Folder::new("en").keep_accents().contains("Layer ١٢", "layer 12"));
|
||||
let digits = ZEROS.iter().map(|&zero| char::from_u32(zero + 7).unwrap());
|
||||
assert!(digits.clone().all(|d| d.is_numeric() && ascii_digit(d) == Some('7')));
|
||||
assert_eq!(ascii_digit('\u{1D800}'), None);
|
||||
assert_eq!(ascii_digit('/'), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accents_count_only_whole_letters() {
|
||||
let f = Folder::new("fr").keep_accents();
|
||||
assert!(!f.contains("ré", "re"));
|
||||
assert!(f.contains("ré", "RÉ") && f.contains("re\u{301}", "ré"));
|
||||
assert!(f.contains("ré", "é"));
|
||||
// Kana voicing marks stay even with accents ignored: か doesn't find が.
|
||||
assert!(!Folder::new("ja").contains("が", "か"));
|
||||
// Nor does a Hangul syllable without its final consonant: 하 doesn't find 한.
|
||||
let ko = Folder::new("ko");
|
||||
assert!(!ko.contains("한국", "하") && !ko.keep_accents().contains("한국", "하"));
|
||||
assert!(ko.contains("한국", "한") && ko.contains("하늘", "하"));
|
||||
// Conjoining jamo spell the same syllable; compatibility jamo stand alone.
|
||||
assert!(!ko.contains("\u{1112}\u{1161}\u{11AB}", "하") && ko.contains("\u{1112}\u{1161}\u{11AB}", "한"));
|
||||
assert!(!ko.contains("하\u{11AB}", "하"));
|
||||
for (haystack, needle) in [("ㅠㅠ", "ㅠ"), ("ㅠㅠ", "ㅠㅠ"), ("ㅋㅠ", "ㅋ"), ("ㅋㅠ", "ㅠ"), ("ㅋㅋㅋ", "ㅋㅋ"), ("ㄳ", "ㄳ"), ("값ㄳ", "ㄳ")]
|
||||
{
|
||||
assert!(ko.contains(haystack, needle), "{haystack} {needle}");
|
||||
}
|
||||
assert_eq!(ko.fold("ㅋㅠㅠ").find(&ko.fold("ㅠ")).map(|r| r.start), Some("ㅋ".len()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_ranges_round_trip() {
|
||||
let f = Folder::new("de");
|
||||
for s in ["Straße", "ffi A", "e\u{301}\u{AD}x", "", "İı", "\u{301}a"] {
|
||||
let folded = f.fold(s);
|
||||
let text = folded.as_str();
|
||||
// A leading mark folds to nothing and has no part in any match.
|
||||
let whole = if s.starts_with('\u{301}') { 2..s.len() } else { 0..s.len() };
|
||||
assert_eq!(folded.source_range(0..text.len()), whole, "{s:?}");
|
||||
// Every folded character maps to a non-empty source range that folds back to text
|
||||
// containing it.
|
||||
for (i, c) in text.char_indices() {
|
||||
let r = folded.source_range(i..i + c.len_utf8());
|
||||
assert!(!r.is_empty() && f.key(&s[r.clone()]).contains(c), "{s:?} {i} {r:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_is_idempotent() {
|
||||
// A folded query folds to itself, so a stored key can be searched with a fresh fold.
|
||||
for locale in ["en", "tr"] {
|
||||
for f in [Folder::new(locale), Folder::new(locale).keep_accents()] {
|
||||
for c in ('\0'..='\u{FFFF}').chain('\u{1D400}'..='\u{1D7FF}') {
|
||||
let once = f.key(c.encode_utf8(&mut [0; 4]));
|
||||
assert_eq!(f.key(&once), once, "{locale} {:?} U+{:04X}", f, c as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
//! Numbers, percentages and counts written for a formatting [`Region`], on ICU4X's decimal
|
||||
//! formatter with CLDR data for every CLDR locale (`data/generate.sh`).
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use fixed_decimal::{Decimal, Sign};
|
||||
use icu_decimal::{DecimalFormatter, parts};
|
||||
use icu_locale_core::Locale;
|
||||
use icu_locale_core::extensions::unicode::{key, value};
|
||||
use writeable::{Part, PartsWrite, Writeable};
|
||||
|
||||
use crate::Region;
|
||||
use crate::data::{self, PERCENT};
|
||||
use crate::number::Marks;
|
||||
|
||||
/// Which digits numbers are written in.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum Digits {
|
||||
/// The locale's own: Arabic-Indic in Egypt (`١٢٣`), Persian in Iran (`۱۲۳`), else `0`–`9`.
|
||||
#[default]
|
||||
Locale,
|
||||
/// `0`–`9` everywhere, for users who read Arabic or Persian with Latin digits.
|
||||
Latin,
|
||||
}
|
||||
|
||||
/// How numbers are written in a formatting region: digits, decimal and grouping separators,
|
||||
/// grouping sizes (`1,234,567`, Indian `12,34,567`) and the percent sign. Build it once per region
|
||||
/// and keep it; [`crate::I18n`] holds one for counts, sizes and measures.
|
||||
#[derive(Debug)]
|
||||
pub struct Format {
|
||||
/// `None` only if the data doesn't load: numbers are then written as Rust writes them.
|
||||
decimal: Option<DecimalFormatter>,
|
||||
/// The system's separators where they differ from the locale's; an empty `group` is none.
|
||||
group: Option<String>,
|
||||
point: Option<String>,
|
||||
percent: (&'static str, &'static str),
|
||||
/// The marks [`Format::parse`] reads.
|
||||
pub(crate) marks: Marks,
|
||||
}
|
||||
|
||||
impl Format {
|
||||
/// The format for `region`'s number locale. With Latin digits, a decimal or grouping separator
|
||||
/// the region carries (Windows' and macOS's own settings) replaces the locale's.
|
||||
pub fn new(region: &Region, digits: Digits) -> Format {
|
||||
let mut locale = Locale::try_from_str(®ion.numbers).unwrap_or(Locale::UNKNOWN);
|
||||
if digits == Digits::Latin {
|
||||
locale.extensions.unicode.keywords.set(key!("nu"), value!("latn"));
|
||||
}
|
||||
let decimal = data::provider().and_then(|p| DecimalFormatter::try_new_with_buffer_provider(p, (&locale).into(), Default::default()).ok());
|
||||
let mut format = Format { decimal, group: None, point: None, percent: ("", "%"), marks: Marks::default() };
|
||||
// The locale's own separators and digits, read from a number that shows them all.
|
||||
let probe = format.parts(&Decimal::try_from_str("-1234567.5").unwrap_or_default());
|
||||
let latin = probe.integer.starts_with(|c: char| c.is_ascii_digit());
|
||||
if latin {
|
||||
if let Some(point) = region.decimal.map(String::from).filter(|p| *p != probe.point) {
|
||||
format.point = Some(point);
|
||||
}
|
||||
if let Some(g) = region.grouping.map(|g| g.map(String::from).unwrap_or_default()).filter(|g| *g != probe.group) {
|
||||
format.group = Some(g);
|
||||
}
|
||||
// A grouping mark equal to the decimal mark (`1,234,5`) wouldn't read back. With a
|
||||
// decimal comma and the locale's grouping, `1,234.5` becomes `1.234,5`; a grouping
|
||||
// comma the system sets as well (Windows always sets one) leaves no grouping.
|
||||
let point = format.point.as_deref().unwrap_or(&probe.point);
|
||||
if format.group.as_deref().unwrap_or(&probe.group) == point {
|
||||
let swapped = region.grouping.is_none() && probe.point != point;
|
||||
format.group = Some(if swapped { probe.point.clone() } else { String::new() });
|
||||
}
|
||||
}
|
||||
format.percent = percent_affixes(®ion.numbers, latin);
|
||||
let point = format.point.clone().unwrap_or(probe.point);
|
||||
let group = format.group.clone().unwrap_or(probe.group);
|
||||
// Latin digits typed into an Arabic-Indic format take the locale's Latin marks.
|
||||
let comma = match (latin, digits) {
|
||||
(true, _) => point == "," || group == ".",
|
||||
(false, Digits::Locale) => !Format::new(region, Digits::Latin).marks.point,
|
||||
(false, Digits::Latin) => false,
|
||||
};
|
||||
format.marks = Marks::new(&point, &group, !comma);
|
||||
format
|
||||
}
|
||||
|
||||
/// The format for a locale tag (`de-CH`, `ar-EG`), with the locale's own digits.
|
||||
pub fn from_tag(tag: &str) -> Format {
|
||||
Format::new(&Region::from_tag(tag), Digits::Locale)
|
||||
}
|
||||
|
||||
/// A whole number: `1,234,567`, `1.234.567`, `١٬٢٣٤٬٥٦٧`.
|
||||
pub fn integer(&self, n: impl Into<i128>) -> String {
|
||||
self.write(&Decimal::from(n.into()))
|
||||
}
|
||||
|
||||
/// `value` rounded to `decimals` digits after the decimal separator; infinities and NaN are
|
||||
/// `∞`, `-∞` and `NaN`.
|
||||
pub fn number(&self, value: f64, decimals: usize) -> String {
|
||||
match to_decimal(value, decimals) {
|
||||
Some(d) => self.write(&d),
|
||||
None => non_finite(value).to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::number`] without grouping separators, for values such as pixel sizes and years:
|
||||
/// `1920`, `١٩٢٠`, `1234,5`.
|
||||
pub fn number_ungrouped(&self, value: f64, decimals: usize) -> String {
|
||||
match to_decimal(value, decimals) {
|
||||
Some(d) => {
|
||||
let p = self.parts_with(&d, Some(""));
|
||||
p.sign + &p.text
|
||||
}
|
||||
None => non_finite(value).to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `ratio` as a percentage with `decimals` digits after the decimal separator: `0.5` is
|
||||
/// `50%`, `50 %` (French, German), `%50` (Turkish), `٥٠٪` (Egyptian Arabic).
|
||||
pub fn percent(&self, ratio: f64, decimals: usize) -> String {
|
||||
let Some(d) = to_decimal(ratio * 100.0, decimals) else {
|
||||
return format!("{}{}{}", self.percent.0, non_finite(ratio), self.percent.1);
|
||||
};
|
||||
let p = self.parts(&d);
|
||||
format!("{}{}{}{}", p.sign, self.percent.0, p.text, self.percent.1)
|
||||
}
|
||||
|
||||
/// `d` as text, the sign in place.
|
||||
pub(crate) fn write(&self, d: &Decimal) -> String {
|
||||
let p = self.parts(d);
|
||||
p.sign + &p.text
|
||||
}
|
||||
|
||||
fn parts(&self, d: &Decimal) -> Written {
|
||||
self.parts_with(d, self.group.as_deref())
|
||||
}
|
||||
|
||||
/// `d` taken apart, with `group` in place of the locale's grouping separator if set (`""`
|
||||
/// drops it).
|
||||
fn parts_with(&self, d: &Decimal, group: Option<&str>) -> Written {
|
||||
let mut sink = Sink { group, point: self.point.as_deref(), into: Target::Text, w: Written::default() };
|
||||
let written = match &self.decimal {
|
||||
Some(f) => f.format(d).write_to_parts(&mut sink),
|
||||
None => fmt::Write::write_str(&mut sink, &d.to_string()),
|
||||
};
|
||||
if written.is_err() {
|
||||
return Written { text: d.to_string(), ..Written::default() };
|
||||
}
|
||||
sink.w
|
||||
}
|
||||
}
|
||||
|
||||
/// A formatted number taken apart: its sign, the rest, and the separators and integer digits as
|
||||
/// the locale wrote them.
|
||||
#[derive(Default)]
|
||||
struct Written {
|
||||
sign: String,
|
||||
text: String,
|
||||
integer: String,
|
||||
group: String,
|
||||
point: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Target {
|
||||
Text,
|
||||
Sign,
|
||||
/// A separator the region replaces; the locale's goes to `group` or `point` only.
|
||||
Replaced,
|
||||
}
|
||||
|
||||
/// Writes the formatter's parts into [`Written`], swapping in the region's separators.
|
||||
struct Sink<'a> {
|
||||
group: Option<&'a str>,
|
||||
point: Option<&'a str>,
|
||||
into: Target,
|
||||
w: Written,
|
||||
}
|
||||
|
||||
impl fmt::Write for Sink<'_> {
|
||||
fn write_str(&mut self, s: &str) -> fmt::Result {
|
||||
match self.into {
|
||||
Target::Text => self.w.text.push_str(s),
|
||||
Target::Sign => self.w.sign.push_str(s),
|
||||
Target::Replaced => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartsWrite for Sink<'_> {
|
||||
type SubPartsWrite = Self;
|
||||
|
||||
fn with_part(&mut self, part: Part, mut f: impl FnMut(&mut Self) -> fmt::Result) -> fmt::Result {
|
||||
let outer = self.into;
|
||||
let start = self.w.text.len();
|
||||
let replacement = match part {
|
||||
p if p == parts::GROUP => self.group,
|
||||
p if p == parts::DECIMAL => self.point,
|
||||
_ => None,
|
||||
};
|
||||
if let Some(r) = replacement {
|
||||
self.w.text.push_str(r);
|
||||
self.into = Target::Replaced;
|
||||
} else if part == parts::MINUS_SIGN || part == parts::PLUS_SIGN {
|
||||
self.into = Target::Sign;
|
||||
}
|
||||
let result = f(self);
|
||||
self.into = outer;
|
||||
if replacement.is_none() {
|
||||
let written = self.w.text.get(start..).unwrap_or_default();
|
||||
let slot = match part {
|
||||
p if p == parts::GROUP => &mut self.w.group,
|
||||
p if p == parts::DECIMAL => &mut self.w.point,
|
||||
p if p == parts::INTEGER => &mut self.w.integer,
|
||||
_ => return result,
|
||||
};
|
||||
if slot.is_empty() {
|
||||
*slot = written.to_owned();
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` rounded to `decimals` digits after the point; `None` for infinities and NaN. A value
|
||||
/// that rounds to zero has no sign.
|
||||
pub(crate) fn to_decimal(value: f64, decimals: usize) -> Option<Decimal> {
|
||||
if !value.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let mut d = Decimal::try_from_str(&format!("{value:.decimals$}")).ok()?;
|
||||
if d.absolute.is_zero() {
|
||||
d.sign = Sign::None;
|
||||
}
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// CLDR's root symbols for a value that isn't finite.
|
||||
fn non_finite(value: f64) -> &'static str {
|
||||
match value {
|
||||
f64::INFINITY => "∞",
|
||||
f64::NEG_INFINITY => "-∞",
|
||||
_ => "NaN",
|
||||
}
|
||||
}
|
||||
|
||||
/// The percent affixes for a number locale (`ar-EG`), found by dropping trailing subtags.
|
||||
fn percent_affixes(tag: &str, latin: bool) -> (&'static str, &'static str) {
|
||||
let mut tag = tag;
|
||||
loop {
|
||||
if let Some((_, _, before, after)) = PERCENT.iter().find(|(l, lat, _, _)| *lat == latin && l.eq_ignore_ascii_case(tag)) {
|
||||
return (before, after);
|
||||
}
|
||||
match tag.rsplit_once('-') {
|
||||
Some((parent, _)) => tag = parent,
|
||||
None => return ("", "%"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn latin(tag: &str) -> Format {
|
||||
Format::new(&Region::from_tag(tag), Digits::Latin)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locale_digits_and_separators() {
|
||||
for (tag, integer, number) in [
|
||||
("en", "1,234,567", "1,234.5"),
|
||||
("ja", "1,234,567", "1,234.5"),
|
||||
("de", "1.234.567", "1.234,5"),
|
||||
("fr", "1\u{202f}234\u{202f}567", "1\u{202f}234,5"),
|
||||
("hi", "12,34,567", "1,234.5"),
|
||||
("ar-EG", "١٬٢٣٤٬٥٦٧", "١٬٢٣٤٫٥"),
|
||||
("fa", "۱٬۲۳۴٬۵۶۷", "۱٬۲۳۴٫۵"),
|
||||
] {
|
||||
let f = Format::from_tag(tag);
|
||||
assert_eq!((f.integer(1_234_567), f.number(1234.5, 1)), (integer.into(), number.into()), "{tag}");
|
||||
}
|
||||
// CLDR writes Arabic without a region in Latin digits.
|
||||
assert_eq!(Format::from_tag("ar").number(1234.5, 1), "1,234.5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ungrouped_numbers() {
|
||||
for (tag, want) in [("en", "1920"), ("de", "-1234567,5"), ("hi", "1234567"), ("ar-EG", "١٩٢٠")] {
|
||||
let value = if tag == "de" {
|
||||
-1_234_567.5
|
||||
} else if tag == "hi" {
|
||||
1_234_567.0
|
||||
} else {
|
||||
1920.0
|
||||
};
|
||||
let decimals = usize::from(tag == "de");
|
||||
assert_eq!(Format::from_tag(tag).number_ungrouped(value, decimals), want, "{tag}");
|
||||
}
|
||||
let mut region = Region::from_tag("en-US");
|
||||
region.decimal = Some(',');
|
||||
assert_eq!(Format::new(®ion, Digits::Locale).number_ungrouped(1234.5, 1), "1234,5", "the system's decimal mark stays");
|
||||
assert_eq!(Format::from_tag("en").number_ungrouped(f64::INFINITY, 0), "∞");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forced_latin_digits() {
|
||||
assert_eq!(latin("ar-EG").number(1234.5, 1), "1,234.5");
|
||||
assert_eq!(latin("fa").integer(1_234_567), "1,234,567");
|
||||
assert_eq!(latin("de").number(1234.5, 1), "1.234,5", "a Latin locale is unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cldr_separators_for_every_region() {
|
||||
for (tag, want) in [
|
||||
("en-PL", "1.234.567,5"),
|
||||
("en-DE", "1.234.567,5"),
|
||||
("ar-MA", "1.234.567,5"),
|
||||
("de-CH", "1'234'567.5"),
|
||||
("nb-NO", "1\u{a0}234\u{a0}567,5"),
|
||||
("sk-SK", "1\u{a0}234\u{a0}567,5"),
|
||||
("bn-BD", "১২,৩৪,৫৬৭.৫"),
|
||||
("he-IL", "1,234,567.5"),
|
||||
("km", "1,234,567.5"),
|
||||
("lo", "1.234.567,5"),
|
||||
] {
|
||||
assert_eq!(Format::from_tag(tag).number(1_234_567.5, 1), want, "{tag}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_separators() {
|
||||
// A decimal comma the system sets moves the grouping out of its way.
|
||||
let mut region = Region::from_tag("en-US");
|
||||
region.decimal = Some(',');
|
||||
assert_eq!(Format::new(®ion, Digits::Locale).number(1234.5, 1), "1.234,5");
|
||||
let mut region = Region::from_tag("de-DE");
|
||||
region.grouping = Some(Some('\u{a0}'));
|
||||
assert_eq!(Format::new(®ion, Digits::Locale).number(1234.5, 1), "1\u{a0}234,5");
|
||||
region.decimal = Some('.');
|
||||
assert_eq!(Format::new(®ion, Digits::Locale).number(1234.5, 1), "1\u{a0}234.5");
|
||||
region.grouping = Some(None);
|
||||
assert_eq!(Format::new(®ion, Digits::Locale).integer(1_234_567), "1234567", "no grouping");
|
||||
// A system's separators don't apply to Arabic-Indic digits.
|
||||
let mut region = Region::from_tag("ar-EG");
|
||||
region.grouping = Some(Some(','));
|
||||
assert_eq!(Format::new(®ion, Digits::Locale).number(1234.5, 1), "١٬٢٣٤٫٥");
|
||||
}
|
||||
|
||||
/// Windows always sets `sThousand`, so a decimal comma the user picks arrives beside a grouping
|
||||
/// comma: the numbers drop grouping rather than read `1,234,5`.
|
||||
#[test]
|
||||
fn a_system_grouping_mark_equal_to_the_decimal_mark_is_dropped() {
|
||||
let reg = |pairs: &'static [(&'static str, &'static str)]| move |n: &str| pairs.iter().find(|(k, _)| *k == n).map(|(_, v)| v.to_string());
|
||||
let region = crate::region::from_windows(reg(&[("LocaleName", "en-US"), ("sDecimal", ","), ("sThousand", ",")]), || None);
|
||||
let format = Format::new(®ion, Digits::Locale);
|
||||
assert_eq!((format.number(1234.5, 1), format.integer(1_234_567)), ("1234,5".to_owned(), "1234567".to_owned()));
|
||||
let region = crate::region::from_windows(reg(&[("LocaleName", "de-DE"), ("sDecimal", ","), ("sThousand", ",")]), || None);
|
||||
assert_eq!(Format::new(®ion, Digits::Locale).number(1234.5, 1), "1234,5");
|
||||
let region = crate::region::from_windows(reg(&[("LocaleName", "en-US"), ("sDecimal", "."), ("sThousand", ".")]), || None);
|
||||
assert_eq!(Format::new(®ion, Digits::Locale).number(1234.5, 1), "1234.5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_digit_system_the_region_names_is_used() {
|
||||
assert_eq!(Format::new(&Region::from_tag("ar-EG-u-nu-latn"), Digits::Locale).number(1234.5, 1), "1,234.5");
|
||||
assert_eq!(Format::new(&Region::from_tag("ar_EG@numbers=latn"), Digits::Locale).integer(5), "5");
|
||||
assert_eq!(Format::new(&Region::from_tag("en-US-u-nu-arab"), Digits::Locale).integer(5), "٥");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percentages() {
|
||||
for (tag, want) in
|
||||
[("en", "50%"), ("de", "50\u{a0}%"), ("fr", "12,5\u{a0}%"), ("tr", "%50"), ("ar-EG", "٥٠٪\u{61c}"), ("fa", "۵۰٪"), ("hi", "50%")]
|
||||
{
|
||||
let decimals = if tag == "fr" { 1 } else { 0 };
|
||||
let ratio = if tag == "fr" { 0.125 } else { 0.5 };
|
||||
assert_eq!(Format::from_tag(tag).percent(ratio, decimals), want, "{tag}");
|
||||
}
|
||||
assert_eq!(Format::from_tag("tr").percent(-0.2, 0), "-%20", "the sign leads the pattern");
|
||||
assert_eq!(latin("fa").percent(0.5, 0), "50%");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signs_and_odd_values() {
|
||||
let en = Format::from_tag("en");
|
||||
assert_eq!(en.number(-1234.5, 0), "-1,234");
|
||||
assert_eq!(en.number(-0.04, 1), "0.0", "no sign on zero");
|
||||
assert_eq!(en.number(f64::INFINITY, 1), "∞");
|
||||
assert_eq!(en.number(f64::NEG_INFINITY, 1), "-∞");
|
||||
assert_eq!(en.number(f64::NAN, 1), "NaN");
|
||||
assert_eq!(Format::from_tag("de").percent(f64::NAN, 0), "NaN\u{a0}%");
|
||||
assert_eq!(en.integer(-5_i64), "-5");
|
||||
}
|
||||
}
|
||||
+465
-55
@@ -3,15 +3,60 @@
|
||||
//! An app embeds the [craft-i18n](https://github.com/benandez/craft-i18n) catalogs at build time
|
||||
//! as an [`Embedded`] static, builds one [`I18n`] from it, and looks English source text up in a
|
||||
//! [`Lang`]. A missing translation is the English itself; nothing here fails.
|
||||
//!
|
||||
//! Counts ([`I18n::trn`]), file sizes and measures write their numbers as the formatting
|
||||
//! [`Region`] does ([`I18n::format`]): grouped (`1.234`, `12,34,567`) and in the region's digits
|
||||
//! (`١٬٢٣٤`). Text that goes into documents or file names should use [`I18n::trn_plain`], which
|
||||
//! writes `0`–`9` without grouping.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod catalog;
|
||||
#[cfg(feature = "collate")]
|
||||
mod collate;
|
||||
mod fold;
|
||||
mod format;
|
||||
mod number;
|
||||
mod region;
|
||||
mod scripts;
|
||||
mod size;
|
||||
|
||||
/// The CLDR number and plural data for every CLDR locale, from `data/generate.sh`.
|
||||
mod data {
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use icu_locale_fallback::LocaleFallbacker;
|
||||
use icu_provider_adapters::fallback::LocaleFallbackProvider;
|
||||
use icu_provider_blob::BlobDataProvider;
|
||||
|
||||
include!("../data/locales.rs");
|
||||
|
||||
/// The number and plural data, read once; `None` if the blob doesn't load.
|
||||
pub(crate) fn provider() -> Option<&'static LocaleFallbackProvider<BlobDataProvider>> {
|
||||
static PROVIDER: OnceLock<Option<LocaleFallbackProvider<BlobDataProvider>>> = OnceLock::new();
|
||||
PROVIDER
|
||||
.get_or_init(|| {
|
||||
let blob = BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/numbers.postcard")).ok()?;
|
||||
Some(LocaleFallbackProvider::new(blob, LocaleFallbacker::new().static_to_owned()))
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::sync::{Mutex, OnceLock, PoisonError};
|
||||
use std::sync::{Arc, Mutex, OnceLock, PoisonError, RwLock};
|
||||
|
||||
use intl_pluralrules::{PluralCategory, PluralRuleType, PluralRules};
|
||||
use unic_langid::LanguageIdentifier;
|
||||
use icu_locale_core::Locale as IcuLocale;
|
||||
use icu_plurals::{PluralCategory, PluralOperands, PluralRules};
|
||||
use unicode_bidi::{BidiClass, bidi_class};
|
||||
|
||||
#[cfg(feature = "collate")]
|
||||
pub use collate::Collator;
|
||||
pub use fold::{Folded, Folder};
|
||||
pub use format::{Digits, Format};
|
||||
pub use number::{NumberError, parse_number};
|
||||
pub use region::{HourCycle, Measurement, Paper, Region};
|
||||
pub use scripts::{Direction, Han, Script, base_direction, direction, han, scripts};
|
||||
pub use size::{FileSize, SizeUnit};
|
||||
|
||||
/// The catalogs an app embeds, one entry per locale: (locale, shared catalog, the app's catalog).
|
||||
/// A missing catalog is `""`.
|
||||
@@ -101,6 +146,8 @@ pub struct I18n {
|
||||
pseudo: Mutex<BTreeMap<String, &'static str>>,
|
||||
/// [`I18n::system_lang`], read once.
|
||||
system: OnceLock<Lang>,
|
||||
/// [`I18n::format`]; the system region's until [`I18n::set_format`].
|
||||
format: RwLock<Option<Arc<Format>>>,
|
||||
}
|
||||
|
||||
impl I18n {
|
||||
@@ -144,7 +191,7 @@ impl I18n {
|
||||
l.chain = chain;
|
||||
}
|
||||
}
|
||||
(I18n { locales, pseudo: Mutex::default(), system: OnceLock::new() }, problems)
|
||||
(I18n { locales, pseudo: Mutex::default(), system: OnceLock::new(), format: RwLock::default() }, problems)
|
||||
}
|
||||
|
||||
/// Parse every locale and list every problem, `<locale>/<common|app>: line N: …`, for a test or
|
||||
@@ -206,9 +253,36 @@ impl I18n {
|
||||
self.find(lang, &[("@id", id), ("", label)]).unwrap_or(label)
|
||||
}
|
||||
|
||||
/// A count's wording in `lang`, `{n}` filled in. `one` and `other` are the English forms;
|
||||
/// they are also the key of the `@plural` row, and the fallback.
|
||||
/// A count's wording in `lang`, `{n}` filled in as [`I18n::format`] writes numbers: grouped and
|
||||
/// in the region's digits, as a left-to-right isolate ([`ltr`]) when the wording has a
|
||||
/// right-to-left letter. `one` and `other` are the English forms; they are also the key of the
|
||||
/// `@plural` row, and the fallback.
|
||||
pub fn trn(&self, lang: Lang, n: u64, one: &str, other: &str) -> String {
|
||||
let format = self.format();
|
||||
self.plural(lang, Some(PluralOperands::from(n)), n == 1, &format.integer(n), one, other)
|
||||
}
|
||||
|
||||
/// [`I18n::trn`] with `{n}` in `0`–`9` without grouping (`Copy 1234`) and no isolate marks
|
||||
/// ([`strip_isolates`]), for text that goes into documents, file names or anything read back
|
||||
/// later.
|
||||
pub fn trn_plain(&self, lang: Lang, n: u64, one: &str, other: &str) -> String {
|
||||
strip_isolates(&self.plural(lang, Some(PluralOperands::from(n)), n == 1, &n.to_string(), one, other))
|
||||
}
|
||||
|
||||
/// [`I18n::trn`] for a count with `decimals` digits after the decimal separator (`1.5 files`).
|
||||
/// The plural form follows the digits shown, so `1.0` takes English `other`; infinities and NaN
|
||||
/// (`∞`, `NaN`) take `other` too.
|
||||
pub fn trn_decimal(&self, lang: Lang, n: f64, decimals: usize, one: &str, other: &str) -> String {
|
||||
let format = self.format();
|
||||
let Some(d) = format::to_decimal(n, decimals) else {
|
||||
return self.plural(lang, None, false, &format.number(n, decimals), one, other);
|
||||
};
|
||||
let english_one = d.to_string() == "1";
|
||||
self.plural(lang, Some(PluralOperands::from(&d)), english_one, &format.write(&d), one, other)
|
||||
}
|
||||
|
||||
/// `operands` `None` is the `other` category.
|
||||
fn plural(&self, lang: Lang, operands: Option<PluralOperands>, english_one: bool, n: &str, one: &str, other: &str) -> String {
|
||||
let key = format!("{one}|{other}");
|
||||
let chain = self.locale(lang).map_or(&[][..], |l| l.chain.as_slice());
|
||||
let text = chain
|
||||
@@ -217,19 +291,45 @@ impl I18n {
|
||||
let locale = self.locales.get(i)?;
|
||||
let forms = locale.parsed().rows.get("@plural")?.get(&key)?;
|
||||
let (rules, categories) = locale.plural.as_ref()?;
|
||||
let category = rules.select(n).ok()?;
|
||||
// A category whole numbers up to 1000 never reach (French `many`) takes the last form.
|
||||
let index = categories.iter().position(|c| *c == category).unwrap_or(categories.len().saturating_sub(1));
|
||||
let category = operands.map_or(PluralCategory::Other, |o| rules.category_for(o));
|
||||
// A category whole numbers up to 1000 never reach has no form of its own. Russian
|
||||
// and Ukrainian decimals (`other`) take the `few` form (`1,5 файла`); any other
|
||||
// (French `many` for a million) takes the last.
|
||||
let index = categories
|
||||
.iter()
|
||||
.position(|c| *c == category)
|
||||
.or_else(|| categories.iter().position(|c| *c == PluralCategory::Few))
|
||||
.unwrap_or(categories.len().saturating_sub(1));
|
||||
forms.split('|').nth(index)
|
||||
})
|
||||
.unwrap_or(if n == 1 { one } else { other });
|
||||
let text = fmt(text, &[("n", &n.to_string())]);
|
||||
.unwrap_or(if english_one { one } else { other });
|
||||
let text = fmt(text, &[("n", <r(n))]);
|
||||
if lang == Lang::PSEUDO {
|
||||
return marked(&text);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// How counts, file sizes and measures write numbers: [`Region::system`]'s format with the
|
||||
/// locale's digits until [`I18n::set_format`], and again after [`I18n::reset_format`].
|
||||
pub fn format(&self) -> Arc<Format> {
|
||||
if let Some(f) = self.format.read().unwrap_or_else(PoisonError::into_inner).as_ref() {
|
||||
return Arc::clone(f);
|
||||
}
|
||||
let mut slot = self.format.write().unwrap_or_else(PoisonError::into_inner);
|
||||
Arc::clone(slot.get_or_insert_with(|| Arc::new(Format::new(&Region::system(), Digits::Locale))))
|
||||
}
|
||||
|
||||
/// Write numbers as `format` does from now on: the user's region setting, or Latin digits.
|
||||
pub fn set_format(&self, format: Format) {
|
||||
*self.format.write().unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(format));
|
||||
}
|
||||
|
||||
/// Write numbers as the system region does again, undoing [`I18n::set_format`].
|
||||
pub fn reset_format(&self) {
|
||||
*self.format.write().unwrap_or_else(PoisonError::into_inner) = None;
|
||||
}
|
||||
|
||||
/// The languages to offer: English first, then the offered locales by code. Never the
|
||||
/// pseudo locale.
|
||||
pub fn languages(&self) -> Vec<Lang> {
|
||||
@@ -248,12 +348,10 @@ impl I18n {
|
||||
self.locale(lang).and_then(Locale::language_name).unwrap_or_else(|| self.code(lang))
|
||||
}
|
||||
|
||||
/// Whether the language is written right to left. Putting text into display order is the
|
||||
/// app's job.
|
||||
/// Whether the language is written right to left ([`direction`]). Putting text into display
|
||||
/// order is the app's job.
|
||||
pub fn rtl(&self, lang: Lang) -> bool {
|
||||
let code = self.code(lang);
|
||||
let language = code.split('-').next().unwrap_or(code);
|
||||
matches!(language, "ar" | "ckb" | "dv" | "fa" | "he" | "ps" | "sd" | "ug" | "ur" | "yi")
|
||||
direction(self.code(lang)) == Direction::Rtl
|
||||
}
|
||||
|
||||
/// The language for a system locale tag (`fr_CA.UTF-8`, `zh-Hant-MO`); `C` and `POSIX` are
|
||||
@@ -310,29 +408,168 @@ impl I18n {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill `{name}` placeholders from `args` in one pass. Unknown placeholders stay as written, and
|
||||
/// inserted values are never read as templates, so a file name containing `{n}` stays intact.
|
||||
/// Fill `{name}` placeholders from `args` in one pass. When the template or an inserted value
|
||||
/// has a right-to-left letter (Hebrew, Arabic and the like), or a value has a bidi control
|
||||
/// (an embedding, override, isolate or mark), each value goes in as a first-strong isolate
|
||||
/// (FSI…PDI), so its direction can't reorder the sentence around it: a Latin file name in an
|
||||
/// Arabic message stays where the translator put it, and an override in a file name ends with
|
||||
/// the name. Embeddings, overrides and isolates a value opens are closed inside its isolate. A
|
||||
/// value that already is one isolate keeps it; pass numbers, paths and codes through [`ltr`].
|
||||
/// Other text gets no marks, and a value's own isolate is taken off. Unknown placeholders stay as written,
|
||||
/// and inserted values are never read as templates, so a file name containing `{n}` stays intact.
|
||||
pub fn fmt(template: &str, args: &[(&str, &str)]) -> String {
|
||||
let mut out = String::with_capacity(template.len());
|
||||
fill(template, args, true)
|
||||
}
|
||||
|
||||
/// [`fmt`] without isolates, for text that goes where the marks would get in the way: file
|
||||
/// names, logs, terminals, text compared or parsed later. Every isolate mark is taken off, in
|
||||
/// the template and in the values.
|
||||
pub fn fmt_plain(template: &str, args: &[(&str, &str)]) -> String {
|
||||
strip_isolates(&fill(template, args, false))
|
||||
}
|
||||
|
||||
const LRI: char = '\u{2066}';
|
||||
const RLI: char = '\u{2067}';
|
||||
const FSI: char = '\u{2068}';
|
||||
const PDI: char = '\u{2069}';
|
||||
const LRE: char = '\u{202A}';
|
||||
const RLE: char = '\u{202B}';
|
||||
const PDF: char = '\u{202C}';
|
||||
const LRO: char = '\u{202D}';
|
||||
const RLO: char = '\u{202E}';
|
||||
const LRM: char = '\u{200E}';
|
||||
const RLM: char = '\u{200F}';
|
||||
const ALM: char = '\u{061C}';
|
||||
|
||||
/// `value` as a first-strong isolate (FSI…PDI): it takes the direction of its first strong
|
||||
/// letter and can't reorder the text around it. What [`fmt`] does to each value in text with a
|
||||
/// right-to-left letter.
|
||||
pub fn isolate(value: &str) -> String {
|
||||
wrap(FSI, value)
|
||||
}
|
||||
|
||||
/// `value` as a left-to-right isolate (LRI…PDI), for numbers, paths, file sizes, timecodes and
|
||||
/// codes, which read left to right in every language. In an RTL first-strong isolate, the
|
||||
/// segments of `/home/مستخدم/file.txt` would run right to left. [`fmt`] takes the isolate off
|
||||
/// again in text with no right-to-left letter.
|
||||
pub fn ltr(value: &str) -> String {
|
||||
wrap(LRI, value)
|
||||
}
|
||||
|
||||
/// `text` without isolate marks (LRI, RLI, FSI, PDI): a [`fmt`] or [`I18n::trn`] result made fit
|
||||
/// for a file name, a log or a comparison.
|
||||
pub fn strip_isolates(text: &str) -> String {
|
||||
text.chars().filter(|c| !matches!(*c, LRI | RLI | FSI | PDI)).collect()
|
||||
}
|
||||
|
||||
/// `value` between `initiator` and PDI, with every embedding, override and isolate it opens
|
||||
/// closed inside: a stray PDF or PDI is dropped, and open ones are closed in order. Under the
|
||||
/// bidi algorithm the outer PDI alone would close them, but a renderer that handles only
|
||||
/// embeddings would let them run on into the rest of the text.
|
||||
fn wrap(initiator: char, value: &str) -> String {
|
||||
let mut out = String::with_capacity(value.len() + 6);
|
||||
out.push(initiator);
|
||||
// One entry per open initiator: true for an isolate, false for an embedding or override.
|
||||
let mut open: Vec<bool> = Vec::new();
|
||||
for c in value.chars() {
|
||||
match c {
|
||||
LRI | RLI | FSI => open.push(true),
|
||||
LRE | RLE | LRO | RLO => open.push(false),
|
||||
PDF if open.last() == Some(&false) => {
|
||||
open.pop();
|
||||
}
|
||||
PDF => continue,
|
||||
PDI if open.contains(&true) => {
|
||||
while open.pop() == Some(false) {
|
||||
out.push(PDF);
|
||||
}
|
||||
}
|
||||
PDI => continue,
|
||||
_ => {}
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
while let Some(isolate) = open.pop() {
|
||||
out.push(if isolate { PDI } else { PDF });
|
||||
}
|
||||
out.push(PDI);
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `value`, without its own isolate, has a bidi control: an embedding, override,
|
||||
/// isolate or mark that could reorder the text around it unless it is contained.
|
||||
fn has_bidi_control(value: &str) -> bool {
|
||||
!value.is_ascii() && unwrap_isolate(value).chars().any(|c| matches!(c, LRE | RLE | PDF | LRO | RLO | LRI | RLI | FSI | PDI | LRM | RLM | ALM))
|
||||
}
|
||||
|
||||
/// Whether `text` has a strong right-to-left character (bidi class R or AL): the text that needs
|
||||
/// isolates.
|
||||
fn has_rtl(text: &str) -> bool {
|
||||
!text.is_ascii() && text.chars().any(|c| matches!(bidi_class(c), BidiClass::R | BidiClass::AL))
|
||||
}
|
||||
|
||||
/// `value` without its isolate, if it is exactly one.
|
||||
fn unwrap_isolate(value: &str) -> &str {
|
||||
if is_one_isolate(value) {
|
||||
// The initiator and PDI are three bytes each in UTF-8.
|
||||
value.get(3..value.len() - 3).unwrap_or(value)
|
||||
} else {
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `value` is exactly one isolate: an initiator, then the PDI that closes it last.
|
||||
fn is_one_isolate(value: &str) -> bool {
|
||||
let mut depth = 0_usize;
|
||||
let mut chars = value.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
LRI | RLI | FSI => depth += 1,
|
||||
PDI if depth > 0 => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return chars.peek().is_none();
|
||||
}
|
||||
}
|
||||
_ if depth == 0 => return false,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn fill(template: &str, args: &[(&str, &str)], isolated: bool) -> String {
|
||||
let mut pieces: Vec<(&str, bool)> = Vec::new();
|
||||
let mut rest = template;
|
||||
while let Some((before, after_open)) = rest.split_once('{') {
|
||||
out.push_str(before);
|
||||
pieces.push((before, false));
|
||||
let Some((name, after_close)) = after_open.split_once('}') else {
|
||||
out.push('{');
|
||||
pieces.push(("{", false));
|
||||
rest = after_open;
|
||||
break;
|
||||
};
|
||||
match args.iter().find(|(k, _)| *k == name) {
|
||||
Some((_, value)) => out.push_str(value),
|
||||
None => {
|
||||
out.push('{');
|
||||
out.push_str(name);
|
||||
out.push('}');
|
||||
}
|
||||
Some((_, value)) => pieces.push((value, true)),
|
||||
None => pieces.extend([("{", false), (name, false), ("}", false)]),
|
||||
}
|
||||
rest = after_close;
|
||||
}
|
||||
out.push_str(rest);
|
||||
pieces.push((rest, false));
|
||||
let isolated = isolated && pieces.iter().any(|(text, value)| has_rtl(text) || (*value && has_bidi_control(text)));
|
||||
let mut out = String::with_capacity(template.len());
|
||||
for (text, value) in pieces {
|
||||
match (value, isolated) {
|
||||
(false, _) => out.push_str(text),
|
||||
(true, false) => out.push_str(unwrap_isolate(text)),
|
||||
(true, true) if text.is_empty() => {}
|
||||
// Rebuilt rather than copied, so what it opens inside is closed too.
|
||||
(true, true) if is_one_isolate(text) => {
|
||||
let initiator = text.chars().next().unwrap_or(FSI);
|
||||
out.push_str(&wrap(initiator, unwrap_isolate(text)));
|
||||
}
|
||||
(true, true) => out.push_str(&isolate(text)),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -340,7 +577,9 @@ pub fn fmt(template: &str, args: &[(&str, &str)]) -> String {
|
||||
/// Chinese without a script picks one by region; Portuguese falls back to `pt-br` last, when
|
||||
/// there is no `pt`. A glibc script modifier (`sr_RS@latin`) becomes the script subtag. With a
|
||||
/// script (`sr-Latn-RS`), a code without one is tried only when that is its language's usual
|
||||
/// script, so Latin Serbian never picks Cyrillic `sr`, while `sr-Cyrl-RS` does.
|
||||
/// script, so Latin Serbian never picks Cyrillic `sr`, while `sr-Cyrl-RS` does. A region that
|
||||
/// implies a script (CLDR likely subtags) counts as that script after the tag as written:
|
||||
/// `pa-PK` → `pa-pk`, `pa-arab-pk`, `pa-arab`.
|
||||
fn candidates(tag: &str) -> Vec<String> {
|
||||
let tag = tag.trim().to_ascii_lowercase();
|
||||
let base = tag.split(['.', '@']).next().unwrap_or("").replace('_', "-");
|
||||
@@ -357,6 +596,16 @@ fn candidates(tag: &str) -> Vec<String> {
|
||||
parts.insert(1, s);
|
||||
}
|
||||
let script = parts.get(1).copied().filter(|s| s.len() == 4 && s.bytes().all(|b| b.is_ascii_alphabetic()));
|
||||
// Chinese picks its script by region below, keeping plain `zh` as the last resort.
|
||||
if script.is_none()
|
||||
&& primary != "zh"
|
||||
&& let Some(implied) = parts.get(1).filter(|r| is_region(r)).and_then(|r| scripts::region_script(primary, r))
|
||||
{
|
||||
let mut out = vec![parts.join("-")];
|
||||
parts.insert(1, implied);
|
||||
out.extend(candidates(&parts.join("-")));
|
||||
return out;
|
||||
}
|
||||
let mut out: Vec<String> = (1..=parts.len()).rev().map(|n| parts.get(..n).unwrap_or_default().join("-")).collect();
|
||||
if let Some(s) = script
|
||||
&& usual_script(primary).is_some_and(|usual| usual != s)
|
||||
@@ -364,7 +613,8 @@ fn candidates(tag: &str) -> Vec<String> {
|
||||
out.retain(|c| c.split('-').any(|p| p == s));
|
||||
}
|
||||
if primary == "zh" && !parts.iter().any(|p| matches!(*p, "hans" | "hant")) {
|
||||
let script = if parts.iter().any(|p| matches!(*p, "tw" | "hk" | "mo")) { "zh-hant" } else { "zh-hans" };
|
||||
let hant = parts.iter().skip(1).any(|p| scripts::region_script("zh", p) == Some("hant"));
|
||||
let script = if hant { "zh-hant" } else { "zh-hans" };
|
||||
out.insert(out.len().saturating_sub(1), script.to_owned());
|
||||
}
|
||||
if primary == "pt" && !out.iter().any(|c| c == "pt-br") {
|
||||
@@ -393,10 +643,10 @@ fn marked(text: &str) -> String {
|
||||
// ponytail: the multi-script languages a Craft app could plausibly ship; add a row with the locale.
|
||||
fn usual_script(language: &str) -> Option<&'static str> {
|
||||
Some(match language {
|
||||
"be" | "mn" | "sr" => "cyrl",
|
||||
"be" | "kk" | "ky" | "mn" | "sr" | "tg" => "cyrl",
|
||||
"zh" => "hans",
|
||||
"az" | "bs" | "ha" | "uz" => "latn",
|
||||
"ks" | "sd" => "arab",
|
||||
"az" | "bs" | "ha" | "ku" | "ms" | "uz" => "latn",
|
||||
"ks" | "sd" | "ug" => "arab",
|
||||
"pa" => "guru",
|
||||
_ => return None,
|
||||
})
|
||||
@@ -423,17 +673,22 @@ fn bare(code: &str) -> Locale {
|
||||
}
|
||||
|
||||
/// `code`'s CLDR cardinal rules and the categories whole numbers 0..=1000 reach, in CLDR order
|
||||
/// (zero, one, two, few, many, other): one `@plural` form each. Regional and scripted codes fall
|
||||
/// back to the language's rules. CLDR's `pt` is Brazilian (0 is singular), so Portuguese other
|
||||
/// than `pt-br` takes `pt-PT`'s.
|
||||
/// (zero, one, two, few, many, other): one `@plural` form each. The rules are looked up by
|
||||
/// language alone: CLDR's parent of `sr-Latn` and `zh-Hant` is the root, whose only category is
|
||||
/// `other`. CLDR's `pt` is Brazilian (0 is singular), so Portuguese other than `pt-br` takes
|
||||
/// `pt-PT`'s. `None` for a language CLDR has no plural rules for.
|
||||
fn plural_rules(code: &str) -> Option<(PluralRules, Vec<PluralCategory>)> {
|
||||
let code = if code == "pt" || (code.starts_with("pt-") && code != "pt-br") { "pt-pt" } else { code };
|
||||
let id: LanguageIdentifier = code.parse().ok()?;
|
||||
let language = LanguageIdentifier::from_parts(id.language, None, None, &[]);
|
||||
let rules = PluralRules::create(id, PluralRuleType::CARDINAL).or_else(|_| PluralRules::create(language, PluralRuleType::CARDINAL)).ok()?;
|
||||
let id = IcuLocale::try_from_str(code).ok()?.id;
|
||||
let language = id.language.as_str();
|
||||
if !data::PLURAL_LANGUAGES.contains(&language) {
|
||||
return None;
|
||||
}
|
||||
let brazil = id.region.is_some_and(|r| r.as_str() == "BR");
|
||||
let locale = IcuLocale::try_from_str(if language == "pt" && !brazil { "pt-PT" } else { language }).ok()?;
|
||||
let rules = PluralRules::try_new_cardinal_with_buffer_provider(data::provider()?, (&locale).into()).ok()?;
|
||||
let mut categories = Vec::new();
|
||||
for n in 0..=1000_u32 {
|
||||
let c = rules.select(n).ok()?;
|
||||
let c = rules.category_for(n);
|
||||
if !categories.contains(&c) {
|
||||
categories.push(c);
|
||||
}
|
||||
@@ -444,12 +699,12 @@ fn plural_rules(code: &str) -> Option<(PluralRules, Vec<PluralCategory>)> {
|
||||
|
||||
fn rank(c: &PluralCategory) -> u8 {
|
||||
match c {
|
||||
PluralCategory::ZERO => 0,
|
||||
PluralCategory::ONE => 1,
|
||||
PluralCategory::TWO => 2,
|
||||
PluralCategory::FEW => 3,
|
||||
PluralCategory::MANY => 4,
|
||||
PluralCategory::OTHER => 5,
|
||||
PluralCategory::Zero => 0,
|
||||
PluralCategory::One => 1,
|
||||
PluralCategory::Two => 2,
|
||||
PluralCategory::Few => 3,
|
||||
PluralCategory::Many => 4,
|
||||
PluralCategory::Other => 5,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -473,10 +728,12 @@ mod tests {
|
||||
("de", "\tBad\n@nope\tA\tB\n\tUndo\tRückgängig\n", ""),
|
||||
];
|
||||
|
||||
/// `embedded`, offering every locale in it.
|
||||
/// `embedded`, offering every locale in it, with `en-US` numbers rather than the machine's.
|
||||
fn all(embedded: &'static Embedded) -> (I18n, Vec<String>) {
|
||||
let codes: Vec<&str> = embedded.iter().map(|(c, _, _)| *c).collect();
|
||||
I18n::new(embedded, &codes)
|
||||
let (i, problems) = I18n::new(embedded, &codes);
|
||||
i.set_format(Format::from_tag("en-US"));
|
||||
(i, problems)
|
||||
}
|
||||
|
||||
fn i18n() -> I18n {
|
||||
@@ -547,6 +804,8 @@ mod tests {
|
||||
("fr", "@plural\t{n} page|{n} pages\t{n} page|{n} pages\n", ""),
|
||||
("ru", "@plural\t{n} file|{n} files\t{n} файл|{n} файла|{n} файлов\n", ""),
|
||||
("ja", "@plural\t{n} file|{n} files\t{n} 個\n", ""),
|
||||
("ar", "@plural\t{n} file|{n} files\t{n} ملفات|{n} ملف واحد|{n} ملفان|{n} ملفات|{n} ملفًا|{n} ملف\n", ""),
|
||||
("fa", "@plural\t{n} page|{n} pages\t{n} صفحه|{n} صفحه\n", ""),
|
||||
];
|
||||
|
||||
#[test]
|
||||
@@ -555,6 +814,76 @@ mod tests {
|
||||
assert_eq!(fmt("{z} {", &[]), "{z} {");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn left_to_right_text_gets_no_marks() {
|
||||
assert_eq!(fmt("Saved {name} in {dir}.", &[("name", "Report 2.pdf"), ("dir", <r("/home/sara"))]), "Saved Report 2.pdf in /home/sara.");
|
||||
assert_eq!(fmt("{a}", &[("a", "x"), ("b", "שלום")]), "x", "an unused value doesn't count");
|
||||
assert_eq!(fmt_plain("{a}", &[("a", &isolate("x"))]), "x");
|
||||
assert_eq!(fmt_plain("\u{2066}{a} {b}", &[("a", "x\u{2069}"), ("b", &isolate(<r("y")))]), "x y");
|
||||
let i = all(P).0;
|
||||
assert_eq!(i.trn(Lang::EN, 2, "{n} page", "{n} pages"), "2 pages");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_to_left_text_isolates_values() {
|
||||
let saved = fmt("تم حفظ {name} في {dir}.", &[("name", "Report 2.pdf"), ("dir", <r("/home/سارة/docs"))]);
|
||||
assert_eq!(saved, "تم حفظ \u{2068}Report 2.pdf\u{2069} في \u{2066}/home/سارة/docs\u{2069}.");
|
||||
assert_eq!(strip_isolates(&saved), "تم حفظ Report 2.pdf في /home/سارة/docs.");
|
||||
assert_eq!(fmt("Opened {name}.", &[("name", "שלום.txt")]), "Opened \u{2068}שלום.txt\u{2069}.");
|
||||
assert_eq!(fmt("[{a}] {b}", &[("a", ""), ("b", "ש")]), "[] \u{2068}ש\u{2069}");
|
||||
let i = all(P).0;
|
||||
assert_eq!(i.trn(lang(&i, "fa"), 3, "{n} page", "{n} pages"), "\u{2066}3\u{2069} صفحه");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_cannot_escape_its_isolate() {
|
||||
assert_eq!(isolate("a\u{2069}b"), "\u{2068}ab\u{2069}");
|
||||
assert_eq!(isolate("a\u{2067}b"), "\u{2068}a\u{2067}b\u{2069}\u{2069}");
|
||||
let one = ltr("12");
|
||||
assert_eq!(fmt("ש {n}", &[("n", &one)]), format!("ש {one}"));
|
||||
// Two isolates side by side are not one, so they get wrapped.
|
||||
assert_eq!(fmt("ש{v}", &[("v", "\u{2066}a\u{2069}\u{2066}b\u{2069}")]), "ש\u{2068}\u{2066}a\u{2069}\u{2066}b\u{2069}\u{2069}");
|
||||
}
|
||||
|
||||
/// `text` in display order, as one line in a left-to-right paragraph, without bidi controls.
|
||||
fn visual(text: &str) -> String {
|
||||
let info = unicode_bidi::BidiInfo::new(text, Some(unicode_bidi::Level::ltr()));
|
||||
let para = &info.paragraphs[0];
|
||||
let shown = info.reorder_line(para, para.range.clone());
|
||||
shown
|
||||
.chars()
|
||||
.filter(|c| bidi_class(*c) != BidiClass::BN && !"\u{202A}\u{202B}\u{202C}\u{202D}\u{202E}\u{2066}\u{2067}\u{2068}\u{2069}".contains(*c))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_with_bidi_controls_cannot_reorder_the_sentence() {
|
||||
let file_names = [
|
||||
"\u{202E}fdp.exe",
|
||||
"\u{202B}abc def",
|
||||
"\u{202D}abc def",
|
||||
"\u{2067}abc def",
|
||||
"\u{2068}abc\u{2069}\u{202E}def",
|
||||
"\u{202E}abc\u{2069}",
|
||||
"x\u{200F}",
|
||||
"x\u{061C}",
|
||||
];
|
||||
for name in file_names {
|
||||
let text = fmt("Open {name} -> {name} now?", &[("name", name)]);
|
||||
let shown = visual(&text);
|
||||
assert!(shown.starts_with("Open ") && shown.contains(" -> ") && shown.ends_with(" now?"), "{name:?}: {shown:?}");
|
||||
let i = all(P).0;
|
||||
let wording = i.trn(Lang::EN, 2, "{n} page in {name}, done", "{n} pages in {name}, done");
|
||||
let shown = visual(&fmt(&wording, &[("name", name)]));
|
||||
assert!(shown.starts_with("2 pages in ") && shown.ends_with(", done"), "{name:?}: {shown:?}");
|
||||
}
|
||||
// An override the value opens is closed inside its isolate, and a stray PDF dropped.
|
||||
assert_eq!(fmt("Open {name}.", &[("name", "\u{202E}abc")]), "Open \u{2068}\u{202E}abc\u{202C}\u{2069}.");
|
||||
assert_eq!(fmt("Open {name}.", &[("name", "a\u{202C}b")]), "Open \u{2068}ab\u{2069}.");
|
||||
assert_eq!(fmt("Open {n}.", &[("n", <r("\u{202B}1"))]), "Open \u{2066}\u{202B}1\u{202C}\u{2069}.");
|
||||
assert_eq!(isolate("\u{2067}a\u{202E}b\u{2069}c"), "\u{2068}\u{2067}a\u{202E}b\u{202C}\u{2069}c\u{2069}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_other() {
|
||||
let (i, problems) = all(P);
|
||||
@@ -589,7 +918,56 @@ mod tests {
|
||||
#[test]
|
||||
fn beyond_sweep() {
|
||||
let i = all(P).0;
|
||||
assert_eq!(i.trn(lang(&i, "fr"), 1_000_000, "{n} page", "{n} pages"), "1000000 pages");
|
||||
i.set_format(Format::from_tag("fr"));
|
||||
assert_eq!(i.trn(lang(&i, "fr"), 1_000_000, "{n} page", "{n} pages"), "1\u{202f}000\u{202f}000 pages");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_follow_the_region() {
|
||||
let i = all(P).0;
|
||||
i.set_format(Format::from_tag("ar-EG"));
|
||||
assert_eq!(i.trn(lang(&i, "ar"), 1234, "{n} file", "{n} files"), "\u{2066}١٬٢٣٤\u{2069} ملفًا");
|
||||
i.set_format(Format::new(&Region::from_tag("ar-EG"), Digits::Latin));
|
||||
assert_eq!(i.trn(lang(&i, "ar"), 1234, "{n} file", "{n} files"), "\u{2066}1,234\u{2069} ملفًا");
|
||||
// An English interface with a German region.
|
||||
i.set_format(Format::from_tag("de-DE"));
|
||||
assert_eq!(i.trn(Lang::EN, 12_345, "{n} file", "{n} files"), "12.345 files");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_counts_and_the_system_format() {
|
||||
let i = all(P).0;
|
||||
i.set_format(Format::from_tag("ar-EG"));
|
||||
assert_eq!(i.trn_plain(lang(&i, "ar"), 1234, "{n} file", "{n} files"), "1234 ملفًا");
|
||||
i.set_format(Format::from_tag("de-DE"));
|
||||
assert_eq!(i.trn_plain(Lang::EN, 12_345, "copy {n}", "copy {n}"), "copy 12345");
|
||||
i.reset_format();
|
||||
assert_eq!(
|
||||
i.trn(Lang::EN, 5, "{n} file", "{n} files"),
|
||||
fmt("{n} files", &[("n", &Format::new(&Region::system(), Digits::Locale).integer(5))])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimal_counts() {
|
||||
let i = all(P).0;
|
||||
i.set_format(Format::from_tag("en"));
|
||||
assert_eq!(i.trn_decimal(Lang::EN, 1.5, 1, "{n} file", "{n} files"), "1.5 files");
|
||||
assert_eq!(i.trn_decimal(Lang::EN, 1.0, 1, "{n} file", "{n} files"), "1.0 files", "visible decimals are plural");
|
||||
assert_eq!(i.trn_decimal(Lang::EN, 1.0, 0, "{n} file", "{n} files"), "1 file");
|
||||
// Russian decimals are `other`, which integers never reach: the `few` form.
|
||||
i.set_format(Format::from_tag("ru"));
|
||||
let ru = lang(&i, "ru");
|
||||
assert_eq!(i.trn_decimal(ru, 1.5, 1, "{n} file", "{n} files"), "1,5 файла");
|
||||
assert_eq!(i.trn_decimal(ru, 21.0, 0, "{n} file", "{n} files"), "21 файл");
|
||||
// Arabic decimals are `other`.
|
||||
i.set_format(Format::from_tag("ar-EG"));
|
||||
let ar = lang(&i, "ar");
|
||||
assert_eq!(i.trn_decimal(ar, 2.5, 1, "{n} file", "{n} files"), "\u{2066}٢٫٥\u{2069} ملف");
|
||||
assert_eq!(i.trn_decimal(ar, 3.0, 0, "{n} file", "{n} files"), "\u{2066}٣\u{2069} ملفات");
|
||||
// Not a number: the translated `other` form.
|
||||
assert_eq!(i.trn_decimal(ru, f64::NAN, 1, "{n} file", "{n} files"), "NaN файла");
|
||||
assert_eq!(i.trn_decimal(Lang::EN, f64::INFINITY, 1, "{n} file", "{n} files"), "∞ files");
|
||||
}
|
||||
|
||||
static L: &Embedded =
|
||||
@@ -630,6 +1008,8 @@ mod tests {
|
||||
("zh", Some("zh-hans")),
|
||||
("zh-Hant-MO", Some("zh-hant")),
|
||||
("zh_CN", Some("zh-hans")),
|
||||
("zh-US", Some("zh-hant")),
|
||||
("zh_SG", Some("zh-hans")),
|
||||
("C", Some("en")),
|
||||
("POSIX", Some("en")),
|
||||
("en_US", Some("en")),
|
||||
@@ -641,6 +1021,20 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn region_implies_script() {
|
||||
assert_eq!(candidates("pa-PK"), ["pa-pk", "pa-arab-pk", "pa-arab"]);
|
||||
assert_eq!(candidates("pa_PK.UTF-8"), ["pa-pk", "pa-arab-pk", "pa-arab"]);
|
||||
assert_eq!(candidates("pa-IN"), ["pa-in", "pa"]);
|
||||
assert_eq!(candidates("sd-IN"), ["sd-in", "sd-deva-in", "sd-deva"]);
|
||||
assert_eq!(candidates("pa-Guru-PK"), ["pa-guru-pk", "pa-guru", "pa"]);
|
||||
assert_eq!(candidates("zh-US"), ["zh-us", "zh-hant", "zh"]);
|
||||
assert_eq!(candidates("zh-SG"), ["zh-sg", "zh-hans", "zh"]);
|
||||
assert_eq!(candidates("kk-CN"), ["kk-cn", "kk-arab-cn", "kk-arab"]);
|
||||
assert_eq!(candidates("kk-KZ"), ["kk-kz", "kk"]);
|
||||
assert_eq!(candidates("ug-KZ"), ["ug-kz", "ug-cyrl-kz", "ug-cyrl"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_tags_takes_first_match() {
|
||||
let i = all(L).0;
|
||||
@@ -740,15 +1134,31 @@ mod tests {
|
||||
assert_eq!(i.trn(lang(&i, "pt-br"), 0, "{n} file", "{n} files"), "0 arquivo");
|
||||
}
|
||||
|
||||
/// The same counts as craft-i18n's checker (`plural_form_counts`), which rejects a catalog
|
||||
/// whose `@plural` rows list any other.
|
||||
/// The counts craft-i18n's checker expects, which rejects a catalog whose `@plural` rows list
|
||||
/// any other: every directory in craft-i18n's `locales/`, then languages it may add.
|
||||
#[test]
|
||||
fn plural_form_counts() {
|
||||
for (locale, n) in
|
||||
[("en", 2), ("fr", 2), ("ja", 1), ("vi", 1), ("ru", 3), ("pl", 3), ("cs", 3), ("sl", 4), ("ar", 6), ("pt", 2), ("pt-br", 2), ("tr", 2)]
|
||||
{
|
||||
#[rustfmt::skip]
|
||||
let catalogs = [
|
||||
("ar", 6), ("bg", 2), ("cs", 3), ("da", 2), ("de", 2), ("el", 2), ("es", 2), ("et", 2),
|
||||
("fi", 2), ("fr", 2), ("hr", 3), ("hu", 2), ("id", 1), ("it", 2), ("ja", 1), ("ka", 2),
|
||||
("kk", 2), ("ko", 1), ("lt", 3), ("nl", 2), ("pl", 3), ("pt-br", 2), ("ru", 3), ("sl", 4),
|
||||
("sr", 3), ("sr-latn", 3), ("sv", 2), ("te", 2), ("tr", 2), ("uk", 3), ("vi", 1),
|
||||
("zh-hans", 1), ("zh-hant", 1),
|
||||
];
|
||||
let more = [("en", 2), ("pt", 2), ("he", 3), ("ro", 3), ("nb", 2), ("ca", 2), ("sk", 3), ("th", 1), ("ms", 1), ("fa", 2), ("hi", 2)];
|
||||
for (locale, n) in catalogs.into_iter().chain(more) {
|
||||
assert_eq!(plural_rules(locale).map(|(_, c)| c.len()), Some(n), "{locale}");
|
||||
}
|
||||
assert!(plural_rules("tlh").is_none(), "no CLDR rules");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serbian_latin_plurals() {
|
||||
let i = all(&[("sr-latn", "@plural\t{n} file|{n} files\t{n} fajl|{n} fajla|{n} fajlova\n", "")]).0;
|
||||
let sr = lang(&i, "sr-latn");
|
||||
let files = |n| i.trn(sr, n, "{n} file", "{n} files");
|
||||
assert_eq!((files(1), files(3), files(5)), ("1 fajl".into(), "3 fajla".into(), "5 fajlova".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,395 @@
|
||||
//! Reading numbers people type or paste, in any digits and with their locale's separators.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use crate::Format;
|
||||
|
||||
/// Why [`Format::parse`] rejected a text.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum NumberError {
|
||||
/// No digits: empty, or only spaces and a sign.
|
||||
Empty,
|
||||
/// A character that isn't a digit, sign, decimal mark or grouping mark.
|
||||
Unexpected(char),
|
||||
/// Digits from more than one set (`1٢`).
|
||||
MixedDigits,
|
||||
/// A decimal or grouping mark where the locale puts none (`1.234,5` in English, `1,2.5` in
|
||||
/// German).
|
||||
Separator,
|
||||
/// Too large for an `f64`.
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
impl fmt::Display for NumberError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
NumberError::Empty => write!(f, "no digits"),
|
||||
NumberError::Unexpected(c) => write!(f, "unexpected character {c:?}"),
|
||||
NumberError::MixedDigits => write!(f, "digits from more than one script"),
|
||||
NumberError::Separator => write!(f, "misplaced or ambiguous decimal or grouping mark"),
|
||||
NumberError::TooLarge => write!(f, "number too large"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for NumberError {}
|
||||
|
||||
/// The marks a [`Format`] writes, as [`Format::parse`] reads them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Marks {
|
||||
/// `.` is the decimal mark and `,` grouping; else the other way round. For a format in
|
||||
/// Arabic-Indic digits, as the locale writes Latin ones.
|
||||
pub(crate) point: bool,
|
||||
/// The format's own decimal and grouping marks when they are neither `.` nor `,` (`٫`, `'`, a
|
||||
/// mark the system sets).
|
||||
decimal: Option<char>,
|
||||
group: Option<char>,
|
||||
}
|
||||
|
||||
impl Default for Marks {
|
||||
fn default() -> Self {
|
||||
Marks { point: true, decimal: None, group: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Marks {
|
||||
pub(crate) fn new(decimal: &str, group: &str, point: bool) -> Marks {
|
||||
let own = |s: &str| {
|
||||
let mut chars = s.chars();
|
||||
chars.next().filter(|c| !matches!(c, '.' | ',') && chars.next().is_none())
|
||||
};
|
||||
Marks { point, decimal: own(decimal), group: own(group) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Format {
|
||||
/// The number in `text`: what this format writes, and what people type or paste.
|
||||
///
|
||||
/// - Digits: any Unicode decimal digits (ASCII, Arabic-Indic, Persian, Devanagari, Bengali,
|
||||
/// Thai, full-width, …), all from one set.
|
||||
/// - Decimal mark: the format's, `٫` in every format, and the locale's `.` or `,` when Latin
|
||||
/// digits are typed into an Arabic-Indic format. A lone `.` in a comma locale is the decimal
|
||||
/// mark when it can't be grouping (`1.5`, `0.250`, `1234.5`, `.5`), but `1.234` and
|
||||
/// `1.234.567` stay grouped; the same holds for `,` in a point locale.
|
||||
/// - Grouping: the format's, the other of `.` and `,`, spaces (NBSP, narrow NBSP, thin), `'`,
|
||||
/// `’` and `٬`, one kind per number, in groups of three or the Indian 2-2-3 (`12,34,567`).
|
||||
/// Never in the fraction.
|
||||
/// - Sign: a leading `-`, `−` (U+2212), full-width `-` or `+`.
|
||||
/// - Bidi marks and isolates (LRM, RLM, ALM, LRI…PDI) around or inside are ignored, so a
|
||||
/// number formatted for an RTL interface reads back.
|
||||
///
|
||||
/// Percent signs, units and the space before a unit (`50 %`, `12 px`) are not read; strip them
|
||||
/// first. Anything else is an error rather than a guess.
|
||||
pub fn parse(&self, text: &str) -> Result<f64, NumberError> {
|
||||
let marks = self.marks;
|
||||
let text: String = text.chars().filter(|c| !is_bidi_mark(*c)).collect();
|
||||
let mut rest = text.trim();
|
||||
let negative = match rest.chars().next() {
|
||||
Some(c @ ('-' | '−' | '-' | '+' | '+')) => {
|
||||
rest = rest.get(c.len_utf8()..).unwrap_or("");
|
||||
matches!(c, '-' | '−' | '-')
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
let mut tokens = Vec::with_capacity(rest.len());
|
||||
let mut zero = None;
|
||||
for c in rest.chars() {
|
||||
let token = match c {
|
||||
c if Some(c) == marks.decimal => Token::Decimal,
|
||||
c if Some(c) == marks.group => Token::Group(c),
|
||||
'.' | '.' => Token::Point,
|
||||
',' | ',' => Token::Comma,
|
||||
'٫' => Token::Decimal,
|
||||
'٬' => Token::Group('٬'),
|
||||
'\'' | '’' => Token::Group('\''),
|
||||
' ' | '\u{a0}' | '\u{202f}' | '\u{2009}' => Token::Group(' '),
|
||||
_ => {
|
||||
let (z, d) = digit(c).ok_or(NumberError::Unexpected(c))?;
|
||||
if *zero.get_or_insert(z) != z {
|
||||
return Err(NumberError::MixedDigits);
|
||||
}
|
||||
Token::Digit(d)
|
||||
}
|
||||
};
|
||||
tokens.push(token);
|
||||
}
|
||||
if zero.is_none() {
|
||||
return Err(if tokens.is_empty() { NumberError::Empty } else { NumberError::Separator });
|
||||
}
|
||||
let point = if lone_decimal(&tokens, marks.point) { !marks.point } else { marks.point };
|
||||
let digits = read(&tokens, point).ok_or(NumberError::Separator)?;
|
||||
let value: f64 = digits.parse().map_err(|_| NumberError::Separator)?;
|
||||
if !value.is_finite() {
|
||||
return Err(NumberError::TooLarge);
|
||||
}
|
||||
Ok(if negative { -value } else { value })
|
||||
}
|
||||
}
|
||||
|
||||
/// The number in `text` as `locale` (a language tag, `de-CH`, `ar_EG.UTF-8`) writes it:
|
||||
/// [`Format::parse`] for [`Format::from_tag`]. Build the [`Format`] once to read many numbers. A
|
||||
/// locale CLDR doesn't know reads as CLDR's root does (`1,234.5`).
|
||||
pub fn parse_number(text: &str, locale: &str) -> Result<f64, NumberError> {
|
||||
Format::from_tag(locale).parse(text)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Token {
|
||||
Digit(u8),
|
||||
Point,
|
||||
Comma,
|
||||
/// A decimal mark in every reading: `٫`, or the format's own.
|
||||
Decimal,
|
||||
/// A grouping mark in every reading, by kind (space, apostrophe, `٬`, the format's own).
|
||||
Group(char),
|
||||
}
|
||||
|
||||
/// Whether the locale's grouping mark of `.` and `,` (`.` when `point` is false) is the decimal
|
||||
/// mark here because it can't be grouping: it is the only mark of the two, there is one of it, and
|
||||
/// the digits before it are none, start with 0 or are more than three, or the digits after it
|
||||
/// aren't three.
|
||||
fn lone_decimal(tokens: &[Token], point: bool) -> bool {
|
||||
let (group, decimal) = if point { (Token::Comma, Token::Point) } else { (Token::Point, Token::Comma) };
|
||||
if tokens.contains(&decimal) || tokens.contains(&Token::Decimal) || tokens.iter().filter(|t| **t == group).count() != 1 {
|
||||
return false;
|
||||
}
|
||||
let Some(at) = tokens.iter().position(|t| *t == group) else { return false };
|
||||
let (int, frac) = (tokens.get(..at).unwrap_or_default(), tokens.get(at + 1..).unwrap_or_default());
|
||||
int.is_empty() || int.first() == Some(&Token::Digit(0)) || int.len() > 3 || frac.len() != 3
|
||||
}
|
||||
|
||||
/// The ASCII number `tokens` spell when the decimal mark is `.` (`point`) or `,`; `None` when the
|
||||
/// marks don't fit that reading.
|
||||
fn read(tokens: &[Token], point: bool) -> Option<String> {
|
||||
let tokens: Vec<Token> = tokens
|
||||
.iter()
|
||||
.map(|t| match t {
|
||||
Token::Point if point => Token::Decimal,
|
||||
Token::Point => Token::Group('.'),
|
||||
Token::Comma if point => Token::Group(','),
|
||||
Token::Comma => Token::Decimal,
|
||||
t => *t,
|
||||
})
|
||||
.collect();
|
||||
let (int, frac) = match tokens.iter().position(|t| *t == Token::Decimal) {
|
||||
Some(i) => (tokens.get(..i)?, tokens.get(i + 1..)?),
|
||||
None => (&tokens[..], &[][..]),
|
||||
};
|
||||
let ascii =
|
||||
|part: &[Token]| -> Option<String> { part.iter().map(|t| if let Token::Digit(d) = t { Some(char::from(b'0' + d)) } else { None }).collect() };
|
||||
let frac = ascii(frac)?;
|
||||
let mut group = None;
|
||||
let mut groups = Vec::new();
|
||||
for chunk in int.split(|t| matches!(t, Token::Group(_))) {
|
||||
groups.push(ascii(chunk)?);
|
||||
}
|
||||
for t in int {
|
||||
if let Token::Group(g) = t
|
||||
&& *group.get_or_insert(*g) != *g
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if let [first, middle @ .., last] = groups.as_slice()
|
||||
&& group.is_some()
|
||||
{
|
||||
let width = middle.first().map_or(3, String::len);
|
||||
let first_max = if width == 2 { 2 } else { 3 };
|
||||
let fits = (1..=first_max).contains(&first.len())
|
||||
&& !first.starts_with('0')
|
||||
&& last.len() == 3
|
||||
&& middle.iter().all(|g| g.len() == width)
|
||||
&& (2..=3).contains(&width);
|
||||
if !fits {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let int = groups.concat();
|
||||
if int.is_empty() && frac.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(format!("{}.{}", if int.is_empty() { "0" } else { &int }, if frac.is_empty() { "0" } else { &frac }))
|
||||
}
|
||||
|
||||
/// The first code point of each run of ten Unicode decimal digits (general category Nd), Unicode
|
||||
/// 16.0.
|
||||
const ZEROS: [u32; 76] = [
|
||||
0x30, 0x660, 0x6F0, 0x7C0, 0x966, 0x9E6, 0xA66, 0xAE6, 0xB66, 0xBE6, 0xC66, 0xCE6, 0xD66, 0xDE6, 0xE50, 0xED0, 0xF20, 0x1040, 0x1090, 0x17E0,
|
||||
0x1810, 0x1946, 0x19D0, 0x1A80, 0x1A90, 0x1B50, 0x1BB0, 0x1C40, 0x1C50, 0xA620, 0xA8D0, 0xA900, 0xA9D0, 0xA9F0, 0xAA50, 0xABF0, 0xFF10, 0x104A0,
|
||||
0x10D30, 0x10D40, 0x11066, 0x110F0, 0x11136, 0x111D0, 0x112F0, 0x11450, 0x114D0, 0x11650, 0x116C0, 0x116D0, 0x116DA, 0x11730, 0x118E0, 0x11950,
|
||||
0x11BF0, 0x11C50, 0x11D50, 0x11DA0, 0x11F50, 0x16130, 0x16A60, 0x16AC0, 0x16B50, 0x16D70, 0x1CCF0, 0x1D7CE, 0x1D7D8, 0x1D7E2, 0x1D7EC, 0x1D7F6,
|
||||
0x1E140, 0x1E2F0, 0x1E4F0, 0x1E5F1, 0x1E950, 0x1FBF0,
|
||||
];
|
||||
|
||||
/// `c`'s digit set (its zero) and value.
|
||||
fn digit(c: char) -> Option<(u32, u8)> {
|
||||
let c = u32::from(c);
|
||||
let zero = match ZEROS.binary_search(&c) {
|
||||
Ok(i) => ZEROS.get(i),
|
||||
Err(i) => ZEROS.get(i.checked_sub(1)?),
|
||||
}?;
|
||||
let value = c - zero;
|
||||
u8::try_from(value).ok().filter(|v| *v < 10).map(|v| (*zero, v))
|
||||
}
|
||||
|
||||
/// Marks bidi formatting adds around numbers: LRM, RLM, ALM, embeddings, overrides and isolates.
|
||||
fn is_bidi_mark(c: char) -> bool {
|
||||
matches!(c, '\u{200e}' | '\u{200f}' | '\u{061c}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Digits, Region};
|
||||
|
||||
#[test]
|
||||
fn every_digit_set() {
|
||||
for zero in ZEROS {
|
||||
let d = |n: u32| char::from_u32(zero + n).unwrap();
|
||||
let all: String = (0..10).rev().map(d).collect();
|
||||
assert_eq!(parse_number(&all, "en"), Ok(9_876_543_210.0), "{zero:X}");
|
||||
let grouped = format!("-{}{}{},{}{}{}.{}", d(1), d(2), d(3), d(4), d(5), d(6), d(7));
|
||||
assert_eq!(parse_number(&grouped, "en"), Ok(-123_456.7), "{zero:X}");
|
||||
assert!((0..10).all(|n| d(n).is_numeric()), "{zero:X}");
|
||||
}
|
||||
assert_eq!(digit('\u{1D800}'), None);
|
||||
assert_eq!(digit('/'), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locale_forms() {
|
||||
for (text, locale, want) in [
|
||||
("1,234.5", "en", 1234.5),
|
||||
("1.234,5", "de", 1234.5),
|
||||
("1 234,5", "fr", 1234.5),
|
||||
("1\u{202f}234,5", "fr", 1234.5),
|
||||
("1\u{a0}234,5", "ru", 1234.5),
|
||||
("1’234.5", "de-CH", 1234.5),
|
||||
("1'234.5", "de_CH.UTF-8", 1234.5),
|
||||
("1,234", "en", 1234.0),
|
||||
("1,234", "de", 1.234),
|
||||
("1.234", "pt-br", 1234.0),
|
||||
("1,5", "es", 1.5),
|
||||
("1.5", "es-419", 1.5),
|
||||
("١٬٢٣٤٫٥", "ar", 1234.5),
|
||||
("١٢٫٥", "ar", 12.5),
|
||||
("12.5", "ar", 12.5),
|
||||
("12,5", "ar-MA", 12.5),
|
||||
("۱۲٫۵", "fa", 12.5),
|
||||
("−۴۲", "fa", -42.0),
|
||||
("123,456.7", "ja", 123_456.7),
|
||||
("-5", "ja", -5.0),
|
||||
("१२,३४,५६७.८९", "hi", 1_234_567.89),
|
||||
("১২,৩৪,৫৬৭", "bn", 1_234_567.0),
|
||||
("౧,౨౩,౪౫౬", "te", 123_456.0),
|
||||
("๑,๒๓๔.๕", "th", 1234.5),
|
||||
("1,234,567", "en", 1_234_567.0),
|
||||
("−3,5", "sv", -3.5),
|
||||
("+7", "en", 7.0),
|
||||
(".5", "en", 0.5),
|
||||
("5.", "en", 5.0),
|
||||
(" 42 ", "en", 42.0),
|
||||
("\u{2066}-1,5\u{2069}", "de", -1.5),
|
||||
("\u{061c}-١٢", "ar", -12.0),
|
||||
("1,234.5", "xx", 1234.5),
|
||||
("12", "xx", 12.0),
|
||||
("1,5", "en-PL", 1.5),
|
||||
("1.234,5", "en-DE", 1234.5),
|
||||
("1.234,5", "lo", 1234.5),
|
||||
("1,234.5", "km", 1234.5),
|
||||
] {
|
||||
assert_eq!(parse_number(text, locale), Ok(want), "{text:?} in {locale}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_instead_of_guesses() {
|
||||
for (text, locale, want) in [
|
||||
("", "en", NumberError::Empty),
|
||||
(" ", "en", NumberError::Empty),
|
||||
("-", "en", NumberError::Empty),
|
||||
(",", "en", NumberError::Separator),
|
||||
("1.2.3", "en", NumberError::Separator),
|
||||
("1,,234", "en", NumberError::Separator),
|
||||
("1,234,", "en", NumberError::Separator),
|
||||
("1.234,5", "en", NumberError::Separator),
|
||||
("1 234'567", "en", NumberError::Separator),
|
||||
("1.234 567", "de", NumberError::Separator),
|
||||
("0.123,4", "de", NumberError::Separator),
|
||||
("1.5,2", "en", NumberError::Separator),
|
||||
("123,45,678", "hi", NumberError::Separator),
|
||||
("12٫3٫4", "ar", NumberError::Separator),
|
||||
("1٫5.2", "ar", NumberError::Separator),
|
||||
("1٢", "ar", NumberError::MixedDigits),
|
||||
("12abc", "en", NumberError::Unexpected('a')),
|
||||
("1e5", "en", NumberError::Unexpected('e')),
|
||||
("--5", "en", NumberError::Unexpected('-')),
|
||||
("5-", "en", NumberError::Unexpected('-')),
|
||||
("- 5", "en", NumberError::Separator),
|
||||
] {
|
||||
assert_eq!(parse_number(text, locale), Err(want), "{text:?} in {locale}");
|
||||
}
|
||||
assert_eq!(parse_number(&"9".repeat(400), "en"), Err(NumberError::TooLarge));
|
||||
for unit in ["50 %", "50%", "12 px", "1,5 MB"] {
|
||||
assert!(parse_number(unit, "de").is_err(), "{unit}: units are the caller's to strip");
|
||||
}
|
||||
}
|
||||
|
||||
/// A lone mark that can't be grouping is the decimal mark; one that can stays grouping.
|
||||
#[test]
|
||||
fn lone_marks() {
|
||||
for (text, locale, want) in [
|
||||
("1.5", "de", 1.5),
|
||||
("0.250", "de", 0.25),
|
||||
("1234.5", "de", 1234.5),
|
||||
(".5", "de", 0.5),
|
||||
("-12.34", "ru", -12.34),
|
||||
("1.234", "de", 1234.0),
|
||||
("1.234.567", "de", 1_234_567.0),
|
||||
("1,5", "en", 1.5),
|
||||
("0,5", "en", 0.5),
|
||||
("12,34", "en", 12.34),
|
||||
("1234,567", "en", 1234.567),
|
||||
("1,234", "en", 1234.0),
|
||||
("12,345", "en", 12345.0),
|
||||
] {
|
||||
assert_eq!(parse_number(text, locale), Ok(want), "{text:?} in {locale}");
|
||||
}
|
||||
}
|
||||
|
||||
/// What a format writes reads back, in its digits and with its separators, the system's
|
||||
/// included.
|
||||
#[test]
|
||||
fn reads_what_format_writes() {
|
||||
let mut formats: Vec<Format> = ["en", "de", "de-CH", "fr", "hi", "ar-EG", "fa", "bn-BD", "ar-MA", "en-PL", "nb", "pt-PT", "sv"]
|
||||
.iter()
|
||||
.flat_map(|t| [Format::from_tag(t), Format::new(&Region::from_tag(t), Digits::Latin)])
|
||||
.collect();
|
||||
for (tag, decimal, grouping) in [
|
||||
("en-US", Some(','), None),
|
||||
("en-US", Some('.'), Some(Some('\u{a0}'))),
|
||||
("en-US", None, Some(None)),
|
||||
("en-US", Some('·'), Some(Some('_'))),
|
||||
("de-DE", Some('·'), None),
|
||||
] {
|
||||
let mut region = Region::from_tag(tag);
|
||||
region.decimal = decimal;
|
||||
region.grouping = grouping;
|
||||
formats.push(Format::new(®ion, Digits::Locale));
|
||||
}
|
||||
// Windows sets both marks: a decimal comma the user picks arrives beside a grouping comma.
|
||||
let reg = |pairs: &'static [(&'static str, &'static str)]| move |n: &str| pairs.iter().find(|(k, _)| *k == n).map(|(_, v)| v.to_string());
|
||||
let windows = crate::region::from_windows(reg(&[("LocaleName", "en-US"), ("sDecimal", ","), ("sThousand", ",")]), || None);
|
||||
formats.push(Format::new(&windows, Digits::Locale));
|
||||
formats.push(Format::new(&Region::from_tag("ar-EG-u-nu-latn"), Digits::Locale));
|
||||
formats.push(Format::new(&Region::from_tag("C"), Digits::Locale));
|
||||
for f in &formats {
|
||||
for value in [0.0, 1.5, -1234.25, 1_234_567.89, 12.0, 1234.0] {
|
||||
let text = f.number(value, 2);
|
||||
assert_eq!(f.parse(&text), Ok(value), "{text:?} ({f:?})");
|
||||
}
|
||||
let text = f.integer(1_234_567);
|
||||
assert_eq!(f.parse(&text), Ok(1_234_567.0), "{text:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
//! The formatting region: how numbers, times and measurements are written, apart from the
|
||||
//! interface language. An English interface in Poland still writes `2,54 cm` on A4.
|
||||
//!
|
||||
//! The territory lists come from Unicode CLDR's supplemental `measurementData` (Unicode License):
|
||||
//! `paperSize` US-Letter and `measurementSystem` US. Decimal and grouping separators come from
|
||||
//! the number locale's CLDR data ([`crate::Format`]); the region carries its own only where the
|
||||
//! system sets them.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// Territories whose default paper is US Letter (CLDR `paperSize type="US-Letter"`).
|
||||
const LETTER: &[&str] = &["BZ", "CA", "CL", "CO", "CR", "GT", "MX", "NI", "PA", "PH", "PR", "SV", "US", "VE"];
|
||||
|
||||
/// Territories that measure in inches (CLDR `measurementSystem type="US"`).
|
||||
const INCHES: &[&str] = &["LR", "MM", "US"];
|
||||
|
||||
/// How lengths, distances and weights are measured.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Measurement {
|
||||
/// Centimetres, kilometres and kilograms (CLDR `metric` and `UK`).
|
||||
Metric,
|
||||
/// Inches, miles and pounds (CLDR `US`).
|
||||
Us,
|
||||
}
|
||||
|
||||
/// The paper a new document starts on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Paper {
|
||||
A4,
|
||||
Letter,
|
||||
}
|
||||
|
||||
/// A clock the user chose, where the system says so apart from the locale.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum HourCycle {
|
||||
/// 1 to 12 with AM and PM.
|
||||
H12,
|
||||
/// 0 to 23.
|
||||
H23,
|
||||
}
|
||||
|
||||
/// The conventions numbers, times and measurements follow. Read it with [`Region::system`] or,
|
||||
/// for the user's saved choice, [`Region::from_setting`]; the fields are public so an app can
|
||||
/// keep a separate choice of, say, measurement.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Region {
|
||||
/// The locale numbers are written in, BCP 47 (`pl-PL`, `sr-Latn-RS`).
|
||||
pub numbers: String,
|
||||
/// The locale dates and times are written in, BCP 47.
|
||||
pub time: String,
|
||||
pub measurement: Measurement,
|
||||
pub paper: Paper,
|
||||
/// The decimal separator the system sets (Windows, macOS); `None` follows the locale.
|
||||
pub decimal: Option<char>,
|
||||
/// The grouping separator the system sets (Windows, macOS): `Some(None)` for none at all
|
||||
/// (`1234567`); `None` follows the locale.
|
||||
pub grouping: Option<Option<char>>,
|
||||
/// The clock the system sets (Windows, macOS); `None` follows the locale.
|
||||
pub hour_cycle: Option<HourCycle>,
|
||||
}
|
||||
|
||||
impl Default for Region {
|
||||
/// `en-US`: Letter, inches.
|
||||
fn default() -> Self {
|
||||
Region::from_parts(&Tag::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl Region {
|
||||
/// The region a BCP 47 or POSIX locale tag names (`pl-PL`, `de_AT.UTF-8@euro`, `zh-Hans-CN`,
|
||||
/// `en-US-u-ms-metric`, Apple's `en_US@rg=plzzzz`). The Unicode extensions `ms` (measurement),
|
||||
/// `hc` (clock), `rg` (region override) and `nu` (digits; Apple's `@numbers=`) are read, and
|
||||
/// `nu` stays in the number and time locales (`ar-EG-u-nu-latn`). `C` and `POSIX` are the C
|
||||
/// locale: English, A4, metric, a `.` decimal and no grouping. An empty or unreadable tag is
|
||||
/// `en-US`; a bare `en` is the United States, any other bare language has no territory.
|
||||
pub fn from_tag(tag: &str) -> Region {
|
||||
match Tag::parse(tag) {
|
||||
Some(tag) => Region::from_parts(&tag),
|
||||
None if is_c_locale(tag) => {
|
||||
Region { measurement: Measurement::Metric, paper: Paper::A4, decimal: Some('.'), grouping: Some(None), ..Region::default() }
|
||||
}
|
||||
None => Region::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The region for an app's saved region setting: `""` or `auto` (any case) is
|
||||
/// [`Region::system`], anything else a locale tag for [`Region::from_tag`].
|
||||
pub fn from_setting(setting: &str) -> Region {
|
||||
let setting = setting.trim();
|
||||
if setting.is_empty() || setting.eq_ignore_ascii_case("auto") { Region::system() } else { Region::from_tag(setting) }
|
||||
}
|
||||
|
||||
/// The system's region, read once, then cached:
|
||||
///
|
||||
/// - Windows: the regional format and its customised separators, measurement system, paper
|
||||
/// and short time format (Settings › Time & language › Language & region).
|
||||
/// - macOS and iOS: the current locale (its identifier carries the Region setting), its
|
||||
/// separators and metric setting, and its hour format.
|
||||
/// - Linux and the BSDs: `LC_ALL`, else each of `LC_NUMERIC`, `LC_TIME`, `LC_MEASUREMENT` and
|
||||
/// `LC_PAPER` on its own, else `LANG`.
|
||||
/// - The web and Android: the preferred language, the only locale they expose.
|
||||
pub fn system() -> Region {
|
||||
static SYSTEM: OnceLock<Region> = OnceLock::new();
|
||||
SYSTEM.get_or_init(read_system).clone()
|
||||
}
|
||||
|
||||
fn from_parts(tag: &Tag) -> Region {
|
||||
let territory = tag.territory.as_str();
|
||||
let measurement = tag.measurement.unwrap_or(if INCHES.contains(&territory) { Measurement::Us } else { Measurement::Metric });
|
||||
Region {
|
||||
numbers: tag.bcp47(),
|
||||
time: tag.bcp47(),
|
||||
measurement,
|
||||
paper: if LETTER.contains(&territory) { Paper::Letter } else { Paper::A4 },
|
||||
decimal: None,
|
||||
grouping: None,
|
||||
hour_cycle: tag.hour_cycle,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts of a locale tag the region uses.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct Tag {
|
||||
/// Lower case (`pl`).
|
||||
language: String,
|
||||
/// Title case (`Latn`); empty when the tag has none.
|
||||
script: String,
|
||||
/// Upper case (`PL`, or a UN M.49 number like `419`); empty when the tag has none.
|
||||
territory: String,
|
||||
measurement: Option<Measurement>,
|
||||
hour_cycle: Option<HourCycle>,
|
||||
/// The `nu` keyword (`latn`, `arab`); empty when the tag has none.
|
||||
digits: String,
|
||||
}
|
||||
|
||||
impl Default for Tag {
|
||||
fn default() -> Self {
|
||||
Tag { language: "en".into(), script: String::new(), territory: "US".into(), measurement: None, hour_cycle: None, digits: String::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Tag {
|
||||
fn parse(tag: &str) -> Option<Tag> {
|
||||
// Locale tags are short; anything long is junk and only its start is read.
|
||||
let tag: String = tag.chars().take(64).collect();
|
||||
let (tag, modifier) = tag.split_once('@').unwrap_or((&tag, ""));
|
||||
let tag = tag.split('.').next().unwrap_or_default().trim();
|
||||
if is_c_locale(tag) {
|
||||
return None;
|
||||
}
|
||||
let mut parts = tag.split(['-', '_']);
|
||||
let language = parts.next().unwrap_or_default();
|
||||
if !(2..=3).contains(&language.len()) || !language.chars().all(|c| c.is_ascii_alphabetic()) {
|
||||
return None;
|
||||
}
|
||||
let mut out = Tag {
|
||||
language: language.to_ascii_lowercase(),
|
||||
script: String::new(),
|
||||
territory: String::new(),
|
||||
measurement: None,
|
||||
hour_cycle: None,
|
||||
digits: String::new(),
|
||||
};
|
||||
let mut extension = None;
|
||||
for p in parts.by_ref() {
|
||||
// A singleton starts the extensions (`-u-…`, `-x-…`).
|
||||
if p.len() == 1 {
|
||||
extension = Some(p.to_ascii_lowercase());
|
||||
break;
|
||||
}
|
||||
if out.territory.is_empty() && out.script.is_empty() && p.len() == 4 && p.chars().all(|c| c.is_ascii_alphabetic()) {
|
||||
out.script = title_case(p);
|
||||
} else if out.territory.is_empty() && is_territory(p) {
|
||||
out.territory = p.to_ascii_uppercase();
|
||||
}
|
||||
}
|
||||
let mut keywords: Vec<(String, String)> = Vec::new();
|
||||
if extension.as_deref() == Some("u") {
|
||||
let mut key = String::new();
|
||||
for p in parts {
|
||||
if p.len() == 1 {
|
||||
break;
|
||||
}
|
||||
if p.len() == 2 {
|
||||
key = p.to_ascii_lowercase();
|
||||
} else if !key.is_empty() {
|
||||
keywords.push((std::mem::take(&mut key), p.to_ascii_lowercase()));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Apple's and ICU's `@rg=plzzzz;ms=metric` keywords, and glibc's `@latin` script modifier.
|
||||
for m in modifier.split(';') {
|
||||
match m.split_once('=') {
|
||||
Some((k, v)) => keywords.push((k.trim().to_ascii_lowercase(), v.trim().to_ascii_lowercase())),
|
||||
None if m.eq_ignore_ascii_case("latin") => out.script = "Latn".into(),
|
||||
None if m.eq_ignore_ascii_case("cyrillic") => out.script = "Cyrl".into(),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
for (key, value) in keywords {
|
||||
match (key.as_str(), value.as_str()) {
|
||||
("ms", "metric" | "uksystem") => out.measurement = Some(Measurement::Metric),
|
||||
("ms", "ussystem") => out.measurement = Some(Measurement::Us),
|
||||
("hc", "h11" | "h12") => out.hour_cycle = Some(HourCycle::H12),
|
||||
("hc", "h23" | "h24") => out.hour_cycle = Some(HourCycle::H23),
|
||||
("nu" | "numbers", v) if (3..=8).contains(&v.len()) && v.chars().all(|c| c.is_ascii_alphanumeric()) => out.digits = v.into(),
|
||||
("rg", v) if v.len() == 6 && v.ends_with("zzzz") && v.get(..2).is_some_and(is_territory) => {
|
||||
out.territory = v.get(..2).unwrap_or_default().to_ascii_uppercase();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if out.territory.is_empty() && out.language == "en" {
|
||||
out.territory = "US".into();
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn bcp47(&self) -> String {
|
||||
let tag = [self.language.as_str(), &self.script, &self.territory].into_iter().filter(|p| !p.is_empty()).collect::<Vec<_>>().join("-");
|
||||
if self.digits.is_empty() { tag } else { format!("{tag}-u-nu-{}", self.digits) }
|
||||
}
|
||||
}
|
||||
|
||||
fn is_territory(p: &str) -> bool {
|
||||
(p.len() == 2 && p.chars().all(|c| c.is_ascii_alphabetic())) || (p.len() == 3 && p.chars().all(|c| c.is_ascii_digit()))
|
||||
}
|
||||
|
||||
fn title_case(p: &str) -> String {
|
||||
let lower = p.to_ascii_lowercase();
|
||||
let mut chars = lower.chars();
|
||||
chars.next().map(|c| c.to_ascii_uppercase().to_string() + chars.as_str()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether a locale tag names the C locale (`C`, `C.UTF-8`, `POSIX`).
|
||||
fn is_c_locale(tag: &str) -> bool {
|
||||
let tag = tag.split(['@', '.']).next().unwrap_or_default().trim();
|
||||
tag.eq_ignore_ascii_case("c") || tag.eq_ignore_ascii_case("posix")
|
||||
}
|
||||
|
||||
/// The region from the POSIX locale variables `var` reads. An empty variable is unset; `C` in
|
||||
/// `LC_ALL` or an `LC_*` variable is the C locale's conventions. `LANG` set to `C` or unset gives
|
||||
/// way to the platform's preferred locale.
|
||||
#[cfg(any(test, all(unix, not(any(target_vendor = "apple", target_os = "android")))))]
|
||||
fn from_posix(var: impl Fn(&str) -> Option<String>, platform: impl FnOnce() -> Option<String>) -> Region {
|
||||
let var = |name: &str| var(name).filter(|v| !v.trim().is_empty());
|
||||
if let Some(all) = var("LC_ALL") {
|
||||
return Region::from_tag(&all);
|
||||
}
|
||||
let lang = var("LANG").filter(|v| !is_c_locale(v)).or_else(platform).unwrap_or_default();
|
||||
let tag = |name: &str| var(name).unwrap_or_else(|| lang.clone());
|
||||
let time = Region::from_tag(&tag("LC_TIME"));
|
||||
Region {
|
||||
time: time.time,
|
||||
hour_cycle: time.hour_cycle,
|
||||
measurement: Region::from_tag(&tag("LC_MEASUREMENT")).measurement,
|
||||
paper: Region::from_tag(&tag("LC_PAPER")).paper,
|
||||
..Region::from_tag(&tag("LC_NUMERIC"))
|
||||
}
|
||||
}
|
||||
|
||||
/// The region from the values under `HKEY_CURRENT_USER\Control Panel\International` that `value`
|
||||
/// reads, where Windows keeps the regional format and the user's changes to it. `LocaleName` is
|
||||
/// the format (`pl-PL`), else the platform's preferred locale.
|
||||
#[cfg(any(test, windows))]
|
||||
pub(crate) fn from_windows(value: impl Fn(&str) -> Option<String>, platform: impl FnOnce() -> Option<String>) -> Region {
|
||||
let mut region = Region::from_tag(&value("LocaleName").or_else(platform).unwrap_or_default());
|
||||
region.decimal = value("sDecimal").as_deref().and_then(single_char);
|
||||
region.grouping = value("sThousand").as_deref().and_then(grouping);
|
||||
match value("iMeasure").as_deref().map(str::trim) {
|
||||
Some("0") => region.measurement = Measurement::Metric,
|
||||
Some("1") => region.measurement = Measurement::Us,
|
||||
_ => {}
|
||||
}
|
||||
// DMPAPER_LETTER and DMPAPER_A4; other sizes keep the territory's.
|
||||
match value("iPaperSize").as_deref().map(str::trim) {
|
||||
Some("1") => region.paper = Paper::Letter,
|
||||
Some("9") => region.paper = Paper::A4,
|
||||
_ => {}
|
||||
}
|
||||
region.hour_cycle = value("sShortTime").as_deref().and_then(hour_cycle_of).or(region.hour_cycle);
|
||||
region
|
||||
}
|
||||
|
||||
/// The region from Apple's current locale: its identifier (`en_PL`, `en_GB@rg=uszzzz`), its
|
||||
/// metric setting and separators, and the hour format its `j` skeleton gives (`HH`, `h a`).
|
||||
#[cfg(any(test, target_vendor = "apple"))]
|
||||
fn from_apple(identifier: &str, metric: bool, decimal: &str, grouping: &str, hours: Option<&str>) -> Region {
|
||||
let mut region = Region::from_tag(identifier);
|
||||
region.measurement = if metric { Measurement::Metric } else { Measurement::Us };
|
||||
region.decimal = single_char(decimal);
|
||||
region.grouping = self::grouping(grouping);
|
||||
region.hour_cycle = hours.and_then(hour_cycle_of).or(region.hour_cycle);
|
||||
region
|
||||
}
|
||||
|
||||
/// A grouping separator the system sets: none at all when empty (Windows' `sThousand` the user
|
||||
/// cleared), else one character.
|
||||
#[cfg(any(test, windows, target_vendor = "apple"))]
|
||||
fn grouping(s: &str) -> Option<Option<char>> {
|
||||
if s.is_empty() { Some(None) } else { single_char(s).map(Some) }
|
||||
}
|
||||
|
||||
/// A separator that is one character; Windows allows up to three, which the region can't carry.
|
||||
#[cfg(any(test, windows, target_vendor = "apple"))]
|
||||
fn single_char(s: &str) -> Option<char> {
|
||||
let mut chars = s.chars();
|
||||
let c = chars.next()?;
|
||||
chars.next().is_none().then_some(c)
|
||||
}
|
||||
|
||||
/// The clock a time pattern (`HH:mm`, `h:mm tt`, `h 'Uhr'`) uses; quoted literals are skipped.
|
||||
#[cfg(any(test, windows, target_vendor = "apple"))]
|
||||
fn hour_cycle_of(pattern: &str) -> Option<HourCycle> {
|
||||
let mut quoted = false;
|
||||
for c in pattern.chars() {
|
||||
match c {
|
||||
'\'' => quoted = !quoted,
|
||||
'H' | 'k' if !quoted => return Some(HourCycle::H23),
|
||||
'h' | 'K' if !quoted => return Some(HourCycle::H12),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn read_system() -> Region {
|
||||
let key = windows_registry::CURRENT_USER.open(r"Control Panel\International").ok();
|
||||
from_windows(|name| key.as_ref()?.get_string(name).ok(), sys_locale::get_locale)
|
||||
}
|
||||
|
||||
#[cfg(target_vendor = "apple")]
|
||||
fn read_system() -> Region {
|
||||
use objc2_foundation::{NSDateFormatter, NSLocale, NSString};
|
||||
let locale = NSLocale::currentLocale();
|
||||
let hours = NSDateFormatter::dateFormatFromTemplate_options_locale(&NSString::from_str("j"), 0, Some(&locale)).map(|f| f.to_string());
|
||||
from_apple(
|
||||
&locale.localeIdentifier().to_string(),
|
||||
locale.usesMetricSystem(),
|
||||
&locale.decimalSeparator().to_string(),
|
||||
&locale.groupingSeparator().to_string(),
|
||||
hours.as_deref(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(any(target_vendor = "apple", target_os = "android"))))]
|
||||
fn read_system() -> Region {
|
||||
from_posix(|name| std::env::var(name).ok(), sys_locale::get_locale)
|
||||
}
|
||||
|
||||
#[cfg(not(any(windows, unix)))]
|
||||
fn read_system() -> Region {
|
||||
Region::from_tag(&sys_locale::get_locale().unwrap_or_default())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
fn read_system() -> Region {
|
||||
Region::from_tag(&sys_locale::get_locale().unwrap_or_default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn conventions(r: &Region) -> (Paper, Measurement) {
|
||||
(r.paper, r.measurement)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_locale_tags() {
|
||||
assert_eq!(Region::from_tag("pl-PL").numbers, "pl-PL");
|
||||
assert_eq!(Region::from_tag("de_AT.UTF-8@euro").numbers, "de-AT");
|
||||
assert_eq!(Region::from_tag("zh-hans-cn").numbers, "zh-Hans-CN");
|
||||
assert_eq!(Region::from_tag("sr_RS@latin").numbers, "sr-Latn-RS");
|
||||
assert_eq!(Region::from_tag("es-419").numbers, "es-419");
|
||||
assert_eq!(Region::from_tag("fr").numbers, "fr");
|
||||
assert_eq!(Region::from_tag("en").numbers, "en-US", "bare English is the US");
|
||||
for junk in ["", "1234", "x", "--", "ünïcode-ÄÄ", &"a".repeat(10_000)] {
|
||||
assert_eq!(Region::from_tag(junk), Region::default(), "{junk:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// glibc's C locale: A4 and metric (`C-paper.c`, `C-measurement.c`), `.` and no grouping.
|
||||
#[test]
|
||||
fn the_c_locale_is_a4_metric_and_ungrouped() {
|
||||
for c in ["C", "POSIX", "C.UTF-8", "c.utf8", " C "] {
|
||||
let r = Region::from_tag(c);
|
||||
assert_eq!(
|
||||
(r.numbers.as_str(), r.paper, r.measurement, r.decimal, r.grouping),
|
||||
("en-US", Paper::A4, Measurement::Metric, Some('.'), Some(None)),
|
||||
"{c:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chosen_digit_system_stays_in_the_locale() {
|
||||
assert_eq!(Region::from_tag("ar-EG-u-nu-latn").numbers, "ar-EG-u-nu-latn");
|
||||
let r = Region::from_tag("ar_EG@numbers=latn");
|
||||
assert_eq!((r.numbers.as_str(), r.time.as_str()), ("ar-EG-u-nu-latn", "ar-EG-u-nu-latn"));
|
||||
assert_eq!(Region::from_tag("en-US-u-nu-arab-ms-metric").numbers, "en-US-u-nu-arab");
|
||||
assert_eq!(Region::from_tag("ar-EG-u-nu-x").numbers, "ar-EG", "not a numbering system");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_extensions_and_apple_keywords() {
|
||||
let r = Region::from_tag("en-US-u-ms-metric-hc-h23");
|
||||
assert_eq!((r.numbers.as_str(), r.measurement, r.hour_cycle), ("en-US", Measurement::Metric, Some(HourCycle::H23)));
|
||||
assert_eq!(Region::from_tag("en-GB-u-hc-h12").hour_cycle, Some(HourCycle::H12));
|
||||
assert_eq!(Region::from_tag("de-DE-x-ms-ussystem").measurement, Measurement::Metric, "private use isn't read");
|
||||
let r = Region::from_tag("en_GB@rg=uszzzz");
|
||||
assert_eq!((r.numbers.as_str(), r.paper, r.measurement), ("en-US", Paper::Letter, Measurement::Us));
|
||||
assert_eq!(Region::from_tag("en_US@rg=plzzzz;ms=metric").numbers, "en-PL");
|
||||
}
|
||||
|
||||
/// Paper and measurement follow the territory; separators are left to the number locale.
|
||||
#[test]
|
||||
fn conventions_follow_the_territory() {
|
||||
assert_eq!(conventions(&Region::from_tag("pl-PL")), (Paper::A4, Measurement::Metric));
|
||||
assert_eq!(conventions(&Region::from_tag("en-US")), (Paper::Letter, Measurement::Us));
|
||||
assert_eq!(conventions(&Region::from_tag("fr-CA")), (Paper::Letter, Measurement::Metric));
|
||||
assert_eq!(conventions(&Region::from_tag("en-GB")), (Paper::A4, Measurement::Metric));
|
||||
let r = Region::from_tag("de-CH");
|
||||
assert_eq!((r.decimal, r.grouping), (None, None));
|
||||
assert_eq!(Region::from_tag("es-MX").paper, Paper::Letter);
|
||||
assert_eq!(Region::from_tag("ja-JP").paper, Paper::A4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_setting_overrides_the_system() {
|
||||
assert_eq!(Region::from_setting(" pl-PL "), Region::from_tag("pl-PL"));
|
||||
assert_eq!(Region::from_setting("AUTO"), Region::system());
|
||||
assert_eq!(Region::from_setting(""), Region::system());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn posix_variables_set_each_convention() {
|
||||
let env = |pairs: &'static [(&'static str, &'static str)]| move |n: &str| pairs.iter().find(|(k, _)| *k == n).map(|(_, v)| v.to_string());
|
||||
let none = || None;
|
||||
let r = from_posix(env(&[("LANG", "en_US.UTF-8"), ("LC_NUMERIC", "pl_PL.UTF-8"), ("LC_TIME", "en_GB.UTF-8"), ("LC_PAPER", "de_DE")]), none);
|
||||
assert_eq!((r.numbers.as_str(), r.time.as_str(), r.decimal), ("pl-PL", "en-GB", None));
|
||||
assert_eq!((r.paper, r.measurement), (Paper::A4, Measurement::Us), "paper from LC_PAPER, measurement from LANG");
|
||||
assert_eq!(from_posix(env(&[("LANG", "it_IT.UTF-8"), ("LC_ALL", "en_US"), ("LC_PAPER", "de_DE")]), none).paper, Paper::Letter);
|
||||
assert_eq!(from_posix(env(&[("LANG", "en_US"), ("LC_MEASUREMENT", "it_IT")]), none).measurement, Measurement::Metric);
|
||||
assert_eq!(from_posix(env(&[("LANG", "C.UTF-8"), ("LC_ALL", "")]), || Some("it-IT".into())).numbers, "it-IT");
|
||||
assert_eq!(from_posix(env(&[]), none), Region::default());
|
||||
// `C` in an LC_* variable is the C locale's conventions, not an unset variable.
|
||||
let r = from_posix(env(&[("LANG", "de_DE.UTF-8"), ("LC_NUMERIC", "C"), ("LC_TIME", "C.UTF-8")]), none);
|
||||
assert_eq!((r.numbers.as_str(), r.time.as_str(), r.paper), ("en-US", "en-US", Paper::A4));
|
||||
assert_eq!(from_posix(env(&[("LANG", "de_DE.UTF-8"), ("LC_ALL", "C")]), none), Region::from_tag("C"));
|
||||
let r = from_posix(env(&[("LANG", "en_US.UTF-8"), ("LC_PAPER", "C"), ("LC_MEASUREMENT", "C.UTF-8")]), none);
|
||||
assert_eq!((r.paper, r.measurement, r.decimal), (Paper::A4, Measurement::Metric, None));
|
||||
assert_eq!(from_posix(env(&[("LANG", "C"), ("LC_NUMERIC", "")]), || Some("it-IT".into())).numbers, "it-IT");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_regional_format_and_its_changes() {
|
||||
let reg = |pairs: &'static [(&'static str, &'static str)]| move |n: &str| pairs.iter().find(|(k, _)| *k == n).map(|(_, v)| v.to_string());
|
||||
let r = from_windows(
|
||||
reg(&[("LocaleName", "pl-PL"), ("sDecimal", ","), ("sThousand", "\u{a0}"), ("iMeasure", "0"), ("sShortTime", "HH:mm")]),
|
||||
|| None,
|
||||
);
|
||||
assert_eq!((r.numbers.as_str(), r.decimal, r.grouping, r.hour_cycle), ("pl-PL", Some(','), Some(Some('\u{a0}')), Some(HourCycle::H23)));
|
||||
// An English format in the US with the user's metric and A4 choices and a decimal comma.
|
||||
let r = from_windows(
|
||||
reg(&[("LocaleName", "en-US"), ("sDecimal", ","), ("iMeasure", "0"), ("iPaperSize", "9"), ("sShortTime", "h:mm tt")]),
|
||||
|| None,
|
||||
);
|
||||
assert_eq!(
|
||||
(r.decimal, r.grouping, r.measurement, r.paper, r.hour_cycle),
|
||||
(Some(','), None, Measurement::Metric, Paper::A4, Some(HourCycle::H12))
|
||||
);
|
||||
let r = from_windows(reg(&[("sDecimal", "dec"), ("sThousand", "")]), || Some("de-DE".into()));
|
||||
assert_eq!((r.numbers.as_str(), r.decimal), ("de-DE", None), "a separator longer than one character keeps the locale's");
|
||||
assert_eq!(r.grouping, Some(None), "an empty grouping separator is no grouping");
|
||||
assert_eq!(from_windows(reg(&[("sThousand", "abc")]), || None).grouping, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apple_locale_values() {
|
||||
let r = from_apple("en_PL", true, ",", "\u{a0}", Some("HH"));
|
||||
assert_eq!(
|
||||
(r.numbers.as_str(), r.paper, r.decimal, r.grouping, r.hour_cycle),
|
||||
("en-PL", Paper::A4, Some(','), Some(Some('\u{a0}')), Some(HourCycle::H23))
|
||||
);
|
||||
let r = from_apple("en_US", false, ".", ",", Some("h a"));
|
||||
assert_eq!((r.measurement, r.hour_cycle), (Measurement::Us, Some(HourCycle::H12)));
|
||||
assert_eq!(from_apple("de_DE", true, ",", ".", Some("H 'Uhr'")).hour_cycle, Some(HourCycle::H23));
|
||||
assert_eq!(hour_cycle_of("'h' mm"), None, "quoted letters are text");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
//! The scripts a language is written in, its direction, and which regional forms its Han
|
||||
//! characters take, for picking fonts and laying out the interface.
|
||||
|
||||
/// A writing system, by its ISO 15924 code.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
#[non_exhaustive]
|
||||
pub enum Script {
|
||||
Arab,
|
||||
Armn,
|
||||
Beng,
|
||||
Cyrl,
|
||||
Deva,
|
||||
Ethi,
|
||||
Geor,
|
||||
Grek,
|
||||
Gujr,
|
||||
Guru,
|
||||
Hang,
|
||||
Hani,
|
||||
Hebr,
|
||||
Hira,
|
||||
Kana,
|
||||
Khmr,
|
||||
Knda,
|
||||
Laoo,
|
||||
Latn,
|
||||
Mlym,
|
||||
Mong,
|
||||
Mymr,
|
||||
Orya,
|
||||
Sinh,
|
||||
Syrc,
|
||||
Taml,
|
||||
Telu,
|
||||
Thaa,
|
||||
Thai,
|
||||
Tibt,
|
||||
}
|
||||
|
||||
impl Script {
|
||||
/// The ISO 15924 code, `Latn`.
|
||||
pub fn code(self) -> &'static str {
|
||||
match self {
|
||||
Script::Arab => "Arab",
|
||||
Script::Armn => "Armn",
|
||||
Script::Beng => "Beng",
|
||||
Script::Cyrl => "Cyrl",
|
||||
Script::Deva => "Deva",
|
||||
Script::Ethi => "Ethi",
|
||||
Script::Geor => "Geor",
|
||||
Script::Grek => "Grek",
|
||||
Script::Gujr => "Gujr",
|
||||
Script::Guru => "Guru",
|
||||
Script::Hang => "Hang",
|
||||
Script::Hani => "Hani",
|
||||
Script::Hebr => "Hebr",
|
||||
Script::Hira => "Hira",
|
||||
Script::Kana => "Kana",
|
||||
Script::Khmr => "Khmr",
|
||||
Script::Knda => "Knda",
|
||||
Script::Laoo => "Laoo",
|
||||
Script::Latn => "Latn",
|
||||
Script::Mlym => "Mlym",
|
||||
Script::Mong => "Mong",
|
||||
Script::Mymr => "Mymr",
|
||||
Script::Orya => "Orya",
|
||||
Script::Sinh => "Sinh",
|
||||
Script::Syrc => "Syrc",
|
||||
Script::Taml => "Taml",
|
||||
Script::Telu => "Telu",
|
||||
Script::Thaa => "Thaa",
|
||||
Script::Thai => "Thai",
|
||||
Script::Tibt => "Tibt",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether text in this script runs right to left.
|
||||
pub fn rtl(self) -> bool {
|
||||
matches!(self, Script::Arab | Script::Hebr | Script::Syrc | Script::Thaa)
|
||||
}
|
||||
}
|
||||
|
||||
/// Which way a language's text, and an interface in it, runs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Direction {
|
||||
Ltr,
|
||||
Rtl,
|
||||
}
|
||||
|
||||
/// The regional glyph forms Han characters take, as in the Noto CJK face names (SC, TC, HK, JP,
|
||||
/// KR). The same code point is drawn differently in each, so a font stack picks its Han face by
|
||||
/// this, not by script.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum Han {
|
||||
/// Simplified Chinese, mainland China and Singapore (SC).
|
||||
Simplified,
|
||||
/// Traditional Chinese, Taiwan (TC).
|
||||
Traditional,
|
||||
/// Traditional Chinese, Hong Kong and Macau (HK).
|
||||
HongKong,
|
||||
/// Japanese kanji (JP).
|
||||
Japanese,
|
||||
/// Korean hanja (KR).
|
||||
Korean,
|
||||
}
|
||||
|
||||
/// The scripts a language tag's interface text is written in (`ja` → Hani, Hira, Kana; `sr` →
|
||||
/// Cyrl; `sr-latn` → Latn), the main one first. Any case and glibc form (`sr_RS.UTF-8@latin`). A
|
||||
/// script subtag wins, then a region that implies a script (`pa-PK` → Arab), then the language's
|
||||
/// usual script. Latin product names and units appear in every language, so Latn is listed only
|
||||
/// where it is the language's own script. A language not in the table is taken to be written in
|
||||
/// Latin.
|
||||
// ponytail: the languages a Craft app ships or could plausibly ship; add a row with the locale.
|
||||
pub fn scripts(tag: &str) -> &'static [Script] {
|
||||
use Script::*;
|
||||
let tag = Subtags::parse(tag);
|
||||
if let Some(s) = tag.script.as_deref().and_then(subtag_scripts) {
|
||||
return s;
|
||||
}
|
||||
if let Some(s) = tag.region.as_deref().and_then(|region| region_script(&tag.language, region)).and_then(subtag_scripts) {
|
||||
return s;
|
||||
}
|
||||
match tag.language.as_str() {
|
||||
"ja" => &[Hani, Hira, Kana],
|
||||
"ko" => &[Hang, Hani],
|
||||
"zh" | "yue" | "wuu" => &[Hani],
|
||||
"be" | "bg" | "ba" | "ce" | "cv" | "kk" | "ky" | "mk" | "mn" | "ru" | "sah" | "sr" | "tg" | "tt" | "uk" => &[Cyrl],
|
||||
"el" => &[Grek],
|
||||
"ar" | "ckb" | "fa" | "ks" | "ps" | "sd" | "ug" | "ur" => &[Arab],
|
||||
"he" | "yi" => &[Hebr],
|
||||
"syr" => &[Syrc],
|
||||
"dv" => &[Thaa],
|
||||
"ka" => &[Geor],
|
||||
"hy" => &[Armn],
|
||||
"hi" | "mr" | "ne" | "sa" | "kok" | "mai" | "bho" => &[Deva],
|
||||
"bn" | "as" | "mni" => &[Beng],
|
||||
"pa" => &[Guru],
|
||||
"gu" => &[Gujr],
|
||||
"or" => &[Orya],
|
||||
"ta" => &[Taml],
|
||||
"te" => &[Telu],
|
||||
"kn" => &[Knda],
|
||||
"ml" => &[Mlym],
|
||||
"si" => &[Sinh],
|
||||
"th" => &[Thai],
|
||||
"lo" => &[Laoo],
|
||||
"km" => &[Khmr],
|
||||
"my" => &[Mymr],
|
||||
"am" | "ti" => &[Ethi],
|
||||
"bo" | "dz" => &[Tibt],
|
||||
_ => &[Latn],
|
||||
}
|
||||
}
|
||||
|
||||
/// The direction of a language tag's text: right to left when its main script is.
|
||||
pub fn direction(tag: &str) -> Direction {
|
||||
match scripts(tag).first() {
|
||||
Some(s) if s.rtl() => Direction::Rtl,
|
||||
_ => Direction::Ltr,
|
||||
}
|
||||
}
|
||||
|
||||
/// The direction of a paragraph of text, from its first strong character (UAX #9 rules P2 and
|
||||
/// P3): the contents of isolates (LRI, RLI or FSI up to the matching PDI) are skipped, and the
|
||||
/// search stops at the first paragraph separator. `None` when the paragraph has no strong
|
||||
/// character; P3 then reads it as left to right, and an app may use the interface direction.
|
||||
pub fn base_direction(text: &str) -> Option<Direction> {
|
||||
match unicode_bidi::get_base_direction(text) {
|
||||
unicode_bidi::Direction::Ltr => Some(Direction::Ltr),
|
||||
unicode_bidi::Direction::Rtl => Some(Direction::Rtl),
|
||||
unicode_bidi::Direction::Mixed => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The forms a language tag's Han characters take: `zh-CN`, `zh-SG`, `zh-Hans` and plain `zh` →
|
||||
/// Simplified; `zh-TW`, `zh-Hant` and the other regions CLDR writes in Traditional characters
|
||||
/// (`zh-US`, `zh-AU`) → Traditional; `zh-HK`, `zh-MO`, `zh-Hant-HK` and `yue` → HongKong; `ja` →
|
||||
/// Japanese; `ko` → Korean. `None` for a language not written with Han, which leaves the choice
|
||||
/// to the font stack.
|
||||
pub fn han(tag: &str) -> Option<Han> {
|
||||
let tag = Subtags::parse(tag);
|
||||
let hong_kong = matches!(tag.region.as_deref(), Some("hk" | "mo"));
|
||||
// `Hani` names Han without saying which forms, so the region still decides.
|
||||
let script = tag.script.as_deref().filter(|s| *s != "hani");
|
||||
let script = script.or_else(|| region_script(&tag.language, tag.region.as_deref()?));
|
||||
match (tag.language.as_str(), script) {
|
||||
("ja", _) => Some(Han::Japanese),
|
||||
("ko", _) => Some(Han::Korean),
|
||||
("zh" | "yue" | "wuu", Some("hans")) => Some(Han::Simplified),
|
||||
("yue", Some("hant")) => Some(if tag.region.as_deref() == Some("tw") { Han::Traditional } else { Han::HongKong }),
|
||||
("zh" | "wuu", Some("hant")) => Some(if hong_kong { Han::HongKong } else { Han::Traditional }),
|
||||
// Cantonese is written in Traditional characters with Hong Kong forms unless it says otherwise.
|
||||
("yue", _) => Some(Han::HongKong),
|
||||
("zh" | "wuu", _) => Some(Han::Simplified),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The script subtag of a language in a region where CLDR's likely subtags give it a script
|
||||
/// other than its usual one: `pa-PK` → `arab` (`pa-Arab-PK`), `zh-TW` → `hant`.
|
||||
// ponytail: mn-CN → Mong is left out until vertical Mongolian layout is supported.
|
||||
pub(crate) fn region_script(language: &str, region: &str) -> Option<&'static str> {
|
||||
Some(match (language, region) {
|
||||
("az", "iq" | "ir") | ("ha", "cm" | "sd") | ("kk", "af" | "cn" | "ir" | "mn") | ("ku", "iq" | "ir" | "lb") => "arab",
|
||||
("ky", "cn") | ("ms", "cc") | ("pa", "pk") | ("tg", "pk") | ("uz", "af") => "arab",
|
||||
("az", "ru") | ("ku", "am" | "az" | "ge" | "tm") | ("ug", "kz" | "mn") | ("uz", "cn") => "cyrl",
|
||||
("ky", "tr") | ("sr", "me" | "ro" | "tr") => "latn",
|
||||
("sd", "in") => "deva",
|
||||
("zh", "au" | "bn" | "gb" | "gf" | "hk" | "id" | "mo" | "pa" | "pf" | "ph" | "sr" | "th" | "tw" | "us" | "vn") => "hant",
|
||||
("yue", "cn") => "hans",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The scripts a script subtag stands for, including the CLDR unions (`jpan`, `kore`). `None` for
|
||||
/// one not in [`Script`], so the language's own scripts apply.
|
||||
fn subtag_scripts(subtag: &str) -> Option<&'static [Script]> {
|
||||
use Script::*;
|
||||
Some(match subtag {
|
||||
"hans" | "hant" | "hani" => &[Hani],
|
||||
"jpan" => &[Hani, Hira, Kana],
|
||||
"kore" => &[Hang, Hani],
|
||||
"arab" => &[Arab],
|
||||
"armn" => &[Armn],
|
||||
"beng" => &[Beng],
|
||||
"cyrl" => &[Cyrl],
|
||||
"deva" => &[Deva],
|
||||
"ethi" => &[Ethi],
|
||||
"geor" => &[Geor],
|
||||
"grek" => &[Grek],
|
||||
"gujr" => &[Gujr],
|
||||
"guru" => &[Guru],
|
||||
"hang" => &[Hang],
|
||||
"hebr" => &[Hebr],
|
||||
"khmr" => &[Khmr],
|
||||
"knda" => &[Knda],
|
||||
"laoo" => &[Laoo],
|
||||
"latn" => &[Latn],
|
||||
"mlym" => &[Mlym],
|
||||
"mong" => &[Mong],
|
||||
"mymr" => &[Mymr],
|
||||
"orya" => &[Orya],
|
||||
"sinh" => &[Sinh],
|
||||
"syrc" => &[Syrc],
|
||||
"taml" => &[Taml],
|
||||
"telu" => &[Telu],
|
||||
"thaa" => &[Thaa],
|
||||
"thai" => &[Thai],
|
||||
"tibt" => &[Tibt],
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A language tag's language, script and region subtags, lowercase.
|
||||
struct Subtags {
|
||||
language: String,
|
||||
script: Option<String>,
|
||||
region: Option<String>,
|
||||
}
|
||||
|
||||
impl Subtags {
|
||||
/// `zh-Hant-HK`, `zh_TW.UTF-8` or `sr_RS@latin` (glibc's script modifier).
|
||||
fn parse(tag: &str) -> Subtags {
|
||||
let tag = tag.trim().to_ascii_lowercase();
|
||||
let base = tag.split(['.', '@']).next().unwrap_or("").replace('_', "-");
|
||||
let mut parts = base.split('-').filter(|p| !p.is_empty());
|
||||
let language = parts.next().unwrap_or("").to_owned();
|
||||
let mut script = match tag.split_once('@').map(|(_, m)| m) {
|
||||
Some("latin") => Some("latn".to_owned()),
|
||||
Some("cyrillic") => Some("cyrl".to_owned()),
|
||||
_ => None,
|
||||
};
|
||||
let mut region = None;
|
||||
for part in parts {
|
||||
if part.len() == 4 && part.bytes().all(|b| b.is_ascii_alphabetic()) {
|
||||
script.get_or_insert_with(|| part.to_owned());
|
||||
} else if super::is_region(part) {
|
||||
region = Some(part.to_owned());
|
||||
break;
|
||||
}
|
||||
}
|
||||
Subtags { language, script, region }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Script::*;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn base_direction_of_text() {
|
||||
assert_eq!(base_direction("Hello"), Some(Direction::Ltr));
|
||||
assert_eq!(base_direction("123 שלום"), Some(Direction::Rtl));
|
||||
assert_eq!(base_direction("(مرحبا) hi"), Some(Direction::Rtl));
|
||||
// The isolate's Hebrew is skipped; the Latin after it decides.
|
||||
assert_eq!(base_direction("\u{2067}שלום\u{2069} hello"), Some(Direction::Ltr));
|
||||
assert_eq!(base_direction("\u{2068}abc\u{2069} שלום"), Some(Direction::Rtl));
|
||||
// Only the first paragraph counts.
|
||||
assert_eq!(base_direction("123\nשלום"), None);
|
||||
assert_eq!(base_direction("1920 × 1080"), None);
|
||||
assert_eq!(base_direction(""), None);
|
||||
}
|
||||
|
||||
/// Every locale the craft-i18n catalogs or an app ship, as the apps spell them.
|
||||
#[test]
|
||||
fn shipped_locales() {
|
||||
for (tag, want, han_forms) in [
|
||||
("en", &[Latn][..], None),
|
||||
("ar", &[Arab], None),
|
||||
("bg", &[Cyrl], None),
|
||||
("cs", &[Latn], None),
|
||||
("da", &[Latn], None),
|
||||
("de", &[Latn], None),
|
||||
("el", &[Grek], None),
|
||||
("es", &[Latn], None),
|
||||
("es-419", &[Latn], None),
|
||||
("et", &[Latn], None),
|
||||
("fi", &[Latn], None),
|
||||
("fr", &[Latn], None),
|
||||
("hr", &[Latn], None),
|
||||
("hu", &[Latn], None),
|
||||
("id", &[Latn], None),
|
||||
("it", &[Latn], None),
|
||||
("ja", &[Hani, Hira, Kana], Some(Han::Japanese)),
|
||||
("ka", &[Geor], None),
|
||||
("kk", &[Cyrl], None),
|
||||
("ko", &[Hang, Hani], Some(Han::Korean)),
|
||||
("lt", &[Latn], None),
|
||||
("nl", &[Latn], None),
|
||||
("pl", &[Latn], None),
|
||||
("pt", &[Latn], None),
|
||||
("pt-br", &[Latn], None),
|
||||
("pt_BR", &[Latn], None),
|
||||
("ru", &[Cyrl], None),
|
||||
("sl", &[Latn], None),
|
||||
("sr", &[Cyrl], None),
|
||||
("sr-latn", &[Latn], None),
|
||||
("sv", &[Latn], None),
|
||||
("te", &[Telu], None),
|
||||
("tr", &[Latn], None),
|
||||
("uk", &[Cyrl], None),
|
||||
("vi", &[Latn], None),
|
||||
("zh", &[Hani], Some(Han::Simplified)),
|
||||
("zh-cn", &[Hani], Some(Han::Simplified)),
|
||||
("zh-CN", &[Hani], Some(Han::Simplified)),
|
||||
("zh-hans", &[Hani], Some(Han::Simplified)),
|
||||
("zh-Hans", &[Hani], Some(Han::Simplified)),
|
||||
("zh-hant", &[Hani], Some(Han::Traditional)),
|
||||
] {
|
||||
assert_eq!(scripts(tag), want, "{tag}");
|
||||
assert_eq!(han(tag), han_forms, "{tag}");
|
||||
let rtl = tag == "ar";
|
||||
assert_eq!(direction(tag), if rtl { Direction::Rtl } else { Direction::Ltr }, "{tag}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regional_han() {
|
||||
for (tag, want) in [
|
||||
("zh-TW", Han::Traditional),
|
||||
("zh_TW.UTF-8", Han::Traditional),
|
||||
("zh-Hant-TW", Han::Traditional),
|
||||
("zh-HK", Han::HongKong),
|
||||
("zh-MO", Han::HongKong),
|
||||
("zh-Hant-HK", Han::HongKong),
|
||||
("zh-hant-hk", Han::HongKong),
|
||||
("zh-Hans-HK", Han::Simplified),
|
||||
("zh-SG", Han::Simplified),
|
||||
("zh-US", Han::Traditional),
|
||||
("zh_AU.UTF-8", Han::Traditional),
|
||||
("zh-GB", Han::Traditional),
|
||||
("zh-Hans-US", Han::Simplified),
|
||||
("zh-MY", Han::Simplified),
|
||||
("yue-CN", Han::Simplified),
|
||||
("yue-HK", Han::HongKong),
|
||||
("zh-Hans-SG", Han::Simplified),
|
||||
("yue", Han::HongKong),
|
||||
("yue-Hant", Han::HongKong),
|
||||
("yue-Hant-TW", Han::Traditional),
|
||||
("zh-Hani-HK", Han::HongKong),
|
||||
("zh-Hani", Han::Simplified),
|
||||
("yue-Hans", Han::Simplified),
|
||||
("ja-JP", Han::Japanese),
|
||||
("ko_KR.UTF-8", Han::Korean),
|
||||
] {
|
||||
assert_eq!(han(tag), Some(want), "{tag}");
|
||||
}
|
||||
assert_eq!(han("en"), None);
|
||||
assert_eq!(han(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_subtag_wins() {
|
||||
for (tag, want) in [
|
||||
("sr-Latn-RS", &[Latn][..]),
|
||||
("sr_RS@latin", &[Latn]),
|
||||
("sr-Cyrl", &[Cyrl]),
|
||||
("sr_RS.UTF-8", &[Cyrl]),
|
||||
("az-Cyrl", &[Cyrl]),
|
||||
("pa-Arab", &[Arab]),
|
||||
("pa", &[Guru]),
|
||||
("mn-Mong", &[Mong]),
|
||||
("sd-Deva", &[Deva]),
|
||||
("fr-Zyyy", &[Latn]),
|
||||
] {
|
||||
assert_eq!(scripts(tag), want, "{tag}");
|
||||
}
|
||||
assert_eq!(direction("pa-Arab"), Direction::Rtl);
|
||||
assert_eq!(direction("sd-Deva"), Direction::Ltr);
|
||||
assert_eq!(direction("he_IL.UTF-8"), Direction::Rtl);
|
||||
}
|
||||
|
||||
/// CLDR likely subtags: a region can switch a language to another script.
|
||||
#[test]
|
||||
fn region_implies_script() {
|
||||
for (tag, want) in [
|
||||
("pa-PK", &[Arab][..]),
|
||||
("pa_PK.UTF-8", &[Arab]),
|
||||
("pa-IN", &[Guru]),
|
||||
("uz-AF", &[Arab]),
|
||||
("uz-UZ", &[Latn]),
|
||||
("uz-CN", &[Cyrl]),
|
||||
("az-IR", &[Arab]),
|
||||
("az-AZ", &[Latn]),
|
||||
("sd-IN", &[Deva]),
|
||||
("sd-PK", &[Arab]),
|
||||
("ks-IN", &[Arab]),
|
||||
("ms-CC", &[Arab]),
|
||||
("ms-BN", &[Latn]),
|
||||
("sr-ME", &[Latn]),
|
||||
("kk-CN", &[Arab]),
|
||||
("ug-KZ", &[Cyrl]),
|
||||
("pa-Guru-PK", &[Guru]),
|
||||
("sd-Arab-IN", &[Arab]),
|
||||
] {
|
||||
assert_eq!(scripts(tag), want, "{tag}");
|
||||
}
|
||||
assert_eq!(direction("pa-PK"), Direction::Rtl);
|
||||
assert_eq!(direction("uz-AF"), Direction::Rtl);
|
||||
assert_eq!(direction("az-IR"), Direction::Rtl);
|
||||
assert_eq!(direction("sd-IN"), Direction::Ltr);
|
||||
assert_eq!(direction("ug-KZ"), Direction::Ltr);
|
||||
}
|
||||
|
||||
/// The usual scripts tag matching relies on agree with the table.
|
||||
#[test]
|
||||
fn agrees_with_usual_script() {
|
||||
for language in ["be", "kk", "ky", "mn", "sr", "tg", "zh", "az", "bs", "ha", "ku", "ms", "uz", "ks", "sd", "ug", "pa"] {
|
||||
let usual = crate::usual_script(language).and_then(subtag_scripts);
|
||||
assert_eq!(usual, Some(scripts(language)), "{language}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
//! File sizes and other measures with a unit, in the interface language.
|
||||
//!
|
||||
//! Unit names are catalog rows in context `unit`, keyed by the English template with the
|
||||
//! number as `{n}` (`{n} MB`, `{n} px`, `{n}%`), so a translation can change the symbol and its
|
||||
//! spacing (`{n} Mo`, `{n} %`). They are looked up with [`I18n::get`], never the plain row: a
|
||||
//! plain `B` row means bold. A byte count in words is the `@plural` row `{n} byte|{n} bytes`.
|
||||
|
||||
use crate::{I18n, Lang, fmt, ltr};
|
||||
|
||||
/// The context unit rows are in.
|
||||
const CONTEXT: &str = "unit";
|
||||
|
||||
/// A file-size unit.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum SizeUnit {
|
||||
Byte,
|
||||
Kilo,
|
||||
Mega,
|
||||
Giga,
|
||||
Tera,
|
||||
}
|
||||
|
||||
impl SizeUnit {
|
||||
const ALL: [SizeUnit; 5] = [SizeUnit::Byte, SizeUnit::Kilo, SizeUnit::Mega, SizeUnit::Giga, SizeUnit::Tera];
|
||||
}
|
||||
|
||||
/// How [`I18n::file_size`] writes a byte count: the step between units, their names, and the
|
||||
/// digits after the decimal point. Start from [`FileSize::BINARY`], [`FileSize::IEC`] or
|
||||
/// [`FileSize::DECIMAL`] and adjust:
|
||||
///
|
||||
/// ```
|
||||
/// use craft_i18n::{FileSize, SizeUnit};
|
||||
/// // `12 MB`, `3.4 MB`, `640 KB`: decimal steps, whole kilobytes, no decimals from 10 MB.
|
||||
/// let style = FileSize::DECIMAL.smallest(SizeUnit::Kilo).largest(SizeUnit::Mega).unit_decimals(SizeUnit::Kilo, 0).whole_from(10);
|
||||
/// ```
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct FileSize {
|
||||
step: u64,
|
||||
iec: bool,
|
||||
/// Per unit, in [`SizeUnit::ALL`] order; bytes are always whole.
|
||||
decimals: [u8; 5],
|
||||
whole_from: u32,
|
||||
smallest: SizeUnit,
|
||||
largest: SizeUnit,
|
||||
byte_symbol: bool,
|
||||
}
|
||||
|
||||
impl FileSize {
|
||||
/// Steps of 1024 named KB, MB, GB and TB, as Windows Explorer shows sizes; one decimal, bytes
|
||||
/// in words.
|
||||
pub const BINARY: FileSize = FileSize {
|
||||
step: 1024,
|
||||
iec: false,
|
||||
decimals: [0, 1, 1, 1, 1],
|
||||
whole_from: 0,
|
||||
smallest: SizeUnit::Byte,
|
||||
largest: SizeUnit::Tera,
|
||||
byte_symbol: false,
|
||||
};
|
||||
/// Steps of 1024 named KiB, MiB, GiB and TiB.
|
||||
pub const IEC: FileSize = FileSize { iec: true, ..FileSize::BINARY };
|
||||
/// Steps of 1000 named KB, MB, GB and TB, as macOS shows sizes and as download and disk sizes
|
||||
/// are sold.
|
||||
pub const DECIMAL: FileSize = FileSize { step: 1000, ..FileSize::BINARY };
|
||||
|
||||
/// `n` digits after the decimal point in every unit above bytes.
|
||||
pub const fn decimals(mut self, n: u8) -> FileSize {
|
||||
self.decimals = [0, n, n, n, n];
|
||||
self
|
||||
}
|
||||
|
||||
/// `n` digits after the decimal point in `unit` (`0` for whole kilobytes, `2` for gigabytes).
|
||||
pub const fn unit_decimals(mut self, unit: SizeUnit, n: u8) -> FileSize {
|
||||
if !matches!(unit, SizeUnit::Byte) {
|
||||
self.decimals[unit as usize] = n;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// No decimals from `n` of a unit up: `whole_from(10)` writes `9.5 MB` and `12 MB`. `0`, the
|
||||
/// default, keeps them.
|
||||
pub const fn whole_from(mut self, n: u32) -> FileSize {
|
||||
self.whole_from = n;
|
||||
self
|
||||
}
|
||||
|
||||
/// The smallest unit shown. Sizes below it are written in it, rounded up, so a file that
|
||||
/// isn't empty never reads `0 KB`.
|
||||
pub const fn smallest(mut self, unit: SizeUnit) -> FileSize {
|
||||
self.smallest = unit;
|
||||
self
|
||||
}
|
||||
|
||||
/// The largest unit shown; larger sizes are counted in it (`2048 GB`).
|
||||
pub const fn largest(mut self, unit: SizeUnit) -> FileSize {
|
||||
self.largest = unit;
|
||||
self
|
||||
}
|
||||
|
||||
/// Bytes as the symbol `B` (`512 B`) instead of words (`512 bytes`).
|
||||
pub const fn byte_symbol(mut self) -> FileSize {
|
||||
self.byte_symbol = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// The unit `bytes` is written in, the number in it and its digits after the point.
|
||||
fn parts(&self, bytes: u64) -> (SizeUnit, f64, usize) {
|
||||
let (smallest, largest) = (self.smallest.min(self.largest), self.largest);
|
||||
let mut unit = smallest;
|
||||
for &u in SizeUnit::ALL.iter().filter(|u| (smallest..=largest).contains(u)) {
|
||||
if bytes as f64 >= self.scale(u) {
|
||||
unit = u;
|
||||
}
|
||||
}
|
||||
loop {
|
||||
let value = bytes as f64 / self.scale(unit);
|
||||
let round = |decimals: u8| {
|
||||
let factor = 10f64.powi(i32::from(decimals));
|
||||
(if unit == smallest && bytes > 0 && value < 1.0 { (value * factor).ceil() } else { (value * factor).round() }) / factor
|
||||
};
|
||||
let mut decimals = if unit == SizeUnit::Byte { 0 } else { self.decimals.get(unit as usize).copied().unwrap_or(0) };
|
||||
let mut rounded = round(decimals);
|
||||
// After rounding, so 9.96 MB, which rounds to 10.0, is written 10 MB.
|
||||
if self.whole_from > 0 && rounded >= f64::from(self.whole_from) {
|
||||
decimals = 0;
|
||||
rounded = round(0);
|
||||
}
|
||||
// 1023.96 KB rounds to 1024.0 KB: the next unit writes it as 1.0 MB.
|
||||
if rounded >= self.step as f64
|
||||
&& let Some(&next) = SizeUnit::ALL.get(unit as usize + 1)
|
||||
&& next <= largest
|
||||
{
|
||||
unit = next;
|
||||
continue;
|
||||
}
|
||||
return (unit, rounded, usize::from(decimals));
|
||||
}
|
||||
}
|
||||
|
||||
fn scale(&self, unit: SizeUnit) -> f64 {
|
||||
(self.step as f64).powi(unit as i32)
|
||||
}
|
||||
|
||||
/// The English template for `unit`, which is also its catalog key.
|
||||
fn template(&self, unit: SizeUnit) -> &'static str {
|
||||
match (unit, self.iec) {
|
||||
(SizeUnit::Byte, _) => "{n} B",
|
||||
(SizeUnit::Kilo, false) => "{n} KB",
|
||||
(SizeUnit::Mega, false) => "{n} MB",
|
||||
(SizeUnit::Giga, false) => "{n} GB",
|
||||
(SizeUnit::Tera, false) => "{n} TB",
|
||||
(SizeUnit::Kilo, true) => "{n} KiB",
|
||||
(SizeUnit::Mega, true) => "{n} MiB",
|
||||
(SizeUnit::Giga, true) => "{n} GiB",
|
||||
(SizeUnit::Tera, true) => "{n} TiB",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl I18n {
|
||||
/// `bytes` as a file size in `lang`, written the way `style` says (`1.5 MB`, `512 bytes`), the
|
||||
/// number as [`I18n::format`] writes it (`1,5 Mo`).
|
||||
pub fn file_size(&self, lang: Lang, bytes: u64, style: FileSize) -> String {
|
||||
let (unit, n, decimals) = style.parts(bytes);
|
||||
if unit == SizeUnit::Byte && !style.byte_symbol {
|
||||
return self.trn(lang, bytes, "{n} byte", "{n} bytes");
|
||||
}
|
||||
self.unit_text(lang, style.template(unit), &self.format().number(n, decimals))
|
||||
}
|
||||
|
||||
/// `value` with `decimals` digits after the decimal separator in the unit template `unit`, an
|
||||
/// English catalog key with the number as `{n}` (`{n} px`, `{n} dB`), the number as
|
||||
/// [`I18n::format`] writes it. Percentages are [`crate::Format::percent`].
|
||||
pub fn measure(&self, lang: Lang, value: f64, decimals: usize, unit: &str) -> String {
|
||||
self.unit_text(lang, unit, &self.format().number(value, decimals))
|
||||
}
|
||||
|
||||
fn unit_text(&self, lang: Lang, template: &str, n: &str) -> String {
|
||||
fmt(self.get(lang, CONTEXT, template).unwrap_or(template), &[("n", <r(n))])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Embedded, Format};
|
||||
|
||||
static E: &Embedded = &[(
|
||||
"fr",
|
||||
"unit\t{n} KB\t{n} Ko\nunit\t{n} MB\t{n} Mo\nunit\t{n} B\t{n} o\nunit\t{n}%\t{n} %\n\tB\tG\n@plural\t{n} byte|{n} bytes\t{n} octet|{n} octets\n",
|
||||
"",
|
||||
)];
|
||||
|
||||
fn en(bytes: u64, style: FileSize) -> String {
|
||||
let (i18n, _) = I18n::new(&[], &[]);
|
||||
i18n.set_format(Format::from_tag("en-US"));
|
||||
i18n.file_size(Lang::EN, bytes, style)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_decimal_and_iec_steps() {
|
||||
assert_eq!(en(512, FileSize::BINARY), "512 bytes");
|
||||
assert_eq!(en(1023, FileSize::BINARY), "1,023 bytes");
|
||||
assert_eq!(en(1, FileSize::BINARY), "1 byte");
|
||||
assert_eq!(en(1536, FileSize::BINARY), "1.5 KB");
|
||||
assert_eq!(en(1536, FileSize::IEC), "1.5 KiB");
|
||||
assert_eq!(en(1500, FileSize::DECIMAL), "1.5 KB");
|
||||
assert_eq!(en(3 << 30, FileSize::BINARY), "3.0 GB");
|
||||
assert_eq!(en(5 << 40, FileSize::IEC.decimals(0)), "5 TiB");
|
||||
assert_eq!(en(512, FileSize::BINARY.byte_symbol()), "512 B");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn precision_and_unit_range() {
|
||||
// Rounding up to the next unit's step moves to that unit.
|
||||
assert_eq!(en(1_048_575, FileSize::BINARY), "1.0 MB");
|
||||
assert_eq!(en(999_999, FileSize::DECIMAL.decimals(0)), "1 MB");
|
||||
assert_eq!(en(1_610_612_736, FileSize::BINARY.unit_decimals(SizeUnit::Giga, 2)), "1.50 GB");
|
||||
// Lightcraft's denoise sizes: whole kilobytes, at least 1, no decimals from 10 MB.
|
||||
let style = FileSize::DECIMAL.smallest(SizeUnit::Kilo).largest(SizeUnit::Mega).unit_decimals(SizeUnit::Kilo, 0).whole_from(10);
|
||||
assert_eq!(en(1, style), "1 KB");
|
||||
assert_eq!(en(0, style), "0 KB");
|
||||
assert_eq!(en(640_400, style), "640 KB");
|
||||
assert_eq!(en(3_400_000, style), "3.4 MB");
|
||||
assert_eq!(en(12_600_000, style), "13 MB");
|
||||
assert_eq!(en(9_960_000, style), "10 MB", "whole once rounded to 10");
|
||||
assert_eq!(en(9_940_000, style), "9.9 MB");
|
||||
assert_eq!(en(5_000_000_000, style), "5,000 MB");
|
||||
// Only sizes below the smallest unit round up.
|
||||
assert_eq!(en(1025, FileSize::BINARY.smallest(SizeUnit::Kilo).unit_decimals(SizeUnit::Kilo, 0)), "1 KB");
|
||||
assert_eq!(en(100, FileSize::BINARY.smallest(SizeUnit::Kilo).unit_decimals(SizeUnit::Kilo, 0)), "1 KB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_are_left_to_right_isolates_in_rtl_units() {
|
||||
let (i18n, problems) = I18n::new(&[("ar", "unit\t{n} KB\t{n} ك.ب\n", "")], &["ar"]);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
i18n.set_format(Format::from_tag("en-US"));
|
||||
let ar = i18n.from_code("ar").unwrap();
|
||||
assert_eq!(i18n.file_size(ar, 1536, FileSize::BINARY), "\u{2066}1.5\u{2069} ك.ب");
|
||||
assert_eq!(en(1536, FileSize::BINARY), "1.5 KB", "no marks in left-to-right text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unit_names_are_catalog_rows() {
|
||||
let (i18n, problems) = I18n::new(E, &["fr"]);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let fr = i18n.from_code("fr").unwrap();
|
||||
i18n.set_format(Format::from_tag("fr-FR"));
|
||||
assert_eq!(i18n.file_size(fr, 1536, FileSize::BINARY), "1,5 Ko");
|
||||
assert_eq!(i18n.file_size(fr, 512, FileSize::BINARY), "512 octets");
|
||||
assert_eq!(i18n.file_size(fr, 512, FileSize::BINARY.byte_symbol()), "512 o", "not the plain row B (bold)");
|
||||
assert_eq!(i18n.file_size(fr, 3 << 30, FileSize::BINARY), "3,0 GB", "a missing row is English");
|
||||
assert_eq!(i18n.measure(fr, 50.0, 0, "{n}%"), "50 %");
|
||||
assert_eq!(i18n.measure(Lang::EN, 12.34, 1, "{n} px"), "12,3 px", "numbers follow the region, not the language");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locale_digits() {
|
||||
let (i18n, _) = I18n::new(&[], &[]);
|
||||
i18n.set_format(Format::from_tag("ar-EG"));
|
||||
assert_eq!(i18n.file_size(Lang::EN, 1536, FileSize::BINARY), "١٫٥ KB");
|
||||
i18n.set_format(Format::from_tag("hi"));
|
||||
assert_eq!(i18n.file_size(Lang::EN, 1_234_567, FileSize::DECIMAL.largest(SizeUnit::Byte).byte_symbol()), "12,34,567 B");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
[package]
|
||||
name = "craft-keymap"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Keyboard bindings for the Craft suite: chords, keymaps, conflicts, overrides and shortcut-set import"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
egui = { workspace = true, optional = true }
|
||||
craft-ui = { workspace = true, optional = true }
|
||||
craft-i18n = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# `serde` for setting `RawInput` fields only the suite's egui fork has; `default_fonts` for the
|
||||
# dialog's tests.
|
||||
egui = { workspace = true, features = ["serde", "default_fonts"] }
|
||||
craft-settings = { workspace = true }
|
||||
tempfile = "3"
|
||||
sha2 = "0.10"
|
||||
egui_kittest = "0.37"
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
|
||||
[features]
|
||||
egui = ["dep:egui"]
|
||||
# The Keyboard Shortcuts dialog.
|
||||
ui = ["egui", "dep:craft-ui", "dep:craft-i18n"]
|
||||
# Screenshots of the dialog for review (tests/ui_snapshot.rs; needs a GPU or software adapter).
|
||||
snapshot = ["ui", "egui_kittest/wgpu"]
|
||||
@@ -0,0 +1,489 @@
|
||||
# Craft Keymap
|
||||
|
||||
`craft-keymap` holds the data and logic for keyboard bindings in the Craft apps: chords and their
|
||||
text forms, bindings from chords to commands, scopes, conflicts, user overrides, named sets, an
|
||||
import pipeline for other applications' shortcut sets, and an editor model. Each application
|
||||
supplies its command catalog, its file-format readers and its UI.
|
||||
|
||||
## Boundaries
|
||||
|
||||
- Data and logic, plus a shared Keyboard Shortcuts dialog behind the `ui` feature. The apps keep
|
||||
the command catalog (ids, labels, menu paths, defaults), the readers for other applications'
|
||||
files, file dialogs and running the commands.
|
||||
- Never crashes: no panics, no `unsafe`. Loading settings never fails; what cannot be used is
|
||||
kept or reported (`Keymap::problems`, the import report).
|
||||
- Hostile input is capped: commands, bindings per command, text lengths, import entries, keys,
|
||||
path segments and fuzzy suggestions (the `MAX_*` constants). What is cut is counted.
|
||||
- Reserved chords are opt-in. A keymap reserves no chord unless the app passes a list to
|
||||
`Keymap::with_reserved`, e.g. `reserved::system(platform)` for the operating system's window
|
||||
switching and closing chords. A reserved chord cannot be assigned or bound.
|
||||
- Dependencies: `serde` and `serde_json`; `egui` with the `egui` feature; `craft-ui` and
|
||||
`craft-i18n` with the `ui` feature.
|
||||
|
||||
## A catalog and dispatch
|
||||
|
||||
A command with parameters has the key `window.panel {"panel":"layers"}` in settings and reports.
|
||||
Tools of one group share a key and cycle. A binding can name a scope other than the command's
|
||||
home scope.
|
||||
|
||||
```rust
|
||||
use craft_keymap::{Active, Bindable, Binding, Chord, CommandRef, Keymap, Kind, Lookup, Platform, Scope, Scopes};
|
||||
use serde_json::json;
|
||||
|
||||
let key = |text: &str| Binding::parse(text).unwrap();
|
||||
let layers = CommandRef::with_params("window.panel", json!({"panel": "layers"}));
|
||||
let select = Kind::Tool { group: Some("select".into()) };
|
||||
let catalog = vec![
|
||||
Bindable::new("file.save", "Save", Scope::app()).with_path(vec!["File".into(), "Save".into()]).with_default(key("Cmd+S")),
|
||||
Bindable::new(layers.clone(), "Layers", Scope::app()).with_path(vec!["Window".into(), "Layers".into()]).with_default(key("F7")),
|
||||
Bindable::new("tool.marquee", "Marquee Tool", Scope::app()).with_kind(select.clone()).with_default(key("M")),
|
||||
Bindable::new("tool.ellipse", "Elliptical Marquee Tool", Scope::app()).with_kind(select).with_default(key("M")),
|
||||
// Home scope: the Timeline panel, where it wins over the app's L.
|
||||
Bindable::new("timeline.loop", "Loop", Scope::new("Timeline").unwrap()).with_default(key("L")),
|
||||
Bindable::new("layer.lock", "Lock Layer", Scope::app()).with_default(key("L")),
|
||||
// An app command whose binding works only in the Text context.
|
||||
Bindable::new("type.bold", "Bold", Scope::app()).with_default(key("Text: Cmd+B")),
|
||||
];
|
||||
let keymap = Keymap::new(catalog, Scopes::new().with_panel("Timeline").with_context("Text"), Platform::Mac);
|
||||
|
||||
// Dispatch: the chord pressed, whether it is a double press, and what has the keyboard.
|
||||
let press = |text: &str, active: &Active| keymap.lookup(&Chord::parse(text).unwrap(), false, active);
|
||||
assert_eq!(press("F7", &Active::NONE), Lookup::Run(layers));
|
||||
assert_eq!(press("L", &Active::panel("Timeline")), Lookup::Run("timeline.loop".into()));
|
||||
assert_eq!(press("L", &Active::NONE), Lookup::Run("layer.lock".into()));
|
||||
assert_eq!(press("M", &Active::NONE), Lookup::Cycle(vec!["tool.marquee".into(), "tool.ellipse".into()]));
|
||||
let editing = Active { contexts: &["Text"], typing: true, ..Active::NONE };
|
||||
assert_eq!(press("Cmd+B", &editing), Lookup::Run("type.bold".into()));
|
||||
assert_eq!(press("M", &editing), Lookup::None, "plain keys go to the text field");
|
||||
```
|
||||
|
||||
While a text field has the keyboard (`Active::typing`), the keymap's `TypingRule` decides which
|
||||
app and panel bindings wait: plain keys (the default), everything without the command modifier,
|
||||
or everything. Under every rule, the platform's text-editing chords (`text_editing_chords`) go
|
||||
to the field too: undo and redo, select all, and moving and deleting by word, line and text
|
||||
(Cmd+Z, Alt+Left and Cmd+Backspace on macOS; Ctrl+Z, Ctrl+Y, Ctrl+Left and Ctrl+Home
|
||||
elsewhere). Other command chords, such as Cmd+S, still fire. Bindings in an active context
|
||||
always fire, so `Text: Cmd+B` works while typing, and a `Text: Cmd+Z` binding takes undo from
|
||||
the field.
|
||||
|
||||
With the `egui` feature, `egui::Dispatcher` does this for a frame's key events (see Features).
|
||||
|
||||
## Chords
|
||||
|
||||
A [`Chord`](src/chord.rs) is a key plus the modifiers `cmd`, `ctrl`, `alt` and `shift`. `cmd` is
|
||||
the command modifier: ⌘ on macOS, Ctrl on Windows and Linux. `ctrl` is the Mac Control key; off
|
||||
macOS it folds into `cmd` (`Chord::effective`).
|
||||
|
||||
- Canonical text, as stored and sent: `Cmd+Ctrl+Alt+Shift+K`, `Cmd++` for Plus, `A A` for a
|
||||
double press.
|
||||
- `Chord::parse` also reads common aliases (`⇧⌘Z`, `opt+left`, `Ctrl+Cmd+M`).
|
||||
- `Chord::display(Platform)` gives `⇧⌘Z` on macOS and `Ctrl+Shift+Z` elsewhere.
|
||||
- `chord::foreign::read_foreign` reads key text written by other applications (Windows or Mac
|
||||
modifier names, numeric keypad keys).
|
||||
|
||||
## Keyboard layouts
|
||||
|
||||
[`layout`](src/layout.rs) decides which chord a key press means, the same way for matching
|
||||
(`Layout::candidates`), the shortcut recorder (`Layout::resolve`) and labels
|
||||
(`Chord::display_for`):
|
||||
|
||||
1. Letters A–Z: the layout's Latin letter for the key. On a layout that is not Latin (Russian,
|
||||
Arabic, Hebrew, Greek, Thai), the suite's egui reports the Latin layout's character for each
|
||||
key: Ctrl+С on Dvorak + Russian is Dvorak's Ctrl+J, and Ctrl+Й, `'` on Dvorak, runs no letter
|
||||
binding. Without that report, the letter the toolkit reports for shortcuts, else the key's
|
||||
position. On a Latin layout (Dvorak, AZERTY), the letter typed. Arabic Ctrl+Shift+D is
|
||||
Ctrl+Shift+D, not the `]` it types.
|
||||
2. Digits: the digit typed, else the key's position (AZERTY's `&é"` row). A digit-row key that
|
||||
types punctuation also matches its digit when the punctuation has no binding.
|
||||
3. Punctuation: the character typed, without Shift when the layout needs Shift for it: German
|
||||
`/` is ⇧7, so ⇧⌘7 runs ⌘/.
|
||||
4. Whether a layout is Latin is decided for the layout, not per key.
|
||||
5. With Shift held on a Latin layout, a press that egui reports as the letter at its own
|
||||
position, because the character typed has no key (Dvorak's ⇧, types `<`), runs nothing when
|
||||
that position has been seen typing something other than its letter: once a `,` has been
|
||||
typed, Ctrl+Shift+, never runs Ctrl+Shift+W. A change in the reported Latin status clears
|
||||
what the positions typed; an app that learns of a layout switch itself calls
|
||||
`Layout::forget_letters`.
|
||||
6. Labels show letters and digits by name, and a punctuation key as the character the layout
|
||||
types at its position when that character has no key of its own (`Ctrl+Ü` for Ctrl+[ on
|
||||
German).
|
||||
|
||||
A `KeyInput` holds what the toolkit reports for one press: modifiers, the key typed, the
|
||||
physical key, and, when the platform reports them, the layout's Latin letter (Windows
|
||||
virtual-key code, macOS ⌘ table, Linux Latin layout group) and whether Shift was needed. A
|
||||
`Layout` holds whether the layout is Latin, as the platform reports it or as plain typing shows
|
||||
it (`Layout::observe`), and the characters it types at punctuation positions.
|
||||
|
||||
## Storing overrides
|
||||
|
||||
`Overrides` is a field of the app's settings type. It is stored as a map of one text per command
|
||||
(`{ "file.save": "Cmd+Alt+S", "edit.copy": "" }`, `""` for no shortcut) while no command has more
|
||||
than one binding, so apps that stored that map before keep reading it in older builds. Once a
|
||||
command has several bindings it is stored as an array of `{ command, keys }` tables
|
||||
(`[{ command = "file.save", keys = ["Cmd+Alt+S", "F12"] }]`). Both forms load, and in the map form
|
||||
a list of texts loads too.
|
||||
|
||||
In a craft-settings type, put `#[serde(with = "craft_keymap::keymap::overrides_list")]` on the
|
||||
field, which always writes the array: craft-settings merges tables key by key with what the file
|
||||
holds but replaces an array whole, so only the array lets a reset command (an entry removed) stay
|
||||
removed after saving. Hand-written `[[shortcuts]]` blocks load as the array.
|
||||
|
||||
Texts the keymap cannot use (a key name from a newer version, an unknown scope, a reserved chord)
|
||||
stay in the entry when the command is edited, unless the edit leaves it without bindings.
|
||||
`Keymap::problems` lists them.
|
||||
|
||||
```rust
|
||||
use craft_keymap::{Binding, Keymap, Overrides, Platform, Policy, Scopes};
|
||||
use craft_settings::{Location, Settings, SettingsStore};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Default, Clone, PartialEq)]
|
||||
#[serde(default)]
|
||||
struct Prefs {
|
||||
#[serde(with = "craft_keymap::keymap::overrides_list")]
|
||||
shortcuts: Overrides,
|
||||
}
|
||||
|
||||
impl Settings for Prefs {
|
||||
const APP_ID: &'static str = "acmecraft";
|
||||
const SCHEMA_VERSION: u32 = 1;
|
||||
}
|
||||
|
||||
// `catalog` is the app's Vec<Bindable>.
|
||||
let (mut store, _report) = SettingsStore::<Prefs>::open(Location::Auto);
|
||||
let mut keymap = Keymap::new(catalog, Scopes::new(), Platform::current()).with_overrides(store.get().shortcuts.clone());
|
||||
// Entries for unknown commands and texts that do not parse are kept and listed here.
|
||||
let _problems = keymap.problems();
|
||||
|
||||
// After each change in the shortcut editor:
|
||||
keymap.set_bindings(&"file.save".into(), vec![Binding::parse("Cmd+Alt+S").unwrap()], Policy::Steal).ok();
|
||||
store.update(|p| p.shortcuts = keymap.overrides().clone());
|
||||
```
|
||||
|
||||
## Editing
|
||||
|
||||
- `set_bindings(&command, bindings, policy)` replaces a command's bindings. An editor with one
|
||||
shortcut per command calls it with the one binding (`vec![binding]`); `assign` adds a binding
|
||||
to those the command has.
|
||||
- `remove` takes one binding away, `clear` leaves the command without shortcuts, `reset` gives it
|
||||
its defaults back and `reset_all` does so for every command.
|
||||
- `Policy` says what happens to other commands holding the chord: `Steal` takes it from them,
|
||||
`Keep` lets both keep it and reports the clash, `Refuse` changes nothing and returns
|
||||
`AssignError::Taken`.
|
||||
- `conflicts()` lists every pair of commands on one chord; `conflicts_with(&command)` lists the
|
||||
commands that share one command's chords, with that command as `a`.
|
||||
|
||||
## Shortcut sets
|
||||
|
||||
`Profiles` holds the user's named sets of overrides and which one is active. The app's built-in
|
||||
sets (`&[(&str, Overrides)]`, the first one the default) are passed to each call and never change.
|
||||
An app with sets stores only `Profiles`, in place of the `Overrides` field above: the keymap's
|
||||
overrides are the active set's, and the dialog's OK stores them there. The sets, and each set's
|
||||
overrides, are stored as arrays, so a deleted set or entry leaves a craft-settings file.
|
||||
|
||||
```rust
|
||||
use craft_keymap::{Keymap, Platform, Profiles, Scopes};
|
||||
use craft_settings::{Location, SettingsStore};
|
||||
|
||||
#[derive(Serialize, Deserialize, Default, Clone, PartialEq)]
|
||||
#[serde(default)]
|
||||
struct Prefs {
|
||||
shortcut_sets: Profiles,
|
||||
}
|
||||
|
||||
// `builtins` is the app's &[(&str, Overrides)], the first set the default.
|
||||
let (mut store, _report) = SettingsStore::<Prefs>::open(Location::Auto);
|
||||
let mut sets = store.get().shortcut_sets.clone();
|
||||
sets.reconcile(&builtins);
|
||||
let keymap = Keymap::new(catalog, Scopes::new(), Platform::current()).with_overrides(sets.active_overrides(&builtins).clone());
|
||||
|
||||
// The dialog edits `sets` and `keymap`. On Outcome::Ok (or Changed, to save live):
|
||||
store.update(|p| p.shortcut_sets = sets.clone());
|
||||
```
|
||||
|
||||
- `names`, `get`, `active_name`, `active_overrides` (hand them to `Keymap::set_overrides`);
|
||||
`sets` (the user's sets) and `active` (the stored name, which `active_name` resolves to a set).
|
||||
- `select` switches sets; `duplicate(from, to)` copies a built-in or user set; `save_as`,
|
||||
`rename` and `delete` work on user sets only.
|
||||
- `store(overrides, builtins, copy_name)` saves the editor's result to the active set. Editing a
|
||||
built-in set makes a user copy named after `copy_name`, which becomes active.
|
||||
- New names are made unique (`Custom 2`, `Custom 3`) and compare without case. A user set named
|
||||
like a built-in added later is renamed by `reconcile`.
|
||||
- `export(name)` writes one set as JSON
|
||||
(`{"format":"craft-keymap","version":1,"name":…,"overrides":…}`); `import(text)` reads it into
|
||||
a new set. A file from a newer version is refused (`ProfileError::NewerVersion`).
|
||||
- Loading never fails. `problems()` lists what loading dropped: sets with a bad or repeated name,
|
||||
overrides that are neither a list nor a map, sets past `MAX_SETS`, and a `version` newer than
|
||||
this crate writes. The app shows them before the next save writes the sets without them.
|
||||
Stored `Profiles` carry `version = 1`; a file without it reads as version 1.
|
||||
- `import_plan(&plan, &keymap, name)` applies an import plan (see Importing a shortcut set) to a
|
||||
copy of the keymap and keeps the result as a new set, so another application's set becomes one
|
||||
the user can switch to and away from.
|
||||
|
||||
```rust
|
||||
use craft_keymap::{Overrides, Profiles};
|
||||
|
||||
let mut classic = Overrides::new();
|
||||
classic.insert("edit.copy", vec!["Cmd+Shift+C".into()]);
|
||||
let builtins = [("Craft", Overrides::new()), ("Classic", classic)];
|
||||
let mut sets = Profiles::default();
|
||||
assert_eq!(sets.active_name(&builtins), "Craft");
|
||||
|
||||
sets.duplicate("Classic", "Mine", &builtins).unwrap();
|
||||
let text = sets.export("Mine", &builtins).unwrap();
|
||||
assert_eq!(sets.import(&text, &builtins), Ok("Mine 2".into()));
|
||||
assert_eq!(sets.active_overrides(&builtins), sets.get("Mine", &builtins).unwrap());
|
||||
```
|
||||
|
||||
## Importing a shortcut set
|
||||
|
||||
The app's reader turns a file (an InDesign Show Set, an Illustrator `.kys`) into an
|
||||
[`import::ForeignSet`](src/import.rs): entries with a menu, a path and keys read by
|
||||
`ForeignKey::read`. The reader builds it with `ForeignSet::new(entries)`, `with_name` and
|
||||
`with_truncated`; the struct is `#[non_exhaustive]`, so struct literals outside the crate do not
|
||||
compile. `import::plan` matches each entry to one command and changes nothing;
|
||||
`ImportPlan::apply` applies the plan and returns an `ImportReport` (serde, camelCase). Report
|
||||
rows carry the entry's `item` (its path) and `line`.
|
||||
|
||||
```rust
|
||||
use craft_keymap::{Bindable, Binding, ContextRule, Flavor, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, Keymap, Platform};
|
||||
use craft_keymap::{Scope, Scopes, plan};
|
||||
|
||||
let save = Bindable::new("file.save", "Save", Scope::app())
|
||||
.with_path(vec!["File".into(), "Save".into()])
|
||||
.with_default(Binding::parse("Cmd+S").unwrap());
|
||||
let mut keymap = Keymap::new(vec![save], Scopes::new(), Platform::Windows);
|
||||
|
||||
let read = |text: &str| ForeignKey::read(Some("Default"), text, Flavor::Windows);
|
||||
let set = ForeignSet::new(vec![
|
||||
ForeignEntry::new(Some("File"), ["Save"]).with_key(read("Ctrl+Alt+S")).at_line(12),
|
||||
ForeignEntry::new(Some("File"), ["Frobnicate"]).with_key(read("Ctrl+F")).at_line(13),
|
||||
])
|
||||
.with_name("My Set");
|
||||
let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], ..ImportOptions::default() };
|
||||
let planned = plan(&set, &keymap, &options);
|
||||
// A review UI can show planned.commands and planned.report here.
|
||||
let report = planned.apply(&mut keymap);
|
||||
assert_eq!(report.changed[0].to, ["Cmd+Alt+S"]);
|
||||
assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File > Frobnicate", Some(13)));
|
||||
```
|
||||
|
||||
- Matching, most specific first, each step needing exactly one command: the user's remembered
|
||||
answers, the full menu path, the joined submenu segments as a label or alias in that menu, the
|
||||
label in that menu, the joined segments as a label or alias anywhere, the label anywhere. An
|
||||
entry with no menu and several segments matches only by its full path, unless the reader marks
|
||||
it `in_panel_menu()`. Tool entries match only tools.
|
||||
- Names are compared after `import::normalize_label`: case, `…`, `...`, `&`, colons and extra
|
||||
spaces aside, so the alias `Preferences: General…` matches `Edit > Preferences > General...`.
|
||||
Aliases (`Bindable::with_alias`) count wherever labels do, and import paths
|
||||
(`Bindable::with_import_path`, such as `["Tools", label]` for a tool) wherever menu paths do;
|
||||
the dialog makes no areas or groups from import paths.
|
||||
- Panel menus: sources list panel-menu items with the panel's name in front (InDesign's Panel
|
||||
Menus area writes `Character: All Caps`; Illustrator and Photoshop sets have similar areas).
|
||||
The reader splits the name into segments and marks the entry `ForeignEntry::in_panel_menu()`.
|
||||
Such an entry also matches a catalog path that ends with its segments (with the command's
|
||||
label or the path's last segment last), and its last segment alone as a label. The last
|
||||
segment alone counts only when the first segment, the panel, is a segment of some catalog
|
||||
path, so `History: New Document` matches nothing in an app without a History panel. An entry
|
||||
without keys that matched only these ways leaves the command's shortcuts alone and is listed
|
||||
in `matched_without_change` (reason `PanelMenu`).
|
||||
- Show/Hide: a source often lists one toggle as two items, `Show Rulers` and `Hide Rulers`. Names
|
||||
are matched as written first. When no step finds a command, the steps run again on commands
|
||||
marked `Bindable::toggle()`, with a leading `Show `, `Hide ` or `Show/Hide ` dropped from the
|
||||
entry's label and from the command's label, aliases and path labels. A command not marked as a
|
||||
toggle never matches through a dropped prefix, so `Hide Conveyor` does not match `Conveyor`.
|
||||
- `ImportOptions.contexts` says what each source context becomes (home scope, another scope, the
|
||||
home scope only without a home entry, or skipped).
|
||||
- The set wins: a chord it gives to a command is taken from commands outside it (except twins
|
||||
sharing it as a default), a later entry takes a chord from an earlier one (as when the entries
|
||||
are applied in file order; the earlier key is listed in `skipped`), and an entry without keys
|
||||
can clear its command. It clears it only when no entry matched to the same command has keys,
|
||||
whatever the order of the entries.
|
||||
- Keys read approximately (a numeric keypad key bound as the main key) are listed in
|
||||
`approximated`.
|
||||
- With `ImportOptions.suggest`, unmatched entries get fuzzy candidates (`import::namematch`);
|
||||
they are reported, never applied. Only the first 200 unmatched entries with keys get them, and
|
||||
only the first 200 characters of a name are compared. Keys in `ContextRule::Skip` contexts do
|
||||
not count: an unmatched entry with only such keys counts in `unmatched_without_shortcut`.
|
||||
- `truncated` counts what was cut at the caps (`MAX_IMPORT_ENTRIES` and the others), plus the
|
||||
entries the app's reader dropped at its own limits, which it passes as `ForeignSet.truncated`.
|
||||
|
||||
## Editor
|
||||
|
||||
`editor` is the model behind a shortcut dialog; the app draws it.
|
||||
|
||||
- `EditSession::begin(&keymap)` when the dialog opens. Each change is one undo step:
|
||||
`assign`, `replace` (record over one key of a command), `remove`, `clear`, `reset`, `reset_all`,
|
||||
or any keymap edit through `session.edit(&mut keymap, |km| …)`. `undo`, `redo`, `cancel` (back
|
||||
to the state at open) and `is_modified`.
|
||||
- Conflicts: `editor::holders(&keymap, &command, &binding)` lists the commands that hold the key
|
||||
while the user records; `Keymap::conflicts_with(&command)` marks the rows whose keys are
|
||||
shared after a `Keep`. Assigning with `Policy::Refuse` returns `AssignError::Taken` and changes
|
||||
nothing; the user's answer is a second call with `Policy::Steal` or `Policy::Keep`.
|
||||
- `Recorder::press(chord, time)` gives `Single`, `Double` (the same chord again within
|
||||
`DOUBLE_PRESS`, 0.6 s) or `Cancel` (Escape).
|
||||
- `editor::search(&keymap, query, platform)` filters the catalog by label, alias, menu path,
|
||||
command id and key text, canonical or as shown on `platform`.
|
||||
|
||||
```rust
|
||||
use craft_keymap::editor::holders;
|
||||
use craft_keymap::{AssignError, Binding, Chord, EditSession, Policy, Recorded, Recorder};
|
||||
|
||||
// `keymap` is the app's Keymap, `now` the input time in seconds.
|
||||
let mut session = EditSession::begin(&keymap);
|
||||
let mut recorder = Recorder::new();
|
||||
let save = "file.save".into();
|
||||
// The user presses Cmd+C in the shortcut field of Save.
|
||||
if let Recorded::Single(trigger) = recorder.press(Chord::parse("Cmd+C").unwrap(), now) {
|
||||
let binding = Binding::new(trigger);
|
||||
let _shown = holders(&keymap, &save, &binding);
|
||||
if let Err(AssignError::Taken(_)) = session.assign(&mut keymap, &save, binding.clone(), Policy::Refuse) {
|
||||
// The user chose to take the key from Copy.
|
||||
session.assign(&mut keymap, &save, binding, Policy::Steal).ok();
|
||||
}
|
||||
}
|
||||
// OK: store `keymap.overrides()` (`Profiles::store` for sets). Cancel:
|
||||
session.cancel(&mut keymap);
|
||||
```
|
||||
|
||||
## Shortcuts dialog
|
||||
|
||||
With the `ui` feature, `ui::ShortcutsDialog` draws the Keyboard Shortcuts dialog over a `Keymap`
|
||||
and, optionally, `Profiles`: a table of the catalog grouped by menu, recording, conflicts, undo,
|
||||
named sets, import review and a summary. It edits the keymap in place, so menus show new keys at
|
||||
once, and Cancel puts everything back as it was when the dialog opened.
|
||||
|
||||
Adopt it in three steps:
|
||||
|
||||
1. Build the `Keymap` from the catalog and keep the built-in sets (`Builtins`), as above.
|
||||
2. While the dialog is open, keep a `DialogState` and call `show` (a window) or `ui` (the body,
|
||||
for the app's own modal or preferences page) every frame.
|
||||
3. Act on the `Outcome` it returns, and drop the state when `is_open()` turns false.
|
||||
|
||||
Apps that import other applications' sets read each file into a `ForeignSet` built with
|
||||
`ForeignSet::new` ([Importing a shortcut set](#importing-a-shortcut-set)).
|
||||
|
||||
```rust,ignore
|
||||
use craft_keymap::ui::{DialogState, I18nText, Options, Outcome, ShortcutsDialog};
|
||||
|
||||
// "Keyboard Shortcuts…" opens it; "Edit Shortcut…" also calls `state.select(&command)`.
|
||||
self.shortcuts = Some(DialogState::new());
|
||||
|
||||
// Every frame, before the app's own dispatch:
|
||||
if let Some(state) = &mut self.shortcuts {
|
||||
let text = I18nText { i18n: &self.i18n, lang: self.lang };
|
||||
let dialog = ShortcutsDialog::new(&mut self.keymap, &text).options(&self.shortcut_options);
|
||||
let dialog = dialog.sets(&mut self.settings.shortcut_sets, &BUILTINS);
|
||||
match dialog.show(ctx, state) {
|
||||
Some(Outcome::Ok) => self.save_settings(),
|
||||
// After each edit, and after a Cancel that undid edits.
|
||||
Some(Outcome::Changed) => self.rebuild_menus(),
|
||||
Some(Outcome::Import { formats }) => self.pick_import_file(formats),
|
||||
Some(Outcome::Export { name, json }) => self.save_file(&name, json),
|
||||
Some(Outcome::Summary { name, html, .. }) => self.show_summary(&name, html),
|
||||
Some(Outcome::Remembered(answers)) => self.settings.import_answers.extend(answers),
|
||||
_ => {}
|
||||
}
|
||||
if !state.is_open() {
|
||||
self.shortcuts = None;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Outcomes:
|
||||
|
||||
| Outcome | The app |
|
||||
|---|---|
|
||||
| `Ok` | Saves `Profiles` (with sets) or `keymap.overrides()`. |
|
||||
| `Cancel` | Nothing to save: the keymap and the sets are as they were at open. When Cancel undid edits, `Changed` follows. |
|
||||
| `Changed` | Updates its menus, or saves at once if it saves live. It comes after each edit and after a Cancel that undid edits. When a frame also has another outcome, `Changed` comes on the next frame; `is_open()` stays true until it has. |
|
||||
| `Import { formats }` | Opens a file of one of the formats, then calls `import_json` (craft-keymap JSON, `ui::JSON_FORMAT`) or reads it into a `ForeignSet` and calls `review_import`. |
|
||||
| `Export { name, json }`, `ExportAs { format, name, keymap }` | Writes the set where the user chooses (a download on the web). |
|
||||
| `Summary { name, html, text }` | Shows, saves or prints the summary. |
|
||||
| `Remembered(answers)` | Keeps the user's import answers for the next import (`ImportOptions::remembered`). |
|
||||
|
||||
The crate never opens a file dialog or touches the file system. When the app's own step fails
|
||||
while the dialog is open (a file it cannot read), `state.show_error(text)` shows the translated
|
||||
message under the table until the user dismisses it or the next action replaces it.
|
||||
|
||||
Key dispatch while the dialog is open:
|
||||
|
||||
- Skip `Dispatcher::dispatch` while `DialogState::is_open()` is true. The dialog takes the
|
||||
frame's key, text and clipboard events itself while it records, so the chord the user presses
|
||||
reaches the recorder and runs nothing.
|
||||
- A native macOS menu handles its key equivalents before egui sees them, so Cmd+Q, Cmd+, and
|
||||
the other menu chords never reach the recorder. While `is_recording()` is true, pause them:
|
||||
feed them to egui as key presses, or rebuild the menu without accelerators.
|
||||
|
||||
Words come from `ui::Text`. Apps on craft-i18n pass `I18nText`; others implement `ui` and
|
||||
`plural` over their own lookup, and `rtl` and `visual` (the app's bidi reordering) for
|
||||
right-to-left languages, which mirror the layout. Chord text is never reordered. `ui::STRINGS`
|
||||
and `ui::PLURALS` list every string the dialog looks up, for the translation catalog.
|
||||
`Options` sets the conflict mode, double-press recording, area tabs, the on-screen keyboard,
|
||||
read-only rows for keys outside the catalog, the app's import and export formats, an `accept`
|
||||
rule for which keys a command may get, and a `visible` rule for which catalog entries the table
|
||||
lists (hidden entries keep their keys and still count in conflicts).
|
||||
|
||||
## Features
|
||||
|
||||
- `egui`: conversions to and from egui keys and modifiers; `KeyInput::from_egui`;
|
||||
`egui::matches`, which accepts the shifted key egui reports for a Shift binding (`Shift+;`
|
||||
matches `:`); and `egui::Dispatcher`, which runs a frame's key presses against the keymap,
|
||||
reading them by the layout it learns from typing or is given (`with_layout`, `layout()`):
|
||||
|
||||
```rust,ignore
|
||||
let hits = ctx.input_mut(|i| dispatcher.dispatch(i, &keymap, &active));
|
||||
for hit in hits {
|
||||
app.run(&hit.command);
|
||||
}
|
||||
```
|
||||
|
||||
A press that runs a command is removed from egui's events, with the text it typed, so widgets
|
||||
do not see it too. Each `Hit` carries the `trigger` that matched and `exact`, which is false
|
||||
when the press matched through a stand-in (`:` for `Shift+;`, `+` for `=`).
|
||||
`dispatch_filtered` takes a predicate that can decline a hit, for example a chord the native
|
||||
menu has already handled: the press and its text then stay in egui's events, in their place.
|
||||
While a text field has the keyboard, plain clipboard key presses and presses that typed text in the
|
||||
same frame stay with it. That covers AltGr, which a browser on Windows reports as Ctrl+Alt
|
||||
followed by the text; a Ctrl+Alt press that types nothing is a command chord.
|
||||
`Dispatcher::new().with_repeat(true)` also runs commands on key repeats (held arrows).
|
||||
|
||||
On the desktop, egui-winit sends egui's Copy, Cut and Paste events in place of the key press
|
||||
for any chord of Cmd with C, X or V (Ctrl off macOS); the web build sends the press and then
|
||||
the event. For the plain chords Cmd+C, Cmd+X and Cmd+V (and Cmd+Insert, Shift+Delete,
|
||||
Shift+Insert), the events stay with the app by default, so a binding on those chords runs only
|
||||
with `with_clipboard_events(true)`. Then the events count as their chords outside text fields,
|
||||
and a Paste event's text moves to `Hit::pasted`. On the web, the press runs the command and
|
||||
takes the event, with its text, along. An app whose paste command asks egui for a paste gets a
|
||||
Paste event back, which runs that command again; such an app keeps the default. A clipboard
|
||||
event with more modifiers held (Cmd+Shift+V, Cmd+Alt+C) always counts as its chord, also while
|
||||
typing, and stays when that chord has no binding. egui-winit sends no Paste event when the
|
||||
clipboard is empty or holds an image, so a binding on a Cmd+V chord cannot run then on the
|
||||
desktop.
|
||||
|
||||
- `ui`: the Shortcuts dialog (see above). Implies `egui`.
|
||||
- `snapshot` (development): `tests/ui_snapshot.rs` writes PNGs of the dialog to
|
||||
`CRAFT_KEYMAP_SNAPSHOT_DIR` for review, using the same font input as the dialog tests.
|
||||
|
||||
### Fonts for UI tests
|
||||
|
||||
Apps own their runtime font setup, including coverage of the Mac key symbols displayed by the
|
||||
Shortcuts dialog. The library does not install or replace an app's fonts.
|
||||
|
||||
UI tests need an absolute `CRAFT_FONTS_DIR` pointing to a checkout of
|
||||
[`craft-fonts`](https://github.com/storytold/craft-fonts) at
|
||||
`b076417b5880bd4154bd22f00695b1d28c6bea83`. For example, after preparing that checkout:
|
||||
|
||||
```sh
|
||||
CRAFT_FONTS_DIR=/absolute/path/to/craft-fonts cargo test -p craft-keymap --features ui --locked
|
||||
```
|
||||
|
||||
Dialog tests and requested snapshots share a helper that verifies the SHA256 of
|
||||
`fonts/noto-sans-symbols/NotoSansSymbols.ttf` and
|
||||
`fonts/noto-sans-symbols-2/NotoSansSymbols2-Regular.ttf`, then appends these and egui's bundled
|
||||
Hack as fallbacks before the first layout pass. It checks printable ASCII, the full key-symbol
|
||||
and dialog-icon repertoire, and the accented pseudolocale in both default font families.
|
||||
Missing inputs, changed bytes and missing glyphs fail the tests; no system font probing or tofu
|
||||
fallback is used. Linux, macOS and Windows keymap CI supply this exact checkout. The WASM
|
||||
compile-only job needs no runtime font files. Optional screenshots still require their output
|
||||
directory and a graphics adapter; they are review images, not golden comparisons.
|
||||
@@ -0,0 +1,679 @@
|
||||
//! Keys, modifiers, chords and their text forms.
|
||||
//!
|
||||
//! Canonical text is `Cmd+Ctrl+Alt+Shift+Key`, written by [`Chord`]'s `Display` and read back by
|
||||
//! [`Chord::parse`]. A double press is the chord twice, separated by a space: `A A`.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
use crate::layout::Layout;
|
||||
|
||||
pub mod foreign;
|
||||
|
||||
/// The longest chord or trigger text [`Chord::parse`] and [`Trigger::parse`] accept, in bytes.
|
||||
pub const MAX_CHORD_TEXT: usize = 64;
|
||||
|
||||
/// The platform a keymap is used on. It decides display text and whether `ctrl` folds into `cmd`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
#[non_exhaustive]
|
||||
pub enum Platform {
|
||||
Mac,
|
||||
Windows,
|
||||
Linux,
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
/// The platform this build runs on. Web builds count as Linux; with the `egui` feature,
|
||||
/// `egui::platform` gives the browser's operating system.
|
||||
pub const fn current() -> Platform {
|
||||
if cfg!(target_os = "macos") {
|
||||
Platform::Mac
|
||||
} else if cfg!(target_os = "windows") {
|
||||
Platform::Windows
|
||||
} else {
|
||||
Platform::Linux
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn is_mac(self) -> bool {
|
||||
matches!(self, Platform::Mac)
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! keys {
|
||||
($($variant:ident => $name:literal),* $(,)?) => {
|
||||
/// A key on the keyboard, independent of any UI toolkit.
|
||||
///
|
||||
/// Digits are the main row; numeric keypad keys map to the same keys.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
#[non_exhaustive]
|
||||
pub enum Key {
|
||||
$($variant),*
|
||||
}
|
||||
|
||||
impl Key {
|
||||
/// Every key, in declaration order.
|
||||
pub const ALL: &'static [Key] = &[$(Key::$variant),*];
|
||||
|
||||
/// The canonical name: `K`, `5`, `F5`, `PageUp`, `;`.
|
||||
pub const fn name(self) -> &'static str {
|
||||
match self {
|
||||
$(Key::$variant => $name),*
|
||||
}
|
||||
}
|
||||
|
||||
// The Rust variant name, which is also egui's `Key` variant name except for arrows.
|
||||
const fn variant_name(self) -> &'static str {
|
||||
match self {
|
||||
$(Key::$variant => stringify!($variant)),*
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
keys! {
|
||||
A => "A", B => "B", C => "C", D => "D", E => "E", F => "F", G => "G", H => "H", I => "I",
|
||||
J => "J", K => "K", L => "L", M => "M", N => "N", O => "O", P => "P", Q => "Q", R => "R",
|
||||
S => "S", T => "T", U => "U", V => "V", W => "W", X => "X", Y => "Y", Z => "Z",
|
||||
Num0 => "0", Num1 => "1", Num2 => "2", Num3 => "3", Num4 => "4",
|
||||
Num5 => "5", Num6 => "6", Num7 => "7", Num8 => "8", Num9 => "9",
|
||||
F1 => "F1", F2 => "F2", F3 => "F3", F4 => "F4", F5 => "F5", F6 => "F6", F7 => "F7",
|
||||
F8 => "F8", F9 => "F9", F10 => "F10", F11 => "F11", F12 => "F12", F13 => "F13",
|
||||
F14 => "F14", F15 => "F15", F16 => "F16", F17 => "F17", F18 => "F18", F19 => "F19",
|
||||
F20 => "F20", F21 => "F21", F22 => "F22", F23 => "F23", F24 => "F24", F25 => "F25",
|
||||
F26 => "F26", F27 => "F27", F28 => "F28", F29 => "F29", F30 => "F30", F31 => "F31",
|
||||
F32 => "F32", F33 => "F33", F34 => "F34", F35 => "F35",
|
||||
Escape => "Escape", Tab => "Tab", Backspace => "Backspace", Enter => "Enter",
|
||||
Space => "Space", Insert => "Insert", Delete => "Delete", Home => "Home", End => "End",
|
||||
PageUp => "PageUp", PageDown => "PageDown",
|
||||
Up => "Up", Down => "Down", Left => "Left", Right => "Right",
|
||||
Minus => "-", Equals => "=", Plus => "+", OpenBracket => "[", CloseBracket => "]",
|
||||
Backslash => "\\", Semicolon => ";", Quote => "'", Backtick => "`",
|
||||
Comma => ",", Period => ".", Slash => "/",
|
||||
Colon => ":", Pipe => "|", Questionmark => "?", Exclamationmark => "!",
|
||||
OpenCurlyBracket => "{", CloseCurlyBracket => "}",
|
||||
}
|
||||
|
||||
/// Key aliases beyond the canonical and egui variant names. Matched without regard to ASCII case.
|
||||
const KEY_ALIASES: &[(&str, Key)] = &[
|
||||
("esc", Key::Escape),
|
||||
("⎋", Key::Escape),
|
||||
("return", Key::Enter),
|
||||
("⏎", Key::Enter),
|
||||
("↩", Key::Enter),
|
||||
("del", Key::Delete),
|
||||
("⌦", Key::Delete),
|
||||
("⌫", Key::Backspace),
|
||||
("⇥", Key::Tab),
|
||||
("pgup", Key::PageUp),
|
||||
("pgdn", Key::PageDown),
|
||||
("page up", Key::PageUp),
|
||||
("page down", Key::PageDown),
|
||||
("arrowup", Key::Up),
|
||||
("arrowdown", Key::Down),
|
||||
("arrowleft", Key::Left),
|
||||
("arrowright", Key::Right),
|
||||
("↑", Key::Up),
|
||||
("↓", Key::Down),
|
||||
("←", Key::Left),
|
||||
("→", Key::Right),
|
||||
("spacebar", Key::Space),
|
||||
("ins", Key::Insert),
|
||||
("equal", Key::Equals),
|
||||
("grave", Key::Backtick),
|
||||
("backquote", Key::Backtick),
|
||||
("apostrophe", Key::Quote),
|
||||
];
|
||||
|
||||
impl Key {
|
||||
/// Reads a key name: canonical (`K`, `PageUp`, `;`), egui variant names (`ArrowUp`, `Num5`,
|
||||
/// `Semicolon`) and the aliases `esc`, `return`, `del`, `pgup`, `pgdn`, `spacebar`, `ins`,
|
||||
/// and the Mac key glyphs. Case does not matter.
|
||||
pub fn parse(name: &str) -> Option<Key> {
|
||||
Key::ALL
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|k| k.name().eq_ignore_ascii_case(name) || k.variant_name().eq_ignore_ascii_case(name))
|
||||
.or_else(|| KEY_ALIASES.iter().find(|(alias, _)| alias.eq_ignore_ascii_case(name)).map(|&(_, k)| k))
|
||||
}
|
||||
|
||||
/// `A` to `Z`.
|
||||
pub const fn is_letter(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Key::A
|
||||
| Key::B
|
||||
| Key::C
|
||||
| Key::D
|
||||
| Key::E
|
||||
| Key::F
|
||||
| Key::G
|
||||
| Key::H
|
||||
| Key::I
|
||||
| Key::J
|
||||
| Key::K
|
||||
| Key::L
|
||||
| Key::M
|
||||
| Key::N
|
||||
| Key::O
|
||||
| Key::P
|
||||
| Key::Q
|
||||
| Key::R
|
||||
| Key::S
|
||||
| Key::T
|
||||
| Key::U
|
||||
| Key::V
|
||||
| Key::W
|
||||
| Key::X
|
||||
| Key::Y
|
||||
| Key::Z
|
||||
)
|
||||
}
|
||||
|
||||
/// `0` to `9`.
|
||||
pub const fn is_digit(self) -> bool {
|
||||
matches!(self, Key::Num0 | Key::Num1 | Key::Num2 | Key::Num3 | Key::Num4 | Key::Num5 | Key::Num6 | Key::Num7 | Key::Num8 | Key::Num9)
|
||||
}
|
||||
|
||||
/// Punctuation and symbol keys: `-`, `=`, `+`, brackets, `\`, `;`, `'`, `` ` ``, `,`, `.`,
|
||||
/// `/` and the shifted symbols `:`, `|`, `?`, `!`, `{`, `}`.
|
||||
pub const fn is_symbol(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Key::Minus
|
||||
| Key::Equals
|
||||
| Key::Plus
|
||||
| Key::OpenBracket
|
||||
| Key::CloseBracket
|
||||
| Key::Backslash
|
||||
| Key::Semicolon
|
||||
| Key::Quote
|
||||
| Key::Backtick
|
||||
| Key::Comma
|
||||
| Key::Period
|
||||
| Key::Slash
|
||||
| Key::Colon
|
||||
| Key::Pipe
|
||||
| Key::Questionmark
|
||||
| Key::Exclamationmark
|
||||
| Key::OpenCurlyBracket
|
||||
| Key::CloseCurlyBracket
|
||||
)
|
||||
}
|
||||
|
||||
/// The letter, digit or symbol key for a typed character, ignoring case.
|
||||
pub fn from_char(c: char) -> Option<Key> {
|
||||
let mut buf = [0; 4];
|
||||
let text: &str = c.encode_utf8(&mut buf);
|
||||
Key::ALL.iter().copied().find(|k| (k.is_letter() || k.is_digit() || k.is_symbol()) && k.name().eq_ignore_ascii_case(text))
|
||||
}
|
||||
|
||||
/// `F1` to `F35`.
|
||||
pub const fn is_function_key(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Key::F1
|
||||
| Key::F2
|
||||
| Key::F3
|
||||
| Key::F4
|
||||
| Key::F5
|
||||
| Key::F6
|
||||
| Key::F7
|
||||
| Key::F8
|
||||
| Key::F9
|
||||
| Key::F10
|
||||
| Key::F11
|
||||
| Key::F12
|
||||
| Key::F13
|
||||
| Key::F14
|
||||
| Key::F15
|
||||
| Key::F16
|
||||
| Key::F17
|
||||
| Key::F18
|
||||
| Key::F19
|
||||
| Key::F20
|
||||
| Key::F21
|
||||
| Key::F22
|
||||
| Key::F23
|
||||
| Key::F24
|
||||
| Key::F25
|
||||
| Key::F26
|
||||
| Key::F27
|
||||
| Key::F28
|
||||
| Key::F29
|
||||
| Key::F30
|
||||
| Key::F31
|
||||
| Key::F32
|
||||
| Key::F33
|
||||
| Key::F34
|
||||
| Key::F35
|
||||
)
|
||||
}
|
||||
|
||||
/// The key as macOS menus show it: arrows and editing keys as glyphs.
|
||||
pub(crate) fn mac_symbol(self) -> &'static str {
|
||||
match self {
|
||||
Key::Up => "↑",
|
||||
Key::Down => "↓",
|
||||
Key::Left => "←",
|
||||
Key::Right => "→",
|
||||
Key::Enter => "⏎",
|
||||
Key::Backspace => "⌫",
|
||||
Key::Delete => "⌦",
|
||||
Key::Escape => "⎋",
|
||||
Key::Tab => "⇥",
|
||||
k => k.text_name(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The key as Windows and Linux show it.
|
||||
pub(crate) fn text_name(self) -> &'static str {
|
||||
match self {
|
||||
Key::PageUp => "Page Up",
|
||||
Key::PageDown => "Page Down",
|
||||
k => k.name(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Key {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.name())
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Key {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.serialize_str(self.name())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Key {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Key, D::Error> {
|
||||
let text = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
|
||||
if text.len() > MAX_CHORD_TEXT {
|
||||
return Err(serde::de::Error::custom(ParseError::TooLong));
|
||||
}
|
||||
Key::parse(&text).ok_or_else(|| serde::de::Error::custom(ParseError::UnknownKey(text.into_owned())))
|
||||
}
|
||||
}
|
||||
|
||||
/// Modifier keys held with a chord's key.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct Mods {
|
||||
/// The command modifier: ⌘ on macOS, Ctrl on Windows and Linux.
|
||||
pub cmd: bool,
|
||||
/// The Control key on macOS. Off macOS it folds into `cmd`.
|
||||
pub ctrl: bool,
|
||||
/// Alt, Option on macOS.
|
||||
pub alt: bool,
|
||||
pub shift: bool,
|
||||
}
|
||||
|
||||
impl Mods {
|
||||
pub const NONE: Mods = Mods { cmd: false, ctrl: false, alt: false, shift: false };
|
||||
pub const CMD: Mods = Mods { cmd: true, ctrl: false, alt: false, shift: false };
|
||||
pub const CTRL: Mods = Mods { cmd: false, ctrl: true, alt: false, shift: false };
|
||||
pub const ALT: Mods = Mods { cmd: false, ctrl: false, alt: true, shift: false };
|
||||
pub const SHIFT: Mods = Mods { cmd: false, ctrl: false, alt: false, shift: true };
|
||||
|
||||
pub const fn is_none(self) -> bool {
|
||||
!(self.cmd || self.ctrl || self.alt || self.shift)
|
||||
}
|
||||
|
||||
/// The modifiers as `platform` sees them: off macOS `ctrl` becomes `cmd`.
|
||||
pub const fn effective(self, platform: Platform) -> Mods {
|
||||
if platform.is_mac() || !self.ctrl { self } else { Mods { cmd: true, ctrl: false, ..self } }
|
||||
}
|
||||
}
|
||||
|
||||
/// A key with modifiers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct Chord {
|
||||
pub mods: Mods,
|
||||
pub key: Key,
|
||||
}
|
||||
|
||||
/// Why chord or trigger text was refused.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum ParseError {
|
||||
Empty,
|
||||
/// Longer than [`MAX_CHORD_TEXT`].
|
||||
TooLong,
|
||||
/// Modifiers with no key, or a trailing `+`.
|
||||
MissingKey,
|
||||
UnknownKey(String),
|
||||
UnknownModifier(String),
|
||||
DuplicateModifier(String),
|
||||
/// Two different chords: key sequences are not supported.
|
||||
Sequence,
|
||||
}
|
||||
|
||||
impl fmt::Display for ParseError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
ParseError::Empty => f.write_str("empty shortcut"),
|
||||
ParseError::TooLong => write!(f, "shortcut longer than {MAX_CHORD_TEXT} bytes"),
|
||||
ParseError::MissingKey => f.write_str("shortcut has no key"),
|
||||
ParseError::UnknownKey(k) => write!(f, "unknown key `{k}`"),
|
||||
ParseError::UnknownModifier(m) => write!(f, "unknown modifier `{m}`"),
|
||||
ParseError::DuplicateModifier(m) => write!(f, "modifier `{m}` given twice"),
|
||||
ParseError::Sequence => f.write_str("key sequences are not supported"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ParseError {}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Modifier {
|
||||
Cmd,
|
||||
Ctrl,
|
||||
Alt,
|
||||
Shift,
|
||||
}
|
||||
|
||||
fn modifier_named(name: &str) -> Option<Modifier> {
|
||||
const NAMES: &[(&str, Modifier)] = &[
|
||||
("cmd", Modifier::Cmd),
|
||||
("command", Modifier::Cmd),
|
||||
("meta", Modifier::Cmd),
|
||||
("super", Modifier::Cmd),
|
||||
("mod", Modifier::Cmd),
|
||||
("⌘", Modifier::Cmd),
|
||||
("ctrl", Modifier::Ctrl),
|
||||
("control", Modifier::Ctrl),
|
||||
("ctl", Modifier::Ctrl),
|
||||
("⌃", Modifier::Ctrl),
|
||||
("alt", Modifier::Alt),
|
||||
("opt", Modifier::Alt),
|
||||
("option", Modifier::Alt),
|
||||
("⌥", Modifier::Alt),
|
||||
("shift", Modifier::Shift),
|
||||
("⇧", Modifier::Shift),
|
||||
];
|
||||
NAMES.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|&(_, m)| m)
|
||||
}
|
||||
|
||||
/// A modifier glyph at the start of `text`, and the text after it.
|
||||
fn strip_glyph(text: &str) -> Option<(Modifier, &str)> {
|
||||
let mut chars = text.chars();
|
||||
let m = match chars.next()? {
|
||||
'⌘' => Modifier::Cmd,
|
||||
'⌃' => Modifier::Ctrl,
|
||||
'⌥' => Modifier::Alt,
|
||||
'⇧' => Modifier::Shift,
|
||||
_ => return None,
|
||||
};
|
||||
Some((m, chars.as_str()))
|
||||
}
|
||||
|
||||
fn add_modifier(mods: &mut Mods, m: Modifier, written: &str) -> Result<(), ParseError> {
|
||||
let slot = match m {
|
||||
Modifier::Cmd => &mut mods.cmd,
|
||||
Modifier::Ctrl => &mut mods.ctrl,
|
||||
Modifier::Alt => &mut mods.alt,
|
||||
Modifier::Shift => &mut mods.shift,
|
||||
};
|
||||
if *slot {
|
||||
return Err(ParseError::DuplicateModifier(written.to_owned()));
|
||||
}
|
||||
*slot = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Chord {
|
||||
pub const fn new(mods: Mods, key: Key) -> Chord {
|
||||
Chord { mods, key }
|
||||
}
|
||||
|
||||
/// The key with no modifiers.
|
||||
pub const fn plain(key: Key) -> Chord {
|
||||
Chord { mods: Mods::NONE, key }
|
||||
}
|
||||
|
||||
/// Reads canonical text (`Cmd+Shift+Z`) and the common aliases: modifier words in any order
|
||||
/// and case (`cmd command meta super mod`, `ctrl control ctl`, `alt opt option`, `shift`),
|
||||
/// Mac glyphs, glued (`⇧⌘Z`) or with `+`, and the key names [`Key::parse`] reads. `Cmd++` is
|
||||
/// Cmd with the Plus key.
|
||||
pub fn parse(text: &str) -> Result<Chord, ParseError> {
|
||||
if text.len() > MAX_CHORD_TEXT {
|
||||
return Err(ParseError::TooLong);
|
||||
}
|
||||
let mut rest = text.trim();
|
||||
if rest.is_empty() {
|
||||
return Err(ParseError::Empty);
|
||||
}
|
||||
let mut mods = Mods::NONE;
|
||||
// Each pass consumes at least one byte, so the loop ends within MAX_CHORD_TEXT passes.
|
||||
loop {
|
||||
if let Some((m, after)) = strip_glyph(rest) {
|
||||
add_modifier(&mut mods, m, rest.get(..rest.len() - after.len()).unwrap_or_default())?;
|
||||
// `⌘+K` and `⌘K` are the same; in `⌘+` the `+` is the key.
|
||||
rest = match after.strip_prefix('+') {
|
||||
Some(r) if !r.is_empty() => r,
|
||||
_ => after,
|
||||
};
|
||||
if rest.trim().is_empty() {
|
||||
return Err(ParseError::MissingKey);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A `+` in first position is the Plus key, never a separator.
|
||||
let first = rest.chars().next().map_or(0, char::len_utf8);
|
||||
let separator = rest.get(first..).and_then(|r| r.find('+')).map(|i| i + first);
|
||||
match separator {
|
||||
Some(i) => {
|
||||
let token = rest.get(..i).unwrap_or_default().trim();
|
||||
let after = rest.get(i + 1..).unwrap_or_default();
|
||||
if after.trim().is_empty() {
|
||||
return Err(ParseError::MissingKey);
|
||||
}
|
||||
let m = modifier_named(token).ok_or_else(|| ParseError::UnknownModifier(token.to_owned()))?;
|
||||
add_modifier(&mut mods, m, token)?;
|
||||
rest = after;
|
||||
}
|
||||
None => {
|
||||
let token = rest.trim();
|
||||
if modifier_named(token).is_some() {
|
||||
return Err(ParseError::MissingKey);
|
||||
}
|
||||
let key = Key::parse(token).ok_or_else(|| ParseError::UnknownKey(token.to_owned()))?;
|
||||
return Ok(Chord { mods, key });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonical text, the same as `to_string()`: `Cmd+Ctrl+Alt+Shift+Key`.
|
||||
pub fn portable(&self) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
|
||||
/// The chord as `platform` sees it: off macOS `ctrl` folds into `cmd`. Lookups and conflict
|
||||
/// checks compare effective chords.
|
||||
pub const fn effective(self, platform: Platform) -> Chord {
|
||||
Chord { mods: self.mods.effective(platform), key: self.key }
|
||||
}
|
||||
|
||||
/// Text for menus and settings: `⌃⌥⇧⌘K` on macOS, `Ctrl+Alt+Shift+K` elsewhere.
|
||||
pub fn display(&self, platform: Platform) -> String {
|
||||
self.display_key(platform, None)
|
||||
}
|
||||
|
||||
/// [`display`](Self::display) for the keys of `layout`: a punctuation key shows the character
|
||||
/// the layout types at its position when that character has no key of its own (`Ctrl+Ü` for
|
||||
/// Ctrl+[ on German). Letters and digits show as in `display`.
|
||||
pub fn display_for(&self, platform: Platform, layout: &Layout) -> String {
|
||||
self.display_key(platform, layout.key_label(self.key).as_deref())
|
||||
}
|
||||
|
||||
fn display_key(&self, platform: Platform, key_text: Option<&str>) -> String {
|
||||
let m = self.mods.effective(platform);
|
||||
let mut s = String::new();
|
||||
if platform.is_mac() {
|
||||
for (on, glyph) in [(m.ctrl, "⌃"), (m.alt, "⌥"), (m.shift, "⇧"), (m.cmd, "⌘")] {
|
||||
if on {
|
||||
s.push_str(glyph);
|
||||
}
|
||||
}
|
||||
s.push_str(key_text.unwrap_or(self.key.mac_symbol()));
|
||||
} else {
|
||||
for (on, name) in [(m.cmd, "Ctrl+"), (m.alt, "Alt+"), (m.shift, "Shift+")] {
|
||||
if on {
|
||||
s.push_str(name);
|
||||
}
|
||||
}
|
||||
s.push_str(key_text.unwrap_or(self.key.text_name()));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
pub const fn is_function_key(&self) -> bool {
|
||||
self.key.is_function_key()
|
||||
}
|
||||
|
||||
/// No cmd, ctrl or alt. Shift alone still counts as plain: such chords are tool keys that
|
||||
/// typing in a text field would trigger.
|
||||
pub const fn is_plain(&self) -> bool {
|
||||
!(self.mods.cmd || self.mods.ctrl || self.mods.alt)
|
||||
}
|
||||
|
||||
/// Holds the command modifier: cmd, or ctrl (Control on macOS, folded into cmd elsewhere).
|
||||
pub const fn has_command(&self) -> bool {
|
||||
self.mods.cmd || self.mods.ctrl
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Key> for Chord {
|
||||
fn from(key: Key) -> Chord {
|
||||
Chord::plain(key)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Chord {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
for (on, name) in [(self.mods.cmd, "Cmd+"), (self.mods.ctrl, "Ctrl+"), (self.mods.alt, "Alt+"), (self.mods.shift, "Shift+")] {
|
||||
if on {
|
||||
f.write_str(name)?;
|
||||
}
|
||||
}
|
||||
f.write_str(self.key.name())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::str::FromStr for Chord {
|
||||
type Err = ParseError;
|
||||
fn from_str(s: &str) -> Result<Chord, ParseError> {
|
||||
Chord::parse(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Chord {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.collect_str(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Chord {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Chord, D::Error> {
|
||||
let text = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
|
||||
Chord::parse(&text).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
/// What starts a command: a chord, pressed once or twice in a row.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct Trigger {
|
||||
pub chord: Chord,
|
||||
/// The chord pressed twice.
|
||||
pub double: bool,
|
||||
}
|
||||
|
||||
impl Trigger {
|
||||
pub const fn single(chord: Chord) -> Trigger {
|
||||
Trigger { chord, double: false }
|
||||
}
|
||||
|
||||
pub const fn double(chord: Chord) -> Trigger {
|
||||
Trigger { chord, double: true }
|
||||
}
|
||||
|
||||
/// Reads a chord as [`Chord::parse`] does, or the same chord twice separated by whitespace
|
||||
/// (`A A`) as a double press. Two different chords are [`ParseError::Sequence`].
|
||||
pub fn parse(text: &str) -> Result<Trigger, ParseError> {
|
||||
if text.len() > MAX_CHORD_TEXT {
|
||||
return Err(ParseError::TooLong);
|
||||
}
|
||||
let single = match Chord::parse(text) {
|
||||
Ok(chord) => return Ok(Trigger::single(chord)),
|
||||
Err(e) => e,
|
||||
};
|
||||
let mut parts = text.split_whitespace();
|
||||
match (parts.next(), parts.next(), parts.next()) {
|
||||
(Some(first), Some(second), None) => {
|
||||
let (first, second) = (Chord::parse(first)?, Chord::parse(second)?);
|
||||
if first == second { Ok(Trigger::double(first)) } else { Err(ParseError::Sequence) }
|
||||
}
|
||||
_ => Err(single),
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonical text, the same as `to_string()`.
|
||||
pub fn portable(&self) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
|
||||
pub const fn effective(self, platform: Platform) -> Trigger {
|
||||
Trigger { chord: self.chord.effective(platform), double: self.double }
|
||||
}
|
||||
|
||||
/// [`Chord::display`], twice with a space between for a double press.
|
||||
pub fn display(&self, platform: Platform) -> String {
|
||||
let one = self.chord.display(platform);
|
||||
if self.double { format!("{one} {one}") } else { one }
|
||||
}
|
||||
|
||||
/// [`Chord::display_for`], twice with a space between for a double press.
|
||||
pub fn display_for(&self, platform: Platform, layout: &Layout) -> String {
|
||||
let one = self.chord.display_for(platform, layout);
|
||||
if self.double { format!("{one} {one}") } else { one }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Chord> for Trigger {
|
||||
fn from(chord: Chord) -> Trigger {
|
||||
Trigger::single(chord)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Trigger {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if self.double { write!(f, "{0} {0}", self.chord) } else { write!(f, "{}", self.chord) }
|
||||
}
|
||||
}
|
||||
|
||||
impl std::str::FromStr for Trigger {
|
||||
type Err = ParseError;
|
||||
fn from_str(s: &str) -> Result<Trigger, ParseError> {
|
||||
Trigger::parse(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Trigger {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.collect_str(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Trigger {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Trigger, D::Error> {
|
||||
let text = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
|
||||
Trigger::parse(&text).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Key text as other applications write it in their shortcut files and menus.
|
||||
//!
|
||||
//! Windows sets name the command modifier `Ctrl`; Mac sets name it `Cmd` and use `Ctrl` for the
|
||||
//! Control key. [`read_foreign`] reads either into a [`Trigger`], tolerating separators
|
||||
//! (`+`, `-`, space), spelled-out key names (`Page Down`, `Up Arrow`) and numeric keypad keys.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{Chord, Key, MAX_CHORD_TEXT, Mods, Trigger};
|
||||
|
||||
/// Which modifier naming a shortcut set uses.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Flavor {
|
||||
/// `Ctrl` is the command modifier.
|
||||
Windows,
|
||||
/// `Cmd` is the command modifier and `Ctrl` the Control key.
|
||||
Mac,
|
||||
}
|
||||
|
||||
impl Flavor {
|
||||
/// Mac when any text names cmd, command, opt or option, or uses ⌘ or ⌥; Windows otherwise.
|
||||
pub fn detect<I, S>(texts: I) -> Flavor
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: AsRef<str>,
|
||||
{
|
||||
let mac = texts.into_iter().any(|t| {
|
||||
let t = t.as_ref();
|
||||
t.contains(['⌘', '⌥']) || {
|
||||
let lower = t.to_ascii_lowercase();
|
||||
lower.contains("cmd") || lower.contains("command") || lower.contains("opt")
|
||||
}
|
||||
});
|
||||
if mac { Flavor::Mac } else { Flavor::Windows }
|
||||
}
|
||||
}
|
||||
|
||||
/// Something [`read_foreign`] changed while reading that an import report may mention.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum ReadNote {
|
||||
/// A numeric keypad key was read as the main key of the same name.
|
||||
Numpad,
|
||||
}
|
||||
|
||||
/// Why foreign key text could not be read.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum ForeignError {
|
||||
Empty,
|
||||
/// Longer than [`MAX_CHORD_TEXT`].
|
||||
TooLong,
|
||||
UnknownKey(String),
|
||||
/// A modifier with no counterpart here, such as the Windows key.
|
||||
UnsupportedModifier(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ForeignError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ForeignError::Empty => f.write_str("empty shortcut"),
|
||||
ForeignError::TooLong => write!(f, "shortcut longer than {MAX_CHORD_TEXT} bytes"),
|
||||
ForeignError::UnknownKey(k) => write!(f, "unknown key `{k}`"),
|
||||
ForeignError::UnsupportedModifier(m) => write!(f, "unsupported modifier `{m}`"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ForeignError {}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Word {
|
||||
Command,
|
||||
Control,
|
||||
Alt,
|
||||
Shift,
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
const GLYPHS: &[(char, Word)] = &[('⌘', Word::Command), ('⌃', Word::Control), ('⌥', Word::Alt), ('⇧', Word::Shift)];
|
||||
|
||||
// Longer words first where one is a prefix of another.
|
||||
const WORDS: &[(&str, Word)] = &[
|
||||
("command", Word::Command),
|
||||
("cmd", Word::Command),
|
||||
("control", Word::Control),
|
||||
("ctrl", Word::Control),
|
||||
("option", Word::Alt),
|
||||
("opt", Word::Alt),
|
||||
("alt", Word::Alt),
|
||||
("shift", Word::Shift),
|
||||
("windows", Word::Unsupported),
|
||||
("win", Word::Unsupported),
|
||||
("meta", Word::Unsupported),
|
||||
("super", Word::Unsupported),
|
||||
];
|
||||
|
||||
/// Key names some applications use that [`Key::parse`] does not read. Compared after removing
|
||||
/// whitespace and lower-casing.
|
||||
const FOREIGN_KEYS: &[(&str, Key)] = &[
|
||||
("uparrow", Key::Up),
|
||||
("downarrow", Key::Down),
|
||||
("leftarrow", Key::Left),
|
||||
("rightarrow", Key::Right),
|
||||
("pageup", Key::PageUp),
|
||||
("pagedown", Key::PageDown),
|
||||
("⇞", Key::PageUp),
|
||||
("⇟", Key::PageDown),
|
||||
("↖", Key::Home),
|
||||
("↘", Key::End),
|
||||
("⌤", Key::Enter),
|
||||
("forwarddelete", Key::Delete),
|
||||
("help", Key::Insert),
|
||||
];
|
||||
|
||||
/// Reads one shortcut as another application writes it: `Shift+Ctrl+S`, `Ctrl+Num 5`,
|
||||
/// `Page Down`, `⇧⌘S`, `Opt-Left`. `flavor` decides what `Ctrl` means. The notes say what was
|
||||
/// approximated.
|
||||
pub fn read_foreign(text: &str, flavor: Flavor) -> Result<(Trigger, Vec<ReadNote>), ForeignError> {
|
||||
if text.len() > MAX_CHORD_TEXT {
|
||||
return Err(ForeignError::TooLong);
|
||||
}
|
||||
let mut rest = text.trim();
|
||||
if rest.is_empty() {
|
||||
return Err(ForeignError::Empty);
|
||||
}
|
||||
let mut mods = Mods::NONE;
|
||||
// Each pass consumes at least one byte.
|
||||
'strip: loop {
|
||||
for &(glyph, word) in GLYPHS {
|
||||
if let Some(after) = rest.strip_prefix(glyph) {
|
||||
apply(&mut mods, word, flavor, rest.get(..glyph.len_utf8()).unwrap_or_default())?;
|
||||
let after = after.trim_start();
|
||||
rest = match after.strip_prefix('+') {
|
||||
Some(r) if !r.trim().is_empty() => r.trim_start(),
|
||||
_ => after,
|
||||
};
|
||||
continue 'strip;
|
||||
}
|
||||
}
|
||||
for &(name, word) in WORDS {
|
||||
let (Some(head), Some(after)) = (rest.get(..name.len()), rest.get(name.len()..)) else { continue };
|
||||
// A modifier word needs a separator and a key after it: `Alt` alone is a key name.
|
||||
let mut chars = after.chars();
|
||||
if head.eq_ignore_ascii_case(name) && matches!(chars.next(), Some('+' | '-' | ' ')) && !chars.as_str().trim().is_empty() {
|
||||
apply(&mut mods, word, flavor, head)?;
|
||||
rest = after_separator(chars.as_str());
|
||||
continue 'strip;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
let (key, numpad) = foreign_key(rest).ok_or_else(|| ForeignError::UnknownKey(rest.trim().to_owned()))?;
|
||||
let notes = if numpad { vec![ReadNote::Numpad] } else { Vec::new() };
|
||||
Ok((Trigger::single(Chord::new(mods, key)), notes))
|
||||
}
|
||||
|
||||
/// The text after a modifier word and its first separator; `Ctrl + S` reads like `Ctrl+S`.
|
||||
fn after_separator(after: &str) -> &str {
|
||||
let after = after.trim_start();
|
||||
match after.strip_prefix(['+', '-']) {
|
||||
Some(r) if !r.trim().is_empty() => r.trim_start(),
|
||||
_ => after,
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(mods: &mut Mods, word: Word, flavor: Flavor, written: &str) -> Result<(), ForeignError> {
|
||||
match word {
|
||||
Word::Command => mods.cmd = true,
|
||||
Word::Control if flavor == Flavor::Mac => mods.ctrl = true,
|
||||
Word::Control => mods.cmd = true,
|
||||
Word::Alt => mods.alt = true,
|
||||
Word::Shift => mods.shift = true,
|
||||
Word::Unsupported => return Err(ForeignError::UnsupportedModifier(written.to_owned())),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The key a foreign key name stands for, and whether it was on the numeric keypad.
|
||||
fn foreign_key(name: &str) -> Option<(Key, bool)> {
|
||||
let squashed: String = name.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();
|
||||
if squashed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// egui reports keypad keys as the main keys, so `Num 5` binds `5`.
|
||||
let keypad = squashed.strip_prefix("numpad").or_else(|| squashed.strip_prefix("num")).filter(|r| !r.is_empty() && *r != "lock");
|
||||
let (n, numpad) = match keypad {
|
||||
Some(r) => (r, true),
|
||||
None => (squashed.as_str(), false),
|
||||
};
|
||||
let key = FOREIGN_KEYS.iter().find(|(alias, _)| *alias == n).map(|&(_, k)| k).or_else(|| Key::parse(n))?;
|
||||
Some((key, numpad))
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Commands with parameters and their binding keys.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
/// Longest binding key [`CommandRef::parse_key`] accepts, in bytes.
|
||||
pub const MAX_KEY: usize = 256;
|
||||
|
||||
/// A command id with the parameters a binding runs it with.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CommandRef {
|
||||
pub id: String,
|
||||
/// `Null` for no parameters.
|
||||
#[serde(default)]
|
||||
pub params: Value,
|
||||
}
|
||||
|
||||
impl CommandRef {
|
||||
/// A command without parameters.
|
||||
pub fn new(id: impl Into<String>) -> CommandRef {
|
||||
CommandRef { id: id.into(), params: Value::Null }
|
||||
}
|
||||
|
||||
pub fn with_params(id: impl Into<String>, params: Value) -> CommandRef {
|
||||
CommandRef { id: id.into(), params }
|
||||
}
|
||||
|
||||
/// The binding key: the id, or `id {json}` with object keys sorted and no spaces. `Null` and
|
||||
/// an empty object give the bare id.
|
||||
pub fn key(&self) -> String {
|
||||
match &self.params {
|
||||
Value::Null => self.id.clone(),
|
||||
Value::Object(m) if m.is_empty() => self.id.clone(),
|
||||
p => {
|
||||
let mut out = String::with_capacity(self.id.len() + 16);
|
||||
out.push_str(&self.id);
|
||||
out.push(' ');
|
||||
write_canonical(p, &mut out);
|
||||
out
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a binding key: the id up to the first space, then JSON parameters. `None` for an
|
||||
/// empty id, a key over [`MAX_KEY`] bytes or parameters that are not JSON.
|
||||
pub fn parse_key(key: &str) -> Option<CommandRef> {
|
||||
if key.len() > MAX_KEY {
|
||||
return None;
|
||||
}
|
||||
let (id, params) = match key.split_once(' ') {
|
||||
Some((id, rest)) => (id, serde_json::from_str(rest).ok()?),
|
||||
None => (key, Value::Null),
|
||||
};
|
||||
if id.is_empty() || id.chars().any(char::is_whitespace) {
|
||||
return None;
|
||||
}
|
||||
Some(CommandRef { id: id.to_string(), params })
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for CommandRef {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.key())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for CommandRef {
|
||||
fn from(id: &str) -> CommandRef {
|
||||
CommandRef::new(id)
|
||||
}
|
||||
}
|
||||
|
||||
// Written by hand so the key does not depend on serde_json's map order: an app's dependency graph
|
||||
// may turn on `preserve_order`.
|
||||
fn write_canonical(v: &Value, out: &mut String) {
|
||||
match v {
|
||||
Value::Null => out.push_str("null"),
|
||||
Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
|
||||
Value::Number(n) => out.push_str(&n.to_string()),
|
||||
Value::String(s) => write_string(s, out),
|
||||
Value::Array(items) => {
|
||||
out.push('[');
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(',');
|
||||
}
|
||||
write_canonical(item, out);
|
||||
}
|
||||
out.push(']');
|
||||
}
|
||||
Value::Object(map) => {
|
||||
let mut keys: Vec<&String> = map.keys().collect();
|
||||
keys.sort();
|
||||
out.push('{');
|
||||
for (i, k) in keys.into_iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(',');
|
||||
}
|
||||
write_string(k, out);
|
||||
out.push(':');
|
||||
if let Some(item) = map.get(k) {
|
||||
write_canonical(item, out);
|
||||
}
|
||||
}
|
||||
out.push('}');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_string(s: &str, out: &mut String) {
|
||||
out.push('"');
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
//! The model behind a shortcut editor: an edit session with undo, a chord recorder, conflict
|
||||
//! queries and search.
|
||||
//!
|
||||
//! A shortcut dialog drives it like this:
|
||||
//!
|
||||
//! ```
|
||||
//! use craft_keymap::editor::holders;
|
||||
//! use craft_keymap::{AssignError, Bindable, Binding, Chord, EditSession, Keymap, Platform, Policy, Recorded, Recorder, Scope, Scopes};
|
||||
//!
|
||||
//! let catalog = vec![
|
||||
//! Bindable::new("file.save", "Save", Scope::app()).with_default(Binding::parse("Cmd+S").unwrap()),
|
||||
//! Bindable::new("edit.copy", "Copy", Scope::app()).with_default(Binding::parse("Cmd+C").unwrap()),
|
||||
//! ];
|
||||
//! let mut keymap = Keymap::new(catalog, Scopes::new(), Platform::Mac);
|
||||
//! let now = 12.5;
|
||||
//!
|
||||
//! let mut session = EditSession::begin(&keymap);
|
||||
//! let mut recorder = Recorder::new();
|
||||
//! let save = "file.save".into();
|
||||
//! // The user presses Cmd+C in the shortcut field of Save.
|
||||
//! if let Recorded::Single(trigger) = recorder.press(Chord::parse("Cmd+C").unwrap(), now) {
|
||||
//! let binding = Binding::new(trigger);
|
||||
//! assert_eq!(holders(&keymap, &save, &binding)[0].command, "edit.copy".into());
|
||||
//! if let Err(AssignError::Taken(_)) = session.assign(&mut keymap, &save, binding.clone(), Policy::Refuse) {
|
||||
//! // The user chose to take the key from Copy.
|
||||
//! session.assign(&mut keymap, &save, binding, Policy::Steal).ok();
|
||||
//! }
|
||||
//! }
|
||||
//! assert!(keymap.bindings(&"edit.copy".into()).is_empty());
|
||||
//! // OK: store `keymap.overrides()` (`Profiles::store` for sets). Cancel:
|
||||
//! session.cancel(&mut keymap);
|
||||
//! assert_eq!(keymap.bindings(&"edit.copy".into()), [Binding::parse("Cmd+C").unwrap()]);
|
||||
//! ```
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::chord::{Chord, Key, Platform, Trigger};
|
||||
use crate::command::CommandRef;
|
||||
use crate::keymap::{AssignError, Assigned, Bindable, Binding, Holder, Keymap, Overrides, Policy};
|
||||
|
||||
/// Undo steps an [`EditSession`] keeps; older ones are dropped.
|
||||
pub const MAX_UNDO: usize = 500;
|
||||
/// Most bytes of undo snapshots an [`EditSession`] keeps (keys and texts, plus a fixed estimate
|
||||
/// per entry and per text for their allocations); older steps are dropped, though the latest one
|
||||
/// always stays.
|
||||
pub const MAX_UNDO_BYTES: usize = 64 << 20;
|
||||
|
||||
/// Seconds within which a second press of the same chord counts as a double press.
|
||||
pub const DOUBLE_PRESS: f64 = 0.6;
|
||||
|
||||
/// One opening of a shortcut editor: the overrides it started from, and undo and redo as
|
||||
/// snapshots of [`Overrides`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct EditSession {
|
||||
start: Overrides,
|
||||
/// Snapshots with their [`size`].
|
||||
undo: VecDeque<(Overrides, usize)>,
|
||||
undo_bytes: usize,
|
||||
redo: Vec<Overrides>,
|
||||
}
|
||||
|
||||
/// Heap bytes a snapshot entry costs beyond its strings' bytes: the key's `String`, the list and
|
||||
/// the map node, estimated.
|
||||
const ENTRY_OVERHEAD: usize = size_of::<String>() + 64;
|
||||
/// Bytes a text costs beyond its own: its `String` and allocator rounding, estimated.
|
||||
const TEXT_OVERHEAD: usize = size_of::<String>() + 16;
|
||||
|
||||
/// The estimated bytes of a snapshot, so many short texts count as more than their length.
|
||||
fn size(o: &Overrides) -> usize {
|
||||
o.iter().map(|(k, texts)| ENTRY_OVERHEAD + k.len() + texts.iter().map(|t| TEXT_OVERHEAD + t.len()).sum::<usize>()).sum()
|
||||
}
|
||||
|
||||
impl EditSession {
|
||||
/// Starts a session on `keymap`'s current overrides; [`cancel`](Self::cancel) returns to them.
|
||||
pub fn begin(keymap: &Keymap) -> EditSession {
|
||||
EditSession { start: keymap.overrides().clone(), undo: VecDeque::new(), undo_bytes: 0, redo: Vec::new() }
|
||||
}
|
||||
|
||||
/// Runs one edit. When it changes the overrides it becomes an undo step and clears redo.
|
||||
pub fn edit<R>(&mut self, keymap: &mut Keymap, f: impl FnOnce(&mut Keymap) -> R) -> R {
|
||||
let before = keymap.overrides().clone();
|
||||
let out = f(keymap);
|
||||
if *keymap.overrides() != before {
|
||||
self.push_undo(before);
|
||||
self.redo.clear();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Adds a binding as one undo step. With [`Policy::Refuse`] a chord other commands hold gives
|
||||
/// [`AssignError::Taken`] and changes nothing, so the dialog can ask whether to steal or keep;
|
||||
/// the answer is a second call with [`Policy::Steal`] or [`Policy::Keep`].
|
||||
pub fn assign(&mut self, keymap: &mut Keymap, command: &CommandRef, binding: Binding, policy: Policy) -> Result<Assigned, AssignError> {
|
||||
self.edit(keymap, |km| km.assign(command, binding, policy))
|
||||
}
|
||||
|
||||
/// Replaces one binding of a command with another as one undo step, as when the user records
|
||||
/// over a key in the list. Conflicts follow `policy` as in [`EditSession::assign`].
|
||||
pub fn replace(
|
||||
&mut self,
|
||||
keymap: &mut Keymap,
|
||||
command: &CommandRef,
|
||||
old: &Binding,
|
||||
new: Binding,
|
||||
policy: Policy,
|
||||
) -> Result<Assigned, AssignError> {
|
||||
let list: Vec<Binding> = keymap.bindings(command).into_iter().map(|b| if b == *old { new.clone() } else { b }).collect();
|
||||
self.edit(keymap, |km| km.set_bindings(command, list, policy))
|
||||
}
|
||||
|
||||
/// Removes one binding of a command as one undo step.
|
||||
pub fn remove(&mut self, keymap: &mut Keymap, command: &CommandRef, binding: &Binding) -> bool {
|
||||
self.edit(keymap, |km| km.remove(command, binding))
|
||||
}
|
||||
|
||||
/// Leaves a command without bindings as one undo step.
|
||||
pub fn clear(&mut self, keymap: &mut Keymap, command: &CommandRef) -> bool {
|
||||
self.edit(keymap, |km| km.clear(command))
|
||||
}
|
||||
|
||||
/// Gives a command its default bindings back as one undo step.
|
||||
pub fn reset(&mut self, keymap: &mut Keymap, command: &CommandRef) -> bool {
|
||||
self.edit(keymap, |km| km.reset(command))
|
||||
}
|
||||
|
||||
/// Gives every command its defaults as one undo step.
|
||||
pub fn reset_all(&mut self, keymap: &mut Keymap) {
|
||||
self.edit(keymap, Keymap::reset_all);
|
||||
}
|
||||
|
||||
fn push_undo(&mut self, snapshot: Overrides) {
|
||||
let bytes = size(&snapshot);
|
||||
self.undo.push_back((snapshot, bytes));
|
||||
self.undo_bytes += bytes;
|
||||
while self.undo.len() > 1 && (self.undo.len() > MAX_UNDO || self.undo_bytes > MAX_UNDO_BYTES) {
|
||||
if let Some((_, b)) = self.undo.pop_front() {
|
||||
self.undo_bytes -= b;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reverts the last edit; false when there is none.
|
||||
pub fn undo(&mut self, keymap: &mut Keymap) -> bool {
|
||||
let Some((previous, bytes)) = self.undo.pop_back() else { return false };
|
||||
self.undo_bytes -= bytes;
|
||||
self.redo.push(keymap.overrides().clone());
|
||||
keymap.set_overrides(previous);
|
||||
true
|
||||
}
|
||||
|
||||
/// Applies the last undone edit again; false when there is none.
|
||||
pub fn redo(&mut self, keymap: &mut Keymap) -> bool {
|
||||
let Some(next) = self.redo.pop() else { return false };
|
||||
self.push_undo(keymap.overrides().clone());
|
||||
keymap.set_overrides(next);
|
||||
true
|
||||
}
|
||||
|
||||
pub fn can_undo(&self) -> bool {
|
||||
!self.undo.is_empty()
|
||||
}
|
||||
|
||||
pub fn can_redo(&self) -> bool {
|
||||
!self.redo.is_empty()
|
||||
}
|
||||
|
||||
/// Restores the overrides the session started with and forgets its undo history.
|
||||
pub fn cancel(&mut self, keymap: &mut Keymap) {
|
||||
keymap.set_overrides(self.start.clone());
|
||||
self.undo.clear();
|
||||
self.undo_bytes = 0;
|
||||
self.redo.clear();
|
||||
}
|
||||
|
||||
/// Whether `keymap`'s overrides differ from those the session started with.
|
||||
pub fn is_modified(&self, keymap: &Keymap) -> bool {
|
||||
*keymap.overrides() != self.start
|
||||
}
|
||||
}
|
||||
|
||||
/// The other commands whose bindings clash with `binding` given to `command`: what
|
||||
/// [`Policy::Steal`] would take and [`Policy::Keep`] would leave clashing. Tools of the command's
|
||||
/// group and twins sharing a default key are not listed. A dialog shows these while the user
|
||||
/// records, before anything is assigned.
|
||||
pub fn holders(keymap: &Keymap, command: &CommandRef, binding: &Binding) -> Vec<Holder> {
|
||||
keymap.clashing(command, std::slice::from_ref(binding))
|
||||
}
|
||||
|
||||
/// What a press means to the recorder.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Recorded {
|
||||
Single(Trigger),
|
||||
/// The chord just recorded, pressed again within [`DOUBLE_PRESS`]: it replaces that single.
|
||||
Double(Trigger),
|
||||
/// Escape without modifiers: stop recording.
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// Turns the presses of a shortcut field into triggers.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Recorder {
|
||||
last: Option<(Chord, f64)>,
|
||||
}
|
||||
|
||||
impl Recorder {
|
||||
pub fn new() -> Recorder {
|
||||
Recorder::default()
|
||||
}
|
||||
|
||||
/// Records a press at `now_secs` (any monotonic clock, such as egui's `input.time`).
|
||||
pub fn press(&mut self, chord: Chord, now_secs: f64) -> Recorded {
|
||||
if chord.key == Key::Escape && chord.mods.is_none() {
|
||||
self.last = None;
|
||||
return Recorded::Cancel;
|
||||
}
|
||||
// After a double the next press starts over, so a third press is a single again.
|
||||
if let Some((last, at)) = self.last.take()
|
||||
&& last == chord
|
||||
&& now_secs >= at
|
||||
&& now_secs - at < DOUBLE_PRESS
|
||||
{
|
||||
return Recorded::Double(Trigger::double(chord));
|
||||
}
|
||||
self.last = Some((chord, now_secs));
|
||||
Recorded::Single(Trigger::single(chord))
|
||||
}
|
||||
|
||||
/// Forgets the last press, so the next one cannot become a double.
|
||||
pub fn reset(&mut self) {
|
||||
self.last = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The bindables matching `query`, in catalog order: a case-insensitive substring of the label,
|
||||
/// an alias, a menu path segment, the command id, or a binding's canonical or `platform` display
|
||||
/// text. An empty query matches everything.
|
||||
pub fn search<'a>(keymap: &'a Keymap, query: &str, platform: Platform) -> Vec<&'a Bindable> {
|
||||
let q = query.trim().to_lowercase();
|
||||
keymap
|
||||
.catalog()
|
||||
.iter()
|
||||
.filter(|b| {
|
||||
if q.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let hit = |s: &str| s.to_lowercase().contains(&q);
|
||||
hit(&b.label)
|
||||
|| b.aliases.iter().any(|a| hit(a))
|
||||
|| b.paths.iter().flatten().any(|s| hit(s))
|
||||
|| hit(&b.command.id)
|
||||
|| keymap.bindings(&b.command).iter().any(|binding| hit(&binding.trigger.to_string()) || hit(&binding.trigger.display(platform)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,598 @@
|
||||
//! Conversions between the crate's keys and egui's, matching egui key presses to chords, and a
|
||||
//! [`Dispatcher`] that turns a frame's key events into the commands they run. [`platform`] gives
|
||||
//! the platform to build a keymap for, the browser's operating system included on the web.
|
||||
|
||||
use ::egui::os::OperatingSystem;
|
||||
use ::egui::{Context, Event, InputState, Key as EguiKey, KeyboardShortcut, Modifiers};
|
||||
|
||||
use crate::chord::{Chord, Key, Mods, Platform, Trigger};
|
||||
use crate::command::CommandRef;
|
||||
use crate::keymap::{Keymap, Lookup};
|
||||
use crate::layout::{KeyInput, Layout};
|
||||
use crate::scope::Active;
|
||||
|
||||
/// The platform to build a keymap for in this context. Unlike [`Platform::current`], a web build
|
||||
/// gets the browser's operating system, which eframe reads from the user agent, so a Mac browser
|
||||
/// shows and matches Cmd shortcuts. eframe sets it before the first frame; an app that builds its
|
||||
/// keymap earlier rebuilds it when this differs.
|
||||
pub fn platform(ctx: &Context) -> Platform {
|
||||
Platform::from(ctx.os())
|
||||
}
|
||||
|
||||
/// iOS counts as Mac; Android and unknown systems count as Linux.
|
||||
impl From<OperatingSystem> for Platform {
|
||||
fn from(os: OperatingSystem) -> Platform {
|
||||
match os {
|
||||
OperatingSystem::Mac | OperatingSystem::IOS => Platform::Mac,
|
||||
OperatingSystem::Windows => Platform::Windows,
|
||||
OperatingSystem::Nix | OperatingSystem::Android | OperatingSystem::Unknown => Platform::Linux,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Both matches are generated from one list so that a key added to `Key` without an egui
|
||||
// counterpart fails to compile.
|
||||
macro_rules! egui_keys {
|
||||
($($ours:ident = $theirs:ident),* ; $($same:ident),* $(,)?) => {
|
||||
impl Key {
|
||||
/// The key for an egui key. `None` for modifier keys, Copy, Cut, Paste, BrowserBack
|
||||
/// and IntlBackslash.
|
||||
pub fn from_egui(key: EguiKey) -> Option<Key> {
|
||||
match key {
|
||||
$(EguiKey::$theirs => Some(Key::$ours),)*
|
||||
$(EguiKey::$same => Some(Key::$same),)*
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_egui(self) -> EguiKey {
|
||||
match self {
|
||||
$(Key::$ours => EguiKey::$theirs,)*
|
||||
$(Key::$same => EguiKey::$same,)*
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
egui_keys! {
|
||||
Up = ArrowUp, Down = ArrowDown, Left = ArrowLeft, Right = ArrowRight;
|
||||
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
|
||||
Num0, Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9,
|
||||
F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20,
|
||||
F21, F22, F23, F24, F25, F26, F27, F28, F29, F30, F31, F32, F33, F34, F35,
|
||||
Escape, Tab, Backspace, Enter, Space, Insert, Delete, Home, End, PageUp, PageDown,
|
||||
Minus, Equals, Plus, OpenBracket, CloseBracket, Backslash, Semicolon, Quote, Backtick,
|
||||
Comma, Period, Slash, Colon, Pipe, Questionmark, Exclamationmark, OpenCurlyBracket, CloseCurlyBracket,
|
||||
}
|
||||
|
||||
impl Mods {
|
||||
/// The modifiers egui reports, read for `platform`. On macOS cmd is ⌘ and ctrl the Control
|
||||
/// key; elsewhere Ctrl is cmd and ctrl stays false.
|
||||
pub fn from_egui(mods: &Modifiers, platform: Platform) -> Mods {
|
||||
if platform.is_mac() {
|
||||
// egui sets `command` together with `mac_cmd` on macOS; synthetic events may set
|
||||
// only one of them.
|
||||
Mods { cmd: mods.mac_cmd || mods.command, ctrl: mods.ctrl, alt: mods.alt, shift: mods.shift }
|
||||
} else {
|
||||
Mods { cmd: mods.ctrl || mods.command, ctrl: false, alt: mods.alt, shift: mods.shift }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Chord {
|
||||
/// The egui shortcut for this chord, for egui's own shortcut text and `consume_shortcut`.
|
||||
/// cmd becomes egui's `command` and ctrl its `ctrl`, which egui folds the same way off
|
||||
/// macOS.
|
||||
pub fn to_egui_shortcut(&self) -> KeyboardShortcut {
|
||||
let m = self.mods;
|
||||
KeyboardShortcut::new(Modifiers { alt: m.alt, ctrl: m.ctrl, shift: m.shift, mac_cmd: false, command: m.cmd }, self.key.to_egui())
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyInput {
|
||||
/// What an egui key press reports: the logical key as typed and the physical key. On a layout
|
||||
/// that is not Latin, the suite's egui-winit reports the Latin layout's letter as the logical
|
||||
/// key (Linux, Windows, and macOS with ⌘ held), and crates.io egui the physical key, so
|
||||
/// [`Layout::resolve`] takes a letter there before the position. The Latin layout's character
|
||||
/// comes from the frame's input ([`Dispatcher::dispatch`] fills it in). egui reports no Shift
|
||||
/// level, so [`Layout`] infers it. `None` for events other than key presses and releases.
|
||||
pub fn from_egui(event: &Event, platform: Platform) -> Option<KeyInput> {
|
||||
let Event::Key { key, physical_key, modifiers, .. } = event else { return None };
|
||||
let mut input = KeyInput::new(Mods::from_egui(modifiers, platform));
|
||||
input.typed = Key::from_egui(*key);
|
||||
input.physical = physical_key.and_then(Key::from_egui);
|
||||
Some(input)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a key press egui reported triggers `binding` on `platform`, on a layout about which
|
||||
/// nothing is known, for a press whose physical key is unknown. [`Layout::matches`] takes the
|
||||
/// whole press and the layout.
|
||||
///
|
||||
/// Besides an exact match:
|
||||
/// - Shift with a base key matches the shifted key egui reports (`Shift+;` matches `:`).
|
||||
/// - A shifted symbol bound without Shift matches when Shift is held to type it (`?`).
|
||||
/// - A binding on `=` matches `+` with or without Shift, and a binding on `+` matches
|
||||
/// `Shift+=`, so zoom keys work with and without Shift.
|
||||
pub fn matches(binding: &Chord, key: EguiKey, mods: &Modifiers, platform: Platform) -> bool {
|
||||
let Some(pressed) = Key::from_egui(key) else { return false };
|
||||
Layout::new().matches(binding, &KeyInput::new(Mods::from_egui(mods, platform)).with_typed(pressed), platform)
|
||||
}
|
||||
|
||||
pub use crate::editor::DOUBLE_PRESS;
|
||||
|
||||
/// A command a key press runs.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct Hit {
|
||||
/// The command to run; for tools sharing the chord, the first of `cycle`.
|
||||
pub command: CommandRef,
|
||||
/// Tools of one group sharing the chord, in catalog order (the app picks the next one);
|
||||
/// empty for a plain command.
|
||||
pub cycle: Vec<CommandRef>,
|
||||
/// The chord whose binding matched, with `double` set when the double binding ran.
|
||||
pub trigger: Trigger,
|
||||
/// Whether `trigger` is the chord the press means ([`Layout::resolve`]), the one the shortcut
|
||||
/// recorder records. `false` when the press matched through a stand-in: a Shift binding on the
|
||||
/// US base key (`Shift+;` for `:`), `+` and `=` standing for each other, or a digit-row
|
||||
/// position's digit.
|
||||
pub exact: bool,
|
||||
/// The text of the Paste event that ran the command, or on the web of the Paste event that
|
||||
/// came with the press that ran it.
|
||||
pub pasted: Option<String>,
|
||||
}
|
||||
|
||||
impl Hit {
|
||||
fn from_lookup(lookup: Lookup, trigger: Trigger, exact: bool) -> Option<Hit> {
|
||||
let (command, cycle) = match lookup {
|
||||
Lookup::None => return None,
|
||||
Lookup::Run(command) => (command, Vec::new()),
|
||||
Lookup::Cycle(cycle) => (cycle.first()?.clone(), cycle),
|
||||
};
|
||||
Some(Hit { command, cycle, trigger, exact, pasted: None })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct LastPress {
|
||||
chord: Chord,
|
||||
at: f64,
|
||||
ran_double: bool,
|
||||
/// The focused panel: a press in another panel never completes the pair.
|
||||
panel: Option<String>,
|
||||
}
|
||||
|
||||
/// Runs a keymap against egui's input, one call per frame before the UI reads its keys.
|
||||
///
|
||||
/// It reads key presses (repeats only when [`with_repeat`](Self::with_repeat) is on). A press
|
||||
/// that runs a command is removed from the events, together with the text it typed when it has
|
||||
/// no command modifier, so no widget sees it too. Other events stay.
|
||||
///
|
||||
/// On the desktop, egui-winit sends egui's Copy, Cut and Paste events in place of the key press
|
||||
/// for any chord of Cmd with C, X or V (Ctrl off macOS; on Windows also Shift+Delete, Ctrl+Insert
|
||||
/// and Shift+Insert). The web build sends the key press and then the event. For the plain
|
||||
/// clipboard chords (Cmd+C, Cmd+X, Cmd+V, Cmd+Insert, Shift+Delete, Shift+Insert), the events and
|
||||
/// their presses stay with the app unless [`with_clipboard_events`](Self::with_clipboard_events)
|
||||
/// is on, so bindings on those chords run only with it on. An event with more modifiers held
|
||||
/// counts as its chord, read from the frame's modifiers (Cmd+Shift+V), and runs that chord's
|
||||
/// binding; without one, it stays. On Windows, egui-winit also sends Cut for Ctrl+Shift+Delete
|
||||
/// and Copy for Ctrl+Shift+Insert, which read as Cmd+Shift+X and Cmd+Shift+C.
|
||||
///
|
||||
/// egui-winit sends no Paste event when the clipboard is empty or holds no text (an image), so a
|
||||
/// binding on Cmd+V, or on Cmd and V with more modifiers, cannot run then on the desktop.
|
||||
///
|
||||
/// While [`Active::typing`], the text field keeps, without lookup:
|
||||
/// - the plain clipboard chords' events and presses (other clipboard chords are looked up);
|
||||
/// - a press with a Text event of its own in the frame, since it typed that text. This covers
|
||||
/// AltGr: the browser on Windows reports AltGr+Q (`@` on a German layout) as Ctrl+Alt+Q, and
|
||||
/// the web build's text agent sends the `@` after it. egui-winit reports AltGr with neither Ctrl
|
||||
/// nor Alt. A Ctrl+Alt press without text is a command chord.
|
||||
///
|
||||
/// Other presses are looked up; the keymap's [`TypingRule`](crate::TypingRule) and
|
||||
/// [`text_editing_chords`](crate::text_editing_chords) leave plain keys and the text-editing chords
|
||||
/// (Cmd+Z, word moves) to the field.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Dispatcher {
|
||||
last: Option<LastPress>,
|
||||
repeat: bool,
|
||||
clipboard: bool,
|
||||
/// Whether a press's Text event comes before it when no text field has focus, as eframe's
|
||||
/// web build sends them.
|
||||
text_first: bool,
|
||||
layout: Layout,
|
||||
/// Whether right Alt is held. egui-winit reports AltGr with neither Ctrl nor Alt, so its
|
||||
/// presses would otherwise teach the layout as plain ones.
|
||||
right_alt: bool,
|
||||
}
|
||||
|
||||
/// eframe's web build sends a press's Text event first when no text field has focus.
|
||||
const TEXT_FIRST: bool = cfg!(target_arch = "wasm32");
|
||||
|
||||
impl Default for Dispatcher {
|
||||
fn default() -> Dispatcher {
|
||||
Dispatcher { last: None, repeat: false, clipboard: false, text_first: TEXT_FIRST, layout: Layout::new(), right_alt: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatcher {
|
||||
pub fn new() -> Dispatcher {
|
||||
Dispatcher::default()
|
||||
}
|
||||
|
||||
/// Whether held keys run their command again on each repeat (off by default), so a held
|
||||
/// arrow can nudge. Repeats never count toward a double press.
|
||||
pub fn with_repeat(mut self, on: bool) -> Dispatcher {
|
||||
self.repeat = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether egui's Copy, Cut and Paste events for the plain clipboard chords count as those
|
||||
/// chords (Cmd+C, Cmd+X, Cmd+V; Shift+Delete and Shift+Insert for Cut and Paste with Shift
|
||||
/// alone) outside text fields. Off by default: the events stay in egui's input for the app's
|
||||
/// own handlers. With it on, an event that runs a command is removed, and a Paste event's text
|
||||
/// moves to [`Hit::pasted`]. On the web, the key press runs the command and its clipboard
|
||||
/// event goes with it the same way; when the press runs nothing, or the hit is declined, both
|
||||
/// stay. An app that asks egui for a paste (`ViewportCommand::RequestPaste`) to run its paste
|
||||
/// command gets a Paste event back, which with this on runs that command again.
|
||||
pub fn with_clipboard_events(mut self, on: bool) -> Dispatcher {
|
||||
self.clipboard = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Starts from what the platform reports about the keyboard layout. The dispatcher also
|
||||
/// learns from what plain presses type ([`Layout::observe`]), and takes whether the layout
|
||||
/// is Latin from egui when the integration reports it (egui-winit on Linux, with the suite's
|
||||
/// egui).
|
||||
pub fn with_layout(mut self, layout: Layout) -> Dispatcher {
|
||||
self.layout = layout;
|
||||
self
|
||||
}
|
||||
|
||||
/// The keyboard layout as known so far, for the shortcut recorder and labels
|
||||
/// ([`Chord::display_for`]).
|
||||
pub fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
|
||||
/// For reporting a layout switch ([`Layout::set_latin`]).
|
||||
pub fn layout_mut(&mut self) -> &mut Layout {
|
||||
&mut self.layout
|
||||
}
|
||||
|
||||
/// The commands this frame's key presses run with `active` focus, in press order.
|
||||
///
|
||||
/// A chord pressed again within [`DOUBLE_PRESS`] in the same panel runs its double binding
|
||||
/// when it has one; the first press has already run the single binding. The press after a
|
||||
/// double starts over.
|
||||
pub fn dispatch(&mut self, input: &mut InputState, keymap: &Keymap, active: &Active) -> Vec<Hit> {
|
||||
self.dispatch_filtered(input, keymap, active, |_| true)
|
||||
}
|
||||
|
||||
/// [`dispatch`](Self::dispatch), with `accept` deciding each hit before its event is removed.
|
||||
/// A declined hit is left out of the result and its event, with any text it typed, stays in
|
||||
/// egui's input in its place. A declined press still counts toward a double press.
|
||||
pub fn dispatch_filtered(&mut self, input: &mut InputState, keymap: &Keymap, active: &Active, mut accept: impl FnMut(&Hit) -> bool) -> Vec<Hit> {
|
||||
let platform = keymap.platform();
|
||||
let now = input.time;
|
||||
let frame_mods = Mods::from_egui(&input.modifiers, platform);
|
||||
let mut hits = Vec::new();
|
||||
let mut kept = Vec::with_capacity(input.events.len());
|
||||
let events = std::mem::take(&mut input.events);
|
||||
let text_of = text_of_press(&events, self.text_first && !active.typing);
|
||||
self.report_latin(input.keyboard_layout_is_latin());
|
||||
self.learn(&events, &text_of, platform);
|
||||
let mut drop = vec![false; events.len()];
|
||||
// The web build sends both a clipboard key press and the clipboard event it causes. The
|
||||
// press decides: its event goes with it when it runs a command and stays otherwise.
|
||||
let causes = clipboard_event_follows(&events, &self.layout, platform, input);
|
||||
let mut caused_taken: Vec<Option<bool>> = vec![None; events.len()];
|
||||
for (i, event) in events.into_iter().enumerate() {
|
||||
match &event {
|
||||
Event::Key { pressed: true, repeat, .. } if !*repeat || self.repeat => {
|
||||
let input = key_input(&event, platform, input);
|
||||
let held = input.mods;
|
||||
if let Some(chord) = self.layout.resolve(&input) {
|
||||
let plain_clip = is_plain_clipboard(chord.key, chord.mods);
|
||||
let keep =
|
||||
if active.typing { text_of[i].is_some() || plain_clip } else { !self.clipboard && plain_clip && causes[i].is_some() };
|
||||
if keep {
|
||||
if let Some((j, _)) = causes[i] {
|
||||
caused_taken[j] = Some(false);
|
||||
}
|
||||
kept.push((i, event));
|
||||
continue;
|
||||
}
|
||||
let caused = causes[i].clone();
|
||||
let hit = self.press(&input, *repeat, now, keymap, active).map(|mut hit| {
|
||||
hit.pasted = caused.as_ref().and_then(|(_, text)| text.clone());
|
||||
hit
|
||||
});
|
||||
let hit = hit.filter(&mut accept);
|
||||
if let Some((j, _)) = caused {
|
||||
caused_taken[j] = Some(hit.is_some());
|
||||
}
|
||||
if let Some(hit) = hit {
|
||||
hits.push(hit);
|
||||
if let Some(j) = text_of[i].filter(|_| !(held.cmd || held.ctrl)) {
|
||||
drop[j] = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A repeat that does not run leaves its clipboard event in place with it.
|
||||
Event::Key { pressed: true, repeat: true, .. } => {
|
||||
if let Some((j, _)) = causes[i] {
|
||||
caused_taken[j] = Some(false);
|
||||
}
|
||||
}
|
||||
// Desktop clipboard events, and web ones whose press stayed or ran nothing.
|
||||
Event::Copy | Event::Cut | Event::Paste(_) => match caused_taken[i] {
|
||||
Some(true) => continue,
|
||||
Some(false) => {}
|
||||
None => {
|
||||
let (key, held, _) = clipboard_chord(&event, frame_mods);
|
||||
// A focused text field copies and pastes on the plain chords itself.
|
||||
let look = !is_plain_clipboard(key, held) || (self.clipboard && !active.typing);
|
||||
let hit = if look { self.press(&KeyInput::new(held).with_typed(key), false, now, keymap, active) } else { None };
|
||||
if let Some(mut hit) = hit {
|
||||
if let Event::Paste(text) = &event {
|
||||
hit.pasted = Some(text.clone());
|
||||
}
|
||||
if accept(&hit) {
|
||||
hits.push(hit);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
kept.push((i, event));
|
||||
}
|
||||
input.events = kept.into_iter().filter(|(i, _)| !drop[*i]).map(|(_, e)| e).collect();
|
||||
hits
|
||||
}
|
||||
|
||||
/// Takes the platform's answer on whether the layout is Latin. `None` (not reported) leaves
|
||||
/// the layout as it is, so an earlier report or typing decides.
|
||||
fn report_latin(&mut self, reported: Option<bool>) {
|
||||
if reported.is_some() {
|
||||
self.layout.set_latin(reported);
|
||||
}
|
||||
}
|
||||
|
||||
/// Teaches the layout what this frame's presses typed.
|
||||
fn learn(&mut self, events: &[Event], text_of: &[Option<usize>], platform: Platform) {
|
||||
for (event, text) in events.iter().zip(text_of) {
|
||||
match event {
|
||||
Event::Key { physical_key: Some(EguiKey::AltRight), pressed, .. } => self.right_alt = *pressed,
|
||||
Event::WindowFocused(false) => self.right_alt = false,
|
||||
_ => {}
|
||||
}
|
||||
if self.right_alt {
|
||||
continue;
|
||||
}
|
||||
let Some(Event::Text(text)) = text.and_then(|j| events.get(j)) else { continue };
|
||||
if let Some(KeyInput { mods, physical: Some(physical), .. }) = KeyInput::from_egui(event, platform) {
|
||||
self.layout.observe(physical, mods, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn press(&mut self, input: &KeyInput, repeat: bool, now: f64, keymap: &Keymap, active: &Active) -> Option<Hit> {
|
||||
let chords = self.layout.candidates(input);
|
||||
let first = *chords.first()?;
|
||||
let find = |double: bool| {
|
||||
chords.iter().find_map(|&chord| Hit::from_lookup(keymap.lookup(&chord, double, active), Trigger { chord, double }, chord == first))
|
||||
};
|
||||
if repeat {
|
||||
return find(false);
|
||||
}
|
||||
let again = self
|
||||
.last
|
||||
.as_ref()
|
||||
.is_some_and(|l| l.chord == first && !l.ran_double && l.panel.as_deref() == active.panel && now >= l.at && now - l.at < DOUBLE_PRESS);
|
||||
let double = if again { find(true) } else { None };
|
||||
self.last = Some(LastPress { chord: first, at: now, ran_double: double.is_some(), panel: active.panel.map(str::to_owned) });
|
||||
double.or_else(|| find(false))
|
||||
}
|
||||
}
|
||||
|
||||
/// A clipboard event: Copy, Cut or Paste.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Clip {
|
||||
Copy,
|
||||
Cut,
|
||||
Paste,
|
||||
}
|
||||
|
||||
/// For each clipboard key press whose clipboard event comes later in the frame, as the web build
|
||||
/// sends them: the index of that event, and the text of a Paste event.
|
||||
/// The suite's egui fork has an inherent `InputState::keyboard_layout_is_latin`; crates.io egui
|
||||
/// has neither the method nor the field. A method call picks an inherent method over a trait
|
||||
/// method of the same name, so [`Dispatcher::dispatch`] reaches egui's method on the fork and
|
||||
/// this `None` everywhere else.
|
||||
#[allow(dead_code, reason = "unused when egui has the inherent method")]
|
||||
trait KeyboardLayoutIsLatin {
|
||||
fn keyboard_layout_is_latin(&self) -> Option<bool> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyboardLayoutIsLatin for InputState {}
|
||||
|
||||
/// The suite's egui fork has an inherent `InputState::latin_layout_char`, the character a key
|
||||
/// pressed this frame types on the Latin layout shortcuts follow; crates.io egui reports none.
|
||||
/// Reached as [`KeyboardLayoutIsLatin`] is.
|
||||
#[allow(dead_code, reason = "unused when egui has the inherent method")]
|
||||
trait LatinLayoutChar {
|
||||
fn latin_layout_char(&self, _physical_key: EguiKey) -> Option<char> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl LatinLayoutChar for InputState {}
|
||||
|
||||
/// A press as [`KeyInput::from_egui`] reads it, with the Latin layout's character `input` reports
|
||||
/// for its key.
|
||||
fn key_input(event: &Event, platform: Platform, input: &InputState) -> KeyInput {
|
||||
let mut key = KeyInput::from_egui(event, platform).unwrap_or_default();
|
||||
if let Event::Key { physical_key: Some(physical), .. } = event {
|
||||
key.latin = input.latin_layout_char(*physical);
|
||||
}
|
||||
key
|
||||
}
|
||||
|
||||
fn clipboard_event_follows(events: &[Event], layout: &Layout, platform: Platform, input: &InputState) -> Vec<Option<(usize, Option<String>)>> {
|
||||
let mut out = vec![None; events.len()];
|
||||
let mut ahead: [Option<usize>; 3] = [None; 3];
|
||||
for (i, event) in events.iter().enumerate().rev() {
|
||||
if let Some(seen) = event_clip(event).and_then(|c| ahead.get_mut(c as usize)) {
|
||||
*seen = Some(i);
|
||||
} else if let Event::Key { pressed: true, .. } = event {
|
||||
let chord = layout.resolve(&key_input(event, platform, input));
|
||||
let clip = chord.and_then(|c| clipboard_kind(c.key, c.mods));
|
||||
if let Some(j) = clip.and_then(|c| ahead.get_mut(c as usize)).and_then(Option::take) {
|
||||
let text = if let Some(Event::Paste(text)) = events.get(j) { Some(text.clone()) } else { None };
|
||||
out[i] = Some((j, text));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// For each key press, the index of the Text event it typed. egui-winit, and eframe's web text
|
||||
/// agent while a text field has focus, send the Text after the press, before the next one.
|
||||
/// With `text_first`, eframe's web build with no text field focused, the Text comes right before
|
||||
/// its press, and only for a press without Ctrl or Cmd.
|
||||
fn text_of_press(events: &[Event], text_first: bool) -> Vec<Option<usize>> {
|
||||
let is_text = |e: Option<&Event>| matches!(e, Some(Event::Text(t)) if !t.is_empty());
|
||||
let mut out = vec![None; events.len()];
|
||||
if text_first {
|
||||
for (i, event) in events.iter().enumerate().skip(1) {
|
||||
if let Event::Key { pressed: true, modifiers, .. } = event
|
||||
&& !(modifiers.ctrl || modifiers.command || modifiers.mac_cmd)
|
||||
&& is_text(events.get(i - 1))
|
||||
{
|
||||
out[i] = Some(i - 1);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
let mut text_ahead = None;
|
||||
for (i, event) in events.iter().enumerate().rev() {
|
||||
match event {
|
||||
Event::Key { pressed: true, .. } => out[i] = text_ahead.take(),
|
||||
_ if is_text(Some(event)) => text_ahead = Some(i),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn event_clip(event: &Event) -> Option<Clip> {
|
||||
match event {
|
||||
Event::Copy => Some(Clip::Copy),
|
||||
Event::Cut => Some(Clip::Cut),
|
||||
Event::Paste(_) => Some(Clip::Paste),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The clipboard event a backend sends for a press, if any.
|
||||
pub(crate) fn clipboard_kind(key: Key, held: Mods) -> Option<Clip> {
|
||||
match key {
|
||||
Key::C if held.cmd => Some(Clip::Copy),
|
||||
Key::X if held.cmd => Some(Clip::Cut),
|
||||
Key::V if held.cmd => Some(Clip::Paste),
|
||||
Key::Delete if held.shift => Some(Clip::Cut),
|
||||
Key::Insert if held.shift => Some(Clip::Paste),
|
||||
Key::Insert if held.cmd || held.ctrl => Some(Clip::Copy),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a chord is one of the plain clipboard chords, which egui's text fields act on: Cmd+C,
|
||||
/// Cmd+X, Cmd+V, Cmd+Insert, Shift+Delete and Shift+Insert.
|
||||
fn is_plain_clipboard(key: Key, held: Mods) -> bool {
|
||||
match key {
|
||||
Key::C | Key::X | Key::V => held == Mods::CMD,
|
||||
Key::Insert => held == Mods::CMD || held == Mods::SHIFT,
|
||||
Key::Delete => held == Mods::SHIFT,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The press a clipboard event stands for, with the modifiers held, and the event's kind. Off
|
||||
/// macOS egui-winit also sends Cut for Shift+Delete and Paste for Shift+Insert.
|
||||
pub(crate) fn clipboard_chord(event: &Event, held: Mods) -> (Key, Mods, Clip) {
|
||||
let with_cmd = Mods { cmd: true, ..held };
|
||||
let shift_only = held.shift && !held.cmd;
|
||||
match event {
|
||||
Event::Cut if shift_only => (Key::Delete, held, Clip::Cut),
|
||||
Event::Cut => (Key::X, with_cmd, Clip::Cut),
|
||||
Event::Paste(_) if shift_only => (Key::Insert, held, Clip::Paste),
|
||||
Event::Paste(_) => (Key::V, with_cmd, Clip::Paste),
|
||||
_ => (Key::C, with_cmd, Clip::Copy),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Bindable, Binding, Scope, Scopes};
|
||||
|
||||
#[test]
|
||||
fn web_text_before_its_press_goes_with_that_press() {
|
||||
let km = Keymap::new(
|
||||
vec![Bindable::new("tool.marquee", "Marquee", Scope::app()).with_default(Binding::parse("M").unwrap())],
|
||||
Scopes::new(),
|
||||
Platform::Windows,
|
||||
);
|
||||
let press = |key| Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE };
|
||||
let mut input = InputState::default();
|
||||
input.events = vec![Event::Text("m".into()), press(EguiKey::M), Event::Text("q".into()), press(EguiKey::Q)];
|
||||
let mut d = Dispatcher { text_first: true, ..Dispatcher::new() };
|
||||
let hits = d.dispatch(&mut input, &km, &Active::NONE);
|
||||
assert_eq!(hits.len(), 1);
|
||||
assert_eq!(input.events, [Event::Text("q".into()), press(EguiKey::Q)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_platforms_latin_report_overrides_typing() {
|
||||
/// Stands in for the fork's `InputState`, whose inherent method wins over the fallback.
|
||||
struct ForkInput(Option<bool>);
|
||||
impl ForkInput {
|
||||
fn keyboard_layout_is_latin(&self) -> Option<bool> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
impl KeyboardLayoutIsLatin for ForkInput {}
|
||||
|
||||
let km = Keymap::new(vec![], Scopes::new(), Platform::Windows);
|
||||
let typing = |text: &str| {
|
||||
let mut input = InputState::default();
|
||||
let key = Event::Key { key: EguiKey::C, physical_key: Some(EguiKey::C), pressed: true, repeat: false, modifiers: Modifiers::NONE };
|
||||
input.events = vec![key, Event::Text(text.into())];
|
||||
input
|
||||
};
|
||||
|
||||
// crates.io egui reports nothing, so typing decides.
|
||||
let mut d = Dispatcher::new();
|
||||
assert_eq!(InputState::default().keyboard_layout_is_latin(), None);
|
||||
d.dispatch(&mut typing("с"), &km, &Active::NONE);
|
||||
assert!(!d.layout().is_latin());
|
||||
|
||||
// A report wins over typing, and frames without one keep it.
|
||||
d.report_latin(ForkInput(Some(true)).keyboard_layout_is_latin());
|
||||
assert!(d.layout().is_latin());
|
||||
d.report_latin(ForkInput(None).keyboard_layout_is_latin());
|
||||
d.dispatch(&mut typing("с"), &km, &Active::NONE);
|
||||
assert!(d.layout().is_latin());
|
||||
d.report_latin(ForkInput(Some(false)).keyboard_layout_is_latin());
|
||||
d.dispatch(&mut typing("c"), &km, &Active::NONE);
|
||||
assert!(!d.layout().is_latin());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,351 @@
|
||||
//! Fuzzy matching of a name another application's file writes (a shortcut set's item label)
|
||||
//! against an app's commands, by their ids and labels only. A match is proposed when one candidate
|
||||
//! scores well and clearly ahead of the next; otherwise the best few are offered to choose from.
|
||||
//!
|
||||
//! From VectorCraft `crates/engine/src/namematch.rs`: Dice coefficients over words and over
|
||||
//! character pairs.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// A command a name can stand for.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Candidate {
|
||||
/// A command id such as `select.all`; a `tool:` or `panel:` prefix is ignored.
|
||||
pub id: String,
|
||||
/// Its labels: the English one, the one in the interface language, other names.
|
||||
pub labels: Vec<String>,
|
||||
}
|
||||
|
||||
/// What a name stands for, as far as [`propose`] can tell.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Proposal {
|
||||
/// The candidate at this index of the list, with its score (0 to 1).
|
||||
Match(usize, f64),
|
||||
/// The best candidates, best first, when none stands out.
|
||||
Choice(Vec<usize>),
|
||||
}
|
||||
|
||||
/// The lowest score [`Proposal::Match`] proposes.
|
||||
pub const THRESHOLD: f64 = 0.6;
|
||||
/// How far the best score must lead the next one to be proposed.
|
||||
pub const MARGIN: f64 = 0.1;
|
||||
/// The most candidates a [`Proposal::Choice`] lists.
|
||||
pub const CHOICES: usize = 5;
|
||||
/// The lowest score a [`Proposal::Choice`] lists.
|
||||
pub const CHOICE_FLOOR: f64 = 0.3;
|
||||
/// How many characters of a name or label are compared; the rest is ignored, so a long name
|
||||
/// costs no more than this.
|
||||
pub const MAX_NAME_CHARS: usize = 200;
|
||||
|
||||
/// The first [`MAX_NAME_CHARS`] characters of `s`.
|
||||
fn head(s: &str) -> &str {
|
||||
s.char_indices().nth(MAX_NAME_CHARS).and_then(|(end, _)| s.get(..end)).unwrap_or(s)
|
||||
}
|
||||
|
||||
/// `s` with only its letters and digits, lowercased.
|
||||
fn folded(s: &str) -> String {
|
||||
s.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect()
|
||||
}
|
||||
|
||||
/// The words of `s`, lowercased: runs of letters and digits, split where a lowercase letter or a digit
|
||||
/// meets an uppercase one (`selectAll`: `select`, `all`).
|
||||
fn words(s: &str) -> Vec<String> {
|
||||
let mut out = vec![];
|
||||
let mut word = String::new();
|
||||
let mut prev_lower = false;
|
||||
for c in s.chars() {
|
||||
if !c.is_alphanumeric() {
|
||||
if !word.is_empty() {
|
||||
out.push(std::mem::take(&mut word));
|
||||
}
|
||||
prev_lower = false;
|
||||
continue;
|
||||
}
|
||||
if c.is_uppercase() && prev_lower && !word.is_empty() {
|
||||
out.push(std::mem::take(&mut word));
|
||||
}
|
||||
prev_lower = c.is_lowercase() || c.is_ascii_digit();
|
||||
word.extend(c.to_lowercase());
|
||||
}
|
||||
if !word.is_empty() {
|
||||
out.push(word);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The words of a candidate's id: its segments after any `tool:` or `panel:`, split as [`words`].
|
||||
fn id_words(id: &str) -> Vec<String> {
|
||||
let id = id.strip_prefix("tool:").or_else(|| id.strip_prefix("panel:")).unwrap_or(id);
|
||||
id.split('.').flat_map(words).collect()
|
||||
}
|
||||
|
||||
/// How many words `a` and `b` share, each word counted once, as a Dice coefficient (0 to 1).
|
||||
fn word_overlap(a: &[String], b: &[String]) -> f64 {
|
||||
if a.is_empty() || b.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let mut rest: Vec<&String> = b.iter().collect();
|
||||
let mut shared = 0usize;
|
||||
for w in a {
|
||||
if let Some(i) = rest.iter().position(|x| *x == w) {
|
||||
rest.swap_remove(i);
|
||||
shared += 1;
|
||||
}
|
||||
}
|
||||
(2 * shared) as f64 / (a.len() + b.len()) as f64
|
||||
}
|
||||
|
||||
/// The pairs of neighboring characters in `s`.
|
||||
fn pairs(s: &str) -> Vec<(char, char)> {
|
||||
let c: Vec<char> = s.chars().collect();
|
||||
c.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?))).collect()
|
||||
}
|
||||
|
||||
/// How many character pairs `a` and `b` (each sorted) share, as a Dice coefficient (0 to 1): for
|
||||
/// names written without spaces. Linear in their lengths, so long names in a file stay quick.
|
||||
fn pair_similarity(a: &[(char, char)], b: &[(char, char)]) -> f64 {
|
||||
if a.is_empty() || b.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let (mut i, mut j, mut shared) = (0usize, 0usize, 0usize);
|
||||
while let (Some(p), Some(q)) = (a.get(i), b.get(j)) {
|
||||
match p.cmp(q) {
|
||||
std::cmp::Ordering::Less => i += 1,
|
||||
std::cmp::Ordering::Greater => j += 1,
|
||||
std::cmp::Ordering::Equal => {
|
||||
shared += 1;
|
||||
i += 1;
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
(2 * shared) as f64 / (a.len() + b.len()) as f64
|
||||
}
|
||||
|
||||
/// A name or label as the scores compare it: its letters and digits (lowercased), its words and the
|
||||
/// character pairs of the former (sorted).
|
||||
struct Text {
|
||||
folded: String,
|
||||
words: Vec<String>,
|
||||
pairs: Vec<(char, char)>,
|
||||
}
|
||||
|
||||
impl Text {
|
||||
fn of(s: &str) -> Self {
|
||||
let s = head(s);
|
||||
let folded = folded(s);
|
||||
let mut pairs = pairs(&folded);
|
||||
pairs.sort_unstable();
|
||||
Self { pairs, words: words(s), folded }
|
||||
}
|
||||
}
|
||||
|
||||
/// A candidate as the scores compare it.
|
||||
struct Prepared {
|
||||
/// Its id's words, and those joined.
|
||||
id_words: Vec<String>,
|
||||
id: String,
|
||||
labels: Vec<Text>,
|
||||
}
|
||||
|
||||
impl Prepared {
|
||||
fn of(c: &Candidate) -> Self {
|
||||
let id_words = id_words(&c.id);
|
||||
Self { id: id_words.concat(), id_words, labels: c.labels.iter().map(|l| Text::of(l)).collect() }
|
||||
}
|
||||
|
||||
/// See [`score`].
|
||||
fn score(&self, name: &Text) -> f64 {
|
||||
if name.folded.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
if name.folded == self.id || self.labels.iter().any(|l| l.folded == name.folded) {
|
||||
return 1.0;
|
||||
}
|
||||
let by_words = self.labels.iter().map(|l| word_overlap(&name.words, &l.words)).fold(word_overlap(&name.words, &self.id_words), f64::max);
|
||||
let by_pairs = self.labels.iter().map(|l| pair_similarity(&name.pairs, &l.pairs)).fold(0.0, f64::max);
|
||||
by_words.max(by_pairs * 0.9)
|
||||
}
|
||||
}
|
||||
|
||||
/// How well `name` fits `candidate` (0 to 1): 1 when it equals a label or the id, its letters and
|
||||
/// digits compared without case; else the best of word overlap and character-pair similarity, the
|
||||
/// latter counted a little lower. Only the first [`MAX_NAME_CHARS`] characters of the name and
|
||||
/// of each label count.
|
||||
pub fn score(name: &str, candidate: &Candidate) -> f64 {
|
||||
Prepared::of(candidate).score(&Text::of(name))
|
||||
}
|
||||
|
||||
/// The candidate `name` stands for, when one scores at least 0.6 and 0.1 ahead of every other; else
|
||||
/// the best five that score at least 0.3, to choose from.
|
||||
pub fn propose(name: &str, candidates: &[Candidate]) -> Proposal {
|
||||
Matcher::new(candidates).propose(name)
|
||||
}
|
||||
|
||||
/// [`propose`] for many names against the same candidates: each candidate's words and character
|
||||
/// pairs are worked out once, and a name is scored only against the candidates that share a word or
|
||||
/// a character pair with it (the others score 0).
|
||||
pub struct Matcher {
|
||||
prepared: Vec<Prepared>,
|
||||
/// Candidates by their joined id words and their labels' letters and digits.
|
||||
exact: HashMap<String, Vec<usize>>,
|
||||
/// Candidates by a word of their id or labels.
|
||||
by_word: HashMap<String, Vec<usize>>,
|
||||
/// Candidates by a character pair of their labels.
|
||||
by_pair: HashMap<(char, char), Vec<usize>>,
|
||||
}
|
||||
|
||||
impl Matcher {
|
||||
/// Prepares `candidates` once for many [`Matcher::propose`] calls.
|
||||
pub fn new(candidates: &[Candidate]) -> Self {
|
||||
let prepared: Vec<Prepared> = candidates.iter().map(Prepared::of).collect();
|
||||
let (mut exact, mut by_word, mut by_pair) = (HashMap::new(), HashMap::new(), HashMap::new());
|
||||
fn add<K: std::hash::Hash + Eq>(map: &mut HashMap<K, Vec<usize>>, key: K, i: usize) {
|
||||
let list = map.entry(key).or_default();
|
||||
if list.last() != Some(&i) {
|
||||
list.push(i);
|
||||
}
|
||||
}
|
||||
for (i, p) in prepared.iter().enumerate() {
|
||||
add(&mut exact, p.id.clone(), i);
|
||||
for l in &p.labels {
|
||||
add(&mut exact, l.folded.clone(), i);
|
||||
}
|
||||
for w in p.id_words.iter().chain(p.labels.iter().flat_map(|l| &l.words)) {
|
||||
add(&mut by_word, w.clone(), i);
|
||||
}
|
||||
for pair in p.labels.iter().flat_map(|l| &l.pairs) {
|
||||
add(&mut by_pair, *pair, i);
|
||||
}
|
||||
}
|
||||
Self { prepared, exact, by_word, by_pair }
|
||||
}
|
||||
|
||||
/// See [`propose`].
|
||||
pub fn propose(&self, name: &str) -> Proposal {
|
||||
let text = Text::of(name);
|
||||
let mut seen = vec![false; self.prepared.len()];
|
||||
let lists = self
|
||||
.exact
|
||||
.get(&text.folded)
|
||||
.into_iter()
|
||||
.chain(text.words.iter().filter_map(|w| self.by_word.get(w)))
|
||||
// Each pair looked up once (they are sorted).
|
||||
.chain(text.pairs.chunk_by(|a, b| a == b).filter_map(|c| self.by_pair.get(c.first()?)));
|
||||
let mut scored: Vec<(usize, f64)> = vec![];
|
||||
for &i in lists.flatten() {
|
||||
if let Some(s) = seen.get_mut(i)
|
||||
&& !*s
|
||||
{
|
||||
*s = true;
|
||||
let score = self.prepared.get(i).map_or(0.0, |p| p.score(&text));
|
||||
if score >= CHOICE_FLOOR {
|
||||
scored.push((i, score));
|
||||
}
|
||||
}
|
||||
}
|
||||
scored.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0)));
|
||||
match (scored.first(), scored.get(1)) {
|
||||
(Some(&(i, best)), next) if best >= THRESHOLD && next.is_none_or(|n| best - n.1 >= MARGIN) => Proposal::Match(i, best),
|
||||
_ => Proposal::Choice(scored.iter().take(CHOICES).map(|(i, _)| *i).collect()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn candidates(list: &[(&str, &str)]) -> Vec<Candidate> {
|
||||
list.iter().map(|(id, label)| Candidate { id: id.to_string(), labels: vec![label.to_string()] }).collect()
|
||||
}
|
||||
|
||||
fn proposed<'a>(name: &str, list: &'a [Candidate]) -> Option<&'a str> {
|
||||
match propose(name, list) {
|
||||
Proposal::Match(i, _) => list.get(i).map(|c| c.id.as_str()),
|
||||
Proposal::Choice(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_words_still_find_the_tool() {
|
||||
let tools = candidates(&[
|
||||
("tool:rectangle", "Rectangle Tool"),
|
||||
("tool:roundedRectangle", "Rounded Rectangle Tool"),
|
||||
("tool:rectangularGrid", "Rectangular Grid Tool"),
|
||||
("tool:ellipse", "Ellipse Tool"),
|
||||
]);
|
||||
assert_eq!(proposed("Acme Rectangle Tool", &tools), Some("tool:rectangle"));
|
||||
assert_eq!(proposed("Rounded Rectangle", &tools), Some("tool:roundedRectangle"));
|
||||
assert_eq!(proposed("ellipse tool", &tools), Some("tool:ellipse"), "case aside, the label itself");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn letters_only_names_match_ids() {
|
||||
let commands = candidates(&[("acme.copyAll", "Everything"), ("acme.copyAllOnPage", "Everything on This Page"), ("acme.clear", "Clear Out")]);
|
||||
assert_eq!(proposed("acmecopyall", &commands), Some("acme.copyAll"));
|
||||
assert_eq!(proposed("Acme Copy All On Page", &commands), Some("acme.copyAllOnPage"));
|
||||
assert_eq!(proposed("clear out", &commands), Some("acme.clear"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ties_need_a_choice() {
|
||||
let tools = candidates(&[("tool:rectangle", "Rectangle Tool"), ("tool:ellipse", "Ellipse Tool"), ("tool:star", "Star Tool")]);
|
||||
assert_eq!(propose("Tool", &tools), Proposal::Choice(vec![0, 1, 2]));
|
||||
assert_eq!(propose("Nothing Alike", &tools), Proposal::Choice(vec![]));
|
||||
assert_eq!(propose("", &tools), Proposal::Choice(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_without_spaces_match_by_character_pairs() {
|
||||
let list = vec![
|
||||
Candidate { id: "tool:rectangle".into(), labels: vec!["Rectangle Tool".into(), "長方形ツール".into()] },
|
||||
Candidate { id: "tool:ellipse".into(), labels: vec!["Ellipse Tool".into(), "楕円形ツール".into()] },
|
||||
];
|
||||
assert_eq!(proposed("長方形ツール", &list), Some("tool:rectangle"));
|
||||
assert_eq!(proposed("楕円形 ツール", &list), Some("tool:ellipse"), "spaces and punctuation aside");
|
||||
assert_eq!(proposed("楕円形ツール2", &list), Some("tool:ellipse"), "most character pairs shared");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_index_finds_what_scoring_every_candidate_finds() {
|
||||
let list = candidates(&[
|
||||
("tool:rectangle", "Rectangle Tool"),
|
||||
("tool:roundedRectangle", "Rounded Rectangle Tool"),
|
||||
("tool:ellipse", "Ellipse Tool"),
|
||||
("select.all", "All"),
|
||||
("select.none", "Deselect"),
|
||||
("edit.undo", "Undo"),
|
||||
("foo.bar", "Zzz"),
|
||||
("panel:layers", "Layers"),
|
||||
]);
|
||||
let matcher = Matcher::new(&list);
|
||||
for name in ["Acme Rectangle Tool", "rounded", "acmecopyall", "foobar", "zz", "Lay", "Undo Redo", "ツール", "", "e"] {
|
||||
let mut scored: Vec<(usize, f64)> =
|
||||
list.iter().enumerate().map(|(i, c)| (i, score(name, c))).filter(|(_, s)| *s >= CHOICE_FLOOR).collect();
|
||||
scored.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0)));
|
||||
let every = match (scored.first(), scored.get(1)) {
|
||||
(Some(&(i, best)), next) if best >= THRESHOLD && next.is_none_or(|n| best - n.1 >= MARGIN) => Proposal::Match(i, best),
|
||||
_ => Proposal::Choice(scored.iter().take(CHOICES).map(|(i, _)| *i).collect()),
|
||||
};
|
||||
assert_eq!(matcher.propose(name), every, "{name}");
|
||||
}
|
||||
assert_eq!(proposed("foobar", &list), Some("foo.bar"), "the id alone, sharing no word or pair with the label");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_head_of_a_long_name_counts() {
|
||||
let label: String = "ä€𝄞b".repeat(50);
|
||||
let candidate = Candidate { id: "acme.long".into(), labels: vec![label.clone()] };
|
||||
assert_eq!(head(&label).chars().count(), MAX_NAME_CHARS);
|
||||
assert_eq!(score(&format!("{label}and more words after the head"), &candidate), 1.0);
|
||||
assert_eq!(head("short"), "short");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn words_split_camel_case_and_separators() {
|
||||
assert_eq!(words("selectAll_onArtboard 2x"), ["select", "all", "on", "artboard", "2x"]);
|
||||
assert_eq!(words("Acme\u{a0}Lasso-Tool"), ["acme", "lasso", "tool"]);
|
||||
assert_eq!(id_words("tool:roundedRectangle"), ["rounded", "rectangle"]);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,370 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
|
||||
use serde::de::{self, IgnoredAny, MapAccess, SeqAccess, Visitor};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{DropReason, MAX_BINDING_TEXT, MAX_BINDINGS, MAX_COMMANDS, Problem};
|
||||
use crate::command::MAX_KEY;
|
||||
|
||||
// Load notes are kept for `Keymap::problems`; a hostile file must not grow them without bound.
|
||||
const MAX_NOTES: usize = 64;
|
||||
|
||||
/// The user's changes to the default bindings: binding key → the full list of binding texts
|
||||
/// that replaces the command's defaults (`[]` = no shortcut).
|
||||
///
|
||||
/// Stored in key order as a map of one text per command (`{ "<key>": "Cmd+K" }`, `""` for no
|
||||
/// shortcut) while no entry has more than one text, and otherwise as an array of
|
||||
/// `{ command, keys }` items. [`list`] always writes the array, for craft-settings files. Both
|
||||
/// forms load, and in the map form a list of texts loads too. Loading never fails:
|
||||
/// entries for unknown commands and texts that do not parse are kept verbatim; values that are not
|
||||
/// text, overlong keys and texts, repeated keys (the first entry stays) and entries past the caps
|
||||
/// are dropped, and a value that is neither a list nor a map loads as no overrides. All of these
|
||||
/// are reported by [`Keymap::problems`](super::Keymap::problems).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Overrides {
|
||||
map: BTreeMap<String, Vec<String>>,
|
||||
notes: Vec<Problem>,
|
||||
}
|
||||
|
||||
impl PartialEq for Overrides {
|
||||
fn eq(&self, other: &Overrides) -> bool {
|
||||
self.map == other.map
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Overrides {}
|
||||
|
||||
impl Overrides {
|
||||
pub const fn new() -> Overrides {
|
||||
Overrides { map: BTreeMap::new(), notes: Vec::new() }
|
||||
}
|
||||
|
||||
pub fn get(&self, key: &str) -> Option<&[String]> {
|
||||
self.map.get(key).map(Vec::as_slice)
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> impl Iterator<Item = (&str, &[String])> {
|
||||
self.map.iter().map(|(k, v)| (k.as_str(), v.as_slice()))
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.map.is_empty()
|
||||
}
|
||||
|
||||
/// Sets an entry verbatim. `false` (and nothing stored) for a key over [`MAX_KEY`] bytes, a
|
||||
/// list over [`MAX_BINDINGS`], a text over [`MAX_BINDING_TEXT`] bytes, or a new key past
|
||||
/// [`MAX_COMMANDS`] entries.
|
||||
pub fn insert(&mut self, key: impl Into<String>, texts: Vec<String>) -> bool {
|
||||
let key = key.into();
|
||||
let fits = key.len() <= MAX_KEY
|
||||
&& texts.len() <= MAX_BINDINGS
|
||||
&& texts.iter().all(|t| t.len() <= MAX_BINDING_TEXT)
|
||||
&& (self.map.contains_key(&key) || self.map.len() < MAX_COMMANDS);
|
||||
if fits {
|
||||
self.map.insert(key, texts);
|
||||
}
|
||||
fits
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, key: &str) -> Option<Vec<String>> {
|
||||
self.map.remove(key)
|
||||
}
|
||||
|
||||
/// Removes every entry: all commands get their defaults.
|
||||
pub fn clear(&mut self) {
|
||||
self.map.clear();
|
||||
self.notes.clear();
|
||||
}
|
||||
|
||||
/// What loading dropped.
|
||||
pub fn load_notes(&self) -> &[Problem] {
|
||||
&self.notes
|
||||
}
|
||||
|
||||
fn note(&mut self, problem: Problem) {
|
||||
if self.notes.len() < MAX_NOTES {
|
||||
self.notes.push(problem);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The map form is what apps that store one text per command read, so a file stays readable by
|
||||
// their older builds while no command has more than one binding.
|
||||
impl Serialize for Overrides {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
if self.map.values().all(|keys| single(keys).is_some()) {
|
||||
serializer.collect_map(self.map.iter().map(|(command, keys)| (command, single(keys).unwrap_or_default())))
|
||||
} else {
|
||||
list::serialize(self, serializer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An entry's text in the map form: `""` for no shortcut. `None` for several texts, and for one
|
||||
/// blank text, which the map form reads as no shortcut.
|
||||
fn single(keys: &[String]) -> Option<&str> {
|
||||
match keys {
|
||||
[] => Some(""),
|
||||
[text] if !text.trim().is_empty() => Some(text.as_str()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Serializes [`Overrides`] always as an array of `{ command, keys }` items, for
|
||||
/// `#[serde(with = "craft_keymap::keymap::overrides_list")]`. craft-settings merges a table key
|
||||
/// by key with what the file holds but replaces an array whole, so in a craft-settings file only
|
||||
/// this form lets a reset command (an entry removed) stay removed after saving.
|
||||
pub mod list {
|
||||
use serde::{Deserialize, Deserializer, Serializer};
|
||||
|
||||
use super::{Item, Overrides};
|
||||
|
||||
pub fn serialize<S: Serializer>(overrides: &Overrides, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.collect_seq(overrides.map.iter().map(|(command, keys)| Item { command, keys }))
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Overrides, D::Error> {
|
||||
Overrides::deserialize(deserializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Item<'a> {
|
||||
command: &'a str,
|
||||
keys: &'a [String],
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Overrides {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Overrides, D::Error> {
|
||||
deserializer.deserialize_any(OverridesVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
struct OverridesVisitor;
|
||||
|
||||
/// Collects entries with the caps applied.
|
||||
#[derive(Default)]
|
||||
struct Builder {
|
||||
out: Overrides,
|
||||
ignored: usize,
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
/// Whether an entry for `key` can be stored; notes why not.
|
||||
fn admits(&mut self, key: &str) -> bool {
|
||||
if key.len() > MAX_KEY {
|
||||
self.out.note(Problem::Dropped { key: clip(key, MAX_KEY), reason: DropReason::KeyTooLong });
|
||||
return false;
|
||||
}
|
||||
if self.out.map.len() >= MAX_COMMANDS && !self.out.map.contains_key(key) {
|
||||
self.ignored += 1;
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Stores an entry; a second entry for the same key is ignored and noted.
|
||||
fn add(&mut self, key: String, value: Lenient) {
|
||||
let out = &mut self.out;
|
||||
if out.map.contains_key(&key) {
|
||||
out.note(Problem::DuplicateKey { key });
|
||||
return;
|
||||
}
|
||||
let texts = match value {
|
||||
Lenient::List { texts, other, extra } => {
|
||||
if other {
|
||||
out.note(Problem::Dropped { key: key.clone(), reason: DropReason::NotText });
|
||||
}
|
||||
if extra > 0 {
|
||||
out.note(Problem::Dropped { key: key.clone(), reason: DropReason::TooManyBindings });
|
||||
}
|
||||
texts
|
||||
}
|
||||
Lenient::Text(t) => vec![t],
|
||||
Lenient::Other => {
|
||||
out.note(Problem::Dropped { key, reason: DropReason::NotAList });
|
||||
return;
|
||||
}
|
||||
};
|
||||
let (texts, long): (Vec<String>, Vec<String>) = texts.into_iter().partition(|t| t.len() <= MAX_BINDING_TEXT);
|
||||
if !long.is_empty() {
|
||||
out.note(Problem::Dropped { key: key.clone(), reason: DropReason::TextTooLong });
|
||||
}
|
||||
out.map.insert(key, texts);
|
||||
}
|
||||
|
||||
fn finish(mut self) -> Overrides {
|
||||
if self.ignored > 0 {
|
||||
let ignored = self.ignored;
|
||||
self.out.note(Problem::TooManyCommands { ignored });
|
||||
}
|
||||
self.out
|
||||
}
|
||||
}
|
||||
|
||||
/// No overrides, with a note that the value was not a list or map.
|
||||
fn not_a_list() -> Overrides {
|
||||
let mut out = Overrides::new();
|
||||
out.note(Problem::Dropped { key: String::new(), reason: DropReason::NotAList });
|
||||
out
|
||||
}
|
||||
|
||||
macro_rules! not_a_list {
|
||||
($($name:ident: $t:ty),*) => {
|
||||
$(fn $name<E: de::Error>(self, _: $t) -> Result<Overrides, E> {
|
||||
Ok(not_a_list())
|
||||
})*
|
||||
};
|
||||
}
|
||||
|
||||
impl<'de> Visitor<'de> for OverridesVisitor {
|
||||
type Value = Overrides;
|
||||
|
||||
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("a list of `{ command, keys }` items or a map of binding keys to binding texts")
|
||||
}
|
||||
|
||||
not_a_list!(visit_bool: bool, visit_i64: i64, visit_u64: u64, visit_i128: i128, visit_u128: u128, visit_f64: f64, visit_str: &str, visit_bytes: &[u8], visit_char: char);
|
||||
|
||||
fn visit_unit<E: de::Error>(self) -> Result<Overrides, E> {
|
||||
Ok(not_a_list())
|
||||
}
|
||||
|
||||
fn visit_none<E: de::Error>(self) -> Result<Overrides, E> {
|
||||
Ok(not_a_list())
|
||||
}
|
||||
|
||||
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Overrides, D::Error> {
|
||||
deserializer.deserialize_any(OverridesVisitor)
|
||||
}
|
||||
|
||||
/// The array form, `[{ command = "…", keys = […] }, …]`.
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Overrides, A::Error> {
|
||||
let mut b = Builder::default();
|
||||
while let Some(item) = access.next_element::<Value>()? {
|
||||
let command = item.get("command").and_then(Value::as_str);
|
||||
let keys = item.get("keys").map(Lenient::deserialize).and_then(Result::ok);
|
||||
match (command, keys) {
|
||||
(Some(command), Some(keys)) => {
|
||||
if b.admits(command) {
|
||||
b.add(command.to_string(), keys);
|
||||
}
|
||||
}
|
||||
(command, _) => {
|
||||
let key = clip(command.unwrap_or_default(), MAX_KEY);
|
||||
b.out.note(Problem::Dropped { key, reason: DropReason::NotAList });
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(b.finish())
|
||||
}
|
||||
|
||||
/// The map form, binding key → texts (hand edits, older files). An empty text means no
|
||||
/// shortcut, as in the apps that store one text per command and `""` for a removed shortcut.
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Overrides, A::Error> {
|
||||
let mut b = Builder::default();
|
||||
while let Some(key) = access.next_key::<String>()? {
|
||||
if b.admits(&key) {
|
||||
let value = match access.next_value::<Lenient>()? {
|
||||
Lenient::Text(t) if t.trim().is_empty() => Lenient::List { texts: Vec::new(), other: false, extra: 0 },
|
||||
Lenient::List { mut texts, other, extra } => {
|
||||
texts.retain(|t| !t.trim().is_empty());
|
||||
Lenient::List { texts, other, extra }
|
||||
}
|
||||
value => value,
|
||||
};
|
||||
b.add(key, value);
|
||||
} else {
|
||||
access.next_value::<IgnoredAny>()?;
|
||||
}
|
||||
}
|
||||
Ok(b.finish())
|
||||
}
|
||||
}
|
||||
|
||||
/// Cuts `s` to at most `max` bytes on a char boundary.
|
||||
pub(crate) fn clip(s: &str, max: usize) -> String {
|
||||
let mut end = s.len().min(max);
|
||||
while !s.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
s[..end].to_string()
|
||||
}
|
||||
|
||||
/// An entry's value as found: a list (texts kept up to the cap), one text, or anything else.
|
||||
enum Lenient {
|
||||
List { texts: Vec<String>, other: bool, extra: usize },
|
||||
Text(String),
|
||||
Other,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Lenient {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Lenient, D::Error> {
|
||||
deserializer.deserialize_any(LenientVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
struct LenientVisitor;
|
||||
|
||||
macro_rules! other {
|
||||
($($name:ident: $t:ty),*) => {
|
||||
$(fn $name<E: de::Error>(self, _: $t) -> Result<Lenient, E> {
|
||||
Ok(Lenient::Other)
|
||||
})*
|
||||
};
|
||||
}
|
||||
|
||||
impl<'de> Visitor<'de> for LenientVisitor {
|
||||
type Value = Lenient;
|
||||
|
||||
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("a list of binding texts")
|
||||
}
|
||||
|
||||
fn visit_str<E: de::Error>(self, v: &str) -> Result<Lenient, E> {
|
||||
Ok(Lenient::Text(v.to_string()))
|
||||
}
|
||||
|
||||
fn visit_string<E: de::Error>(self, v: String) -> Result<Lenient, E> {
|
||||
Ok(Lenient::Text(v))
|
||||
}
|
||||
|
||||
other!(visit_bool: bool, visit_i64: i64, visit_u64: u64, visit_i128: i128, visit_u128: u128, visit_f64: f64, visit_bytes: &[u8], visit_char: char);
|
||||
|
||||
fn visit_unit<E: de::Error>(self) -> Result<Lenient, E> {
|
||||
Ok(Lenient::Other)
|
||||
}
|
||||
|
||||
fn visit_none<E: de::Error>(self) -> Result<Lenient, E> {
|
||||
Ok(Lenient::Other)
|
||||
}
|
||||
|
||||
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Lenient, D::Error> {
|
||||
deserializer.deserialize_any(LenientVisitor)
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Lenient, A::Error> {
|
||||
while access.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
|
||||
Ok(Lenient::Other)
|
||||
}
|
||||
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Lenient, A::Error> {
|
||||
let mut texts = Vec::new();
|
||||
let mut other = false;
|
||||
let mut extra = 0usize;
|
||||
while let Some(item) = access.next_element::<Lenient>()? {
|
||||
match item {
|
||||
Lenient::Text(t) if texts.len() < MAX_BINDINGS => texts.push(t),
|
||||
Lenient::Text(_) => extra += 1,
|
||||
_ => other = true,
|
||||
}
|
||||
}
|
||||
Ok(Lenient::List { texts, other, extra })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
//! Which chord a key press means on the active keyboard layout, and the layout's own characters
|
||||
//! for labels.
|
||||
//!
|
||||
//! One rule decides matching ([`Layout::candidates`]), recording ([`Layout::resolve`]) and labels
|
||||
//! ([`Chord::display_for`]):
|
||||
//! 1. **Letters A–Z:** the layout's Latin letter for the key, from [`KeyInput::latin`] when the
|
||||
//! platform reports the Latin layout's character: on Dvorak + Russian the `с` key is Dvorak's
|
||||
//! J, and the `й` key, `'` on Dvorak, runs no letter binding. Without a report, on a layout
|
||||
//! that is not Latin, the letter the toolkit reports as typed, else the key's position (the
|
||||
//! Russian `с` key is C, the Hebrew `/` key is Q); on a Latin layout (Dvorak, AZERTY), the
|
||||
//! letter typed.
|
||||
//! 2. **Digits:** the digit typed, else the key's position (AZERTY's `&é"` row types no digit
|
||||
//! without Shift). A digit-row press that types punctuation also matches its position's digit,
|
||||
//! after the punctuation: AZERTY's `-` key runs Ctrl+- and, when that has no binding, Ctrl+6.
|
||||
//! 3. **Punctuation:** the character typed, without Shift when the layout needs Shift for it
|
||||
//! (German `/` is ⇧7, so ⇧⌘7 is ⌘/; US `:` is ⇧;, so ⇧; is `:`). A Shift binding on a US
|
||||
//! base key also matches the same press (`Shift+;` matches `:`), and `=` and `+` stand for
|
||||
//! each other so zoom keys work with and without Shift.
|
||||
//! 4. **Whether a layout is Latin** is decided for the whole layout ([`Layout::is_latin`]), never
|
||||
//! per key: Dvorak's `'` key on the Q position stays `'`.
|
||||
//! 5. **No position fallback for unnamed characters on moved keys:** egui reports a character
|
||||
//! that has no key (Dvorak's ⇧, types `<`) as the key's position, W. With Shift held on a
|
||||
//! Latin layout, such a press at a letter position that has been seen typing something other
|
||||
//! than its letter resolves to nothing, so Ctrl+Shift+, never runs Ctrl+Shift+W once a `,`
|
||||
//! has been typed. A change in the reported Latin status, or [`Layout::forget_letters`],
|
||||
//! clears what the positions typed.
|
||||
//! 6. **Labels** show letters and digits by name, and a punctuation key as the character the
|
||||
//! layout types at its position when that character has no key of its own: Ctrl+[ is `Ctrl+Ü`
|
||||
//! on German and `Ctrl+Х` on Russian.
|
||||
//!
|
||||
//! [`KeyInput`] carries what the toolkit reports for one press; toolkits that learn more from the
|
||||
//! platform fill more of it. [`Layout`] holds what is known about the layout itself, reported by
|
||||
//! the platform or learned from what plain typing produces ([`Layout::observe`]).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::chord::{Chord, Key, Mods, Platform};
|
||||
|
||||
/// What the toolkit reports about one key press.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct KeyInput {
|
||||
/// The modifiers held, read for the platform as [`Mods`] describes.
|
||||
pub mods: Mods,
|
||||
/// The key for the character the layout typed with `mods` held, when there is one (egui's
|
||||
/// logical key).
|
||||
pub typed: Option<Key>,
|
||||
/// The key at the same position on a US QWERTY keyboard (winit's physical key, the web's
|
||||
/// `code`).
|
||||
pub physical: Option<Key>,
|
||||
/// The character this key types on the layout the platform takes shortcut letters from, when
|
||||
/// it reports one: the layout's ⌘ table on macOS, the first Latin layout group on Linux. A
|
||||
/// letter makes the press that letter; any other character means the key has no Latin letter,
|
||||
/// so the press runs no letter binding (Dvorak's `'` on the key Russian types `й` on is no
|
||||
/// Ctrl+Q).
|
||||
pub latin: Option<char>,
|
||||
/// Whether the layout needs Shift to type `typed`, when the platform reports it. Otherwise
|
||||
/// Shift counts as needed when `typed` differs from `physical`, and without `physical` when
|
||||
/// `typed` is a shifted symbol on a US layout (`:`, `?`, `+`). Only punctuation drops Shift.
|
||||
pub shift_needed: Option<bool>,
|
||||
}
|
||||
|
||||
impl KeyInput {
|
||||
pub const fn new(mods: Mods) -> KeyInput {
|
||||
KeyInput { mods, typed: None, physical: None, latin: None, shift_needed: None }
|
||||
}
|
||||
|
||||
pub const fn with_typed(mut self, key: Key) -> KeyInput {
|
||||
self.typed = Some(key);
|
||||
self
|
||||
}
|
||||
|
||||
pub const fn with_physical(mut self, key: Key) -> KeyInput {
|
||||
self.physical = Some(key);
|
||||
self
|
||||
}
|
||||
|
||||
pub const fn with_latin(mut self, c: char) -> KeyInput {
|
||||
self.latin = Some(c);
|
||||
self
|
||||
}
|
||||
|
||||
pub const fn with_shift_needed(mut self, needed: bool) -> KeyInput {
|
||||
self.shift_needed = Some(needed);
|
||||
self
|
||||
}
|
||||
|
||||
fn needs_shift(&self, typed: Key) -> bool {
|
||||
// A shifted symbol is no key position (egui's numeric keypad Plus is the one physical
|
||||
// key among them), so it says nothing about the Shift level.
|
||||
self.shift_needed.unwrap_or(match self.physical {
|
||||
Some(physical) if us_base(physical).is_none() => physical != typed,
|
||||
_ => us_base(typed).is_some(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The active keyboard layout, as far as the platform reports it or typing has shown it.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Layout {
|
||||
reported_latin: Option<bool>,
|
||||
seen_latin: Option<bool>,
|
||||
/// The character typed without modifiers at each punctuation position.
|
||||
chars: BTreeMap<Key, char>,
|
||||
/// The character, lower case, typed without Cmd, Ctrl or Alt at each letter position.
|
||||
letters: BTreeMap<Key, char>,
|
||||
}
|
||||
|
||||
/// US base keys and the key egui reports for them with Shift held.
|
||||
const SHIFTED: &[(Key, Key)] = &[
|
||||
(Key::Semicolon, Key::Colon),
|
||||
(Key::Slash, Key::Questionmark),
|
||||
(Key::Backslash, Key::Pipe),
|
||||
(Key::OpenBracket, Key::OpenCurlyBracket),
|
||||
(Key::CloseBracket, Key::CloseCurlyBracket),
|
||||
(Key::Equals, Key::Plus),
|
||||
(Key::Num1, Key::Exclamationmark),
|
||||
];
|
||||
|
||||
fn us_base(shifted: Key) -> Option<Key> {
|
||||
SHIFTED.iter().find(|&&(_, s)| s == shifted).map(|&(b, _)| b)
|
||||
}
|
||||
|
||||
const fn without_shift(m: Mods) -> Mods {
|
||||
Mods { shift: false, ..m }
|
||||
}
|
||||
|
||||
/// Letters of the Latin script: ASCII, Latin-1, Latin Extended-A and -B, Latin Extended
|
||||
/// Additional.
|
||||
fn is_latin_letter(c: char) -> bool {
|
||||
c.is_alphabetic() && matches!(c, 'A'..='Z' | 'a'..='z' | '\u{00C0}'..='\u{024F}' | '\u{1E00}'..='\u{1EFF}')
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
/// Nothing known yet: the layout counts as Latin until the platform or typing says otherwise.
|
||||
pub fn new() -> Layout {
|
||||
Layout::default()
|
||||
}
|
||||
|
||||
/// Whether the layout is Latin, as the platform reports it.
|
||||
pub fn with_latin(mut self, latin: bool) -> Layout {
|
||||
self.reported_latin = Some(latin);
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the layout is Latin, as the platform reports it; `None` when it cannot tell, so
|
||||
/// that typing decides. Call again when the user switches layouts. A report that differs
|
||||
/// from the last one means another layout, so what letter positions typed is forgotten
|
||||
/// ([`forget_letters`](Self::forget_letters)).
|
||||
pub fn set_latin(&mut self, latin: Option<bool>) {
|
||||
if latin != self.reported_latin {
|
||||
self.forget_letters();
|
||||
}
|
||||
self.reported_latin = latin;
|
||||
}
|
||||
|
||||
/// Forgets what each letter position has been seen typing, for an app that learns of a
|
||||
/// layout switch the platform does not report: until typing shows the new layout, Shift
|
||||
/// presses at letter positions resolve as their letters again (rule 5).
|
||||
pub fn forget_letters(&mut self) {
|
||||
self.letters.clear();
|
||||
}
|
||||
|
||||
/// Whether letters are read as typed (rule 1): what the platform reported, else what a letter
|
||||
/// key typed last, else true.
|
||||
pub fn is_latin(&self) -> bool {
|
||||
self.reported_latin.or(self.seen_latin).unwrap_or(true)
|
||||
}
|
||||
|
||||
/// The character the layout types without modifiers at the punctuation position `physical`.
|
||||
pub fn with_char(mut self, physical: Key, typed: char) -> Layout {
|
||||
self.set_char(physical, typed);
|
||||
self
|
||||
}
|
||||
|
||||
/// See [`with_char`](Self::with_char). Positions other than punctuation are ignored.
|
||||
pub fn set_char(&mut self, physical: Key, typed: char) {
|
||||
if physical.is_symbol() {
|
||||
self.chars.insert(physical, typed);
|
||||
}
|
||||
}
|
||||
|
||||
/// The character known to be typed without modifiers at the punctuation position `physical`.
|
||||
pub fn char_at(&self, physical: Key) -> Option<char> {
|
||||
self.chars.get(&physical).copied()
|
||||
}
|
||||
|
||||
/// Learns from a press at `physical` with `mods` held that typed `text`: a letter typed at a
|
||||
/// letter position tells whether the layout is Latin, and a character typed without
|
||||
/// modifiers at a punctuation position is that position's label. Presses with Cmd, Ctrl or
|
||||
/// Alt, and text longer than one character, teach nothing.
|
||||
pub fn observe(&mut self, physical: Key, mods: Mods, text: &str) {
|
||||
let mut chars = text.chars();
|
||||
let (Some(c), None) = (chars.next(), chars.next()) else { return };
|
||||
if mods.cmd || mods.ctrl || mods.alt {
|
||||
return;
|
||||
}
|
||||
if physical.is_letter() {
|
||||
// ª, µ and º are Latin-1 symbols on Latin layouts, no sign of another script.
|
||||
if c.is_alphabetic() && !matches!(c, 'ª' | 'µ' | 'º') {
|
||||
self.seen_latin = Some(is_latin_letter(c));
|
||||
}
|
||||
if !c.is_control() {
|
||||
self.letters.insert(physical, c.to_lowercase().next().unwrap_or(c));
|
||||
}
|
||||
} else if !mods.shift && !c.is_control() {
|
||||
self.set_char(physical, c);
|
||||
}
|
||||
}
|
||||
|
||||
/// The chord a press means, as the shortcut recorder records it and lookups try first.
|
||||
/// `None` when the press names no key.
|
||||
pub fn resolve(&self, input: &KeyInput) -> Option<Chord> {
|
||||
let held = input.mods;
|
||||
let latin = input.latin.map(|c| Key::from_char(c).filter(|k| k.is_letter()));
|
||||
if let Some(Some(letter)) = latin {
|
||||
return Some(Chord::new(held, letter));
|
||||
}
|
||||
// A letter typed on a layout that is not Latin is the toolkit's letter for shortcuts, or
|
||||
// egui standing in the position for a letter it has no key for.
|
||||
if latin.is_none()
|
||||
&& !self.is_latin()
|
||||
&& let Some(letter) = input.typed.filter(|k| k.is_letter()).or(input.physical).filter(|k| k.is_letter())
|
||||
{
|
||||
return Some(Chord::new(held, letter));
|
||||
}
|
||||
if held.shift
|
||||
&& let Some(position) = input.physical.filter(|k| k.is_letter())
|
||||
&& input.typed.is_none_or(|typed| typed == position)
|
||||
&& !self.types_own_letter(position)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut key = input.typed.or(input.physical)?;
|
||||
// The Latin layout has no letter here, so a letter egui reports is its position: the
|
||||
// press is the Latin layout's key, or nothing.
|
||||
if let (Some(c), true) = (input.latin, key.is_letter()) {
|
||||
key = Key::from_char(c)?;
|
||||
}
|
||||
let drop_shift = held.shift && key.is_symbol() && input.needs_shift(key);
|
||||
Some(Chord::new(if drop_shift { without_shift(held) } else { held }, key))
|
||||
}
|
||||
|
||||
/// Rule 5: whether a press reported as the letter at its own position can be that letter:
|
||||
/// no only when the position has been seen typing something else, so the press likely typed
|
||||
/// a character egui has no key for.
|
||||
fn types_own_letter(&self, position: Key) -> bool {
|
||||
self.letters.get(&position).is_none_or(|&c| Key::from_char(c) == Some(position))
|
||||
}
|
||||
|
||||
/// The chords a press can run, most specific first: [`resolve`](Self::resolve)'s chord, the
|
||||
/// same press written as Shift with a US base key (`Shift+;` for `:`), `=` for `+` and `+`
|
||||
/// for Shift+`=`, and on the digit row the position's digit.
|
||||
pub fn candidates(&self, input: &KeyInput) -> Vec<Chord> {
|
||||
let Some(first) = self.resolve(input) else { return Vec::new() };
|
||||
let mut out = Vec::with_capacity(4);
|
||||
let mut push = |chord: Chord| {
|
||||
if !out.contains(&chord) {
|
||||
out.push(chord);
|
||||
}
|
||||
};
|
||||
push(first);
|
||||
if input.mods.shift
|
||||
&& !first.mods.shift
|
||||
&& let Some(base) = us_base(first.key)
|
||||
{
|
||||
push(Chord::new(input.mods, base));
|
||||
}
|
||||
match first.key {
|
||||
Key::Plus => push(Chord::new(first.mods, Key::Equals)),
|
||||
Key::Equals if first.mods.shift => push(Chord::new(without_shift(first.mods), Key::Plus)),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(digit) = input.physical.filter(|k| k.is_digit())
|
||||
&& first.key.is_symbol()
|
||||
{
|
||||
push(Chord::new(input.mods, digit));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a press runs `binding` on `platform`: one of its [`candidates`](Self::candidates)
|
||||
/// is the binding.
|
||||
pub fn matches(&self, binding: &Chord, input: &KeyInput, platform: Platform) -> bool {
|
||||
let want = binding.effective(platform);
|
||||
self.candidates(input).iter().any(|c| c.effective(platform) == want)
|
||||
}
|
||||
|
||||
/// Rule 6: the layout's character for the punctuation key `key`, when pressing that position
|
||||
/// means `key` and the layout types `key`'s own character nowhere else that is known.
|
||||
pub(crate) fn key_label(&self, key: Key) -> Option<String> {
|
||||
let typed = self.char_at(key)?;
|
||||
if Key::from_char(typed).is_some() {
|
||||
return None;
|
||||
}
|
||||
let own = key.name().chars().next()?;
|
||||
if self.chars.values().any(|&c| c == own) {
|
||||
return None;
|
||||
}
|
||||
let mut upper = typed.to_uppercase();
|
||||
Some(match (upper.next(), upper.next()) {
|
||||
(Some(u), None) => u.to_string(),
|
||||
_ => typed.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
//! Keyboard bindings for the Craft suite.
|
||||
//!
|
||||
//! [`chord`] holds the key and modifier types, the canonical text form that settings and control
|
||||
//! protocols store, display text per platform, and a reader for other applications' key text.
|
||||
//! [`command`] names what a binding runs, [`scope`] where it works, and [`keymap`] holds an app's
|
||||
//! catalog with default bindings, the user's [`Overrides`], dispatch ([`Keymap::lookup`]),
|
||||
//! editing and conflicts. [`profiles`] keeps named sets of overrides; [`reserved`] lists the
|
||||
//! chords each operating system takes, and a keymap reserves no chord unless the app opts in with
|
||||
//! [`Keymap::with_reserved`], e.g. `with_reserved(reserved::system(platform))`. [`import`] brings
|
||||
//! in other applications' shortcut sets. [`layout`] decides which chord a key press means on the
|
||||
//! user's keyboard layout, for matching, recording and labels. [`editor`] is the model of a
|
||||
//! shortcut editor: undo, a chord recorder, conflict queries and search. With the `egui` feature,
|
||||
//! the `egui` module
|
||||
//! converts to and from egui keys, matches key presses against bindings and dispatches a frame's
|
||||
//! key events.
|
||||
//!
|
||||
//! ```
|
||||
//! use craft_keymap::{Chord, Platform};
|
||||
//!
|
||||
//! let chord = Chord::parse("⇧⌘Z").unwrap();
|
||||
//! assert_eq!(chord.to_string(), "Cmd+Shift+Z");
|
||||
//! assert_eq!(chord.display(Platform::Mac), "⇧⌘Z");
|
||||
//! assert_eq!(chord.display(Platform::Windows), "Ctrl+Shift+Z");
|
||||
//! ```
|
||||
//!
|
||||
//! # A catalog and dispatch
|
||||
//!
|
||||
//! The app lists every command it can bind. A command with parameters has the key
|
||||
//! `window.panel {"panel":"layers"}` in settings and reports. Tools of one group share a key and
|
||||
//! cycle. A binding can name a scope other than the command's home scope.
|
||||
//!
|
||||
//! ```
|
||||
//! use craft_keymap::{Active, Bindable, Binding, Chord, CommandRef, Keymap, Kind, Lookup, Platform, Scope, Scopes};
|
||||
//! use serde_json::json;
|
||||
//!
|
||||
//! let key = |text: &str| Binding::parse(text).unwrap();
|
||||
//! let layers = CommandRef::with_params("window.panel", json!({"panel": "layers"}));
|
||||
//! let select = Kind::Tool { group: Some("select".into()) };
|
||||
//! let catalog = vec![
|
||||
//! Bindable::new("file.save", "Save", Scope::app()).with_path(vec!["File".into(), "Save".into()]).with_default(key("Cmd+S")),
|
||||
//! Bindable::new(layers.clone(), "Layers", Scope::app()).with_path(vec!["Window".into(), "Layers".into()]).with_default(key("F7")),
|
||||
//! Bindable::new("tool.marquee", "Marquee Tool", Scope::app()).with_kind(select.clone()).with_default(key("M")),
|
||||
//! Bindable::new("tool.ellipse", "Elliptical Marquee Tool", Scope::app()).with_kind(select).with_default(key("M")),
|
||||
//! // Home scope: the Timeline panel, where it wins over the app's L.
|
||||
//! Bindable::new("timeline.loop", "Loop", Scope::new("Timeline").unwrap()).with_default(key("L")),
|
||||
//! Bindable::new("layer.lock", "Lock Layer", Scope::app()).with_default(key("L")),
|
||||
//! // An app command whose binding works only in the Text context.
|
||||
//! Bindable::new("type.bold", "Bold", Scope::app()).with_default(key("Text: Cmd+B")),
|
||||
//! ];
|
||||
//! let keymap = Keymap::new(catalog, Scopes::new().with_panel("Timeline").with_context("Text"), Platform::Mac);
|
||||
//! assert_eq!(layers.key(), r#"window.panel {"panel":"layers"}"#);
|
||||
//!
|
||||
//! // Dispatch: the chord pressed, whether it is a double press, and what has the keyboard.
|
||||
//! let press = |text: &str, active: &Active| keymap.lookup(&Chord::parse(text).unwrap(), false, active);
|
||||
//! assert_eq!(press("F7", &Active::NONE), Lookup::Run(layers));
|
||||
//! assert_eq!(press("L", &Active::panel("Timeline")), Lookup::Run("timeline.loop".into()));
|
||||
//! assert_eq!(press("L", &Active::NONE), Lookup::Run("layer.lock".into()));
|
||||
//! assert_eq!(press("M", &Active::NONE), Lookup::Cycle(vec!["tool.marquee".into(), "tool.ellipse".into()]));
|
||||
//! let editing = Active { contexts: &["Text"], typing: true, ..Active::NONE };
|
||||
//! assert_eq!(press("Cmd+B", &editing), Lookup::Run("type.bold".into()));
|
||||
//! assert_eq!(press("M", &editing), Lookup::None, "plain keys go to the text field");
|
||||
//! ```
|
||||
//!
|
||||
//! With the `egui` feature, `egui::Dispatcher` does this for a frame's key events.
|
||||
//!
|
||||
//! # Storing overrides
|
||||
//!
|
||||
//! [`Overrides`] is a field of the app's craft-settings type, marked
|
||||
//! `#[serde(with = "craft_keymap::keymap::overrides_list")]` so that it is stored as an array of
|
||||
//! `{ command, keys }` tables. craft-settings merges tables key by key with what the file holds,
|
||||
//! but replaces an array whole, so a reset command (an entry removed) stays removed after saving.
|
||||
//! Without the attribute, overrides with at most one text per command are written as a table.
|
||||
//!
|
||||
//! ```no_run
|
||||
//! use craft_keymap::{Binding, Keymap, Overrides, Platform, Policy, Scopes};
|
||||
//! use craft_settings::{Location, Settings, SettingsStore};
|
||||
//! use serde::{Deserialize, Serialize};
|
||||
//!
|
||||
//! #[derive(Serialize, Deserialize, Default, Clone, PartialEq)]
|
||||
//! #[serde(default)]
|
||||
//! struct Prefs {
|
||||
//! #[serde(with = "craft_keymap::keymap::overrides_list")]
|
||||
//! shortcuts: Overrides,
|
||||
//! }
|
||||
//!
|
||||
//! impl Settings for Prefs {
|
||||
//! const APP_ID: &'static str = "acmecraft";
|
||||
//! const SCHEMA_VERSION: u32 = 1;
|
||||
//! }
|
||||
//!
|
||||
//! # let catalog = Vec::new();
|
||||
//! let (mut store, _report) = SettingsStore::<Prefs>::open(Location::Auto);
|
||||
//! let mut keymap = Keymap::new(catalog, Scopes::new(), Platform::current()).with_overrides(store.get().shortcuts.clone());
|
||||
//! // Entries for unknown commands and texts that do not parse are kept and listed here.
|
||||
//! let _problems = keymap.problems();
|
||||
//!
|
||||
//! // After each change in the shortcut editor:
|
||||
//! keymap.assign(&"file.save".into(), Binding::parse("Cmd+Alt+S").unwrap(), Policy::Steal).ok();
|
||||
//! store.update(|p| p.shortcuts = keymap.overrides().clone());
|
||||
//! ```
|
||||
//!
|
||||
//! An app with named sets stores only [`Profiles`] in place of the `Overrides` field and builds
|
||||
//! the keymap from the active set:
|
||||
//! `with_overrides(prefs.shortcut_sets.active_overrides(&builtins).clone())`.
|
||||
//!
|
||||
//! # Importing a shortcut set
|
||||
//!
|
||||
//! The app's reader builds a [`ForeignSet`]; [`plan`] matches it without changing anything, so a
|
||||
//! review UI can show [`ImportPlan::commands`] and the report first.
|
||||
//!
|
||||
//! ```
|
||||
//! use craft_keymap::{Bindable, Binding, ContextRule, Flavor, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, Keymap, Platform};
|
||||
//! use craft_keymap::{Scope, Scopes, plan};
|
||||
//!
|
||||
//! let save = Bindable::new("file.save", "Save", Scope::app())
|
||||
//! .with_path(vec!["File".into(), "Save".into()])
|
||||
//! .with_default(Binding::parse("Cmd+S").unwrap());
|
||||
//! let mut keymap = Keymap::new(vec![save], Scopes::new(), Platform::Windows);
|
||||
//!
|
||||
//! let read = |text: &str| ForeignKey::read(Some("Default"), text, Flavor::Windows);
|
||||
//! let set = ForeignSet::new(vec![
|
||||
//! ForeignEntry::new(Some("File"), ["Save"]).with_key(read("Ctrl+Alt+S")).at_line(12),
|
||||
//! ForeignEntry::new(Some("File"), ["Frobnicate"]).with_key(read("Ctrl+F")).at_line(13),
|
||||
//! ])
|
||||
//! .with_name("My Set");
|
||||
//! let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], ..ImportOptions::default() };
|
||||
//! let planned = plan(&set, &keymap, &options);
|
||||
//! assert_eq!(planned.commands.len(), 1);
|
||||
//!
|
||||
//! let report = planned.apply(&mut keymap);
|
||||
//! assert_eq!(report.changed[0].to, ["Cmd+Alt+S"]);
|
||||
//! assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File > Frobnicate", Some(13)));
|
||||
//! assert_eq!(keymap.bindings(&"file.save".into()), [Binding::parse("Cmd+Alt+S").unwrap()]);
|
||||
//! ```
|
||||
|
||||
pub mod chord;
|
||||
pub mod command;
|
||||
pub mod editor;
|
||||
#[cfg(feature = "egui")]
|
||||
pub mod egui;
|
||||
pub mod import;
|
||||
pub mod keymap;
|
||||
pub mod layout;
|
||||
pub mod profiles;
|
||||
pub mod reserved;
|
||||
pub mod scope;
|
||||
#[cfg(feature = "ui")]
|
||||
pub mod ui;
|
||||
|
||||
pub use chord::foreign::Flavor;
|
||||
pub use chord::{Chord, Key, MAX_CHORD_TEXT, Mods, ParseError, Platform, Trigger};
|
||||
pub use command::{CommandRef, MAX_KEY};
|
||||
pub use editor::{DOUBLE_PRESS, EditSession, MAX_UNDO, MAX_UNDO_BYTES, Recorded, Recorder};
|
||||
pub use import::{ContextRule, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportPlan, ImportReport, NoneDefined, Start, plan};
|
||||
pub use keymap::{
|
||||
AssignError, Assigned, Bindable, Binding, BindingError, Conflict, ConflictKind, DropReason, Holder, Keymap, Kind, Lookup, MAX_BINDING_TEXT,
|
||||
MAX_BINDINGS, MAX_COMMANDS, MAX_CONFLICTS, Overrides, Policy, Problem, TypingRule, text_editing_chords,
|
||||
};
|
||||
pub use layout::{KeyInput, Layout};
|
||||
pub use profiles::{Builtins, MAX_EXPORT_BYTES, MAX_SET_NAME, MAX_SETS, ProfileError, Profiles, SetProblem};
|
||||
pub use scope::{Active, MAX_SCOPE_NAME, Scope, ScopeKind, Scopes};
|
||||
@@ -0,0 +1,562 @@
|
||||
//! Named sets of overrides: the app's built-in sets (read only) and the user's own.
|
||||
//!
|
||||
//! ```
|
||||
//! use craft_keymap::{Overrides, Profiles};
|
||||
//!
|
||||
//! let mut classic = Overrides::new();
|
||||
//! classic.insert("edit.copy", vec!["Cmd+Shift+C".into()]);
|
||||
//! let builtins = [("Craft", Overrides::new()), ("Classic", classic)];
|
||||
//! let mut sets = Profiles::default();
|
||||
//! assert_eq!(sets.active_name(&builtins), "Craft");
|
||||
//!
|
||||
//! sets.duplicate("Classic", "Mine", &builtins).unwrap();
|
||||
//! let text = sets.export("Mine", &builtins).unwrap();
|
||||
//! assert_eq!(sets.import(&text, &builtins), Ok("Mine 2".into()));
|
||||
//! assert_eq!(sets.active_overrides(&builtins), sets.get("Mine", &builtins).unwrap());
|
||||
//! ```
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
|
||||
use serde::de::{self, IgnoredAny, MapAccess, SeqAccess, Visitor};
|
||||
use serde::ser::SerializeStruct;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::import::{ImportPlan, ImportReport};
|
||||
use crate::keymap::{Keymap, Overrides};
|
||||
|
||||
/// Most user sets.
|
||||
pub const MAX_SETS: usize = 64;
|
||||
/// Longest set name, in chars.
|
||||
pub const MAX_SET_NAME: usize = 64;
|
||||
/// Largest export document [`Profiles::import`] reads, in bytes.
|
||||
pub const MAX_EXPORT_BYTES: usize = 4 << 20;
|
||||
|
||||
const FORMAT: &str = "craft-keymap";
|
||||
const VERSION: u64 = 1;
|
||||
/// The version stored [`Profiles`] carry; stored profiles without one read as version 1.
|
||||
const STORE_VERSION: u64 = 1;
|
||||
// Load notes are kept for `Profiles::problems`; a hostile file must not grow them without bound.
|
||||
const MAX_NOTES: usize = 64;
|
||||
const IMPORTED: &str = "Imported";
|
||||
|
||||
/// The app's built-in sets: name and overrides against the catalog defaults.
|
||||
pub type Builtins<'a> = [(&'a str, Overrides)];
|
||||
|
||||
/// Why a set operation was refused.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum ProfileError {
|
||||
/// Empty, over [`MAX_SET_NAME`] chars, or with control characters.
|
||||
BadName,
|
||||
NameTaken,
|
||||
NotFound,
|
||||
/// Built-in sets cannot be changed, renamed or deleted.
|
||||
BuiltIn,
|
||||
/// [`MAX_SETS`] user sets exist.
|
||||
TooMany,
|
||||
/// Not a JSON export document.
|
||||
BadFile,
|
||||
/// A `format` other than `craft-keymap`.
|
||||
WrongFormat,
|
||||
/// A `version` newer than this crate reads.
|
||||
NewerVersion(u64),
|
||||
/// Over [`MAX_EXPORT_BYTES`].
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
impl fmt::Display for ProfileError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let s = match self {
|
||||
ProfileError::BadName => "bad set name",
|
||||
ProfileError::NameTaken => "a set with this name exists",
|
||||
ProfileError::NotFound => "no such set",
|
||||
ProfileError::BuiltIn => "built-in sets are read only",
|
||||
ProfileError::TooMany => "too many sets",
|
||||
ProfileError::BadFile => "not a shortcut set file",
|
||||
ProfileError::WrongFormat => "not a craft-keymap file",
|
||||
ProfileError::NewerVersion(v) => return write!(f, "shortcut set file version {v} is newer than this app reads"),
|
||||
ProfileError::TooLarge => "shortcut set file too large",
|
||||
};
|
||||
f.write_str(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ProfileError {}
|
||||
|
||||
/// Something loading dropped from stored [`Profiles`]; [`Profiles::problems`] lists them.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum SetProblem {
|
||||
/// A set without a valid name: none, empty, over [`MAX_SET_NAME`] chars, with control
|
||||
/// characters or with spaces around it. `name` is what was stored, cut to [`MAX_SET_NAME`]
|
||||
/// chars.
|
||||
BadName { name: String },
|
||||
/// A second set of this name; the first one stays.
|
||||
Duplicate { name: String },
|
||||
/// Overrides that are neither a list nor a map.
|
||||
BadOverrides { name: String },
|
||||
/// Sets past [`MAX_SETS`].
|
||||
TooMany { ignored: usize },
|
||||
/// Stored by a newer craft-keymap; what this version reads is loaded.
|
||||
NewerVersion(u64),
|
||||
}
|
||||
|
||||
/// The user's sets and which set is active. The built-in sets are passed to each call.
|
||||
///
|
||||
/// An active name that matches no set means the first built-in set (or no overrides when the app
|
||||
/// has none).
|
||||
///
|
||||
/// A user set may carry a built-in's name, for instance after an update adds that built-in. Until
|
||||
/// [`Profiles::reconcile`] renames it, the user set is the one that name reads and writes. Call
|
||||
/// `reconcile` after loading; every method that changes the profiles calls it first.
|
||||
///
|
||||
/// Stored as `{ version, active, sets }`. Loading never fails: what it drops is listed by
|
||||
/// [`Profiles::problems`], and the next save writes the profiles without it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Profiles {
|
||||
active: String,
|
||||
sets: BTreeMap<String, Overrides>,
|
||||
notes: Vec<SetProblem>,
|
||||
}
|
||||
|
||||
impl PartialEq for Profiles {
|
||||
fn eq(&self, other: &Profiles) -> bool {
|
||||
self.active == other.active && self.sets == other.sets
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Profiles {}
|
||||
|
||||
static NO_OVERRIDES: Overrides = Overrides::new();
|
||||
|
||||
/// A name as given, trimmed; `None` when empty, too long or with control characters.
|
||||
pub fn set_name(name: &str) -> Option<String> {
|
||||
let n = name.trim();
|
||||
let ok = !n.is_empty() && n.chars().count() <= MAX_SET_NAME && !n.chars().any(char::is_control);
|
||||
ok.then(|| n.to_string())
|
||||
}
|
||||
|
||||
impl Profiles {
|
||||
/// The stored active name, which may match no set; [`active_name`](Self::active_name) is the
|
||||
/// set in use.
|
||||
pub fn active(&self) -> &str {
|
||||
&self.active
|
||||
}
|
||||
|
||||
/// The user's sets.
|
||||
pub fn sets(&self) -> &BTreeMap<String, Overrides> {
|
||||
&self.sets
|
||||
}
|
||||
|
||||
/// What loading dropped.
|
||||
pub fn problems(&self) -> &[SetProblem] {
|
||||
&self.notes
|
||||
}
|
||||
|
||||
/// Built-in names first, then the user's sets.
|
||||
pub fn names(&self, builtins: &Builtins) -> Vec<String> {
|
||||
builtins.iter().map(|(n, _)| n.to_string()).chain(self.sets.keys().cloned()).collect()
|
||||
}
|
||||
|
||||
pub fn is_builtin(name: &str, builtins: &Builtins) -> bool {
|
||||
builtins.iter().any(|(n, _)| *n == name)
|
||||
}
|
||||
|
||||
/// The name of the set in use.
|
||||
pub fn active_name<'a>(&'a self, builtins: &'a Builtins) -> &'a str {
|
||||
if self.sets.contains_key(&self.active) || Self::is_builtin(&self.active, builtins) {
|
||||
&self.active
|
||||
} else {
|
||||
builtins.first().map_or("", |(n, _)| n)
|
||||
}
|
||||
}
|
||||
|
||||
/// The overrides of the set in use, to hand to [`Keymap::set_overrides`](crate::Keymap::set_overrides).
|
||||
pub fn active_overrides<'a>(&'a self, builtins: &'a Builtins) -> &'a Overrides {
|
||||
self.get(self.active_name(builtins), builtins).unwrap_or(&NO_OVERRIDES)
|
||||
}
|
||||
|
||||
pub fn get<'a>(&'a self, name: &str, builtins: &'a Builtins) -> Option<&'a Overrides> {
|
||||
self.sets.get(name).or_else(|| builtins.iter().find(|(n, _)| *n == name).map(|(_, o)| o))
|
||||
}
|
||||
|
||||
/// Renames user sets whose name matches a built-in's (ignoring case) to a free name; `active`
|
||||
/// follows. Returns whether anything was renamed.
|
||||
pub fn reconcile(&mut self, builtins: &Builtins) -> bool {
|
||||
let clashing: Vec<String> = self.sets.keys().filter(|k| self.builtin_like(k, builtins)).cloned().collect();
|
||||
let mut renamed = false;
|
||||
for old in clashing {
|
||||
let Some(set) = self.sets.remove(&old) else { continue };
|
||||
// `unique` cannot fail here: a set was just removed, so there is room and the
|
||||
// candidate names outnumber the sets.
|
||||
let name = self.unique(&old, builtins).unwrap_or_else(|_| old.clone());
|
||||
if self.active == old {
|
||||
self.active = name.clone();
|
||||
}
|
||||
renamed |= name != old;
|
||||
self.sets.insert(name, set);
|
||||
}
|
||||
renamed
|
||||
}
|
||||
|
||||
pub fn select(&mut self, name: &str, builtins: &Builtins) -> Result<(), ProfileError> {
|
||||
self.reconcile(builtins);
|
||||
if self.get(name, builtins).is_none() {
|
||||
return Err(ProfileError::NotFound);
|
||||
}
|
||||
self.active = name.to_string();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Saves edited overrides to the set in use. A built-in set is not changed: the edit goes to a
|
||||
/// new set named after `copy_name` (made unique), which becomes active and is returned. The
|
||||
/// new name is returned too when [`Profiles::reconcile`] renamed the set in use.
|
||||
pub fn store(&mut self, overrides: Overrides, builtins: &Builtins, copy_name: &str) -> Result<Option<String>, ProfileError> {
|
||||
let was = self.active_name(builtins).to_string();
|
||||
self.reconcile(builtins);
|
||||
let active = self.active_name(builtins).to_string();
|
||||
if let Some(set) = self.sets.get_mut(&active) {
|
||||
*set = overrides;
|
||||
return Ok((active != was).then_some(active));
|
||||
}
|
||||
if self.get(&active, builtins) == Some(&overrides) || (active.is_empty() && overrides.is_empty()) {
|
||||
return Ok(None);
|
||||
}
|
||||
let base = set_name(copy_name).ok_or(ProfileError::BadName)?;
|
||||
self.add(&base, overrides, builtins).map(Some)
|
||||
}
|
||||
|
||||
/// Saves `overrides` as a user set (replacing one of that name) and makes it active.
|
||||
pub fn save_as(&mut self, name: &str, overrides: Overrides, builtins: &Builtins) -> Result<String, ProfileError> {
|
||||
self.reconcile(builtins);
|
||||
let name = set_name(name).ok_or(ProfileError::BadName)?;
|
||||
if self.builtin_like(&name, builtins) {
|
||||
return Err(ProfileError::BuiltIn);
|
||||
}
|
||||
if !self.sets.contains_key(&name) {
|
||||
if self.sets.keys().any(|k| k.to_lowercase() == name.to_lowercase()) {
|
||||
return Err(ProfileError::NameTaken);
|
||||
}
|
||||
if self.sets.len() >= MAX_SETS {
|
||||
return Err(ProfileError::TooMany);
|
||||
}
|
||||
}
|
||||
self.sets.insert(name.clone(), overrides);
|
||||
self.active = name.clone();
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
pub fn rename(&mut self, from: &str, to: &str, builtins: &Builtins) -> Result<String, ProfileError> {
|
||||
self.reconcile(builtins);
|
||||
if Self::is_builtin(from, builtins) {
|
||||
return Err(ProfileError::BuiltIn);
|
||||
}
|
||||
let to = set_name(to).ok_or(ProfileError::BadName)?;
|
||||
if !self.sets.contains_key(from) {
|
||||
return Err(ProfileError::NotFound);
|
||||
}
|
||||
// A settings file can hold names that differ only in case, so a case-only rename still
|
||||
// checks the other sets.
|
||||
let lower = to.to_lowercase();
|
||||
let clash = self.sets.keys().any(|k| k != from && k.to_lowercase() == lower);
|
||||
if to != from && (clash || (self.builtin_like(&to, builtins) && lower != from.to_lowercase())) {
|
||||
return Err(ProfileError::NameTaken);
|
||||
}
|
||||
if let Some(set) = self.sets.remove(from) {
|
||||
self.sets.insert(to.clone(), set);
|
||||
}
|
||||
if self.active == from {
|
||||
self.active = to.clone();
|
||||
}
|
||||
Ok(to)
|
||||
}
|
||||
|
||||
pub fn delete(&mut self, name: &str, builtins: &Builtins) -> Result<(), ProfileError> {
|
||||
self.reconcile(builtins);
|
||||
if Self::is_builtin(name, builtins) {
|
||||
return Err(ProfileError::BuiltIn);
|
||||
}
|
||||
self.sets.remove(name).ok_or(ProfileError::NotFound)?;
|
||||
if self.active == name {
|
||||
self.active = builtins.first().map_or(String::new(), |(n, _)| n.to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Copies a set (built-in or user) to a new user set named `to` (made unique), which becomes
|
||||
/// active. Returns its name.
|
||||
pub fn duplicate(&mut self, from: &str, to: &str, builtins: &Builtins) -> Result<String, ProfileError> {
|
||||
self.reconcile(builtins);
|
||||
let overrides = self.get(from, builtins).ok_or(ProfileError::NotFound)?.clone();
|
||||
let base = set_name(to).ok_or(ProfileError::BadName)?;
|
||||
self.add(&base, overrides, builtins)
|
||||
}
|
||||
|
||||
/// A set as a JSON document: `{"format":"craft-keymap","version":1,"name":…,"overrides":…}`,
|
||||
/// overrides as [`Overrides`] serializes them.
|
||||
pub fn export(&self, name: &str, builtins: &Builtins) -> Result<String, ProfileError> {
|
||||
let overrides = self.get(name, builtins).ok_or(ProfileError::NotFound)?;
|
||||
let doc = json!({"format": FORMAT, "version": VERSION, "name": name, "overrides": overrides});
|
||||
serde_json::to_string_pretty(&doc).map_err(|_| ProfileError::BadFile)
|
||||
}
|
||||
|
||||
/// Reads an exported set into a new user set (renamed when the name is taken) and makes it
|
||||
/// active. Returns its name.
|
||||
pub fn import(&mut self, text: &str, builtins: &Builtins) -> Result<String, ProfileError> {
|
||||
if text.len() > MAX_EXPORT_BYTES {
|
||||
return Err(ProfileError::TooLarge);
|
||||
}
|
||||
let doc: Value = serde_json::from_str(text).map_err(|_| ProfileError::BadFile)?;
|
||||
if doc.get("format").and_then(Value::as_str) != Some(FORMAT) {
|
||||
return Err(ProfileError::WrongFormat);
|
||||
}
|
||||
match doc.get("version").and_then(Value::as_u64) {
|
||||
Some(VERSION) => {}
|
||||
Some(v) if v > VERSION => return Err(ProfileError::NewerVersion(v)),
|
||||
_ => return Err(ProfileError::BadFile),
|
||||
}
|
||||
let overrides = match doc.get("overrides") {
|
||||
Some(v @ (Value::Object(_) | Value::Array(_))) => Overrides::deserialize(v).map_err(|_| ProfileError::BadFile)?,
|
||||
None => Overrides::new(),
|
||||
Some(_) => return Err(ProfileError::BadFile),
|
||||
};
|
||||
self.reconcile(builtins);
|
||||
let base = doc.get("name").and_then(Value::as_str).and_then(set_name).unwrap_or_else(|| IMPORTED.to_string());
|
||||
self.add(&base, overrides, builtins)
|
||||
}
|
||||
|
||||
/// Applies an import plan to a copy of `keymap` (the keymap the plan was made from) and keeps
|
||||
/// the resulting overrides as a new user set, which becomes active; `keymap` is not changed.
|
||||
/// The set is named `name`, else the foreign set's name, else `Imported`, made unique.
|
||||
/// Returns its name and the report of [`ImportPlan::apply`].
|
||||
pub fn import_plan(
|
||||
&mut self,
|
||||
plan: &ImportPlan,
|
||||
keymap: &Keymap,
|
||||
name: Option<&str>,
|
||||
builtins: &Builtins,
|
||||
) -> Result<(String, ImportReport), ProfileError> {
|
||||
self.reconcile(builtins);
|
||||
if self.sets.len() >= MAX_SETS {
|
||||
return Err(ProfileError::TooMany);
|
||||
}
|
||||
let mut copy = keymap.clone();
|
||||
let report = plan.apply(&mut copy);
|
||||
let base = name.or(plan.report.set.as_deref()).and_then(set_name).unwrap_or_else(|| IMPORTED.to_string());
|
||||
let name = self.add(&base, copy.overrides().clone(), builtins)?;
|
||||
Ok((name, report))
|
||||
}
|
||||
|
||||
/// Adds a user set under a unique name from `base` and makes it active.
|
||||
fn add(&mut self, base: &str, overrides: Overrides, builtins: &Builtins) -> Result<String, ProfileError> {
|
||||
let name = self.unique(base, builtins)?;
|
||||
self.sets.insert(name.clone(), overrides);
|
||||
self.active = name.clone();
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
fn builtin_like(&self, name: &str, builtins: &Builtins) -> bool {
|
||||
let lower = name.to_lowercase();
|
||||
builtins.iter().any(|(n, _)| n.to_lowercase() == lower)
|
||||
}
|
||||
|
||||
/// Whether `name` matches a built-in or user set, ignoring case.
|
||||
pub(crate) fn taken(&self, name: &str, builtins: &Builtins) -> bool {
|
||||
let lower = name.to_lowercase();
|
||||
self.builtin_like(name, builtins) || self.sets.keys().any(|k| k.to_lowercase() == lower)
|
||||
}
|
||||
|
||||
/// `base`, or `base 2`, `base 3`… cut to fit [`MAX_SET_NAME`].
|
||||
fn unique(&self, base: &str, builtins: &Builtins) -> Result<String, ProfileError> {
|
||||
if self.sets.len() >= MAX_SETS {
|
||||
return Err(ProfileError::TooMany);
|
||||
}
|
||||
if !self.taken(base, builtins) {
|
||||
return Ok(base.to_string());
|
||||
}
|
||||
// `Custom 2` taken: try `Custom 3`, not `Custom 2 2`.
|
||||
let base = match base.rsplit_once(' ') {
|
||||
Some((stem, n)) if !stem.is_empty() && (1..=3).contains(&n.len()) && n.bytes().all(|b| b.is_ascii_digit()) => stem,
|
||||
_ => base,
|
||||
};
|
||||
for n in 2..(MAX_SETS + builtins.len() + 3) {
|
||||
let suffix = format!(" {n}");
|
||||
let keep = MAX_SET_NAME.saturating_sub(suffix.chars().count());
|
||||
let name: String = base.chars().take(keep).collect::<String>().trim_end().to_string() + &suffix;
|
||||
if !self.taken(&name, builtins) {
|
||||
return Ok(name);
|
||||
}
|
||||
}
|
||||
Err(ProfileError::NameTaken)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Profiles {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let mut s = serializer.serialize_struct("Profiles", 3)?;
|
||||
s.serialize_field("version", &STORE_VERSION)?;
|
||||
s.serialize_field("active", &self.active)?;
|
||||
s.serialize_field("sets", &SetList(&self.sets))?;
|
||||
s.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Profiles {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Profiles, D::Error> {
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct Stored {
|
||||
#[serde(deserialize_with = "lenient_version")]
|
||||
version: Option<u64>,
|
||||
#[serde(deserialize_with = "lenient_name")]
|
||||
active: String,
|
||||
#[serde(deserialize_with = "capped_sets")]
|
||||
sets: Loaded,
|
||||
}
|
||||
let Stored { version, active, sets: Loaded { sets, mut notes, .. } } = Stored::deserialize(deserializer)?;
|
||||
if let Some(v) = version.filter(|v| *v > STORE_VERSION) {
|
||||
notes.insert(0, SetProblem::NewerVersion(v));
|
||||
notes.truncate(MAX_NOTES);
|
||||
}
|
||||
Ok(Profiles { active, sets, notes })
|
||||
}
|
||||
}
|
||||
|
||||
fn lenient_name<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
|
||||
let v = Value::deserialize(deserializer)?;
|
||||
Ok(v.as_str().and_then(set_name).unwrap_or_default())
|
||||
}
|
||||
|
||||
fn lenient_version<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<u64>, D::Error> {
|
||||
Ok(Value::deserialize(deserializer)?.as_u64())
|
||||
}
|
||||
|
||||
// An array of `{ name, overrides }` rather than a table, and each set's overrides in their array
|
||||
// form, so that craft-settings (which replaces arrays whole) drops a deleted set or entry from the
|
||||
// file.
|
||||
struct SetList<'a>(&'a BTreeMap<String, Overrides>);
|
||||
|
||||
impl Serialize for SetList<'_> {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
#[derive(Serialize)]
|
||||
struct Set<'a> {
|
||||
name: &'a str,
|
||||
#[serde(serialize_with = "crate::keymap::overrides_list::serialize")]
|
||||
overrides: &'a Overrides,
|
||||
}
|
||||
serializer.collect_seq(self.0.iter().map(|(name, overrides)| Set { name, overrides }))
|
||||
}
|
||||
}
|
||||
|
||||
/// The sets that loaded, and notes on the ones that did not.
|
||||
#[derive(Default)]
|
||||
struct Loaded {
|
||||
sets: BTreeMap<String, Overrides>,
|
||||
notes: Vec<SetProblem>,
|
||||
ignored: usize,
|
||||
}
|
||||
|
||||
impl Loaded {
|
||||
fn note(&mut self, problem: SetProblem) {
|
||||
if self.notes.len() < MAX_NOTES {
|
||||
self.notes.push(problem);
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps a set with a valid name, stored as written, that is new and fits under [`MAX_SETS`];
|
||||
/// notes why not otherwise.
|
||||
fn add(&mut self, name: &str, overrides: Option<Overrides>) {
|
||||
let shown = || name.chars().take(MAX_SET_NAME).collect::<String>();
|
||||
if !set_name(name).is_some_and(|n| n == name) {
|
||||
self.note(SetProblem::BadName { name: shown() });
|
||||
} else if self.sets.contains_key(name) {
|
||||
self.note(SetProblem::Duplicate { name: shown() });
|
||||
} else if self.sets.len() >= MAX_SETS {
|
||||
self.ignored += 1;
|
||||
} else if let Some(o) = overrides {
|
||||
self.sets.insert(name.to_string(), o);
|
||||
} else {
|
||||
self.note(SetProblem::BadOverrides { name: shown() });
|
||||
}
|
||||
}
|
||||
|
||||
fn done(mut self) -> Loaded {
|
||||
if self.ignored > 0 {
|
||||
let ignored = std::mem::take(&mut self.ignored);
|
||||
self.note(SetProblem::TooMany { ignored });
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
fn capped_sets<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Loaded, D::Error> {
|
||||
deserializer.deserialize_any(SetsVisitor)
|
||||
}
|
||||
|
||||
struct SetsVisitor;
|
||||
|
||||
// Anything other than a list or a map loads as no sets, so the rest of `Profiles` still loads.
|
||||
macro_rules! no_sets {
|
||||
($($name:ident: $t:ty),*) => {
|
||||
$(fn $name<E: de::Error>(self, _: $t) -> Result<Self::Value, E> {
|
||||
Ok(Loaded::default())
|
||||
})*
|
||||
};
|
||||
}
|
||||
|
||||
impl<'de> Visitor<'de> for SetsVisitor {
|
||||
type Value = Loaded;
|
||||
|
||||
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("a list of `{ name, overrides }` items or a map of set names to overrides")
|
||||
}
|
||||
|
||||
no_sets!(visit_bool: bool, visit_i64: i64, visit_u64: u64, visit_i128: i128, visit_u128: u128, visit_f64: f64, visit_str: &str, visit_bytes: &[u8], visit_char: char);
|
||||
|
||||
fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
|
||||
Ok(Loaded::default())
|
||||
}
|
||||
|
||||
fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
|
||||
Ok(Loaded::default())
|
||||
}
|
||||
|
||||
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
|
||||
deserializer.deserialize_any(SetsVisitor)
|
||||
}
|
||||
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Self::Value, A::Error> {
|
||||
let mut out = Loaded::default();
|
||||
while let Some(item) = access.next_element::<Value>()? {
|
||||
let name = item.get("name").and_then(Value::as_str).unwrap_or_default();
|
||||
out.add(name, item.get("overrides").and_then(overrides_of));
|
||||
}
|
||||
Ok(out.done())
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Self::Value, A::Error> {
|
||||
let mut out = Loaded::default();
|
||||
while let Some(key) = access.next_key::<String>()? {
|
||||
if out.sets.len() >= MAX_SETS && !out.sets.contains_key(&key) {
|
||||
access.next_value::<IgnoredAny>()?;
|
||||
out.ignored += 1;
|
||||
} else {
|
||||
let overrides = overrides_of(&access.next_value::<Value>()?);
|
||||
out.add(&key, overrides);
|
||||
}
|
||||
}
|
||||
Ok(out.done())
|
||||
}
|
||||
}
|
||||
|
||||
/// A set's overrides: a list or a map, anything else is no set.
|
||||
fn overrides_of(v: &Value) -> Option<Overrides> {
|
||||
match v {
|
||||
Value::Object(_) | Value::Array(_) => Overrides::deserialize(v).ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//! Chords the operating system takes before the app sees them.
|
||||
//!
|
||||
//! A keymap reserves these only when the app passes them to
|
||||
//! [`Keymap::with_reserved`](crate::Keymap::with_reserved).
|
||||
|
||||
use crate::chord::{Chord, Platform};
|
||||
|
||||
// from photocraft crates/engine/src/prefs.rs `reserved_shortcut`
|
||||
const MAC: &[&str] = &["Cmd+Tab", "Cmd+Shift+Tab", "Cmd+Alt+Escape", "Cmd+`"];
|
||||
const WINDOWS: &[&str] = &["Alt+Tab", "Alt+Shift+Tab", "Alt+F4", "Cmd+Alt+Delete", "Cmd+Escape", "Cmd+Shift+Escape"];
|
||||
// Linux and the BSDs: window switching and closing, and the virtual consoles.
|
||||
const LINUX: &[&str] = &[
|
||||
"Alt+Tab",
|
||||
"Alt+Shift+Tab",
|
||||
"Alt+F4",
|
||||
"Cmd+Alt+Delete",
|
||||
"Cmd+Alt+F1",
|
||||
"Cmd+Alt+F2",
|
||||
"Cmd+Alt+F3",
|
||||
"Cmd+Alt+F4",
|
||||
"Cmd+Alt+F5",
|
||||
"Cmd+Alt+F6",
|
||||
"Cmd+Alt+F7",
|
||||
"Cmd+Alt+F8",
|
||||
"Cmd+Alt+F9",
|
||||
"Cmd+Alt+F10",
|
||||
"Cmd+Alt+F11",
|
||||
"Cmd+Alt+F12",
|
||||
];
|
||||
|
||||
/// The window switching, closing and session chords of `platform`, for
|
||||
/// [`Keymap::with_reserved`](crate::Keymap::with_reserved).
|
||||
pub fn system(platform: Platform) -> Vec<Chord> {
|
||||
let list = match platform {
|
||||
Platform::Mac => MAC,
|
||||
Platform::Windows => WINDOWS,
|
||||
Platform::Linux => LINUX,
|
||||
};
|
||||
list.iter().filter_map(|t| Chord::parse(t).ok()).collect()
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
//! Where a binding works: the whole application, one panel, or a context such as text editing.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
|
||||
/// Longest scope name, in bytes.
|
||||
pub const MAX_SCOPE_NAME: usize = 64;
|
||||
|
||||
const APP: &str = "Application";
|
||||
|
||||
/// The name of a scope. Never empty, at most [`MAX_SCOPE_NAME`] bytes, without `:` or outer
|
||||
/// whitespace.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct Scope(String);
|
||||
|
||||
impl Scope {
|
||||
/// `None` for an empty name, one over [`MAX_SCOPE_NAME`] bytes, one with `:` or a control
|
||||
/// character, or one with whitespace at either end, which binding text would lose.
|
||||
pub fn new(name: impl Into<String>) -> Option<Scope> {
|
||||
let name = name.into();
|
||||
let ok = !name.is_empty() && name.len() <= MAX_SCOPE_NAME && name.trim() == name && !name.chars().any(|c| c == ':' || c.is_control());
|
||||
ok.then_some(Scope(name))
|
||||
}
|
||||
|
||||
/// The application scope, `Application`.
|
||||
pub fn app() -> Scope {
|
||||
Scope(APP.to_string())
|
||||
}
|
||||
|
||||
pub fn is_app(&self) -> bool {
|
||||
self.0 == APP
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Scope {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Scope {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Scope, D::Error> {
|
||||
let name = String::deserialize(deserializer)?;
|
||||
Scope::new(name).ok_or_else(|| serde::de::Error::custom("bad scope name"))
|
||||
}
|
||||
}
|
||||
|
||||
/// What kind of scope a name is.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ScopeKind {
|
||||
Application,
|
||||
/// Works while the panel has the keyboard. Names that are not registered count as panels.
|
||||
Panel,
|
||||
/// Works only while the context is active, in any panel.
|
||||
Context,
|
||||
}
|
||||
|
||||
/// The scope registry: contexts, panels and the pairs of panels that share their shortcuts.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Scopes {
|
||||
panels: Vec<String>,
|
||||
contexts: Vec<String>,
|
||||
shares: Vec<(String, String)>,
|
||||
panel_fallthrough: bool,
|
||||
}
|
||||
|
||||
impl Default for Scopes {
|
||||
fn default() -> Scopes {
|
||||
Scopes { panels: Vec::new(), contexts: Vec::new(), shares: Vec::new(), panel_fallthrough: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// What has the keyboard: the focused panel, the active contexts, and whether a text field is
|
||||
/// being typed in.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Active<'a> {
|
||||
pub panel: Option<&'a str>,
|
||||
pub contexts: &'a [&'a str],
|
||||
pub typing: bool,
|
||||
}
|
||||
|
||||
impl<'a> Active<'a> {
|
||||
/// No panel focused, no context, not typing.
|
||||
pub const NONE: Active<'static> = Active { panel: None, contexts: &[], typing: false };
|
||||
|
||||
pub const fn panel(panel: &'a str) -> Active<'a> {
|
||||
Active { panel: Some(panel), contexts: &[], typing: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl Scopes {
|
||||
pub fn new() -> Scopes {
|
||||
Scopes::default()
|
||||
}
|
||||
|
||||
/// Registers a panel (used by [`Scopes::panels`]; unknown names rank as panels anyway).
|
||||
pub fn with_panel(mut self, name: &str) -> Scopes {
|
||||
if !self.panels.iter().any(|p| p == name) {
|
||||
self.panels.push(name.to_string());
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_context(mut self, name: &str) -> Scopes {
|
||||
if !self.contexts.iter().any(|c| c == name) {
|
||||
self.contexts.push(name.to_string());
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Two panels that show the same thing and share their shortcuts (EffectCraft's Timeline and
|
||||
/// Composition).
|
||||
pub fn with_share(mut self, a: &str, b: &str) -> Scopes {
|
||||
if !self.shares(a, b) {
|
||||
self.shares.push((a.to_string(), b.to_string()));
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether another panel's shortcut still runs when nothing nearer claims the chord. On by
|
||||
/// default.
|
||||
pub fn with_panel_fallthrough(mut self, on: bool) -> Scopes {
|
||||
self.panel_fallthrough = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn panels(&self) -> &[String] {
|
||||
&self.panels
|
||||
}
|
||||
|
||||
pub fn contexts(&self) -> &[String] {
|
||||
&self.contexts
|
||||
}
|
||||
|
||||
pub fn panel_fallthrough(&self) -> bool {
|
||||
self.panel_fallthrough
|
||||
}
|
||||
|
||||
/// Whether `scope` is the application or a registered panel, context or sharing panel.
|
||||
pub fn knows(&self, scope: &Scope) -> bool {
|
||||
let name = scope.as_str();
|
||||
scope.is_app()
|
||||
|| self.panels.iter().any(|p| p == name)
|
||||
|| self.contexts.iter().any(|c| c == name)
|
||||
|| self.shares.iter().any(|(a, b)| a == name || b == name)
|
||||
}
|
||||
|
||||
pub fn kind(&self, scope: &Scope) -> ScopeKind {
|
||||
self.kind_of(scope.as_str())
|
||||
}
|
||||
|
||||
fn kind_of(&self, name: &str) -> ScopeKind {
|
||||
if name == APP {
|
||||
ScopeKind::Application
|
||||
} else if self.contexts.iter().any(|c| c == name) {
|
||||
ScopeKind::Context
|
||||
} else {
|
||||
ScopeKind::Panel
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether panels `a` and `b` (in either order) share their shortcuts.
|
||||
pub fn shares(&self, a: &str, b: &str) -> bool {
|
||||
self.shares.iter().any(|(x, y)| (x == a && y == b) || (x == b && y == a))
|
||||
}
|
||||
|
||||
/// How strongly a binding in `scope` claims a chord: lower wins, `None` does not run. An active
|
||||
/// context 0, the focused panel 1, a panel sharing with it 2, the application 3, any other
|
||||
/// panel 4 with fallthrough on. An inactive context never runs.
|
||||
// from effectcraft#1266 `scope_rank`
|
||||
pub fn rank(&self, scope: &Scope, active: &Active) -> Option<u8> {
|
||||
let name = scope.as_str();
|
||||
match self.kind_of(name) {
|
||||
ScopeKind::Context => active.contexts.contains(&name).then_some(0),
|
||||
ScopeKind::Application => Some(3),
|
||||
ScopeKind::Panel => match active.panel {
|
||||
Some(p) if p == name => Some(1),
|
||||
Some(p) if self.shares(p, name) => Some(2),
|
||||
_ => self.panel_fallthrough.then_some(4),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the same chord in `a` and `b` makes only one of them work: the same scope, two
|
||||
/// panels that share, or two different contexts (both can be active at once). Other pairs that
|
||||
/// can be active together shadow (`Some(false)`): a context over anything else, a panel over
|
||||
/// the application. `None`: never active together (two unrelated panels).
|
||||
pub(crate) fn relation(&self, a: &Scope, b: &Scope) -> Option<bool> {
|
||||
if a == b {
|
||||
return Some(true);
|
||||
}
|
||||
match (self.kind(a), self.kind(b)) {
|
||||
(ScopeKind::Context, ScopeKind::Context) => Some(true),
|
||||
(ScopeKind::Context, _) | (_, ScopeKind::Context) => Some(false),
|
||||
(ScopeKind::Application, _) | (_, ScopeKind::Application) => Some(false),
|
||||
(ScopeKind::Panel, ScopeKind::Panel) => self.shares(a.as_str(), b.as_str()).then_some(true),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
//! Taking a frame's key input while the dialog records, before the app's dispatcher or egui's
|
||||
//! widgets see it.
|
||||
|
||||
use ::egui::{Event, EventFilter, Id, InputState, Ui};
|
||||
|
||||
use crate::chord::{Chord, Key, Mods, Platform};
|
||||
use crate::egui::{Clip, clipboard_chord, clipboard_kind};
|
||||
|
||||
/// The keys a recording widget keeps from egui's focus navigation, so Tab, arrows and Escape are
|
||||
/// recorded instead of moving focus.
|
||||
pub(crate) const FOCUS_LOCK: EventFilter = EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true };
|
||||
|
||||
/// Holds egui's focus on `id` with [`FOCUS_LOCK`]; call each frame the widget records.
|
||||
pub(crate) fn lock_focus(ui: &Ui, id: Id) {
|
||||
ui.memory_mut(|m| m.set_focus_lock_filter(id, FOCUS_LOCK));
|
||||
}
|
||||
|
||||
/// Gives Tab, arrows and Escape back to egui's focus navigation. egui keeps a focused widget's
|
||||
/// filter until focus moves, so a widget that recorded calls this each frame it has focus and
|
||||
/// does not record.
|
||||
pub(crate) fn unlock_focus(ui: &Ui, id: Id) {
|
||||
ui.memory_mut(|m| m.set_focus_lock_filter(id, EventFilter::default()));
|
||||
}
|
||||
|
||||
/// Removes every key, text, IME and clipboard event from `input` and returns the chords pressed,
|
||||
/// in order. Repeats, releases and modifier-only presses give no chord. Copy, Cut and Paste
|
||||
/// count as the presses that cause them (Cmd+C, Cmd+X, Cmd+V, or Shift+Delete and Shift+Insert),
|
||||
/// once when a backend sends both the press and the event.
|
||||
pub(crate) fn take(input: &mut InputState, platform: Platform) -> Vec<Chord> {
|
||||
let frame_mods = Mods::from_egui(&input.modifiers, platform);
|
||||
let mut chords = Vec::new();
|
||||
let mut kept = Vec::with_capacity(input.events.len());
|
||||
let mut clipboard_press: Option<Clip> = None;
|
||||
for event in std::mem::take(&mut input.events) {
|
||||
match &event {
|
||||
Event::Key { key, pressed, repeat, modifiers, .. } => {
|
||||
let Some(key) = Key::from_egui(*key) else { continue };
|
||||
if *pressed && !*repeat {
|
||||
let held = Mods::from_egui(modifiers, platform);
|
||||
if let Some(clip) = clipboard_kind(key, held) {
|
||||
clipboard_press = Some(clip);
|
||||
}
|
||||
chords.push(Chord::new(held, key));
|
||||
}
|
||||
}
|
||||
Event::Copy | Event::Cut | Event::Paste(_) => {
|
||||
let (key, held, clip) = clipboard_chord(&event, frame_mods);
|
||||
if clipboard_press == Some(clip) {
|
||||
clipboard_press = None;
|
||||
} else {
|
||||
chords.push(Chord::new(held, key));
|
||||
}
|
||||
}
|
||||
Event::Text(_) | Event::Ime(_) => {}
|
||||
_ => kept.push(event),
|
||||
}
|
||||
}
|
||||
input.events = kept;
|
||||
chords
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use ::egui::{Context, Key as EguiKey, Modifiers, RawInput};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn run(events: Vec<Event>) -> (Vec<String>, usize) {
|
||||
let ctx = Context::default();
|
||||
let mut out = (Vec::new(), 0);
|
||||
let mut full = ctx.run_ui(RawInput { events, ..RawInput::default() }, |ui| {
|
||||
let chords = ui.ctx().input_mut(|i| take(i, Platform::Mac));
|
||||
out = (chords.iter().map(Chord::to_string).collect(), ui.ctx().input(|i| i.events.len()));
|
||||
});
|
||||
full.textures_delta.clear();
|
||||
out
|
||||
}
|
||||
|
||||
fn press(key: EguiKey, modifiers: Modifiers) -> Event {
|
||||
Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn takes_presses_and_clipboard_events_and_leaves_nothing() {
|
||||
let cmd = Modifiers::MAC_CMD;
|
||||
let events = vec![
|
||||
press(EguiKey::E, cmd),
|
||||
Event::Text("e".into()),
|
||||
Event::Key { key: EguiKey::E, physical_key: None, pressed: false, repeat: false, modifiers: cmd },
|
||||
press(EguiKey::Tab, Modifiers::NONE),
|
||||
// The web build: the press, then the event it causes, counted once.
|
||||
press(EguiKey::C, cmd),
|
||||
Event::Copy,
|
||||
// egui-winit: only the event.
|
||||
Event::Paste("x".into()),
|
||||
Event::PointerGone,
|
||||
];
|
||||
let (chords, left) = run(events);
|
||||
assert_eq!(chords, ["Cmd+E", "Tab", "Cmd+C", "Cmd+V"]);
|
||||
assert_eq!(left, 1, "only the pointer event stays");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,638 @@
|
||||
//! The on-screen keyboard pane (§2.9 of the dialog plan, `Options::keyboard`): a US ANSI layout
|
||||
//! colored by who holds each key with the chosen modifiers, modifier toggles that also follow the
|
||||
//! held modifiers, the shortcuts of the clicked key, and Assign to Selected.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::text::{LayoutJob, TextFormat, TextWrapping};
|
||||
use egui::{
|
||||
Align, Button, Color32, CornerRadius, FontId, Layout, Rect, RichText, Role, ScrollArea, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2,
|
||||
};
|
||||
|
||||
use super::{Draw, fill};
|
||||
use crate::chord::{Chord, Key, Mods, Trigger};
|
||||
use crate::command::CommandRef;
|
||||
use crate::keymap::{Binding, Holder, Keymap, Overrides};
|
||||
use crate::scope::Scope;
|
||||
|
||||
/// The keyboard's width and height in key units: 15 for the main block, a gap, 3 for the
|
||||
/// navigation cluster; six rows and the gap under the function row.
|
||||
const UNITS_W: f32 = 18.5;
|
||||
const UNITS_H: f32 = 6.25;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Mod {
|
||||
Cmd,
|
||||
Ctrl,
|
||||
Alt,
|
||||
Shift,
|
||||
}
|
||||
|
||||
impl Mod {
|
||||
fn id(self) -> &'static str {
|
||||
match self {
|
||||
Mod::Cmd => "cmd",
|
||||
Mod::Ctrl => "ctrl",
|
||||
Mod::Alt => "alt",
|
||||
Mod::Shift => "shift",
|
||||
}
|
||||
}
|
||||
|
||||
fn get(self, m: Mods) -> bool {
|
||||
match self {
|
||||
Mod::Cmd => m.cmd,
|
||||
Mod::Ctrl => m.ctrl,
|
||||
Mod::Alt => m.alt,
|
||||
Mod::Shift => m.shift,
|
||||
}
|
||||
}
|
||||
|
||||
fn flip(self, m: &mut Mods) {
|
||||
match self {
|
||||
Mod::Cmd => m.cmd = !m.cmd,
|
||||
Mod::Ctrl => m.ctrl = !m.ctrl,
|
||||
Mod::Alt => m.alt = !m.alt,
|
||||
Mod::Shift => m.shift = !m.shift,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A keycap: a key, a modifier, a key the dialog does not bind (Caps Lock, Win), or a gap.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Cap {
|
||||
Key(Key),
|
||||
Mod(Mod),
|
||||
CapsLock,
|
||||
/// Win on Windows, Super on Linux; a Mac has none.
|
||||
System,
|
||||
Gap,
|
||||
}
|
||||
|
||||
type Row = &'static [(Cap, f32)];
|
||||
|
||||
const fn k(key: Key) -> (Cap, f32) {
|
||||
(Cap::Key(key), 1.0)
|
||||
}
|
||||
|
||||
const MAIN_ROWS: [Row; 5] = [
|
||||
&[
|
||||
(Cap::Key(Key::Backtick), 1.0),
|
||||
k(Key::Num1),
|
||||
k(Key::Num2),
|
||||
k(Key::Num3),
|
||||
k(Key::Num4),
|
||||
k(Key::Num5),
|
||||
k(Key::Num6),
|
||||
k(Key::Num7),
|
||||
k(Key::Num8),
|
||||
k(Key::Num9),
|
||||
k(Key::Num0),
|
||||
k(Key::Minus),
|
||||
k(Key::Equals),
|
||||
(Cap::Key(Key::Backspace), 2.0),
|
||||
],
|
||||
&[
|
||||
(Cap::Key(Key::Tab), 1.5),
|
||||
k(Key::Q),
|
||||
k(Key::W),
|
||||
k(Key::E),
|
||||
k(Key::R),
|
||||
k(Key::T),
|
||||
k(Key::Y),
|
||||
k(Key::U),
|
||||
k(Key::I),
|
||||
k(Key::O),
|
||||
k(Key::P),
|
||||
k(Key::OpenBracket),
|
||||
k(Key::CloseBracket),
|
||||
(Cap::Key(Key::Backslash), 1.5),
|
||||
],
|
||||
&[
|
||||
(Cap::CapsLock, 1.75),
|
||||
k(Key::A),
|
||||
k(Key::S),
|
||||
k(Key::D),
|
||||
k(Key::F),
|
||||
k(Key::G),
|
||||
k(Key::H),
|
||||
k(Key::J),
|
||||
k(Key::K),
|
||||
k(Key::L),
|
||||
k(Key::Semicolon),
|
||||
k(Key::Quote),
|
||||
(Cap::Key(Key::Enter), 2.25),
|
||||
],
|
||||
&[
|
||||
(Cap::Mod(Mod::Shift), 2.25),
|
||||
k(Key::Z),
|
||||
k(Key::X),
|
||||
k(Key::C),
|
||||
k(Key::V),
|
||||
k(Key::B),
|
||||
k(Key::N),
|
||||
k(Key::M),
|
||||
k(Key::Comma),
|
||||
k(Key::Period),
|
||||
k(Key::Slash),
|
||||
(Cap::Mod(Mod::Shift), 2.75),
|
||||
],
|
||||
&[],
|
||||
];
|
||||
|
||||
const FUNCTION_ROW: Row = &[
|
||||
k(Key::Escape),
|
||||
(Cap::Gap, 1.0),
|
||||
k(Key::F1),
|
||||
k(Key::F2),
|
||||
k(Key::F3),
|
||||
k(Key::F4),
|
||||
(Cap::Gap, 0.5),
|
||||
k(Key::F5),
|
||||
k(Key::F6),
|
||||
k(Key::F7),
|
||||
k(Key::F8),
|
||||
(Cap::Gap, 0.5),
|
||||
k(Key::F9),
|
||||
k(Key::F10),
|
||||
k(Key::F11),
|
||||
k(Key::F12),
|
||||
];
|
||||
|
||||
const MAC_BOTTOM: Row = &[
|
||||
(Cap::Mod(Mod::Ctrl), 1.5),
|
||||
(Cap::Mod(Mod::Alt), 1.25),
|
||||
(Cap::Mod(Mod::Cmd), 1.5),
|
||||
(Cap::Key(Key::Space), 6.5),
|
||||
(Cap::Mod(Mod::Cmd), 1.5),
|
||||
(Cap::Mod(Mod::Alt), 1.25),
|
||||
(Cap::Mod(Mod::Ctrl), 1.5),
|
||||
];
|
||||
|
||||
/// Off macOS the Ctrl keys are the command modifier.
|
||||
const PC_BOTTOM: Row = &[
|
||||
(Cap::Mod(Mod::Cmd), 1.5),
|
||||
(Cap::System, 1.25),
|
||||
(Cap::Mod(Mod::Alt), 1.5),
|
||||
(Cap::Key(Key::Space), 6.5),
|
||||
(Cap::Mod(Mod::Alt), 1.5),
|
||||
(Cap::System, 1.25),
|
||||
(Cap::Mod(Mod::Cmd), 1.5),
|
||||
];
|
||||
|
||||
/// The navigation cluster: (row, column in units, key). Row 0 is the function row.
|
||||
const NAV: &[(usize, f32, Key)] = &[
|
||||
(1, 0.0, Key::Insert),
|
||||
(1, 1.0, Key::Home),
|
||||
(1, 2.0, Key::PageUp),
|
||||
(2, 0.0, Key::Delete),
|
||||
(2, 1.0, Key::End),
|
||||
(2, 2.0, Key::PageDown),
|
||||
(4, 1.0, Key::Up),
|
||||
(5, 0.0, Key::Left),
|
||||
(5, 1.0, Key::Down),
|
||||
(5, 2.0, Key::Right),
|
||||
];
|
||||
|
||||
/// A binding on a key and the scope it works in.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct KeyHolder {
|
||||
pub holder: Holder,
|
||||
pub scope: Scope,
|
||||
}
|
||||
|
||||
/// Who holds a key with given modifiers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Class {
|
||||
Free,
|
||||
App,
|
||||
Scoped,
|
||||
Both,
|
||||
}
|
||||
|
||||
fn class(holders: &[KeyHolder]) -> Class {
|
||||
match (holders.iter().any(|h| h.scope.is_app()), holders.iter().any(|h| !h.scope.is_app())) {
|
||||
(false, false) => Class::Free,
|
||||
(true, false) => Class::App,
|
||||
(false, true) => Class::Scoped,
|
||||
(true, true) => Class::Both,
|
||||
}
|
||||
}
|
||||
|
||||
/// The pane's state between frames.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct KeyboardState {
|
||||
/// Hidden with the header's Keyboard toggle.
|
||||
pub hidden: bool,
|
||||
/// The modifiers toggled on; the held ones are added each frame.
|
||||
pub mods: Mods,
|
||||
/// The key whose shortcuts are listed.
|
||||
pub key: Option<Key>,
|
||||
/// Every binding by effective chord, rebuilt when the overrides change.
|
||||
index: Option<Arc<(Overrides, Index)>>,
|
||||
}
|
||||
|
||||
type Index = HashMap<Chord, Vec<KeyHolder>>;
|
||||
|
||||
impl KeyboardState {
|
||||
fn index(&mut self, keymap: &Keymap) -> Arc<(Overrides, Index)> {
|
||||
if let Some(i) = self.index.as_ref().filter(|i| i.0 == *keymap.overrides()) {
|
||||
return i.clone();
|
||||
}
|
||||
let platform = keymap.platform();
|
||||
let mut map: HashMap<Chord, Vec<KeyHolder>> = HashMap::new();
|
||||
for b in keymap.catalog() {
|
||||
for binding in keymap.bindings(&b.command) {
|
||||
let scope = binding.scope_or(&b.scope).clone();
|
||||
let holder = Holder { command: b.command.clone(), binding };
|
||||
map.entry(holder.binding.trigger.chord.effective(platform)).or_default().push(KeyHolder { holder, scope });
|
||||
}
|
||||
}
|
||||
let index = Arc::new((keymap.overrides().clone(), map));
|
||||
self.index = Some(index.clone());
|
||||
index
|
||||
}
|
||||
}
|
||||
|
||||
fn mod_glyph(m: Mod) -> &'static str {
|
||||
match m {
|
||||
Mod::Cmd => "⌘",
|
||||
Mod::Ctrl => "⌃",
|
||||
Mod::Alt => "⌥",
|
||||
Mod::Shift => "⇧",
|
||||
}
|
||||
}
|
||||
|
||||
/// The English legend printed on a key: Apple's words on macOS, PC words elsewhere.
|
||||
fn cap_name(key: Key, mac: bool) -> &'static str {
|
||||
match (key, mac) {
|
||||
(Key::Escape, true) => "esc",
|
||||
(Key::Escape, false) => "Esc",
|
||||
(Key::Backspace, true) => "delete",
|
||||
(Key::Delete, true) => "fwd del",
|
||||
(Key::Insert, true) => "ins",
|
||||
(Key::Enter, true) => "return",
|
||||
(Key::Tab, true) => "tab",
|
||||
(Key::PageUp, true) => "page up",
|
||||
(Key::PageDown, true) => "page down",
|
||||
(Key::Home, true) => "home",
|
||||
(Key::End, true) => "end",
|
||||
(Key::Insert, false) => "Ins",
|
||||
(Key::PageUp, false) => "PgUp",
|
||||
(Key::PageDown, false) => "PgDn",
|
||||
(Key::Delete, false) => "Del",
|
||||
(Key::Space, true) => "",
|
||||
(Key::Up | Key::Down | Key::Left | Key::Right, _) => key.mac_symbol(),
|
||||
(k, _) => k.text_name(),
|
||||
}
|
||||
}
|
||||
|
||||
fn union(a: Mods, b: Mods) -> Mods {
|
||||
Mods { cmd: a.cmd || b.cmd, ctrl: a.ctrl || b.ctrl, alt: a.alt || b.alt, shift: a.shift || b.shift }
|
||||
}
|
||||
|
||||
/// Black or white, whichever reads better on `fill`.
|
||||
fn ink(fill: Color32) -> Color32 {
|
||||
let l = 0.299 * f32::from(fill.r()) + 0.587 * f32::from(fill.g()) + 0.114 * f32::from(fill.b());
|
||||
if l > 150.0 { Color32::from_gray(24) } else { Color32::from_gray(240) }
|
||||
}
|
||||
|
||||
/// What a frame of the pane asked for.
|
||||
#[derive(Default)]
|
||||
struct Clicks {
|
||||
key: Option<Key>,
|
||||
toggle: Option<Mod>,
|
||||
go: Option<CommandRef>,
|
||||
assign: bool,
|
||||
}
|
||||
|
||||
impl Draw<'_, '_> {
|
||||
/// The pane's height for a middle area of `height`, or `None` when it is off or does not fit.
|
||||
pub(super) fn keyboard_height(&self, height: f32) -> Option<f32> {
|
||||
if !self.env.options.keyboard || self.state.keyboard.hidden {
|
||||
return None;
|
||||
}
|
||||
let h = (height * 0.45).min(320.0).min(height - 160.0);
|
||||
(h >= 120.0).then_some(h)
|
||||
}
|
||||
|
||||
/// The header's toggle that shows and hides the pane.
|
||||
pub(super) fn keyboard_toggle(&mut self, ui: &mut Ui) {
|
||||
if !self.env.options.keyboard {
|
||||
return;
|
||||
}
|
||||
let label = self.ui("Keyboard");
|
||||
let r = ui.add(Button::selectable(!self.state.keyboard.hidden, self.vis(&label)));
|
||||
self.tag(|| "shortcuts.keyboard".into(), r.rect, &label);
|
||||
if r.clicked() {
|
||||
self.state.keyboard.hidden = !self.state.keyboard.hidden;
|
||||
}
|
||||
}
|
||||
|
||||
fn mods_shown(&self) -> &'static [Mod] {
|
||||
if self.env.keymap.platform().is_mac() { &[Mod::Cmd, Mod::Ctrl, Mod::Alt, Mod::Shift] } else { &[Mod::Cmd, Mod::Alt, Mod::Shift] }
|
||||
}
|
||||
|
||||
/// A modifier's name, with its glyph on macOS.
|
||||
fn mod_name(&self, m: Mod) -> String {
|
||||
let word = self.mod_word(m);
|
||||
if self.env.keymap.platform().is_mac() { format!("{} {word}", mod_glyph(m)) } else { word }
|
||||
}
|
||||
|
||||
/// The key's name on its cap: the app's localized name, else the glyph on macOS.
|
||||
fn cap_legend(&self, key: Key) -> String {
|
||||
let p = self.env.keymap.platform();
|
||||
self.env.text.key(key, p).unwrap_or_else(|| cap_name(key, p.is_mac()).to_string())
|
||||
}
|
||||
|
||||
/// A modifier cap's word, without the glyph (which goes above it on macOS).
|
||||
fn mod_word(&self, m: Mod) -> String {
|
||||
match (m, self.env.keymap.platform().is_mac()) {
|
||||
(Mod::Cmd, true) => self.ui("Command"),
|
||||
(Mod::Ctrl, true) => self.ui("Control"),
|
||||
(Mod::Alt, true) => self.ui("Option"),
|
||||
(Mod::Cmd | Mod::Ctrl, false) => self.ui("Ctrl"),
|
||||
(Mod::Alt, false) => self.ui("Alt"),
|
||||
(Mod::Shift, _) => self.ui("Shift"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The key's spoken name: the app's localized name, else the name Windows and Linux show.
|
||||
fn key_name(&self, key: Key) -> String {
|
||||
self.env.text.key(key, self.env.keymap.platform()).unwrap_or_else(|| key.text_name().to_string())
|
||||
}
|
||||
|
||||
/// The holder's label, with its scope when that is not Application.
|
||||
fn holder_text(&self, h: &KeyHolder) -> String {
|
||||
let label = self.label_of(&h.holder.command);
|
||||
if h.scope.is_app() { label } else { fill(self.ui("{label} ({scope})"), &[("label", &label), ("scope", &self.scope_name(&h.scope))]) }
|
||||
}
|
||||
|
||||
pub(super) fn keyboard_pane(&mut self, ui: &mut Ui) {
|
||||
let platform = self.env.keymap.platform();
|
||||
let held = if self.state.recording.is_none() { ui.input(|i| Mods::from_egui(&i.modifiers, platform)) } else { Mods::NONE };
|
||||
let mut clicks = Clicks::default();
|
||||
let rect = ui.max_rect();
|
||||
ui.painter().hline(rect.x_range(), rect.min.y, ui.visuals().widgets.noninteractive.bg_stroke);
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let layout = if platform.is_mac() { self.ui("Keyboard: US (macOS)") } else { self.ui("Keyboard: US") };
|
||||
ui.label(RichText::new(self.vis(&layout)).color(self.style.dim));
|
||||
ui.add_space(8.0);
|
||||
for &m in self.mods_shown() {
|
||||
let name = self.mod_name(m);
|
||||
let on = m.get(union(self.state.keyboard.mods, held));
|
||||
let r = ui.add(Button::selectable(on, self.vis(&name)));
|
||||
self.tag(|| format!("shortcuts.mod.{}", m.id()), r.rect, &name);
|
||||
if r.clicked() {
|
||||
clicks.toggle = Some(m);
|
||||
}
|
||||
}
|
||||
ui.add_space(12.0);
|
||||
self.keyboard_legend(ui);
|
||||
});
|
||||
let mods = union(self.state.keyboard.mods, held);
|
||||
let body = ui.available_rect_before_wrap();
|
||||
let gap = 12.0;
|
||||
let list_w = (body.width() * 0.3).clamp(160.0, 320.0).min(body.width() / 2.0);
|
||||
let rtl = self.env.text.rtl();
|
||||
let (kb, list) = if rtl {
|
||||
(
|
||||
Rect::from_min_max(pos2(body.min.x + list_w + gap, body.min.y), body.max),
|
||||
Rect::from_min_max(body.min, pos2(body.min.x + list_w, body.max.y)),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
Rect::from_min_max(body.min, pos2(body.max.x - list_w - gap, body.max.y)),
|
||||
Rect::from_min_max(pos2(body.max.x - list_w, body.min.y), body.max),
|
||||
)
|
||||
};
|
||||
self.keys_drawn(ui, kb, mods, &mut clicks);
|
||||
self.child(ui, list, |d, ui| d.key_list(ui, mods, &mut clicks));
|
||||
ui.advance_cursor_after_rect(body);
|
||||
|
||||
let kb_state = &mut self.state.keyboard;
|
||||
if let Some(m) = clicks.toggle {
|
||||
// A held modifier is on anyway; clicking it turns the toggle off.
|
||||
if m.get(held) {
|
||||
let mut off = kb_state.mods;
|
||||
if m.get(off) {
|
||||
m.flip(&mut off);
|
||||
}
|
||||
kb_state.mods = off;
|
||||
} else {
|
||||
m.flip(&mut kb_state.mods);
|
||||
}
|
||||
}
|
||||
if let Some(key) = clicks.key {
|
||||
kb_state.key = Some(key);
|
||||
}
|
||||
if let Some(c) = clicks.go {
|
||||
self.state.go_to(&c);
|
||||
}
|
||||
if clicks.assign
|
||||
&& let (Some(command), Some(key)) = (self.state.selected.clone(), self.state.keyboard.key)
|
||||
{
|
||||
let trigger = Trigger::single(Chord { mods, key });
|
||||
let binding = match &self.state.context {
|
||||
Some(scope) => Binding::in_scope(trigger, scope.clone()),
|
||||
None => Binding::new(trigger),
|
||||
};
|
||||
self.state.stop_recording();
|
||||
self.state.commit(self.env, &command, None, binding);
|
||||
}
|
||||
}
|
||||
|
||||
fn keyboard_legend(&self, ui: &mut Ui) {
|
||||
let s = &self.style;
|
||||
for (color, text) in [
|
||||
(s.app_key, self.ui("Application")),
|
||||
(s.scoped_key, self.ui("Panel or context")),
|
||||
(s.both_key, self.ui("Both")),
|
||||
(s.modifier_key, self.ui("Modifier on")),
|
||||
] {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(12.0, 12.0), Sense::hover());
|
||||
ui.painter().rect_filled(r, 2.0, color);
|
||||
ui.label(RichText::new(self.vis(&text)).color(self.style.dim));
|
||||
}
|
||||
}
|
||||
|
||||
/// The keycaps in `area`, scaled to fit.
|
||||
fn keys_drawn(&mut self, ui: &mut Ui, area: Rect, mods: Mods, clicks: &mut Clicks) {
|
||||
let mac = self.env.keymap.platform().is_mac();
|
||||
let u = (area.width() / UNITS_W).min(area.height() / UNITS_H).max(1.0);
|
||||
let origin = area.min;
|
||||
let row_y = |row: usize| origin.y + row as f32 * u + if row > 0 { 0.25 * u } else { 0.0 };
|
||||
let index = self.state.keyboard.index(self.env.keymap);
|
||||
let index = &index.1;
|
||||
let bottom = if mac { MAC_BOTTOM } else { PC_BOTTOM };
|
||||
let rows = std::iter::once(FUNCTION_ROW).chain(MAIN_ROWS[..4].iter().copied()).chain(std::iter::once(bottom));
|
||||
for (r, row) in rows.enumerate() {
|
||||
let mut x = origin.x;
|
||||
for &(cap, w) in row {
|
||||
let rect = Rect::from_min_size(pos2(x, row_y(r)), vec2(w * u, u));
|
||||
x += w * u;
|
||||
self.cap(ui, rect, cap, u, mods, index, clicks);
|
||||
}
|
||||
}
|
||||
let nav_x = origin.x + 15.5 * u;
|
||||
for &(r, col, key) in NAV {
|
||||
let rect = Rect::from_min_size(pos2(nav_x + col * u, row_y(r)), vec2(u, u));
|
||||
self.cap(ui, rect, Cap::Key(key), u, mods, index, clicks);
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn cap(&mut self, ui: &mut Ui, rect: Rect, cap: Cap, u: f32, mods: Mods, index: &Index, clicks: &mut Clicks) {
|
||||
if matches!(cap, Cap::Gap) {
|
||||
return;
|
||||
}
|
||||
let r = rect.shrink((u * 0.05).clamp(1.0, 2.0));
|
||||
let font = FontId::proportional((u * 0.26).clamp(7.0, 12.0));
|
||||
let s = self.style;
|
||||
let (bg, legend, title) = match cap {
|
||||
Cap::Key(key) => {
|
||||
let holders = index.get(&Chord { mods, key }.effective(self.env.keymap.platform())).map_or(&[][..], Vec::as_slice);
|
||||
let bg = match class(holders) {
|
||||
Class::Free => s.free_key,
|
||||
Class::App => s.app_key,
|
||||
Class::Scoped => s.scoped_key,
|
||||
Class::Both => s.both_key,
|
||||
};
|
||||
// The application-wide holder names the key; a scoped one when there is none.
|
||||
let first = holders.iter().find(|h| h.scope.is_app()).or(holders.first());
|
||||
(bg, self.cap_legend(key), first.map(|h| self.label_of(&h.holder.command)))
|
||||
}
|
||||
Cap::Mod(m) => {
|
||||
let glyph = self.env.keymap.platform().is_mac().then(|| mod_glyph(m).to_string());
|
||||
(if m.get(mods) { s.modifier_key } else { s.free_key }, self.mod_word(m), glyph)
|
||||
}
|
||||
Cap::CapsLock => (s.free_key.gamma_multiply(0.7), self.ui("Caps Lock"), None),
|
||||
Cap::System => {
|
||||
let name = if self.env.keymap.platform() == crate::chord::Platform::Windows { self.ui("Win") } else { self.ui("Super") };
|
||||
(s.free_key.gamma_multiply(0.7), name, None)
|
||||
}
|
||||
Cap::Gap => return,
|
||||
};
|
||||
let ink = ink(bg);
|
||||
ui.painter().rect_filled(r, CornerRadius::same(3), bg);
|
||||
let pad = (u * 0.1).clamp(2.0, 4.0);
|
||||
let text_w = (r.width() - 2.0 * pad).max(1.0);
|
||||
let lines = |text: &str, rows: usize, color: Color32| {
|
||||
let mut job = LayoutJob::single_section(text.to_string(), TextFormat::simple(font.clone(), color));
|
||||
job.wrap = TextWrapping { max_width: text_w, max_rows: rows, break_anywhere: false, overflow_character: Some('…') };
|
||||
ui.painter().layout_job(job)
|
||||
};
|
||||
if let Some(t) = &title {
|
||||
let rows = if r.height() > 4.0 * font.size { 2 } else { 1 };
|
||||
let g = lines(&self.vis(t), rows, ink);
|
||||
ui.painter().galley(r.min + vec2(pad, pad * 0.5), g, ink);
|
||||
}
|
||||
// A cap without a command name has room for a two-line legend ("page up").
|
||||
let legend_rows = if title.is_none() && r.height() > 3.0 * font.size { 2 } else { 1 };
|
||||
let g = lines(&self.vis(&legend), legend_rows, ink.gamma_multiply(0.85));
|
||||
ui.painter().galley(pos2(r.min.x + pad, r.max.y - pad * 0.5 - g.size().y), g, ink);
|
||||
|
||||
let Cap::Key(key) = cap else {
|
||||
if let Cap::Mod(m) = cap {
|
||||
// Modifier caps toggle like the buttons above; the buttons are their accessible form.
|
||||
let resp = ui.interact(r, self.base.with(("kbmod", m.id(), r.min.x as i32)), Sense::CLICK);
|
||||
if resp.clicked() {
|
||||
clicks.toggle = Some(m);
|
||||
}
|
||||
if resp.hovered() {
|
||||
ui.painter().rect_stroke(r, CornerRadius::same(3), Stroke::new(1.5, ink), StrokeKind::Inside);
|
||||
}
|
||||
}
|
||||
return;
|
||||
};
|
||||
let holders = index.get(&Chord { mods, key }.effective(self.env.keymap.platform())).map_or(&[][..], Vec::as_slice);
|
||||
let chord = self.chord(&Trigger::single(Chord { mods, key }));
|
||||
let spoken = if mods.is_none() { self.key_name(key) } else { chord };
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
for h in holders {
|
||||
let t = self.holder_text(h);
|
||||
if !names.contains(&t) {
|
||||
names.push(t);
|
||||
}
|
||||
}
|
||||
let a11y = if names.is_empty() { spoken } else { fill(self.ui("{chord}: {label}"), &[("chord", &spoken), ("label", &names.join(", "))]) };
|
||||
let selected = self.state.keyboard.key == Some(key);
|
||||
let resp = ui.interact(r, self.base.with(("key", key.name())), Sense::click());
|
||||
resp.widget_info(|| WidgetInfo::selected(Role::Button, true, selected, &a11y));
|
||||
let description = match class(holders) {
|
||||
Class::Free => self.ui("Not assigned"),
|
||||
Class::App => self.ui("Application"),
|
||||
Class::Scoped => self.ui("Panel or context"),
|
||||
Class::Both => self.ui("Both"),
|
||||
};
|
||||
ui.ctx().accesskit_node_builder(resp.id, |node| node.set_description(description));
|
||||
self.tag(|| format!("shortcuts.key.{}", key.name()), r, &a11y);
|
||||
let v = ui.visuals();
|
||||
if selected {
|
||||
ui.painter().rect_stroke(r, CornerRadius::same(3), Stroke::new(2.0, v.strong_text_color()), StrokeKind::Outside);
|
||||
} else if resp.has_focus() {
|
||||
ui.painter().rect_stroke(r, CornerRadius::same(3), v.selection.stroke, StrokeKind::Outside);
|
||||
} else if resp.hovered() {
|
||||
ui.painter().rect_stroke(r, CornerRadius::same(3), Stroke::new(1.5, ink), StrokeKind::Inside);
|
||||
}
|
||||
if resp.clicked() {
|
||||
clicks.key = Some(key);
|
||||
}
|
||||
if !names.is_empty() {
|
||||
resp.on_hover_text(self.vis(&names.join("\n")));
|
||||
}
|
||||
}
|
||||
|
||||
/// The clicked key's shortcuts with any modifiers, and Assign to Selected.
|
||||
fn key_list(&mut self, ui: &mut Ui, mods: Mods, clicks: &mut Clicks) {
|
||||
let Some(key) = self.state.keyboard.key else {
|
||||
ui.label(RichText::new(self.vis(&self.ui("Click a key to see its shortcuts"))).color(self.style.dim));
|
||||
return;
|
||||
};
|
||||
let platform = self.env.keymap.platform();
|
||||
let title = fill(self.ui("Key: {key}"), &[("key", &self.key_name(key))]);
|
||||
ui.label(RichText::new(self.vis(&title)).strong());
|
||||
if self.env.options.editable {
|
||||
let chord = self.chord(&Trigger::single(Chord { mods, key }));
|
||||
let selected = self.state.selected.clone().filter(|c| self.env.keymap.bindable(c).is_some());
|
||||
let label = self.ui("Assign to Selected");
|
||||
let r = ui.add_enabled(selected.is_some(), Button::new(self.vis(&label)));
|
||||
self.tag(|| "shortcuts.assignKey".into(), r.rect, &label);
|
||||
let r = match &selected {
|
||||
Some(c) => r.on_hover_text(
|
||||
self.vis_chord(&fill(self.ui("Assign {chord} to {label}"), &[("chord", &chord), ("label", &self.label_of(c))]), &chord),
|
||||
),
|
||||
None => r.on_disabled_hover_text(self.vis(&self.ui("Select a command first"))),
|
||||
};
|
||||
if r.clicked() {
|
||||
clicks.assign = true;
|
||||
}
|
||||
}
|
||||
let index = self.state.keyboard.index(self.env.keymap);
|
||||
let mut entries: Vec<(Chord, KeyHolder)> =
|
||||
index.1.iter().filter(|(c, _)| c.key == key).flat_map(|(c, hs)| hs.iter().map(|h| (*c, h.clone()))).collect();
|
||||
entries.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.holder.command.id.cmp(&b.1.holder.command.id)));
|
||||
if entries.is_empty() {
|
||||
ui.label(RichText::new(self.vis(&self.ui("Nothing uses this key"))).color(self.style.dim));
|
||||
return;
|
||||
}
|
||||
let current = Chord { mods, key }.effective(platform);
|
||||
let chord_w = 72.0;
|
||||
let chord_layout = if self.env.text.rtl() { Layout::right_to_left(Align::Center) } else { Layout::left_to_right(Align::Center) };
|
||||
ScrollArea::vertical().id_salt(self.base.with("keylist")).auto_shrink([false, false]).show(ui, |ui| {
|
||||
for (c, h) in &entries {
|
||||
ui.horizontal(|ui| {
|
||||
let mut text = RichText::new(self.chord(&h.holder.binding.trigger));
|
||||
if *c == current {
|
||||
text = text.strong();
|
||||
}
|
||||
ui.allocate_ui_with_layout(vec2(chord_w, ui.spacing().interact_size.y), chord_layout, |ui| ui.label(text));
|
||||
if ui.link(self.vis(&self.holder_text(h))).clicked() {
|
||||
clicks.go = Some(h.holder.command.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
//! The Keyboard Shortcuts dialog (feature `ui`): a table of the catalog with recording,
|
||||
//! conflicts, undo, named sets and import review, over [`Keymap`] and optionally [`Profiles`].
|
||||
//!
|
||||
//! The app keeps a [`DialogState`] while the dialog is open and calls [`ShortcutsDialog::show`]
|
||||
//! (or [`ShortcutsDialog::ui`] inside its own container) every frame. While
|
||||
//! [`DialogState::is_open`] is true the app skips its own key dispatch; the dialog takes the
|
||||
//! frame's key events itself while it records. The app saves on [`Outcome::Ok`] (or on
|
||||
//! [`Outcome::Changed`] for live saving) and drops the state once it is closed.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::chord::Trigger;
|
||||
use crate::command::CommandRef;
|
||||
use crate::import::{ForeignSet, ImportOptions};
|
||||
use crate::keymap::{Bindable, Binding, Keymap};
|
||||
use crate::profiles::{Builtins, ProfileError, Profiles};
|
||||
|
||||
mod capture;
|
||||
mod rows;
|
||||
mod state;
|
||||
mod style;
|
||||
pub mod summary;
|
||||
mod text;
|
||||
mod view;
|
||||
|
||||
pub use state::DialogState;
|
||||
pub use style::DialogStyle;
|
||||
pub use text::{English, I18nText, PLURALS, STRINGS, Text, trigger_text};
|
||||
|
||||
use state::Env;
|
||||
|
||||
/// What the dialog reports for a frame.
|
||||
#[derive(Clone, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum Outcome {
|
||||
/// Closed with OK: save `Profiles` (with sets) or `keymap.overrides()`.
|
||||
Ok,
|
||||
/// Closed with Cancel: the keymap and profiles are back as they were when it opened. When that
|
||||
/// undid edits, `Changed` follows on the next frame.
|
||||
Cancel,
|
||||
/// An edit (for live menus and live saving). When a frame also has another outcome, such as
|
||||
/// `Import` after the Save changes prompt, `Changed` follows on the next frame.
|
||||
Changed,
|
||||
/// The user asked to import: the app opens a file of one of these formats and calls
|
||||
/// [`ShortcutsDialog::import_json`] or [`ShortcutsDialog::review_import`].
|
||||
Import { formats: Vec<&'static str> },
|
||||
/// A set as craft-keymap JSON, for the app to write.
|
||||
Export { name: String, json: String },
|
||||
/// A set in one of [`Options::export_formats`], for the app to write.
|
||||
ExportAs { format: &'static str, name: String, keymap: Box<Keymap> },
|
||||
/// The shortcut summary, for the app to show, save or print.
|
||||
Summary { name: String, html: String, text: String },
|
||||
/// Import answers the user gave (item → command), for the app to keep for later imports.
|
||||
Remembered(BTreeMap<String, CommandRef>),
|
||||
}
|
||||
|
||||
/// What happens when a recorded chord is held by other commands.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ConflictMode {
|
||||
/// Ask with the conflict bar: Take It, Take It and Go to Conflict, Keep Both, Cancel.
|
||||
#[default]
|
||||
Ask,
|
||||
/// Take the chord from the other commands, then say so.
|
||||
Steal,
|
||||
/// Keep both bindings, then say so.
|
||||
Keep,
|
||||
}
|
||||
|
||||
/// An app's own Show entry.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Area {
|
||||
pub id: &'static str,
|
||||
pub label: &'static str,
|
||||
pub rows: fn(&Bindable) -> bool,
|
||||
}
|
||||
|
||||
/// A read-only row for a key outside the catalog.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FixedRow {
|
||||
pub group: String,
|
||||
pub label: String,
|
||||
/// The keys as shown.
|
||||
pub keys: String,
|
||||
/// The trigger, when the row has one, so a catalog binding on it can be pointed out.
|
||||
pub chord: Option<Trigger>,
|
||||
}
|
||||
|
||||
/// A file format an app reads or writes itself.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Format {
|
||||
pub id: &'static str,
|
||||
pub label: &'static str,
|
||||
pub extensions: &'static [&'static str],
|
||||
}
|
||||
|
||||
/// A rule an app adds for which bindings a command may get; `Err` carries the message shown.
|
||||
pub type Accept = Box<dyn Fn(&Bindable, &Binding) -> Result<(), String>>;
|
||||
/// Called for every control once per frame with (automation id, rect, label).
|
||||
pub type OnWidget = Box<dyn Fn(&str, egui::Rect, &str)>;
|
||||
|
||||
/// How the dialog looks and behaves. [`Options::default`] gives the defaults noted on each field;
|
||||
/// set fields on it, or with [`Options::with`].
|
||||
#[non_exhaustive]
|
||||
pub struct Options {
|
||||
/// "Keyboard Shortcuts": the window title [`ShortcutsDialog::show`] draws, and the summary's
|
||||
/// heading. [`ShortcutsDialog::ui`] draws no title; the host's container shows its own.
|
||||
pub title: &'static str,
|
||||
/// true; false shows the table read-only with Close and Summarize.
|
||||
pub editable: bool,
|
||||
/// "Custom": the name edits of a built-in set are saved under.
|
||||
pub custom_set_name: &'static str,
|
||||
/// Ask.
|
||||
pub conflicts: ConflictMode,
|
||||
/// true: Keep Both is offered.
|
||||
pub allow_keep: bool,
|
||||
/// false: a recorded chord waits [`DOUBLE_PRESS`](crate::DOUBLE_PRESS) for a second press.
|
||||
pub double_press: bool,
|
||||
/// false: Backspace or Delete without modifiers removes the binding being recorded over.
|
||||
pub backspace_clears: bool,
|
||||
/// false: Enter when idle is OK.
|
||||
pub enter_is_ok: bool,
|
||||
/// false: rows sort by translated label instead of catalog order.
|
||||
pub sort_by_label: bool,
|
||||
/// false: Show as tabs instead of a dropdown.
|
||||
pub area_tabs: bool,
|
||||
/// The app's own Show entries.
|
||||
pub areas: Vec<Area>,
|
||||
/// `None`: every catalog entry is listed. Otherwise the table, its Show entries and search
|
||||
/// list only the entries it returns true for; the others keep their bindings and still count
|
||||
/// in conflicts.
|
||||
pub visible: Option<fn(&Bindable) -> bool>,
|
||||
/// false: the on-screen keyboard pane.
|
||||
pub keyboard: bool,
|
||||
pub fixed: Vec<FixedRow>,
|
||||
pub import_formats: Vec<Format>,
|
||||
pub export_formats: Vec<Format>,
|
||||
/// true: Summarize is offered.
|
||||
pub summary: bool,
|
||||
pub accept: Option<Accept>,
|
||||
pub on_widget: Option<OnWidget>,
|
||||
/// `None`: [`DialogStyle::from_visuals`].
|
||||
pub style: Option<DialogStyle>,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Options {
|
||||
Options {
|
||||
title: "Keyboard Shortcuts",
|
||||
editable: true,
|
||||
custom_set_name: "Custom",
|
||||
conflicts: ConflictMode::Ask,
|
||||
allow_keep: true,
|
||||
double_press: false,
|
||||
backspace_clears: false,
|
||||
enter_is_ok: false,
|
||||
sort_by_label: false,
|
||||
area_tabs: false,
|
||||
areas: Vec::new(),
|
||||
visible: None,
|
||||
keyboard: false,
|
||||
fixed: Vec::new(),
|
||||
import_formats: Vec::new(),
|
||||
export_formats: Vec::new(),
|
||||
summary: true,
|
||||
accept: None,
|
||||
on_widget: None,
|
||||
style: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Options {
|
||||
/// `self` with `f` applied, for options built in one expression:
|
||||
/// `Options::default().with(|o| o.keyboard = true)`.
|
||||
pub fn with(mut self, f: impl FnOnce(&mut Options)) -> Options {
|
||||
f(&mut self);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The format id of craft-keymap's own JSON in [`Outcome::Import`].
|
||||
pub const JSON_FORMAT: &str = "craft-keymap";
|
||||
|
||||
/// The dialog for one frame: what it edits, borrowed, and how it looks.
|
||||
pub struct ShortcutsDialog<'a> {
|
||||
keymap: &'a mut Keymap,
|
||||
text: &'a dyn Text,
|
||||
sets: Option<(&'a mut Profiles, &'a Builtins<'a>)>,
|
||||
options: Option<&'a Options>,
|
||||
}
|
||||
|
||||
impl<'a> ShortcutsDialog<'a> {
|
||||
pub fn new(keymap: &'a mut Keymap, text: &'a dyn Text) -> Self {
|
||||
ShortcutsDialog { keymap, text, sets: None, options: None }
|
||||
}
|
||||
|
||||
/// Shows and edits named sets.
|
||||
pub fn sets(mut self, profiles: &'a mut Profiles, builtins: &'a Builtins<'a>) -> Self {
|
||||
self.sets = Some((profiles, builtins));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn options(mut self, options: &'a Options) -> Self {
|
||||
self.options = Some(options);
|
||||
self
|
||||
}
|
||||
|
||||
fn with_env<R>(self, f: impl FnOnce(&mut Env) -> R) -> R {
|
||||
let fallback;
|
||||
let options = match self.options {
|
||||
Some(o) => o,
|
||||
None => {
|
||||
fallback = Options::default();
|
||||
&fallback
|
||||
}
|
||||
};
|
||||
let mut env = Env { keymap: self.keymap, sets: self.sets, options, text: self.text };
|
||||
f(&mut env)
|
||||
}
|
||||
|
||||
/// A window with title, body and Cancel/OK, sized to the screen (at least 640×480 where the
|
||||
/// screen allows, at most 1320×900). Closing it with × is Cancel.
|
||||
pub fn show(self, ctx: &egui::Context, state: &mut DialogState) -> Option<Outcome> {
|
||||
self.with_env(|env| {
|
||||
if !state.is_showing() {
|
||||
return state.finish();
|
||||
}
|
||||
let title = env.text.visual(&env.text.ui(env.options.title));
|
||||
let screen = ctx.content_rect().size();
|
||||
let max = egui::vec2(1320.0, 900.0).min(screen - egui::vec2(16.0, 16.0)).max(egui::vec2(240.0, 180.0));
|
||||
let min = egui::vec2(640.0, 480.0).min(max);
|
||||
let mut open = true;
|
||||
let mut out = None;
|
||||
egui::Window::new(title)
|
||||
.id(egui::Id::unique("craft_keymap.shortcuts"))
|
||||
.collapsible(false)
|
||||
.resizable(true)
|
||||
.open(&mut open)
|
||||
.default_size((screen * 0.8).clamp(min, max))
|
||||
.min_size(min)
|
||||
.max_size(max)
|
||||
.show(ctx, |ui| out = frame(ui, env, state));
|
||||
if !open && state.is_showing() {
|
||||
state.cancel(env);
|
||||
out = state.finish();
|
||||
}
|
||||
if state.change_pending() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
out
|
||||
})
|
||||
}
|
||||
|
||||
/// The body only, for a host's own modal, preferences page or backstage, which draws the
|
||||
/// title. It fills the available rectangle.
|
||||
pub fn ui(self, ui: &mut egui::Ui, state: &mut DialogState) -> Option<Outcome> {
|
||||
self.with_env(|env| frame(ui, env, state))
|
||||
}
|
||||
|
||||
/// OK, for hosts that draw their own button.
|
||||
pub fn ok(self, state: &mut DialogState) {
|
||||
self.with_env(|env| {
|
||||
state.begin(env);
|
||||
state.ok(env);
|
||||
});
|
||||
}
|
||||
|
||||
/// Cancel, for hosts that draw their own button.
|
||||
pub fn cancel(self, state: &mut DialogState) {
|
||||
self.with_env(|env| {
|
||||
state.begin(env);
|
||||
state.cancel(env);
|
||||
});
|
||||
}
|
||||
|
||||
/// Reads a craft-keymap JSON set the app loaded after [`Outcome::Import`]. With sets it becomes
|
||||
/// a new set, which is loaded; without, its overrides replace the keymap's as one undo step.
|
||||
/// Returns the set's name.
|
||||
pub fn import_json(self, state: &mut DialogState, text: &str) -> Result<String, ProfileError> {
|
||||
self.with_env(|env| {
|
||||
state.begin(env);
|
||||
state.import_json(env, text)
|
||||
})
|
||||
}
|
||||
|
||||
/// Opens the review of a foreign set the app read: what will change, what did not match and
|
||||
/// why, with suggestions to pick from.
|
||||
pub fn review_import(self, state: &mut DialogState, set: ForeignSet, options: ImportOptions) {
|
||||
self.with_env(|env| {
|
||||
state.begin(env);
|
||||
state.review_import(env, set, options);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame: take recorded keys before anything else sees them, draw, report.
|
||||
fn frame(ui: &mut egui::Ui, env: &mut Env, state: &mut DialogState) -> Option<Outcome> {
|
||||
state.begin(env);
|
||||
state.input(env, ui.ctx());
|
||||
if state.is_showing() {
|
||||
view::body(ui, env, state);
|
||||
}
|
||||
let out = state.finish();
|
||||
if state.change_pending() {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
//! The foreign import review (§2.7 of the dialog plan). It takes the place of the table and
|
||||
//! detail pane: what the set will change, what did not match and why, suggestions to pick from,
|
||||
//! and after the import the report of what was skipped, taken or failed.
|
||||
|
||||
use egui::text::{LayoutJob, TextFormat};
|
||||
use egui::{ComboBox, Label, Rect, RichText, ScrollArea, TextEdit, TextStyle, Ui};
|
||||
|
||||
use super::{Draw, FIELD_W, fill};
|
||||
use crate::chord::foreign::{ForeignError, ReadNote};
|
||||
use crate::command::CommandRef;
|
||||
use crate::import::{FailedChange, ImportPlan, ImportReport, NoChangeReason, SkipReason, UnmatchedReason};
|
||||
|
||||
/// One list row: the item, its line, its keys and a note.
|
||||
struct Entry {
|
||||
item: String,
|
||||
line: Option<usize>,
|
||||
keys: String,
|
||||
note: String,
|
||||
/// The note is what the item becomes (Will change), drawn in the text color, not dimmed.
|
||||
to: bool,
|
||||
/// Chord text inside the note, kept out of bidi reordering.
|
||||
note_chord: String,
|
||||
}
|
||||
|
||||
enum Act {
|
||||
Pick(usize, usize),
|
||||
Import,
|
||||
Close,
|
||||
Copy(String),
|
||||
}
|
||||
|
||||
impl Draw<'_, '_> {
|
||||
/// Draws the review in `rect` while one is open; returns whether it drew.
|
||||
pub(super) fn review(&mut self, ui: &mut Ui, rect: Rect) -> bool {
|
||||
let Some(r) = self.state.review.as_ref() else { return false };
|
||||
let (plan, name, done) = (r.plan.clone(), r.name.clone(), r.done.clone());
|
||||
let mut act = None;
|
||||
self.child(ui, rect, |d, ui| {
|
||||
act = match &done {
|
||||
Some((set, report)) => d.after_report(ui, set, report),
|
||||
None => d.plan_view(ui, &plan, name),
|
||||
};
|
||||
});
|
||||
match act {
|
||||
Some(Act::Pick(s, c)) => self.state.pick_suggestion(self.env, s, c),
|
||||
Some(Act::Import) => self.state.import_reviewed(self.env),
|
||||
Some(Act::Close) => self.state.close_review(),
|
||||
Some(Act::Copy(text)) => ui.ctx().copy_text(text),
|
||||
None => {}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn line_text(&self, line: Option<usize>) -> Option<String> {
|
||||
line.map(|n| fill(self.ui("line {n}"), &[("n", &n.to_string())]))
|
||||
}
|
||||
|
||||
/// "item · line n · keys — note" on one wrapping line, the item in the strong color.
|
||||
fn entry(&self, ui: &mut Ui, e: &Entry) {
|
||||
let font = TextStyle::Body.resolve(ui.style());
|
||||
let strong = ui.visuals().strong_text_color();
|
||||
let dim = self.style.dim;
|
||||
let text = ui.visuals().text_color();
|
||||
let mut parts = vec![(self.vis(&e.item), strong)];
|
||||
if let Some(line) = self.line_text(e.line) {
|
||||
parts.extend([(" · ".to_string(), dim), (self.vis(&line), dim)]);
|
||||
}
|
||||
if !e.keys.is_empty() {
|
||||
parts.extend([(" · ".to_string(), dim), (e.keys.clone(), text)]);
|
||||
}
|
||||
if !e.note.is_empty() {
|
||||
let color = if e.to { text } else { dim };
|
||||
parts.extend([(" — ".to_string(), color), (self.vis_chord(&e.note, &e.note_chord), color)]);
|
||||
}
|
||||
let mut job = LayoutJob::default();
|
||||
for (s, color) in self.ordered(parts) {
|
||||
job.append(&s, 0.0, TextFormat::simple(font.clone(), color));
|
||||
}
|
||||
ui.add(Label::new(job).wrap());
|
||||
}
|
||||
|
||||
fn section(&self, ui: &mut Ui, title: &str, entries: &[Entry]) {
|
||||
if entries.is_empty() {
|
||||
return;
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.label(RichText::new(self.vis(&fill(self.ui("{title} ({n})"), &[("title", title), ("n", &entries.len().to_string())]))).strong());
|
||||
for e in entries {
|
||||
self.entry(ui, e);
|
||||
}
|
||||
}
|
||||
|
||||
fn unmatched_reason(&self, r: UnmatchedReason) -> String {
|
||||
match r {
|
||||
UnmatchedReason::NoMatch => self.ui("no command has this name"),
|
||||
UnmatchedReason::Ambiguous => self.ui("more than one command fits"),
|
||||
UnmatchedReason::Context => self.ui("in a context that is not imported"),
|
||||
UnmatchedReason::Tool => self.ui("only a command of the other kind fits (tool or menu command)"),
|
||||
}
|
||||
}
|
||||
|
||||
fn foreign_error(&self, e: &ForeignError) -> String {
|
||||
match e {
|
||||
ForeignError::Empty => self.ui("empty shortcut"),
|
||||
ForeignError::TooLong => self.ui("the shortcut is too long"),
|
||||
ForeignError::UnknownKey(k) => fill(self.ui("unknown key {key}"), &[("key", k)]),
|
||||
ForeignError::UnsupportedModifier(m) => fill(self.ui("unsupported modifier {key}"), &[("key", m)]),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_note(&self, n: ReadNote) -> String {
|
||||
match n {
|
||||
ReadNote::Numpad => self.ui("numeric keypad key read as main key"),
|
||||
}
|
||||
}
|
||||
|
||||
fn plan_view(&mut self, ui: &mut Ui, plan: &ImportPlan, mut name: String) -> Option<Act> {
|
||||
let mut act = None;
|
||||
let report = &plan.report;
|
||||
let set = report.set.clone().unwrap_or_else(|| self.ui("Imported"));
|
||||
ui.label(RichText::new(self.vis(&fill(self.ui("Import “{set}”"), &[("set", &set)]))).strong());
|
||||
|
||||
let t = self.env.text;
|
||||
let mut counts = vec![t.plural(plan.commands.len() as u64, "{n} command will change", "{n} commands will change")];
|
||||
let more = [
|
||||
(report.unmatched.len(), t.plural(report.unmatched.len() as u64, "{n} item not matched", "{n} items not matched")),
|
||||
(
|
||||
report.unmatched_without_shortcut,
|
||||
t.plural(report.unmatched_without_shortcut as u64, "{n} item without a shortcut", "{n} items without a shortcut"),
|
||||
),
|
||||
(report.unreadable.len(), t.plural(report.unreadable.len() as u64, "{n} item could not be read", "{n} items could not be read")),
|
||||
(report.approximated.len(), t.plural(report.approximated.len() as u64, "{n} key read approximately", "{n} keys read approximately")),
|
||||
(report.truncated, t.plural(report.truncated as u64, "{n} entry cut at a limit", "{n} entries cut at a limit")),
|
||||
];
|
||||
counts.extend(more.into_iter().filter(|(n, _)| *n > 0).map(|(_, s)| s));
|
||||
ui.label(RichText::new(self.vis(&counts.join(" · "))).color(self.style.dim));
|
||||
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let name_label = self.ui("Set name:");
|
||||
let l = ui.label(self.vis(&name_label));
|
||||
let edit = ui.add(TextEdit::singleline(&mut name).id(self.base.with("import_name")).desired_width(FIELD_W)).labelled_by(l.id);
|
||||
self.text_field(&edit);
|
||||
self.tag(|| "shortcuts.import.name".into(), edit.rect, &name_label);
|
||||
let import = if self.env.sets.is_some() { self.ui("Import as New Set") } else { self.ui("Import") };
|
||||
let valid = self.env.sets.is_none() || crate::profiles::set_name(&name).is_some();
|
||||
if self.button(ui, valid, &import, "shortcuts.import.ok") {
|
||||
act = Some(Act::Import);
|
||||
}
|
||||
if self.button(ui, true, &self.ui("Cancel Import"), "shortcuts.import.cancel") {
|
||||
act = Some(Act::Close);
|
||||
}
|
||||
});
|
||||
if let Some(r) = self.state.review.as_mut() {
|
||||
r.name = name;
|
||||
}
|
||||
|
||||
ScrollArea::vertical().id_salt(self.base.with("review")).auto_shrink([false, false]).show(ui, |ui| {
|
||||
let chord_list = |d: &Self, c: &crate::import::Planned| -> String {
|
||||
let home = d.env.keymap.bindable(&c.command).map(|b| b.scope.clone());
|
||||
if c.bindings.is_empty() {
|
||||
return d.ui("None");
|
||||
}
|
||||
c.bindings.iter().map(|b| d.binding_text(&b.binding, home.as_ref())).collect::<Vec<_>>().join(", ")
|
||||
};
|
||||
let changes: Vec<Entry> = plan
|
||||
.commands
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let chords = chord_list(self, c);
|
||||
Entry {
|
||||
item: c.item.clone(),
|
||||
line: c.line,
|
||||
keys: String::new(),
|
||||
note: fill(self.ui("{label}: {chord}"), &[("label", &self.label_of(&c.command)), ("chord", &chords)]),
|
||||
to: true,
|
||||
note_chord: chords,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
self.section(ui, &self.ui("Will change"), &changes);
|
||||
|
||||
if !report.suggestions.is_empty() {
|
||||
ui.add_space(4.0);
|
||||
let title = fill(self.ui("Suggestions ({n})"), &[("n", &report.suggestions.len().to_string())]);
|
||||
ui.label(RichText::new(self.vis(&title)).strong());
|
||||
for (si, s) in report.suggestions.iter().enumerate() {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
self.entry(
|
||||
ui,
|
||||
&Entry {
|
||||
item: s.item.clone(),
|
||||
line: s.line,
|
||||
keys: String::new(),
|
||||
note: String::new(),
|
||||
to: false,
|
||||
note_chord: String::new(),
|
||||
},
|
||||
);
|
||||
let label = fill(self.ui("Command for {item}"), &[("item", &s.item)]);
|
||||
let choose = self.ui("Choose a command…");
|
||||
let combo = ComboBox::from_id_salt(self.base.with(("suggestion", si))).selected_text(self.vis(&choose)).show_ui(ui, |ui| {
|
||||
for (ci, c) in s.candidates.iter().enumerate() {
|
||||
if ui.selectable_label(false, self.vis(&self.label_of(c))).clicked() {
|
||||
act = Some(Act::Pick(si, ci));
|
||||
}
|
||||
}
|
||||
});
|
||||
let resp = combo.response.on_hover_text(self.vis(&label));
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, &label));
|
||||
self.tag(|| format!("shortcuts.import.suggestion.{si}"), resp.rect, &label);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let unmatched: Vec<Entry> = report
|
||||
.unmatched
|
||||
.iter()
|
||||
.map(|u| Entry {
|
||||
item: u.item.clone(),
|
||||
line: u.line,
|
||||
keys: u.keys.clone(),
|
||||
note: self.unmatched_reason(u.reason),
|
||||
to: false,
|
||||
note_chord: String::new(),
|
||||
})
|
||||
.collect();
|
||||
self.section(ui, &self.ui("Not matched"), &unmatched);
|
||||
let unreadable: Vec<Entry> = report
|
||||
.unreadable
|
||||
.iter()
|
||||
.map(|u| Entry {
|
||||
item: u.item.clone(),
|
||||
line: u.line,
|
||||
keys: u.keys.clone(),
|
||||
note: self.foreign_error(&u.reason),
|
||||
to: false,
|
||||
note_chord: String::new(),
|
||||
})
|
||||
.collect();
|
||||
self.section(ui, &self.ui("Unreadable"), &unreadable);
|
||||
let approximated: Vec<Entry> = report
|
||||
.approximated
|
||||
.iter()
|
||||
.map(|a| Entry {
|
||||
item: a.item.clone(),
|
||||
line: a.line,
|
||||
keys: a.keys.clone(),
|
||||
note: self.read_note(a.note),
|
||||
to: false,
|
||||
note_chord: String::new(),
|
||||
})
|
||||
.collect();
|
||||
self.section(ui, &self.ui("Approximated"), &approximated);
|
||||
let kept: Vec<Entry> = report
|
||||
.matched_without_change
|
||||
.iter()
|
||||
.map(|m| Entry {
|
||||
item: m.item.clone(),
|
||||
line: m.line,
|
||||
keys: String::new(),
|
||||
note: match m.reason {
|
||||
NoChangeReason::PanelMenu => {
|
||||
fill(self.ui("{label} keeps its shortcuts (matched by a panel menu name)"), &[("label", &self.label_of(&m.command))])
|
||||
}
|
||||
},
|
||||
to: false,
|
||||
note_chord: String::new(),
|
||||
})
|
||||
.collect();
|
||||
self.section(ui, &self.ui("Matched without change"), &kept);
|
||||
});
|
||||
act
|
||||
}
|
||||
|
||||
fn skip_note(&self, reason: SkipReason, kept_by: Option<&CommandRef>) -> String {
|
||||
match (reason, kept_by) {
|
||||
(SkipReason::Taken, Some(c)) => fill(self.ui("taken by {label}"), &[("label", &self.label_of(c))]),
|
||||
(SkipReason::Taken, None) => self.ui("taken by a later entry"),
|
||||
(SkipReason::Reserved, _) => self.ui("reserved by the system"),
|
||||
(SkipReason::UnknownScope, _) => self.ui("the scope is unknown"),
|
||||
}
|
||||
}
|
||||
|
||||
fn failed_note(&self, change: FailedChange) -> String {
|
||||
match change {
|
||||
FailedChange::Bind => self.ui("the set's shortcuts could not be added"),
|
||||
FailedChange::Clear => self.ui("the shortcuts could not be removed"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The report's lists: skipped keys, shortcuts taken from other commands, failed changes.
|
||||
fn report_lists(&self, report: &ImportReport) -> [(String, Vec<Entry>); 3] {
|
||||
let skipped = report
|
||||
.skipped
|
||||
.iter()
|
||||
.map(|s| Entry {
|
||||
item: s.item.clone(),
|
||||
line: s.line,
|
||||
keys: s.shortcut.clone(),
|
||||
note: self.skip_note(s.reason, s.kept_by.as_ref()),
|
||||
to: false,
|
||||
note_chord: String::new(),
|
||||
})
|
||||
.collect();
|
||||
let cleared = report
|
||||
.conflicts_cleared
|
||||
.iter()
|
||||
.map(|c| Entry {
|
||||
item: self.label_of(&c.command),
|
||||
line: None,
|
||||
keys: c.shortcut.clone(),
|
||||
note: String::new(),
|
||||
to: false,
|
||||
note_chord: String::new(),
|
||||
})
|
||||
.collect();
|
||||
let failed = report
|
||||
.failed
|
||||
.iter()
|
||||
.map(|f| Entry {
|
||||
item: self.label_of(&f.command),
|
||||
line: None,
|
||||
keys: f.shortcuts.join(", "),
|
||||
note: self.failed_note(f.change),
|
||||
to: false,
|
||||
note_chord: String::new(),
|
||||
})
|
||||
.collect();
|
||||
[(self.ui("Skipped"), skipped), (self.ui("Taken from other commands"), cleared), (self.ui("Not changed"), failed)]
|
||||
}
|
||||
|
||||
fn after_report(&mut self, ui: &mut Ui, set: &str, report: &ImportReport) -> Option<Act> {
|
||||
let mut act = None;
|
||||
let heading = fill(self.ui("Imported as “{set}”"), &[("set", set)]);
|
||||
ui.label(RichText::new(self.vis(&heading)).strong());
|
||||
let changed = self.env.text.plural(report.imported as u64, "{n} command changed", "{n} commands changed");
|
||||
ui.label(RichText::new(self.vis(&changed)).color(self.style.dim));
|
||||
let lists = self.report_lists(report);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if self.button(ui, true, &self.ui("Copy Report"), "shortcuts.import.copy") {
|
||||
act = Some(Act::Copy(self.report_text(&heading, &changed, &lists)));
|
||||
}
|
||||
if self.button(ui, true, &self.ui("Done"), "shortcuts.import.done") {
|
||||
act = Some(Act::Close);
|
||||
}
|
||||
});
|
||||
ScrollArea::vertical().id_salt(self.base.with("report")).auto_shrink([false, false]).show(ui, |ui| {
|
||||
for (title, entries) in &lists {
|
||||
self.section(ui, title, entries);
|
||||
}
|
||||
});
|
||||
act
|
||||
}
|
||||
|
||||
/// The report as plain text for Copy Report (logical order).
|
||||
fn report_text(&self, heading: &str, changed: &str, lists: &[(String, Vec<Entry>)]) -> String {
|
||||
let mut out = format!("{heading}\n{changed}\n");
|
||||
for (title, entries) in lists.iter().filter(|(_, e)| !e.is_empty()) {
|
||||
out.push_str(&format!("\n{title}\n"));
|
||||
for e in entries {
|
||||
let mut line = format!(" {}", e.item);
|
||||
for part in [self.line_text(e.line).unwrap_or_default(), e.keys.clone()] {
|
||||
if !part.is_empty() {
|
||||
line.push_str(" · ");
|
||||
line.push_str(&part);
|
||||
}
|
||||
}
|
||||
if !e.note.is_empty() {
|
||||
line.push_str(" — ");
|
||||
line.push_str(&e.note);
|
||||
}
|
||||
out.push_str(&line);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,692 @@
|
||||
//! The table's model: areas (Show), filters, search, group headers, sorting and the cached list of
|
||||
//! lines the table draws.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
|
||||
use crate::chord::{Platform, Trigger};
|
||||
use crate::command::CommandRef;
|
||||
use crate::keymap::{Bindable, Binding, ConflictKind, Keymap, Kind, Overrides};
|
||||
use crate::ui::Options;
|
||||
use crate::ui::text::{Text, trigger_text, visual_around};
|
||||
|
||||
/// One entry of the Show menu.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) enum AreaId {
|
||||
All,
|
||||
/// A top menu, `paths[0][0]`.
|
||||
Menu(String),
|
||||
Tools,
|
||||
/// A panel scope, by name.
|
||||
Panel(String),
|
||||
/// Commands with no path that are not tools.
|
||||
Other,
|
||||
/// An app area from [`Options::areas`], by id.
|
||||
App(&'static str),
|
||||
/// [`Options::fixed`].
|
||||
Fixed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct AreaEntry {
|
||||
pub id: AreaId,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub(crate) enum Filter {
|
||||
#[default]
|
||||
All,
|
||||
WithShortcut,
|
||||
/// An overrides entry exists for the command.
|
||||
Changed,
|
||||
/// The command is in a [`ConflictKind::Clash`].
|
||||
Conflicts,
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
pub(crate) const ALL: [Filter; 4] = [Filter::All, Filter::WithShortcut, Filter::Changed, Filter::Conflicts];
|
||||
|
||||
pub(crate) fn label(self, text: &dyn Text) -> String {
|
||||
match self {
|
||||
Filter::All => text.ui("All"),
|
||||
Filter::WithShortcut => text.ui("With Shortcut"),
|
||||
Filter::Changed => text.ui("Changed"),
|
||||
Filter::Conflicts => text.ui("Conflicts"),
|
||||
}
|
||||
.into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// A binding as a row shows it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Chip {
|
||||
pub binding: Binding,
|
||||
/// Trigger text, plus ` (Scope)` for a scope other than the command's home scope (display order).
|
||||
pub text: String,
|
||||
/// Not one of the command's defaults.
|
||||
pub changed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Row {
|
||||
/// Position in the catalog.
|
||||
pub index: usize,
|
||||
pub command: CommandRef,
|
||||
/// [`CommandRef::key`], for automation ids and the overrides.
|
||||
pub key: String,
|
||||
/// The translated label.
|
||||
pub label: String,
|
||||
/// Translated path parts between the group header and the label, shown dim before it.
|
||||
pub prefix: Vec<String>,
|
||||
pub chips: Vec<Chip>,
|
||||
/// An overrides entry exists.
|
||||
pub changed: bool,
|
||||
/// A tool sharing a key with another tool of its group.
|
||||
pub cycles: bool,
|
||||
/// In a clash.
|
||||
pub conflict: bool,
|
||||
}
|
||||
|
||||
/// A read-only row from [`Options::fixed`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct FixedLine {
|
||||
pub label: String,
|
||||
pub keys: String,
|
||||
/// The label of a catalog command now bound to the row's chord: drawn struck through.
|
||||
pub now_used_by: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) enum Line {
|
||||
Header { name: String, collapsed: bool },
|
||||
Row(Row),
|
||||
Fixed(FixedLine),
|
||||
}
|
||||
|
||||
/// The lines for one query, area, filter and set of overrides.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct Built {
|
||||
pub lines: Vec<Line>,
|
||||
/// Command and fixed rows shown (headers not counted); 0 shows "No matching commands".
|
||||
pub matches: usize,
|
||||
/// Clash pairs in the whole keymap.
|
||||
pub clashes: usize,
|
||||
/// Shadow pairs in the whole keymap, shown as an information line.
|
||||
pub shadows: usize,
|
||||
}
|
||||
|
||||
impl Built {
|
||||
/// The line index of a command's row.
|
||||
pub(crate) fn position(&self, command: &CommandRef) -> Option<usize> {
|
||||
self.lines.iter().position(|l| matches!(l, Line::Row(r) if r.command == *command))
|
||||
}
|
||||
}
|
||||
|
||||
/// What the lines were built from.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct View<'a> {
|
||||
pub query: &'a str,
|
||||
pub area: &'a AreaId,
|
||||
pub filter: Filter,
|
||||
pub collapsed: &'a BTreeSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Key {
|
||||
query: String,
|
||||
area: AreaId,
|
||||
filter: Filter,
|
||||
collapsed: BTreeSet<String>,
|
||||
overrides: Overrides,
|
||||
platform: Platform,
|
||||
}
|
||||
|
||||
/// The built lines, rebuilt only when the view or the keymap's overrides change.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct RowCache {
|
||||
key: Option<Key>,
|
||||
built: Built,
|
||||
}
|
||||
|
||||
impl RowCache {
|
||||
pub(crate) fn get(&mut self, keymap: &Keymap, options: &Options, text: &dyn Text, view: &View) -> &Built {
|
||||
let fresh = self.key.as_ref().is_some_and(|k| {
|
||||
k.query == view.query
|
||||
&& k.area == *view.area
|
||||
&& k.filter == view.filter
|
||||
&& k.collapsed == *view.collapsed
|
||||
&& k.platform == keymap.platform()
|
||||
&& k.overrides == *keymap.overrides()
|
||||
});
|
||||
if !fresh {
|
||||
self.built = build(keymap, options, text, view);
|
||||
self.key = Some(Key {
|
||||
query: view.query.to_string(),
|
||||
area: view.area.clone(),
|
||||
filter: view.filter,
|
||||
collapsed: view.collapsed.clone(),
|
||||
overrides: keymap.overrides().clone(),
|
||||
platform: keymap.platform(),
|
||||
});
|
||||
}
|
||||
&self.built
|
||||
}
|
||||
|
||||
/// The lines last built.
|
||||
pub(crate) fn built(&self) -> &Built {
|
||||
&self.built
|
||||
}
|
||||
}
|
||||
|
||||
fn top_menu(b: &Bindable) -> Option<&str> {
|
||||
b.paths.first().and_then(|p| p.first()).map(String::as_str)
|
||||
}
|
||||
|
||||
fn is_tool(b: &Bindable) -> bool {
|
||||
matches!(b.kind, Kind::Tool { .. })
|
||||
}
|
||||
|
||||
/// The catalog entries the table lists ([`Options::visible`]).
|
||||
fn listed<'k>(keymap: &'k Keymap, options: &Options) -> impl Iterator<Item = &'k Bindable> + Clone {
|
||||
let visible = options.visible;
|
||||
keymap.catalog().iter().filter(move |b| visible.is_none_or(|f| f(b)))
|
||||
}
|
||||
|
||||
/// The Show entries, in catalog order, leaving out areas with no rows.
|
||||
pub(crate) fn areas(keymap: &Keymap, options: &Options, text: &dyn Text) -> Vec<AreaEntry> {
|
||||
let catalog = listed(keymap, options);
|
||||
let mut out = vec![AreaEntry { id: AreaId::All, label: text.ui("All Commands").into_owned() }];
|
||||
let mut menus: Vec<&str> = Vec::new();
|
||||
for m in catalog.clone().filter_map(top_menu) {
|
||||
if !menus.contains(&m) {
|
||||
menus.push(m);
|
||||
}
|
||||
}
|
||||
for m in menus {
|
||||
let label = craft_i18n::fmt(&text.ui("{menu} Menu"), &[("menu", &text.segment(m))]);
|
||||
out.push(AreaEntry { id: AreaId::Menu(m.to_string()), label });
|
||||
}
|
||||
if catalog.clone().any(is_tool) {
|
||||
out.push(AreaEntry { id: AreaId::Tools, label: text.ui("Tools").into_owned() });
|
||||
}
|
||||
let mut panels: Vec<&str> = keymap.scopes().panels().iter().map(String::as_str).collect();
|
||||
for b in catalog.clone().filter(|b| !b.scope.is_app()) {
|
||||
if !panels.contains(&b.scope.as_str()) {
|
||||
panels.push(b.scope.as_str());
|
||||
}
|
||||
}
|
||||
for p in panels.into_iter().filter(|p| catalog.clone().any(|b| b.scope.as_str() == *p)) {
|
||||
out.push(AreaEntry { id: AreaId::Panel(p.to_string()), label: panel_label(text, p) });
|
||||
}
|
||||
if catalog.clone().any(|b| top_menu(b).is_none() && !is_tool(b)) {
|
||||
out.push(AreaEntry { id: AreaId::Other, label: text.ui("Other").into_owned() });
|
||||
}
|
||||
for a in options.areas.iter().filter(|a| catalog.clone().any(a.rows)) {
|
||||
out.push(AreaEntry { id: AreaId::App(a.id), label: text.segment(a.label).into_owned() });
|
||||
}
|
||||
if !options.fixed.is_empty() {
|
||||
out.push(AreaEntry { id: AreaId::Fixed, label: text.ui("Fixed Keys").into_owned() });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn panel_label(text: &dyn Text, panel: &str) -> String {
|
||||
craft_i18n::fmt(&text.ui("{panel} Panel"), &[("panel", &text.segment(panel))])
|
||||
}
|
||||
|
||||
fn in_area(area: &AreaId, b: &Bindable, options: &Options) -> bool {
|
||||
match area {
|
||||
AreaId::All => true,
|
||||
AreaId::Menu(m) => top_menu(b) == Some(m.as_str()),
|
||||
AreaId::Tools => is_tool(b),
|
||||
AreaId::Panel(p) => b.scope.as_str() == p,
|
||||
AreaId::Other => top_menu(b).is_none() && !is_tool(b),
|
||||
AreaId::App(id) => options.areas.iter().any(|a| a.id == *id && (a.rows)(b)),
|
||||
AreaId::Fixed => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first id segment, capitalized: `layer.lock` → `Layer`.
|
||||
fn id_group(id: &str) -> String {
|
||||
let first = id.split('.').next().unwrap_or(id);
|
||||
let mut chars = first.chars();
|
||||
chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A row's group header (`None`: no header) with its rank among groups, and how many path parts
|
||||
/// the header stands for.
|
||||
pub(crate) fn group(area: &AreaId, b: &Bindable, submenus: bool, text: &dyn Text) -> (u8, Option<String>, usize) {
|
||||
let path = b.paths.first().map(Vec::as_slice).unwrap_or_default();
|
||||
let menu = |depth| path.first().map(|m| (0, Some(text.segment(m).into_owned()), depth));
|
||||
match area {
|
||||
AreaId::All => menu(1).unwrap_or_else(|| {
|
||||
if let Kind::Tool { .. } = b.kind {
|
||||
(1, Some(text.ui("Tools").into_owned()), 0)
|
||||
} else if !b.scope.is_app() {
|
||||
(2, Some(panel_label(text, b.scope.as_str())), 0)
|
||||
} else {
|
||||
(3, Some(text.ui("Other").into_owned()), 0)
|
||||
}
|
||||
}),
|
||||
AreaId::Menu(_) if submenus && path.len() >= 3 => (0, path.get(1).map(|s| text.segment(s).into_owned()), 2),
|
||||
AreaId::Menu(_) => (0, None, 1),
|
||||
AreaId::Tools => match &b.kind {
|
||||
Kind::Tool { group: Some(g) } => (0, Some(text.segment(g).into_owned()), usize::MAX),
|
||||
_ => (0, None, usize::MAX),
|
||||
},
|
||||
AreaId::Other => (0, Some(id_group(&b.command.id)), usize::MAX),
|
||||
AreaId::Panel(_) | AreaId::App(_) | AreaId::Fixed => menu(1).unwrap_or((0, None, usize::MAX)),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a query asks for: lowercase text, and the trigger it spells, if any.
|
||||
struct Query {
|
||||
text: String,
|
||||
trigger: Option<Trigger>,
|
||||
}
|
||||
|
||||
impl Query {
|
||||
fn new(q: &str, platform: Platform) -> Query {
|
||||
let text = q.trim().to_lowercase();
|
||||
let trigger = Trigger::parse(q.trim()).ok().map(|t| t.effective(platform));
|
||||
Query { text, trigger }
|
||||
}
|
||||
|
||||
fn hit(&self, s: &str) -> bool {
|
||||
s.to_lowercase().contains(&self.text)
|
||||
}
|
||||
|
||||
/// Label, aliases, path parts and id, as written and translated; then the bindings: the same
|
||||
/// effective trigger when the query spells one, else their canonical or display text. A query
|
||||
/// that spells a chord (`cmd+s`, `⌘S`) does not also match longer chords containing its text.
|
||||
fn matches(&self, b: &Bindable, bindings: &[Binding], text: &dyn Text, platform: Platform) -> bool {
|
||||
if self.text.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let named = self.hit(&b.label)
|
||||
|| self.hit(&text.command(b))
|
||||
|| b.aliases.iter().any(|a| self.hit(a))
|
||||
|| b.paths.iter().flatten().any(|s| self.hit(s) || self.hit(&text.segment(s)))
|
||||
|| self.hit(&b.command.id);
|
||||
named
|
||||
|| match self.trigger {
|
||||
Some(t) => bindings.iter().any(|x| x.trigger.effective(platform) == t),
|
||||
None => bindings.iter().any(|x| {
|
||||
self.hit(&x.trigger.to_string()) || self.hit(&x.trigger.display(platform)) || self.hit(&trigger_text(text, &x.trigger, platform))
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn build(keymap: &Keymap, options: &Options, text: &dyn Text, view: &View) -> Built {
|
||||
let platform = keymap.platform();
|
||||
let catalog = keymap.catalog();
|
||||
let mut built = Built::default();
|
||||
let mut clashing: HashSet<String> = HashSet::new();
|
||||
for c in keymap.conflicts().into_iter().filter(|c| !keymap.twins_in(c)) {
|
||||
match c.kind {
|
||||
ConflictKind::Clash => {
|
||||
built.clashes += 1;
|
||||
clashing.insert(c.a.0.key());
|
||||
clashing.insert(c.b.0.key());
|
||||
}
|
||||
ConflictKind::Shadow => built.shadows += 1,
|
||||
}
|
||||
}
|
||||
let query = Query::new(view.query, platform);
|
||||
if *view.area == AreaId::Fixed {
|
||||
build_fixed(keymap, options, text, view, &query, &mut built);
|
||||
return built;
|
||||
}
|
||||
|
||||
let bindings: Vec<Vec<Binding>> = catalog.iter().map(|b| keymap.bindings(&b.command)).collect();
|
||||
// How many tools of a group hold each effective trigger.
|
||||
let mut tool_keys: HashMap<(Option<&str>, Trigger), usize> = HashMap::new();
|
||||
for (b, list) in catalog.iter().zip(&bindings) {
|
||||
if let Kind::Tool { group } = &b.kind {
|
||||
for x in list {
|
||||
*tool_keys.entry((group.as_deref(), x.trigger.effective(platform))).or_default() += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let submenus = match view.area {
|
||||
AreaId::Menu(m) => listed(keymap, options).any(|b| top_menu(b) == Some(m.as_str()) && b.paths.first().is_some_and(|p| p.len() >= 3)),
|
||||
_ => false,
|
||||
};
|
||||
|
||||
// Groups in first-seen order within their rank.
|
||||
let mut groups: Vec<(u8, Option<String>, Vec<Row>)> = Vec::new();
|
||||
for (index, (b, list)) in catalog.iter().zip(&bindings).enumerate() {
|
||||
let hidden = options.visible.is_some_and(|f| !f(b));
|
||||
if hidden || !in_area(view.area, b, options) || !query.matches(b, list, text, platform) {
|
||||
continue;
|
||||
}
|
||||
let key = b.command.key();
|
||||
let changed = keymap.overrides().get(&key).is_some();
|
||||
let conflict = clashing.contains(&key);
|
||||
let keep = match view.filter {
|
||||
Filter::All => true,
|
||||
Filter::WithShortcut => !list.is_empty(),
|
||||
Filter::Changed => changed,
|
||||
Filter::Conflicts => conflict,
|
||||
};
|
||||
if !keep {
|
||||
continue;
|
||||
}
|
||||
let (rank, header, depth) = group(view.area, b, submenus, text);
|
||||
let path = b.paths.first().map(Vec::as_slice).unwrap_or_default();
|
||||
let prefix = path.get(depth..path.len().saturating_sub(1)).unwrap_or_default().iter().map(|s| text.segment(s).into_owned()).collect();
|
||||
let defaults = &b.defaults;
|
||||
let chips = list
|
||||
.iter()
|
||||
.map(|x| {
|
||||
let mut t = trigger_text(text, &x.trigger, platform);
|
||||
if x.scope_or(&b.scope) != &b.scope {
|
||||
let scope = text.segment(x.scope_or(&b.scope).as_str());
|
||||
let s = craft_i18n::fmt(&text.ui("{chord} ({scope})"), &[("chord", &t), ("scope", &scope)]);
|
||||
t = visual_around(text, &s, &t);
|
||||
}
|
||||
Chip { binding: x.clone(), text: t, changed: !defaults.contains(x) }
|
||||
})
|
||||
.collect();
|
||||
let cycles = match &b.kind {
|
||||
Kind::Tool { group } => list.iter().any(|x| tool_keys.get(&(group.as_deref(), x.trigger.effective(platform))).is_some_and(|n| *n > 1)),
|
||||
Kind::Command => false,
|
||||
};
|
||||
let row = Row { index, command: b.command.clone(), key, label: text.command(b).into_owned(), prefix, chips, changed, cycles, conflict };
|
||||
match groups.iter_mut().find(|(r, h, _)| *r == rank && *h == header) {
|
||||
Some((_, _, rows)) => rows.push(row),
|
||||
None => groups.push((rank, header, vec![row])),
|
||||
}
|
||||
}
|
||||
groups.sort_by_key(|(rank, _, _)| *rank);
|
||||
for (_, header, mut rows) in groups {
|
||||
if options.sort_by_label {
|
||||
rows.sort_by_cached_key(|r| r.label.to_lowercase());
|
||||
}
|
||||
built.matches += rows.len();
|
||||
let collapsed = header.as_ref().is_some_and(|h| view.collapsed.contains(h));
|
||||
if let Some(name) = header {
|
||||
built.lines.push(Line::Header { name, collapsed });
|
||||
}
|
||||
if !collapsed {
|
||||
built.lines.extend(rows.into_iter().map(Line::Row));
|
||||
}
|
||||
}
|
||||
built
|
||||
}
|
||||
|
||||
fn build_fixed(keymap: &Keymap, options: &Options, text: &dyn Text, view: &View, query: &Query, built: &mut Built) {
|
||||
if matches!(view.filter, Filter::Changed | Filter::Conflicts) {
|
||||
return;
|
||||
}
|
||||
let platform = keymap.platform();
|
||||
let mut groups: Vec<(&str, Vec<FixedLine>)> = Vec::new();
|
||||
for f in &options.fixed {
|
||||
if !query.text.is_empty()
|
||||
&& !(query.hit(&f.label)
|
||||
|| query.hit(&f.keys)
|
||||
|| query.hit(&f.group)
|
||||
|| query.trigger.is_some_and(|t| f.chord.is_some_and(|c| c.effective(platform) == t)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let now_used_by = f.chord.and_then(|c| {
|
||||
let c = c.effective(platform);
|
||||
keymap
|
||||
.catalog()
|
||||
.iter()
|
||||
.find(|b| keymap.bindings(&b.command).iter().any(|x| x.trigger.effective(platform) == c))
|
||||
.map(|b| text.command(b).into_owned())
|
||||
});
|
||||
let line = FixedLine { label: f.label.clone(), keys: f.keys.clone(), now_used_by };
|
||||
match groups.iter_mut().find(|(g, _)| *g == f.group) {
|
||||
Some((_, lines)) => lines.push(line),
|
||||
None => groups.push((&f.group, vec![line])),
|
||||
}
|
||||
}
|
||||
for (name, lines) in groups {
|
||||
built.matches += lines.len();
|
||||
let collapsed = view.collapsed.contains(name);
|
||||
built.lines.push(Line::Header { name: name.to_string(), collapsed });
|
||||
if !collapsed {
|
||||
built.lines.extend(lines.into_iter().map(Line::Fixed));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use std::borrow::Cow;
|
||||
|
||||
use super::*;
|
||||
use crate::keymap::Bindable;
|
||||
use crate::scope::{Scope, Scopes};
|
||||
use crate::ui::text::English;
|
||||
use crate::ui::{Area, FixedRow};
|
||||
|
||||
fn key(text: &str) -> Binding {
|
||||
Binding::parse(text).unwrap_or_else(|_| Binding::new(Trigger::single(crate::Chord::from(crate::Key::F35))))
|
||||
}
|
||||
|
||||
/// The fixture of the dialog tests: Save, Save As, Export, Arrange › Bring to Front, two
|
||||
/// tools sharing M, Timeline Loop, Bold in the Text context.
|
||||
pub(crate) fn fixture(platform: Platform) -> Keymap {
|
||||
let tool = Kind::Tool { group: Some("Marquee".into()) };
|
||||
let path = |p: &[&str]| p.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
let timeline = Scope::new("Timeline").unwrap_or_else(Scope::app);
|
||||
let catalog = vec![
|
||||
Bindable::new("file.save", "Save", Scope::app()).with_path(path(&["File", "Save"])).with_default(key("Cmd+S")),
|
||||
Bindable::new("file.saveAs", "Save As…", Scope::app()).with_path(path(&["File", "Save As…"])).with_default(key("Cmd+Shift+S")),
|
||||
Bindable::new("file.export", "Export…", Scope::app()).with_path(path(&["File", "Export…"])).with_default(key("Cmd+E")),
|
||||
Bindable::new("object.front", "Bring to Front", Scope::app()).with_path(path(&["Object", "Arrange", "Bring to Front"])),
|
||||
Bindable::new("tool.marquee", "Marquee Tool", Scope::app()).with_kind(tool.clone()).with_default(key("M")),
|
||||
Bindable::new("tool.ellipse", "Elliptical Marquee Tool", Scope::app()).with_kind(tool).with_default(key("M")),
|
||||
Bindable::new("timeline.loop", "Loop", timeline).with_default(key("L")),
|
||||
Bindable::new("type.bold", "Bold", Scope::app()).with_default(key("Text: Cmd+B")),
|
||||
];
|
||||
Keymap::new(catalog, Scopes::new().with_panel("Timeline").with_context("Text"), platform)
|
||||
}
|
||||
|
||||
fn view<'a>(query: &'a str, area: &'a AreaId, filter: Filter, collapsed: &'a BTreeSet<String>) -> View<'a> {
|
||||
View { query, area, filter, collapsed }
|
||||
}
|
||||
|
||||
fn labels(built: &Built) -> Vec<String> {
|
||||
built
|
||||
.lines
|
||||
.iter()
|
||||
.map(|l| match l {
|
||||
Line::Header { name, .. } => format!("# {name}"),
|
||||
Line::Row(r) => {
|
||||
let chips: Vec<&str> = r.chips.iter().map(|c| c.text.as_str()).collect();
|
||||
let cycles = if r.cycles { " (cycles)" } else { "" };
|
||||
format!("{}{}: {}{cycles}", r.prefix.iter().map(|p| format!("{p} › ")).collect::<String>(), r.label, chips.join(", "))
|
||||
}
|
||||
Line::Fixed(f) => format!("{} = {}{}", f.label, f.keys, f.now_used_by.as_ref().map(|l| format!(" (now {l})")).unwrap_or_default()),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn lines(km: &Keymap, options: &Options, text: &dyn Text, query: &str, area: AreaId, filter: Filter) -> Vec<String> {
|
||||
let none = BTreeSet::new();
|
||||
labels(&build(km, options, text, &view(query, &area, filter, &none)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn areas_follow_paths_kind_and_scope() {
|
||||
let km = fixture(Platform::Mac);
|
||||
let options = Options { areas: vec![Area { id: "type", label: "Type", rows: |b| b.command.id.starts_with("type.") }], ..Options::default() };
|
||||
let names: Vec<String> = areas(&km, &options, &English).into_iter().map(|a| a.label).collect();
|
||||
assert_eq!(names, ["All Commands", "File Menu", "Object Menu", "Tools", "Timeline Panel", "Other", "Type"]);
|
||||
|
||||
let all = lines(&km, &options, &English, "", AreaId::All, Filter::All);
|
||||
assert_eq!(
|
||||
all,
|
||||
[
|
||||
"# File",
|
||||
"Save: ⌘S",
|
||||
"Save As…: ⇧⌘S",
|
||||
"Export…: ⌘E",
|
||||
"# Object",
|
||||
"Arrange › Bring to Front: ",
|
||||
"# Tools",
|
||||
"Marquee Tool: M (cycles)",
|
||||
"Elliptical Marquee Tool: M (cycles)",
|
||||
"# Timeline Panel",
|
||||
"Loop: L",
|
||||
"# Other",
|
||||
"Bold: ⌘B (Text)",
|
||||
]
|
||||
);
|
||||
assert_eq!(lines(&km, &options, &English, "", AreaId::Menu("Object".into()), Filter::All), ["# Arrange", "Bring to Front: "]);
|
||||
assert_eq!(lines(&km, &options, &English, "", AreaId::Panel("Timeline".into()), Filter::All), ["Loop: L"]);
|
||||
assert_eq!(lines(&km, &options, &English, "", AreaId::Other, Filter::All), ["# Timeline", "Loop: L", "# Type", "Bold: ⌘B (Text)"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_by_label_and_collapsed_groups() {
|
||||
let km = fixture(Platform::Mac);
|
||||
let options = Options { sort_by_label: true, ..Options::default() };
|
||||
let area = AreaId::Menu("File".into());
|
||||
let none = BTreeSet::new();
|
||||
assert_eq!(labels(&build(&km, &options, &English, &view("", &area, Filter::All, &none))), ["Export…: ⌘E", "Save: ⌘S", "Save As…: ⇧⌘S"]);
|
||||
let collapsed: BTreeSet<String> = ["File".to_string()].into();
|
||||
let built = build(&km, &options, &English, &view("", &AreaId::All, Filter::All, &collapsed));
|
||||
assert_eq!(built.lines.first(), Some(&Line::Header { name: "File".into(), collapsed: true }));
|
||||
assert!(matches!(built.lines.get(1), Some(Line::Header { .. })));
|
||||
}
|
||||
|
||||
struct Spanish;
|
||||
impl Text for Spanish {
|
||||
fn ui<'a>(&'a self, source: &'a str) -> Cow<'a, str> {
|
||||
source.into()
|
||||
}
|
||||
fn plural(&self, n: u64, one: &str, other: &str) -> String {
|
||||
English.plural(n, one, other)
|
||||
}
|
||||
fn command<'a>(&'a self, b: &'a Bindable) -> Cow<'a, str> {
|
||||
if b.command.id == "file.export" { "Exportar…".into() } else { b.label.as_str().into() }
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_by_name_translation_or_chord() {
|
||||
let km = fixture(Platform::Mac);
|
||||
let o = Options::default();
|
||||
let find = |q: &str| -> Vec<String> {
|
||||
let none = BTreeSet::new();
|
||||
build(&km, &o, &Spanish, &view(q, &AreaId::All, Filter::All, &none))
|
||||
.lines
|
||||
.into_iter()
|
||||
.filter_map(|l| if let Line::Row(r) = l { Some(r.key) } else { None })
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(find("save"), ["file.save", "file.saveAs"]);
|
||||
assert_eq!(find("exportar"), ["file.export"]);
|
||||
assert_eq!(find("cmd+s"), ["file.save"]);
|
||||
assert_eq!(find("⌘S"), ["file.save"]);
|
||||
assert_eq!(find("⇧⌘S"), ["file.saveAs"]);
|
||||
assert_eq!(find("Text: Cmd+B"), Vec::<String>::new(), "a binding text with a scope is not a trigger");
|
||||
assert_eq!(find("cmd+b"), ["type.bold"], "a trigger matches in any scope");
|
||||
assert_eq!(find("arrange"), ["object.front"]);
|
||||
assert!(find("zzz").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_and_conflict_counts() -> Result<(), crate::AssignError> {
|
||||
let mut km = fixture(Platform::Windows);
|
||||
let o = Options::default();
|
||||
km.assign(&"file.export".into(), key("Cmd+S"), crate::Policy::Keep)?;
|
||||
assert_eq!(lines(&km, &o, &English, "", AreaId::All, Filter::Changed), ["# File", "Export…: Ctrl+E, Ctrl+S"]);
|
||||
assert_eq!(lines(&km, &o, &English, "", AreaId::All, Filter::Conflicts), ["# File", "Save: Ctrl+S", "Export…: Ctrl+E, Ctrl+S"]);
|
||||
assert_eq!(lines(&km, &o, &English, "", AreaId::Menu("Object".into()), Filter::WithShortcut), Vec::<String>::new());
|
||||
let none = BTreeSet::new();
|
||||
let built = build(&km, &o, &English, &view("", &AreaId::All, Filter::All, &none));
|
||||
assert_eq!((built.clashes, built.matches), (1, 8));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_paths_make_no_areas_or_groups() {
|
||||
let tool = |id: &str, label: &str| {
|
||||
Bindable::new(id, label, Scope::app())
|
||||
.with_kind(Kind::Tool { group: None })
|
||||
.with_import_path(vec!["Tools".into(), label.into()])
|
||||
.with_default(key("P"))
|
||||
};
|
||||
let km = Keymap::new(vec![tool("tool.pen", "Pen Tool")], Scopes::new(), Platform::Mac);
|
||||
let o = Options::default();
|
||||
let names: Vec<String> = areas(&km, &o, &English).into_iter().map(|a| a.label).collect();
|
||||
assert_eq!(names, ["All Commands", "Tools"]);
|
||||
assert_eq!(lines(&km, &o, &English, "", AreaId::All, Filter::All), ["# Tools", "Pen Tool: P"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_entries_are_not_listed_but_still_conflict() -> Result<(), crate::AssignError> {
|
||||
let mut km = fixture(Platform::Mac);
|
||||
let o = Options { visible: Some(|b| b.command.id != "file.export" && !b.command.id.starts_with("timeline.")), ..Options::default() };
|
||||
let names: Vec<String> = areas(&km, &o, &English).into_iter().map(|a| a.label).collect();
|
||||
assert_eq!(names, ["All Commands", "File Menu", "Object Menu", "Tools", "Other"]);
|
||||
assert_eq!(lines(&km, &o, &English, "", AreaId::Menu("File".into()), Filter::All), ["Save: ⌘S", "Save As…: ⇧⌘S"]);
|
||||
assert!(lines(&km, &o, &English, "export", AreaId::All, Filter::All).is_empty());
|
||||
|
||||
km.assign(&"file.save".into(), key("Cmd+E"), crate::Policy::Keep)?;
|
||||
let none = BTreeSet::new();
|
||||
assert_eq!(build(&km, &o, &English, &view("", &AreaId::All, Filter::All, &none)).clashes, 1);
|
||||
assert_eq!(lines(&km, &o, &English, "", AreaId::All, Filter::Conflicts), ["# File", "Save: ⌘S, ⌘E"]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_sharing_a_default_key_are_no_conflict() -> Result<(), crate::AssignError> {
|
||||
let menu = Bindable::new("app.characterPanel", "Character", Scope::app()).with_path(vec!["Window".into(), "Character".into()]);
|
||||
let catalog = vec![
|
||||
menu.with_default(key("Cmd+T")),
|
||||
Bindable::new("panel.character", "Character Panel", Scope::app()).with_default(key("Cmd+T")),
|
||||
Bindable::new("file.save", "Save", Scope::app()).with_default(key("Cmd+S")),
|
||||
];
|
||||
let mut km = Keymap::new(catalog, Scopes::new(), Platform::Mac);
|
||||
let o = Options::default();
|
||||
let none = BTreeSet::new();
|
||||
let built = build(&km, &o, &English, &view("", &AreaId::All, Filter::All, &none));
|
||||
assert_eq!((built.clashes, built.shadows), (0, 0));
|
||||
assert!(lines(&km, &o, &English, "", AreaId::All, Filter::Conflicts).is_empty());
|
||||
|
||||
km.assign(&"file.save".into(), key("Cmd+T"), crate::Policy::Keep)?;
|
||||
let built = build(&km, &o, &English, &view("", &AreaId::All, Filter::All, &none));
|
||||
assert_eq!(built.clashes, 2, "Save clashes with both twins");
|
||||
let flagged: Vec<String> =
|
||||
built.lines.iter().filter_map(|l| if let Line::Row(r) = l { r.conflict.then(|| r.key.clone()) } else { None }).collect();
|
||||
assert_eq!(flagged, ["app.characterPanel", "panel.character", "file.save"]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_rows_strike_through_when_a_command_takes_their_chord() {
|
||||
let km = fixture(Platform::Mac);
|
||||
let fixed = |label: &str, keys: &str, chord: Option<&str>| FixedRow {
|
||||
group: "Rating".into(),
|
||||
label: label.into(),
|
||||
keys: keys.into(),
|
||||
chord: chord.and_then(|c| Trigger::parse(c).ok()),
|
||||
};
|
||||
let o = Options { fixed: vec![fixed("Rate 1", "1", Some("1")), fixed("Loop", "L", Some("L"))], ..Options::default() };
|
||||
assert_eq!(lines(&km, &o, &English, "", AreaId::Fixed, Filter::All), ["# Rating", "Rate 1 = 1", "Loop = L (now Loop)"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_rebuilds_on_overrides_and_view_changes() -> Result<(), crate::AssignError> {
|
||||
let mut km = fixture(Platform::Mac);
|
||||
let o = Options::default();
|
||||
let mut cache = RowCache::default();
|
||||
let none = BTreeSet::new();
|
||||
let area = AreaId::Menu("File".into());
|
||||
let before = cache.get(&km, &o, &English, &view("", &area, Filter::All, &none)).clone();
|
||||
km.assign(&"file.save".into(), key("F2"), crate::Policy::Steal)?;
|
||||
let after = cache.get(&km, &o, &English, &view("", &area, Filter::All, &none)).clone();
|
||||
assert_ne!(before, after);
|
||||
assert_eq!(cache.get(&km, &o, &English, &view("save as", &area, Filter::All, &none)).matches, 1);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
//! The set row (§2.6 of the dialog plan): the set picker, then New Set…, Rename…, Delete, Save,
|
||||
//! Revert Set, Export, Import… and Summarize…; actions that do not fit go into a More menu. New
|
||||
//! Set… and Rename… open an inline form under the row.
|
||||
|
||||
use craft_ui::layout::fit_toolbar;
|
||||
use egui::{ComboBox, Key as EguiKey, RichText, TextEdit, Ui};
|
||||
|
||||
use super::{Draw, FIELD_W};
|
||||
use crate::profiles::{Profiles, set_name};
|
||||
use crate::ui::state::{DialogState, SetForm, SetFormKind};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Act {
|
||||
New,
|
||||
Rename,
|
||||
Delete,
|
||||
Save,
|
||||
Revert,
|
||||
/// Export as craft-keymap JSON; with app formats the item is a menu.
|
||||
Export,
|
||||
ExportAs(&'static str),
|
||||
Import,
|
||||
Summarize,
|
||||
}
|
||||
|
||||
struct Item {
|
||||
act: Act,
|
||||
text: String,
|
||||
id: &'static str,
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
impl Draw<'_, '_> {
|
||||
/// Drawn above the header when the app passes sets and the dialog is editable.
|
||||
pub(super) fn sets_row(&mut self, ui: &mut Ui) {
|
||||
if !self.env.options.editable {
|
||||
return;
|
||||
}
|
||||
let Some((p, b)) = self.env.sets.as_ref() else { return };
|
||||
let names = p.names(b);
|
||||
let active = p.active_name(b).to_string();
|
||||
let builtin = Profiles::is_builtin(&active, b);
|
||||
let modified = DialogState::is_modified(self.env);
|
||||
let items = self.set_items(builtin, modified);
|
||||
let mut act = None;
|
||||
ui.add_enabled_ui(!self.state.modal(), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let set_label = self.ui("Set:");
|
||||
let l = ui.label(self.vis(&set_label));
|
||||
let mut pick = None;
|
||||
self.combo(ui, "set", &l, &set_label, &active, |ui| {
|
||||
for n in &names {
|
||||
if ui.selectable_label(*n == active, self.vis(n)).clicked() {
|
||||
pick = Some(n.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
if modified {
|
||||
ui.label(RichText::new(self.vis(&self.ui("(modified)"))).color(self.style.dim));
|
||||
}
|
||||
if let Some(n) = pick.filter(|n| *n != active) {
|
||||
self.state.set_form = None;
|
||||
self.state.switch_set(self.env, &n);
|
||||
}
|
||||
act = self.set_toolbar(ui, &items);
|
||||
});
|
||||
self.set_form(ui);
|
||||
});
|
||||
if let Some(a) = act {
|
||||
self.set_act(a, &active);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_items(&self, builtin: bool, modified: bool) -> Vec<Item> {
|
||||
let item = |act, text: &str, id, enabled| Item { act, text: self.ui(text), id, enabled };
|
||||
let export = if self.env.options.export_formats.is_empty() { "Export…" } else { "Export" };
|
||||
let mut items = vec![
|
||||
item(Act::New, "New Set…", "shortcuts.set.new", true),
|
||||
item(Act::Rename, "Rename…", "shortcuts.set.rename", !builtin),
|
||||
item(Act::Delete, "Delete", "shortcuts.set.delete", !builtin),
|
||||
item(Act::Save, "Save", "shortcuts.set.save", modified),
|
||||
item(Act::Revert, "Revert Set", "shortcuts.set.revert", modified),
|
||||
item(Act::Export, export, "shortcuts.set.export", true),
|
||||
item(Act::Import, "Import…", "shortcuts.set.import", true),
|
||||
];
|
||||
if self.env.options.summary {
|
||||
items.push(item(Act::Summarize, "Summarize…", "shortcuts.summarize", true));
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
/// The actions that fit in the row's remaining width, then More with the rest.
|
||||
fn set_toolbar(&self, ui: &mut Ui, items: &[Item]) -> Option<Act> {
|
||||
let more = self.ui("More");
|
||||
let natural: Vec<f32> = items.iter().map(|i| self.button_width(ui, &i.text)).collect();
|
||||
let spacing = ui.spacing().item_spacing.x;
|
||||
let (shown, overflow): (Vec<usize>, Vec<usize>) = match fit_toolbar(&natural, ui.available_width(), spacing, self.button_width(ui, &more)) {
|
||||
Some(fit) => (fit.shown.iter().map(|&(i, _)| i).collect(), fit.overflow),
|
||||
None => (Vec::new(), (0..items.len()).collect()),
|
||||
};
|
||||
let mut act = None;
|
||||
for i in shown {
|
||||
act = act.or(self.set_item(ui, &items[i]));
|
||||
}
|
||||
if !overflow.is_empty() {
|
||||
let r = ui.menu_button(self.vis(&more), |ui| {
|
||||
for &i in &overflow {
|
||||
act = act.or(self.set_item(ui, &items[i]));
|
||||
}
|
||||
});
|
||||
self.tag(|| "shortcuts.set.more".into(), r.response.rect, &more);
|
||||
}
|
||||
act
|
||||
}
|
||||
|
||||
fn set_item(&self, ui: &mut Ui, item: &Item) -> Option<Act> {
|
||||
if item.act == Act::Export && !self.env.options.export_formats.is_empty() {
|
||||
let mut act = None;
|
||||
let r = ui.menu_button(self.vis(&item.text), |ui| {
|
||||
if self.button(ui, true, &self.ui("Keyboard Shortcuts (JSON)"), "shortcuts.set.export.json") {
|
||||
act = Some(Act::Export);
|
||||
}
|
||||
for f in &self.env.options.export_formats {
|
||||
let label = self.env.text.ui(f.label).into_owned();
|
||||
if self.button(ui, true, &label, &format!("shortcuts.set.export.{}", f.id)) {
|
||||
act = Some(Act::ExportAs(f.id));
|
||||
}
|
||||
}
|
||||
});
|
||||
self.tag(|| item.id.into(), r.response.rect, &item.text);
|
||||
return act;
|
||||
}
|
||||
self.button(ui, item.enabled, &item.text, item.id).then_some(item.act)
|
||||
}
|
||||
|
||||
fn set_act(&mut self, act: Act, active: &str) {
|
||||
let form = |kind, name: &str| Some(SetForm { kind, name: name.to_string(), focus: true });
|
||||
match act {
|
||||
Act::New => self.state.set_form = form(SetFormKind::New { based_on: None }, ""),
|
||||
Act::Rename => self.state.set_form = form(SetFormKind::Rename, active),
|
||||
Act::Delete => self.state.ask_delete_set(self.env),
|
||||
Act::Save => self.state.save_set(self.env),
|
||||
Act::Revert => self.state.revert_set(self.env),
|
||||
Act::Export => self.state.export_set(self.env),
|
||||
Act::ExportAs(f) => self.state.export_as(self.env, f),
|
||||
Act::Import => self.state.request_import(self.env),
|
||||
Act::Summarize => self.state.summarize(self.env),
|
||||
}
|
||||
}
|
||||
|
||||
/// New Set… (Name, Based on) or Rename… (Name), under the set row.
|
||||
fn set_form(&mut self, ui: &mut Ui) {
|
||||
let Some(mut form) = self.state.set_form.clone() else { return };
|
||||
let names = self.env.sets.as_ref().map(|(p, b)| p.names(b)).unwrap_or_default();
|
||||
let (mut submit, mut cancel) = (false, false);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let name_label = self.ui("Name:");
|
||||
let l = ui.label(self.vis(&name_label));
|
||||
let edit = ui.add(TextEdit::singleline(&mut form.name).id(self.base.with("set_name")).desired_width(FIELD_W)).labelled_by(l.id);
|
||||
self.text_field(&edit);
|
||||
self.tag(|| "shortcuts.setForm.name".into(), edit.rect, &name_label);
|
||||
if std::mem::take(&mut form.focus) {
|
||||
edit.request_focus();
|
||||
}
|
||||
if edit.lost_focus() {
|
||||
let (enter, escape) = ui.input(|i| (i.key_pressed(EguiKey::Enter), i.key_pressed(EguiKey::Escape)));
|
||||
submit |= enter;
|
||||
cancel |= escape;
|
||||
}
|
||||
if let SetFormKind::New { based_on } = &mut form.kind {
|
||||
let based_label = self.ui("Based on:");
|
||||
let l = ui.label(self.vis(&based_label));
|
||||
let current = self.ui("Current shortcuts");
|
||||
let shown = based_on.clone().unwrap_or_else(|| current.clone());
|
||||
let combo = ComboBox::from_id_salt(self.base.with("based_on")).selected_text(self.vis(&shown)).show_ui(ui, |ui| {
|
||||
if ui.selectable_label(based_on.is_none(), self.vis(¤t)).clicked() {
|
||||
*based_on = None;
|
||||
}
|
||||
for n in &names {
|
||||
if ui.selectable_label(based_on.as_ref() == Some(n), self.vis(n)).clicked() {
|
||||
*based_on = Some(n.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
let combo = combo.response.labelled_by(l.id);
|
||||
self.tag(|| "shortcuts.setForm.basedOn".into(), combo.rect, &based_label);
|
||||
}
|
||||
let ok = match form.kind {
|
||||
SetFormKind::New { .. } => self.ui("Create"),
|
||||
SetFormKind::Rename => self.ui("Rename"),
|
||||
};
|
||||
submit |= self.button(ui, set_name(&form.name).is_some(), &ok, "shortcuts.setForm.ok");
|
||||
cancel |= self.button(ui, true, &self.ui("Cancel"), "shortcuts.setForm.cancel");
|
||||
});
|
||||
if cancel {
|
||||
self.state.set_form = None;
|
||||
return;
|
||||
}
|
||||
if !submit || set_name(&form.name).is_none() {
|
||||
self.state.set_form = Some(form);
|
||||
return;
|
||||
}
|
||||
self.state.message = None;
|
||||
match &form.kind {
|
||||
SetFormKind::New { based_on } => self.state.new_set(self.env, &form.name, based_on.as_deref()),
|
||||
SetFormKind::Rename => self.state.rename_set(self.env, &form.name),
|
||||
}
|
||||
// A refused name keeps the form open for another try.
|
||||
let refused = self.state.message.as_ref().is_some_and(|m| m.refused);
|
||||
self.state.set_form = refused.then_some(form);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,54 @@
|
||||
//! The dialog's colors and the icon-button style built from them.
|
||||
|
||||
use craft_ui::buttons::{ButtonVisuals, IconButtonStyle};
|
||||
use craft_ui::layout::ResizeHandleStyle;
|
||||
use egui::{Color32, Stroke, Visuals};
|
||||
|
||||
/// The dialog's colors.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct DialogStyle {
|
||||
pub accent: Color32,
|
||||
pub warning: Color32,
|
||||
pub dim: Color32,
|
||||
pub changed: Color32,
|
||||
pub app_key: Color32,
|
||||
pub scoped_key: Color32,
|
||||
pub both_key: Color32,
|
||||
pub modifier_key: Color32,
|
||||
pub free_key: Color32,
|
||||
}
|
||||
|
||||
impl DialogStyle {
|
||||
pub fn from_visuals(v: &Visuals) -> DialogStyle {
|
||||
let accent = v.selection.bg_fill;
|
||||
DialogStyle {
|
||||
accent,
|
||||
warning: v.warn_fg_color,
|
||||
dim: v.weak_text_color(),
|
||||
changed: accent,
|
||||
app_key: accent,
|
||||
scoped_key: v.warn_fg_color,
|
||||
both_key: v.error_fg_color,
|
||||
modifier_key: v.widgets.active.bg_fill,
|
||||
free_key: v.widgets.inactive.bg_fill,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Icon buttons (+, ×, ↺, ⌨, ✕) in the colors of the app's visuals.
|
||||
pub(crate) fn icon_buttons(v: &Visuals) -> IconButtonStyle {
|
||||
let w = &v.widgets;
|
||||
IconButtonStyle {
|
||||
normal: ButtonVisuals { fill: Color32::TRANSPARENT, stroke: Stroke::NONE, icon: w.inactive.fg_stroke.color },
|
||||
hovered: ButtonVisuals { fill: w.hovered.weak_bg_fill, stroke: w.hovered.bg_stroke, icon: w.hovered.fg_stroke.color },
|
||||
pressed: Some(ButtonVisuals { fill: w.active.weak_bg_fill, stroke: w.active.bg_stroke, icon: w.active.fg_stroke.color }),
|
||||
selected: ButtonVisuals { fill: v.selection.bg_fill, stroke: Stroke::NONE, icon: v.selection.stroke.color },
|
||||
corner_radius: w.inactive.corner_radius,
|
||||
focus_stroke: v.selection.stroke,
|
||||
}
|
||||
}
|
||||
|
||||
/// The table/detail divider.
|
||||
pub(crate) fn divider(v: &Visuals) -> ResizeHandleStyle {
|
||||
ResizeHandleStyle { hovered: v.widgets.hovered.bg_fill, dragged: v.widgets.active.bg_fill, focused: v.selection.bg_fill }
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
//! The shortcut summary behind Summarize…: every command that has a shortcut, grouped as in the
|
||||
//! dialog's All Commands view, as an HTML page and as plain text. Apps can also call these for a
|
||||
//! cheat sheet outside the dialog.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use crate::keymap::{Binding, Keymap};
|
||||
use crate::scope::Scope;
|
||||
use crate::ui::rows::{AreaId, group};
|
||||
use crate::ui::text::{Text, trigger_text};
|
||||
|
||||
struct Group {
|
||||
rank: u8,
|
||||
name: String,
|
||||
/// (label, shortcuts as shown)
|
||||
rows: Vec<(String, Vec<String>)>,
|
||||
}
|
||||
|
||||
fn binding_text(km: &Keymap, text: &dyn Text, b: &Binding, home: &Scope) -> String {
|
||||
let chord = trigger_text(text, &b.trigger, km.platform());
|
||||
match &b.scope {
|
||||
Some(s) if s != home => {
|
||||
let scope = if s.is_app() { text.ui("Application").into_owned() } else { text.segment(s.as_str()).into_owned() };
|
||||
craft_i18n::fmt(&text.ui("{chord} ({scope})"), &[("chord", &chord), ("scope", &scope)])
|
||||
}
|
||||
_ => chord,
|
||||
}
|
||||
}
|
||||
|
||||
/// Groups in the table's order; commands in catalog order within a group.
|
||||
fn groups(km: &Keymap, text: &dyn Text) -> Vec<Group> {
|
||||
let mut out: Vec<Group> = Vec::new();
|
||||
for b in km.catalog() {
|
||||
let bindings = km.bindings(&b.command);
|
||||
if bindings.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let keys = bindings.iter().map(|x| binding_text(km, text, x, &b.scope)).collect();
|
||||
let (rank, name, _) = group(&AreaId::All, b, false, text);
|
||||
let name = name.unwrap_or_default();
|
||||
let row = (text.command(b).into_owned(), keys);
|
||||
match out.iter_mut().find(|g| g.rank == rank && g.name == name) {
|
||||
Some(g) => g.rows.push(row),
|
||||
None => out.push(Group { rank, name, rows: vec![row] }),
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|g| g.rank);
|
||||
out
|
||||
}
|
||||
|
||||
/// Text for HTML element content and attribute values.
|
||||
pub fn escape_html(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One line of plain text: control characters (line breaks, tabs) become spaces, so a label
|
||||
/// cannot break the layout.
|
||||
fn one_line(s: &str) -> String {
|
||||
s.chars().map(|c| if c.is_control() { ' ' } else { c }).collect()
|
||||
}
|
||||
|
||||
const CSS: &str = "body{font-family:system-ui,sans-serif;margin:2em;color:#111;background:#fff}\
|
||||
h1{font-size:1.4em}h2{font-size:1.1em;margin-top:1.5em;border-bottom:1px solid #ccc}\
|
||||
table{border-collapse:collapse;width:100%}th,td{padding:.2em .6em;vertical-align:top}\
|
||||
th{font-weight:normal;text-align:start;width:60%}tr:nth-child(even){background:#f4f4f4}\
|
||||
kbd{font-family:inherit;border:1px solid #bbb;border-radius:3px;padding:0 .3em;margin-inline-end:.3em;white-space:nowrap}\
|
||||
@media print{body{margin:0}tr{break-inside:avoid}}";
|
||||
|
||||
/// A standalone HTML page titled `title`. Chords are marked left to right so a right-to-left page
|
||||
/// keeps them as written.
|
||||
pub fn html(km: &Keymap, text: &dyn Text, title: &str) -> String {
|
||||
let dir = if text.rtl() { "rtl" } else { "ltr" };
|
||||
let title = escape_html(title);
|
||||
let mut s = String::new();
|
||||
let _ = write!(
|
||||
s,
|
||||
"<!DOCTYPE html>\n<html dir=\"{dir}\">\n<head>\n<meta charset=\"utf-8\">\n<title>{title}</title>\n<style>{CSS}</style>\n</head>\n<body>\n<h1>{title}</h1>\n"
|
||||
);
|
||||
for g in groups(km, text) {
|
||||
let _ = writeln!(s, "<h2>{}</h2>\n<table>", escape_html(&g.name));
|
||||
for (label, keys) in &g.rows {
|
||||
let keys: String = keys.iter().map(|k| format!("<kbd dir=\"ltr\">{}</kbd>", escape_html(k))).collect();
|
||||
let _ = writeln!(s, "<tr><th scope=\"row\">{}</th><td>{keys}</td></tr>", escape_html(label));
|
||||
}
|
||||
s.push_str("</table>\n");
|
||||
}
|
||||
s.push_str("</body>\n</html>\n");
|
||||
s
|
||||
}
|
||||
|
||||
/// Plain text titled `title`: a line per group, then ` label<TAB>shortcuts` per command.
|
||||
pub fn text(km: &Keymap, text: &dyn Text, title: &str) -> String {
|
||||
let mut s = one_line(title);
|
||||
s.push('\n');
|
||||
for g in groups(km, text) {
|
||||
let _ = write!(s, "\n{}\n", one_line(&g.name));
|
||||
for (label, keys) in &g.rows {
|
||||
let _ = writeln!(s, " {}\t{}", one_line(label), one_line(&keys.join(", ")));
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
//! The dialog's words: its own strings, command labels, menu path parts, key names and text
|
||||
//! direction, all supplied by the app through [`Text`].
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::chord::{Key, Platform, Trigger};
|
||||
use crate::keymap::Bindable;
|
||||
|
||||
/// Where the dialog gets its words. Apps on craft-i18n pass [`I18nText`]; others implement the two
|
||||
/// required methods with their own lookup.
|
||||
pub trait Text {
|
||||
/// The dialog's own strings, by English source text (listed in [`STRINGS`]). Placeholders
|
||||
/// (`{chord}`, `{label}`, `{set}`, `{n}`) are filled after the lookup.
|
||||
fn ui<'a>(&'a self, source: &'a str) -> Cow<'a, str>;
|
||||
/// A count's wording with `{n}` filled in. `one` and `other` are the English forms.
|
||||
fn plural(&self, n: u64, one: &str, other: &str) -> String;
|
||||
/// A command's label.
|
||||
fn command<'a>(&'a self, b: &'a Bindable) -> Cow<'a, str> {
|
||||
b.label.as_str().into()
|
||||
}
|
||||
/// A menu path part or a scope name.
|
||||
fn segment<'a>(&'a self, s: &'a str) -> Cow<'a, str> {
|
||||
s.into()
|
||||
}
|
||||
/// Extra lines for a command's tooltip.
|
||||
fn hint(&self, _b: &Bindable) -> Option<String> {
|
||||
None
|
||||
}
|
||||
/// A key cap's name on `platform` (`Strg`, `Umschalt`); `None` keeps the crate's name.
|
||||
fn key(&self, _k: Key, _p: Platform) -> Option<String> {
|
||||
None
|
||||
}
|
||||
/// Whether the interface language is written right to left.
|
||||
fn rtl(&self) -> bool {
|
||||
false
|
||||
}
|
||||
/// A label or message put into display order (the app's bidi reordering). Chord text is never
|
||||
/// passed here.
|
||||
fn visual(&self, s: &str) -> String {
|
||||
s.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Text`] over a craft-i18n catalog.
|
||||
pub struct I18nText<'a> {
|
||||
pub i18n: &'a craft_i18n::I18n,
|
||||
pub lang: craft_i18n::Lang,
|
||||
}
|
||||
|
||||
impl Text for I18nText<'_> {
|
||||
fn ui<'a>(&'a self, source: &'a str) -> Cow<'a, str> {
|
||||
self.i18n.t(self.lang, source).into()
|
||||
}
|
||||
|
||||
fn plural(&self, n: u64, one: &str, other: &str) -> String {
|
||||
self.i18n.trn(self.lang, n, one, other)
|
||||
}
|
||||
|
||||
fn command<'a>(&'a self, b: &'a Bindable) -> Cow<'a, str> {
|
||||
self.i18n.tid(self.lang, &b.command.id, &b.label).into()
|
||||
}
|
||||
|
||||
fn segment<'a>(&'a self, s: &'a str) -> Cow<'a, str> {
|
||||
self.i18n.t(self.lang, s).into()
|
||||
}
|
||||
|
||||
fn key(&self, k: Key, p: Platform) -> Option<String> {
|
||||
// Glyphs (⌫, ↑) need no translation.
|
||||
if p.is_mac() && k.mac_symbol() != k.text_name() {
|
||||
return None;
|
||||
}
|
||||
self.i18n.get(self.lang, "key", k.text_name()).map(str::to_string)
|
||||
}
|
||||
|
||||
fn rtl(&self) -> bool {
|
||||
self.i18n.rtl(self.lang)
|
||||
}
|
||||
}
|
||||
|
||||
/// English [`Text`]: every string as written.
|
||||
pub struct English;
|
||||
|
||||
impl Text for English {
|
||||
fn ui<'a>(&'a self, source: &'a str) -> Cow<'a, str> {
|
||||
source.into()
|
||||
}
|
||||
|
||||
fn plural(&self, n: u64, one: &str, other: &str) -> String {
|
||||
craft_i18n::fmt(if n == 1 { one } else { other }, &[("n", &n.to_string())])
|
||||
}
|
||||
}
|
||||
|
||||
/// A trigger as `platform` shows it, with key names from [`Text::key`]. Modifiers come in the
|
||||
/// order of [`Chord::display`](crate::Chord::display).
|
||||
pub fn trigger_text(text: &dyn Text, trigger: &Trigger, platform: Platform) -> String {
|
||||
let key = trigger.chord.key;
|
||||
let Some(name) = text.key(key, platform) else { return trigger.display(platform) };
|
||||
let base = if platform.is_mac() { key.mac_symbol() } else { key.text_name() };
|
||||
let one = trigger.chord.display(platform);
|
||||
let one = match one.strip_suffix(base) {
|
||||
Some(mods) => format!("{mods}{name}"),
|
||||
None => one,
|
||||
};
|
||||
if trigger.double { format!("{one} {one}") } else { one }
|
||||
}
|
||||
|
||||
/// `s` in display order with `chord`, text inside it, left as it is: chord text never goes
|
||||
/// through [`Text::visual`]. Right to left, the parts before and after the chord change sides.
|
||||
pub(crate) fn visual_around(text: &dyn Text, s: &str, chord: &str) -> String {
|
||||
let Some(i) = s.find(chord).filter(|_| !chord.is_empty()) else { return text.visual(s) };
|
||||
let (before, rest) = s.split_at(i);
|
||||
let (before, after) = (text.visual(before), text.visual(&rest[chord.len()..]));
|
||||
if text.rtl() { format!("{after}{chord}{before}") } else { format!("{before}{chord}{after}") }
|
||||
}
|
||||
|
||||
/// Plural forms the dialog looks up, as `one|other`, the key of craft-i18n's `@plural` rows.
|
||||
pub const PLURALS: &[(&str, &str)] = &[
|
||||
("{n} shortcut is assigned more than once", "{n} shortcuts are assigned more than once"),
|
||||
("{n} saved shortcut could not be used", "{n} saved shortcuts could not be used"),
|
||||
("{n} command will change", "{n} commands will change"),
|
||||
("{n} item without a shortcut", "{n} items without a shortcut"),
|
||||
("{n} item not matched", "{n} items not matched"),
|
||||
("{n} item could not be read", "{n} items could not be read"),
|
||||
("{n} key read approximately", "{n} keys read approximately"),
|
||||
("{n} entry cut at a limit", "{n} entries cut at a limit"),
|
||||
("{n} command changed", "{n} commands changed"),
|
||||
("{n} shortcut also works in another scope", "{n} shortcuts also work in another scope"),
|
||||
("{n} entry was ignored: too many commands", "{n} entries were ignored: too many commands"),
|
||||
];
|
||||
|
||||
/// Every source string the dialog looks up with [`Text::ui`], for the shared catalog.
|
||||
pub const STRINGS: &[&str] = &[
|
||||
// Window and footer.
|
||||
"Keyboard Shortcuts",
|
||||
"Custom",
|
||||
"OK",
|
||||
"Cancel",
|
||||
"Close",
|
||||
"Undo",
|
||||
"Redo",
|
||||
"Reset All…",
|
||||
"Restore every default shortcut in this set?",
|
||||
"Reset All",
|
||||
// Header.
|
||||
"Show:",
|
||||
"Filter:",
|
||||
"Search:",
|
||||
"Search by key",
|
||||
"All Commands",
|
||||
"{menu} Menu",
|
||||
"Tools",
|
||||
"{panel} Panel",
|
||||
"Other",
|
||||
"Fixed Keys",
|
||||
"All",
|
||||
"With Shortcut",
|
||||
"Changed",
|
||||
"Conflicts",
|
||||
"No matching commands",
|
||||
"(cycles)",
|
||||
"{label} (cycles)",
|
||||
"{label} (Changed)",
|
||||
// Table and detail pane.
|
||||
"Command",
|
||||
"Commands",
|
||||
"Detail pane size",
|
||||
"Select a command to see and change its shortcuts",
|
||||
"Shortcut",
|
||||
"Default",
|
||||
"{chord} (Default)",
|
||||
"{chord} ({scope})",
|
||||
"{label} ({scope})",
|
||||
"Application",
|
||||
"Current shortcuts:",
|
||||
"New shortcut:",
|
||||
"New shortcut: {chord}",
|
||||
"press keys",
|
||||
"{chord} (press again for a double press)",
|
||||
"Type…",
|
||||
"Context:",
|
||||
"Assign",
|
||||
"Use Default",
|
||||
"Clear",
|
||||
"Default: {chord}",
|
||||
"None",
|
||||
"Currently assigned to:",
|
||||
"Not assigned",
|
||||
"{label} ({scope}, both work)",
|
||||
"Add a shortcut to {label}",
|
||||
"Remove {chord} from {label}",
|
||||
"Restore the default for {label}",
|
||||
"{label}: {chord}",
|
||||
"{label}: press keys",
|
||||
"Now used by {label}",
|
||||
"{label}: {chord} (Now used by {holder})",
|
||||
// Typed shortcuts and saved texts that do not parse.
|
||||
"the shortcut has no key",
|
||||
"unknown modifier {key}",
|
||||
"modifier {key} given twice",
|
||||
"key sequences are not supported",
|
||||
"the scope name is not valid",
|
||||
// On-screen keyboard.
|
||||
"Keyboard",
|
||||
"Keyboard: US",
|
||||
"Keyboard: US (macOS)",
|
||||
"Control",
|
||||
"Option",
|
||||
"Shift",
|
||||
"Ctrl",
|
||||
"Alt",
|
||||
"Caps Lock",
|
||||
"Win",
|
||||
"Super",
|
||||
"Panel or context",
|
||||
"Both",
|
||||
"Modifier on",
|
||||
"{chord}: {label}",
|
||||
"Click a key to see its shortcuts",
|
||||
"Key: {key}",
|
||||
"Assign to Selected",
|
||||
"Assign {chord} to {label}",
|
||||
"Select a command first",
|
||||
"Nothing uses this key",
|
||||
// Messages and conflicts.
|
||||
"⚠ {chord} is used by {label}",
|
||||
"{chord} was removed from {label}",
|
||||
"Also used by {label}",
|
||||
"{chord} is reserved by the system",
|
||||
"A command can have at most {n} shortcuts",
|
||||
"The scope {scope} is unknown",
|
||||
"Too many shortcuts are assigned",
|
||||
"This command is unknown",
|
||||
"Take It",
|
||||
"Take It and Go to Conflict",
|
||||
"Keep Both",
|
||||
"Go to Conflict",
|
||||
"Cancel the new shortcut",
|
||||
"Dismiss",
|
||||
// Saved shortcuts that could not be used.
|
||||
"{key}: no command has this name",
|
||||
"{key}: “{text}” is not a shortcut ({error})",
|
||||
"{key}: {text} is reserved by the system",
|
||||
"{key}: the scope in “{text}” is unknown",
|
||||
"{key}: listed more than once",
|
||||
"{key}: part of the entry was dropped",
|
||||
// Sets.
|
||||
"Set:",
|
||||
"(modified)",
|
||||
"New Set…",
|
||||
"Rename…",
|
||||
"Delete",
|
||||
"Save",
|
||||
"Revert Set",
|
||||
"Import…",
|
||||
"Export",
|
||||
"Export…",
|
||||
"Summarize…",
|
||||
"{title}: {set}",
|
||||
"Create",
|
||||
"Rename",
|
||||
"More",
|
||||
"Name:",
|
||||
"Based on:",
|
||||
"Current shortcuts",
|
||||
"Save changes to “{set}”?",
|
||||
"Don't Save",
|
||||
"Delete the set “{set}”?",
|
||||
"Keyboard Shortcuts (JSON)",
|
||||
"The name is empty, too long or has control characters",
|
||||
"A set with this name exists",
|
||||
"The set was not found",
|
||||
"Built-in sets cannot be changed",
|
||||
"There are too many sets",
|
||||
"This is not a shortcut set file",
|
||||
"This is not a craft-keymap file",
|
||||
"This file is from a newer version (format {n})",
|
||||
"The file is too large",
|
||||
// Import review.
|
||||
"Import “{set}”",
|
||||
"Set name:",
|
||||
"Import",
|
||||
"Cancel Import",
|
||||
"line {n}",
|
||||
"Will change",
|
||||
"Not matched",
|
||||
"Unreadable",
|
||||
"Approximated",
|
||||
"{title} ({n})",
|
||||
"Suggestions ({n})",
|
||||
"numeric keypad key read as main key",
|
||||
"Matched without change",
|
||||
"Command for {item}",
|
||||
"Choose a command…",
|
||||
"no command has this name",
|
||||
"more than one command fits",
|
||||
"in a context that is not imported",
|
||||
"only a command of the other kind fits (tool or menu command)",
|
||||
"empty shortcut",
|
||||
"the shortcut is too long",
|
||||
"unknown key {key}",
|
||||
"unsupported modifier {key}",
|
||||
"{label} keeps its shortcuts (matched by a panel menu name)",
|
||||
"Import as New Set",
|
||||
"Imported",
|
||||
"Imported as “{set}”",
|
||||
"Skipped",
|
||||
"Taken from other commands",
|
||||
"Not changed",
|
||||
"taken by {label}",
|
||||
"taken by a later entry",
|
||||
"reserved by the system",
|
||||
"the scope is unknown",
|
||||
"the set's shortcuts could not be added",
|
||||
"the shortcuts could not be removed",
|
||||
"Copy Report",
|
||||
"Done",
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::chord::Chord;
|
||||
|
||||
struct German;
|
||||
impl Text for German {
|
||||
fn ui<'a>(&'a self, source: &'a str) -> Cow<'a, str> {
|
||||
source.into()
|
||||
}
|
||||
fn plural(&self, n: u64, _one: &str, other: &str) -> String {
|
||||
other.replace("{n}", &n.to_string())
|
||||
}
|
||||
fn key(&self, k: Key, _p: Platform) -> Option<String> {
|
||||
(k == Key::Delete).then(|| "Entf".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trigger_text_uses_localized_key_names() -> Result<(), crate::ParseError> {
|
||||
let t = Trigger::parse("Cmd+Shift+Delete")?;
|
||||
assert_eq!(trigger_text(&German, &t, Platform::Windows), "Ctrl+Shift+Entf");
|
||||
assert_eq!(trigger_text(&German, &Trigger::parse("F7 F7")?, Platform::Windows), "F7 F7");
|
||||
assert_eq!(trigger_text(&English, &Trigger::single(Chord::parse("⇧⌘Z")?), Platform::Mac), "⇧⌘Z");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every `ui("…")` and `plural(n, "…", "…")` literal in the dialog's sources is listed.
|
||||
#[test]
|
||||
fn every_looked_up_string_is_listed() {
|
||||
let sources = [
|
||||
include_str!("mod.rs"),
|
||||
include_str!("state.rs"),
|
||||
include_str!("rows.rs"),
|
||||
include_str!("capture.rs"),
|
||||
include_str!("view.rs"),
|
||||
include_str!("keyboard.rs"),
|
||||
include_str!("style.rs"),
|
||||
include_str!("sets.rs"),
|
||||
include_str!("review.rs"),
|
||||
include_str!("summary.rs"),
|
||||
];
|
||||
let mut missing = Vec::new();
|
||||
for src in sources {
|
||||
let src = src.split("#[cfg(test)]").next().unwrap_or(src);
|
||||
for (i, open) in src.match_indices(".ui(\"") {
|
||||
let rest = &src[i + open.len()..];
|
||||
if let Some(end) = rest.find('"') {
|
||||
let s = &rest[..end];
|
||||
if !STRINGS.contains(&s) {
|
||||
missing.push(s.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, _) in src.match_indices(".plural(") {
|
||||
let quoted: Vec<&str> = src[i..].split('"').skip(1).step_by(2).take(2).collect();
|
||||
if let [one, other] = quoted[..]
|
||||
&& !PLURALS.contains(&(one, other))
|
||||
{
|
||||
missing.push(format!("{one}|{other}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(missing.is_empty(), "not in STRINGS or PLURALS: {missing:?}");
|
||||
let mut sorted = STRINGS.to_vec();
|
||||
sorted.sort_unstable();
|
||||
sorted.dedup();
|
||||
assert_eq!(sorted.len(), STRINGS.len(), "STRINGS has duplicates");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,178 @@
|
||||
use craft_keymap::chord::foreign::{Flavor, ForeignError, ReadNote, read_foreign};
|
||||
use craft_keymap::{Chord, Key, MAX_CHORD_TEXT, Mods, ParseError, Platform, Trigger};
|
||||
|
||||
fn chord(text: &str) -> Chord {
|
||||
Chord::parse(text).unwrap_or_else(|e| panic!("{text}: {e}"))
|
||||
}
|
||||
|
||||
fn mods(cmd: bool, ctrl: bool, alt: bool, shift: bool) -> Mods {
|
||||
Mods { cmd, ctrl, alt, shift }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_text_round_trips_for_every_key_and_modifier_set() {
|
||||
for &key in Key::ALL {
|
||||
for bits in 0..16u8 {
|
||||
let c = Chord::new(mods(bits & 1 != 0, bits & 2 != 0, bits & 4 != 0, bits & 8 != 0), key);
|
||||
let text = c.to_string();
|
||||
assert_eq!(Chord::parse(&text), Ok(c), "{text}");
|
||||
assert_eq!(Trigger::parse(&format!("{text} {text}")), Ok(Trigger::double(c)), "{text} double");
|
||||
let json = serde_json::to_string(&Trigger::single(c)).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Trigger>(&json).unwrap(), Trigger::single(c));
|
||||
// macOS display text reads back as the same chord.
|
||||
assert_eq!(Chord::parse(&c.display(Platform::Mac)), Ok(c), "{}", c.display(Platform::Mac));
|
||||
}
|
||||
}
|
||||
assert_eq!(chord("Cmd+Ctrl+Alt+Shift+K").to_string(), "Cmd+Ctrl+Alt+Shift+K");
|
||||
assert_eq!(serde_json::to_string(&chord("shift+cmd+k")).unwrap(), "\"Cmd+Shift+K\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aliases_parse_to_canonical_chords() {
|
||||
let cases = [
|
||||
("cmd+shift+z", "Cmd+Shift+Z"),
|
||||
("Shift+Command+Z", "Cmd+Shift+Z"),
|
||||
("meta+z", "Cmd+Z"),
|
||||
("Super+Z", "Cmd+Z"),
|
||||
("mod+z", "Cmd+Z"),
|
||||
("⌘⇧Z", "Cmd+Shift+Z"),
|
||||
("⌃⌥⇧⌘K", "Cmd+Ctrl+Alt+Shift+K"),
|
||||
("⌘+K", "Cmd+K"),
|
||||
("⌘Shift+K", "Cmd+Shift+K"),
|
||||
("control+opt+left", "Ctrl+Alt+Left"),
|
||||
("ctl+option+ArrowUp", "Ctrl+Alt+Up"),
|
||||
// craft-menu writes Ctrl before Cmd.
|
||||
("Ctrl+Cmd+Alt+Shift+M", "Cmd+Ctrl+Alt+Shift+M"),
|
||||
("Ctrl+Cmd+F", "Cmd+Ctrl+F"),
|
||||
("Cmd++", "Cmd++"),
|
||||
("⌘+", "Cmd++"),
|
||||
("+", "+"),
|
||||
("Cmd+Plus", "Cmd++"),
|
||||
("cmd+Equals", "Cmd+="),
|
||||
("Cmd+-", "Cmd+-"),
|
||||
("Cmd + K", "Cmd+K"),
|
||||
("esc", "Escape"),
|
||||
("return", "Enter"),
|
||||
("del", "Delete"),
|
||||
("pgup", "PageUp"),
|
||||
("pgdn", "PageDown"),
|
||||
("arrowdown", "Down"),
|
||||
("spacebar", "Space"),
|
||||
("ins", "Insert"),
|
||||
("f12", "F12"),
|
||||
("Num5", "5"),
|
||||
("Semicolon", ";"),
|
||||
("Questionmark", "?"),
|
||||
("OpenCurlyBracket", "{"),
|
||||
("Backtick", "`"),
|
||||
("⌘⌫", "Cmd+Backspace"),
|
||||
];
|
||||
for (text, canonical) in cases {
|
||||
assert_eq!(chord(text).to_string(), canonical, "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_text_is_refused() {
|
||||
let long = "Cmd+".repeat(MAX_CHORD_TEXT / 4) + "K";
|
||||
assert!(long.len() > MAX_CHORD_TEXT);
|
||||
let cases: &[(&str, ParseError)] = &[
|
||||
("", ParseError::Empty),
|
||||
(" ", ParseError::Empty),
|
||||
(&long, ParseError::TooLong),
|
||||
("+++", ParseError::UnknownModifier("+".into())),
|
||||
("++", ParseError::MissingKey),
|
||||
("Cmd+", ParseError::MissingKey),
|
||||
("Cmd", ParseError::MissingKey),
|
||||
("⌘", ParseError::MissingKey),
|
||||
("Shift+Alt", ParseError::MissingKey),
|
||||
("Cmd+Command+K", ParseError::DuplicateModifier("Command".into())),
|
||||
("⌘⌘K", ParseError::DuplicateModifier("⌘".into())),
|
||||
("Cmd+é", ParseError::UnknownKey("é".into())),
|
||||
("Ctrl+ж+K", ParseError::UnknownModifier("ж".into())),
|
||||
("Hyper+K", ParseError::UnknownModifier("Hyper".into())),
|
||||
("A B", ParseError::Sequence),
|
||||
("Cmd+K Cmd+J", ParseError::Sequence),
|
||||
("A A A", ParseError::UnknownKey("A A A".into())),
|
||||
];
|
||||
for (text, err) in cases {
|
||||
assert_eq!(Trigger::parse(text).as_ref(), Err(err), "{text:?}");
|
||||
}
|
||||
let wide = "⌘".repeat(30);
|
||||
assert_eq!(Chord::parse(&wide), Err(ParseError::TooLong));
|
||||
assert!(serde_json::from_str::<Chord>("\"Cmd+Nope\"").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_follows_the_platform() {
|
||||
let c = chord("Cmd+Ctrl+Alt+Shift+K");
|
||||
assert_eq!(c.display(Platform::Mac), "⌃⌥⇧⌘K");
|
||||
assert_eq!(c.display(Platform::Windows), "Ctrl+Alt+Shift+K");
|
||||
assert_eq!(chord("Ctrl+Up").display(Platform::Mac), "⌃↑");
|
||||
assert_eq!(chord("Ctrl+Up").display(Platform::Linux), "Ctrl+Up");
|
||||
assert_eq!(chord("Cmd+Enter").display(Platform::Mac), "⌘⏎");
|
||||
assert_eq!(chord("Shift+Tab").display(Platform::Mac), "⇧⇥");
|
||||
assert_eq!(chord("Space").display(Platform::Mac), "Space");
|
||||
assert_eq!(chord("Alt+PageDown").display(Platform::Windows), "Alt+Page Down");
|
||||
assert_eq!(Trigger::parse("Cmd+K Cmd+K").unwrap().display(Platform::Mac), "⌘K ⌘K");
|
||||
assert_eq!(Trigger::parse("A A").unwrap().to_string(), "A A");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_folds_into_cmd_off_macos() {
|
||||
let ctrl = chord("Ctrl+S");
|
||||
let cmd = chord("Cmd+S");
|
||||
assert_ne!(ctrl.effective(Platform::Mac), cmd.effective(Platform::Mac));
|
||||
for p in [Platform::Windows, Platform::Linux] {
|
||||
assert_eq!(ctrl.effective(p), cmd);
|
||||
assert_eq!(chord("Cmd+Ctrl+S").effective(p), cmd);
|
||||
}
|
||||
assert!(ctrl.has_command() && cmd.has_command());
|
||||
assert!(chord("Shift+B").is_plain() && !chord("Alt+B").is_plain());
|
||||
assert!(chord("Shift+F35").is_function_key() && !chord("F").is_function_key());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn foreign_windows_text() {
|
||||
let read = |t: &str| read_foreign(t, Flavor::Windows);
|
||||
let ok = |t: &str| read(t).unwrap_or_else(|e| panic!("{t}: {e}"));
|
||||
assert_eq!(ok("Shift+Ctrl+S"), (Trigger::single(chord("Cmd+Shift+S")), vec![]));
|
||||
assert_eq!(ok("Ctrl+,").0, Trigger::single(chord("Cmd+,")));
|
||||
assert_eq!(ok(",").0, Trigger::single(chord(",")));
|
||||
assert_eq!(ok("Ctrl++").0, Trigger::single(chord("Cmd++")));
|
||||
assert_eq!(ok("Ctrl+-").0, Trigger::single(chord("Cmd+-")));
|
||||
assert_eq!(ok("Alt-F4").0, Trigger::single(chord("Alt+F4")));
|
||||
assert_eq!(ok("Ctrl + S").0, Trigger::single(chord("Cmd+S")));
|
||||
assert_eq!(ok("Shift + Ctrl + S").0, Trigger::single(chord("Cmd+Shift+S")));
|
||||
assert_eq!(ok("Ctrl + +").0, Trigger::single(chord("Cmd++")));
|
||||
assert_eq!(ok("Alt - F4").0, Trigger::single(chord("Alt+F4")));
|
||||
assert_eq!(ok("Ctrl Page Down").0, Trigger::single(chord("Cmd+PageDown")));
|
||||
assert_eq!(ok("Shift+Up Arrow").0, Trigger::single(chord("Shift+Up")));
|
||||
assert_eq!(ok("Num +"), (Trigger::single(chord("+")), vec![ReadNote::Numpad]));
|
||||
assert_eq!(ok("Ctrl+Num /"), (Trigger::single(chord("Cmd+/")), vec![ReadNote::Numpad]));
|
||||
assert_eq!(ok("Numpad 5"), (Trigger::single(chord("5")), vec![ReadNote::Numpad]));
|
||||
assert_eq!(ok("Num Enter"), (Trigger::single(chord("Enter")), vec![ReadNote::Numpad]));
|
||||
assert_eq!(read("Win+E"), Err(ForeignError::UnsupportedModifier("Win".into())));
|
||||
assert_eq!(read("Meta+E"), Err(ForeignError::UnsupportedModifier("Meta".into())));
|
||||
assert_eq!(read(""), Err(ForeignError::Empty));
|
||||
assert_eq!(read(&"x".repeat(MAX_CHORD_TEXT + 1)), Err(ForeignError::TooLong));
|
||||
assert_eq!(read("Ctrl+Num Lock"), Err(ForeignError::UnknownKey("Num Lock".into())));
|
||||
assert_eq!(read("Alt"), Err(ForeignError::UnknownKey("Alt".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn foreign_mac_text() {
|
||||
let texts = ["Shift+Cmd+S", "Ctrl+Opt+Left"];
|
||||
assert_eq!(Flavor::detect(texts), Flavor::Mac);
|
||||
assert_eq!(Flavor::detect(["Shift+Ctrl+S", "Alt+F4"]), Flavor::Windows);
|
||||
assert_eq!(Flavor::detect(["⌥⌘K"]), Flavor::Mac);
|
||||
let ok = |t: &str| read_foreign(t, Flavor::Mac).unwrap_or_else(|e| panic!("{t}: {e}")).0;
|
||||
assert_eq!(ok("Shift+Cmd+S"), Trigger::single(chord("Cmd+Shift+S")));
|
||||
assert_eq!(ok("Ctrl+Opt+Left"), Trigger::single(chord("Ctrl+Alt+Left")));
|
||||
assert_eq!(ok("Control-Option-Space"), Trigger::single(chord("Ctrl+Alt+Space")));
|
||||
assert_eq!(ok("⇧⌘S"), Trigger::single(chord("Cmd+Shift+S")));
|
||||
assert_eq!(ok("⌃⌥⇞"), Trigger::single(chord("Ctrl+Alt+PageUp")));
|
||||
assert_eq!(ok("Cmd+,"), Trigger::single(chord("Cmd+,")));
|
||||
// In a Windows set the same ⌃ is the command modifier.
|
||||
assert_eq!(read_foreign("⌃S", Flavor::Windows).map(|r| r.0), Ok(Trigger::single(chord("Cmd+S"))));
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
use craft_keymap::editor::{MAX_UNDO_BYTES, holders, search};
|
||||
use craft_keymap::{
|
||||
AssignError, Bindable, Binding, Chord, CommandRef, DOUBLE_PRESS, EditSession, Holder, Keymap, MAX_BINDING_TEXT, MAX_BINDINGS, MAX_COMMANDS,
|
||||
MAX_UNDO, Overrides, Platform, Policy, Recorded, Recorder, Scope, Scopes, Trigger,
|
||||
};
|
||||
|
||||
fn chord(text: &str) -> Chord {
|
||||
Chord::parse(text).unwrap_or_else(|e| panic!("{text}: {e}"))
|
||||
}
|
||||
|
||||
fn b(text: &str) -> Binding {
|
||||
Binding::parse(text).unwrap_or_else(|e| panic!("{text}: {e}"))
|
||||
}
|
||||
|
||||
fn keymap(platform: Platform) -> Keymap {
|
||||
let catalog = vec![
|
||||
Bindable::new("file.save", "Save", Scope::app()).with_default(b("Cmd+S")).with_path(vec!["File".into(), "Save".into()]),
|
||||
Bindable::new("edit.copy", "Copy", Scope::app()).with_default(b("Cmd+C")).with_alias("Kopieren"),
|
||||
Bindable::new("view.zoomIn", "Zoom In", Scope::app()).with_default(b("Cmd+=")),
|
||||
Bindable::new("tool.brush", "Brush", Scope::app()).with_default(b("B")).with_path(vec!["Tools".into(), "Paint".into()]),
|
||||
];
|
||||
Keymap::new(catalog, Scopes::new(), platform)
|
||||
}
|
||||
|
||||
fn keys(km: &Keymap, id: &str) -> Vec<String> {
|
||||
km.bindings(&CommandRef::new(id)).iter().map(|b| b.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_undo_redo_and_cancel() {
|
||||
let mut km = keymap(Platform::Windows);
|
||||
let mut session = EditSession::begin(&km);
|
||||
let save = CommandRef::new("file.save");
|
||||
|
||||
let assigned = session.edit(&mut km, |km| km.assign(&save, b("Cmd+Shift+S"), Policy::Steal));
|
||||
assert!(assigned.is_ok());
|
||||
session.edit(&mut km, |km| km.clear(&CommandRef::new("edit.copy")));
|
||||
assert_eq!(keys(&km, "file.save"), ["Cmd+S", "Cmd+Shift+S"]);
|
||||
assert!(keys(&km, "edit.copy").is_empty());
|
||||
assert!(session.is_modified(&km));
|
||||
|
||||
// An edit that changes nothing is no undo step.
|
||||
session.edit(&mut km, |km| km.reset(&CommandRef::new("tool.brush")));
|
||||
|
||||
assert!(session.undo(&mut km));
|
||||
assert_eq!(keys(&km, "edit.copy"), ["Cmd+C"]);
|
||||
assert!(session.undo(&mut km));
|
||||
assert_eq!(keys(&km, "file.save"), ["Cmd+S"]);
|
||||
assert!(!session.undo(&mut km));
|
||||
assert!(!session.is_modified(&km));
|
||||
|
||||
assert!(session.redo(&mut km));
|
||||
assert_eq!(keys(&km, "file.save"), ["Cmd+S", "Cmd+Shift+S"]);
|
||||
// A new edit drops what could be redone.
|
||||
session.edit(&mut km, |km| km.clear(&CommandRef::new("tool.brush")));
|
||||
assert!(!session.redo(&mut km));
|
||||
|
||||
session.cancel(&mut km);
|
||||
assert!(!session.is_modified(&km));
|
||||
assert_eq!(keys(&km, "file.save"), ["Cmd+S"]);
|
||||
assert_eq!(keys(&km, "tool.brush"), ["B"]);
|
||||
assert!(!session.can_undo());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_keeps_the_newest_steps() {
|
||||
let mut km = keymap(Platform::Windows);
|
||||
let mut session = EditSession::begin(&km);
|
||||
let brush = CommandRef::new("tool.brush");
|
||||
// Each edit changes the key: N, B, N, … (B is the default).
|
||||
let edits = MAX_UNDO + 11;
|
||||
for i in 0..edits {
|
||||
let key = if i % 2 == 0 { "N" } else { "B" };
|
||||
assert!(session.edit(&mut km, |km| km.set_bindings(&brush, vec![b(key)], Policy::Keep)).is_ok());
|
||||
}
|
||||
let mut steps = 0;
|
||||
while session.undo(&mut km) {
|
||||
steps += 1;
|
||||
}
|
||||
assert_eq!(steps, MAX_UNDO);
|
||||
// The 11 oldest steps are gone: undo stops after the 11th edit, which set N.
|
||||
assert_eq!(keys(&km, "tool.brush"), ["N"]);
|
||||
assert!(session.is_modified(&km));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_history_is_capped_by_size() {
|
||||
let mut km = keymap(Platform::Windows);
|
||||
let mut session = EditSession::begin(&km);
|
||||
// Full-size snapshots of entries for commands the catalog does not have.
|
||||
let big = |tag: char| {
|
||||
let mut o = Overrides::new();
|
||||
for n in 0..MAX_COMMANDS {
|
||||
assert!(o.insert(format!("junk.{n}"), vec![tag.to_string().repeat(MAX_BINDING_TEXT); MAX_BINDINGS]));
|
||||
}
|
||||
o
|
||||
};
|
||||
let (a, b) = (big('a'), big('b'));
|
||||
let string = size_of::<String>();
|
||||
let per = a.iter().map(|(k, t)| string + 64 + k.len() + t.iter().map(|t| string + 16 + t.len()).sum::<usize>()).sum::<usize>();
|
||||
let edits = 2 * MAX_UNDO_BYTES / per + 4;
|
||||
for n in 0..edits {
|
||||
let next = if n % 2 == 0 { a.clone() } else { b.clone() };
|
||||
session.edit(&mut km, |km| km.set_overrides(next));
|
||||
}
|
||||
let mut steps = 0;
|
||||
while session.undo(&mut km) {
|
||||
steps += 1;
|
||||
}
|
||||
assert!(steps >= 2 && steps <= MAX_UNDO_BYTES / per, "{steps} steps of {per} bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recorder_turns_presses_into_triggers() {
|
||||
let mut r = Recorder::new();
|
||||
let a = chord("A");
|
||||
assert_eq!(r.press(a, 1.0), Recorded::Single(Trigger::single(a)));
|
||||
assert_eq!(r.press(a, 1.0 + DOUBLE_PRESS / 2.0), Recorded::Double(Trigger::double(a)));
|
||||
// The press after a double starts over.
|
||||
assert_eq!(r.press(a, 1.4), Recorded::Single(Trigger::single(a)));
|
||||
// Too late for a double.
|
||||
assert_eq!(r.press(a, 1.4 + DOUBLE_PRESS + 0.1), Recorded::Single(Trigger::single(a)));
|
||||
// Another chord in between.
|
||||
assert_eq!(r.press(chord("B"), 3.0), Recorded::Single(Trigger::single(chord("B"))));
|
||||
assert_eq!(r.press(a, 3.1), Recorded::Single(Trigger::single(a)));
|
||||
|
||||
assert_eq!(r.press(chord("Escape"), 3.2), Recorded::Cancel);
|
||||
let shift_escape = chord("Shift+Escape");
|
||||
assert_eq!(r.press(shift_escape, 3.3), Recorded::Single(Trigger::single(shift_escape)));
|
||||
// Two presses in one egui frame share its time.
|
||||
assert_eq!(r.press(a, 4.0), Recorded::Single(Trigger::single(a)));
|
||||
assert_eq!(r.press(a, 4.0), Recorded::Double(Trigger::double(a)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_reads_labels_aliases_paths_ids_and_keys() {
|
||||
let ids = |km: &Keymap, q: &str, p: Platform| search(km, q, p).iter().map(|b| b.command.id.clone()).collect::<Vec<_>>();
|
||||
let win = keymap(Platform::Windows);
|
||||
let mac = keymap(Platform::Mac);
|
||||
assert_eq!(ids(&win, "zoom", Platform::Windows), ["view.zoomIn"]);
|
||||
assert_eq!(ids(&win, "KOPIEREN", Platform::Windows), ["edit.copy"]);
|
||||
assert_eq!(ids(&win, "paint", Platform::Windows), ["tool.brush"]);
|
||||
assert_eq!(ids(&win, "file.sa", Platform::Windows), ["file.save"]);
|
||||
assert_eq!(ids(&win, "ctrl+s", Platform::Windows), ["file.save"]);
|
||||
assert_eq!(ids(&win, "cmd+c", Platform::Windows), ["edit.copy"]);
|
||||
assert_eq!(ids(&mac, "⌘s", Platform::Mac), ["file.save"]);
|
||||
assert_eq!(ids(&mac, "⌘s", Platform::Windows), Vec::<String>::new());
|
||||
assert_eq!(ids(&mac, " ", Platform::Mac).len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dialog_asks_before_stealing_and_undoes_each_answer() {
|
||||
let mut km = keymap(Platform::Mac);
|
||||
let mut session = EditSession::begin(&km);
|
||||
let save = CommandRef::new("file.save");
|
||||
let copy = CommandRef::new("edit.copy");
|
||||
let held = vec![Holder { command: copy.clone(), binding: b("Cmd+C") }];
|
||||
|
||||
// While recording: who else has the key.
|
||||
assert_eq!(holders(&km, &save, &b("Cmd+C")), held);
|
||||
assert!(holders(&km, ©, &b("Cmd+C")).is_empty(), "its own key");
|
||||
assert_eq!(session.assign(&mut km, &save, b("Cmd+C"), Policy::Refuse), Err(AssignError::Taken(held.clone())));
|
||||
assert!(!session.can_undo(), "a refused assignment changes nothing");
|
||||
|
||||
// Keep: both hold it.
|
||||
let kept = session.assign(&mut km, &save, b("Cmd+C"), Policy::Keep).unwrap();
|
||||
assert_eq!(kept.clashes, held);
|
||||
assert_eq!(keys(&km, "edit.copy"), ["Cmd+C"]);
|
||||
assert!(session.undo(&mut km));
|
||||
|
||||
// Steal: the other command loses it.
|
||||
let stolen = session.assign(&mut km, &save, b("Cmd+C"), Policy::Steal).unwrap();
|
||||
assert_eq!(stolen.taken_from, held);
|
||||
assert!(keys(&km, "edit.copy").is_empty());
|
||||
assert_eq!(keys(&km, "file.save"), ["Cmd+S", "Cmd+C"]);
|
||||
|
||||
// Recording over one key of the list replaces it in place.
|
||||
session.replace(&mut km, &save, &b("Cmd+S"), b("Cmd+Shift+S"), Policy::Refuse).unwrap();
|
||||
assert_eq!(keys(&km, "file.save"), ["Cmd+Shift+S", "Cmd+C"]);
|
||||
assert!(session.remove(&mut km, &save, &b("Cmd+C")));
|
||||
assert!(session.clear(&mut km, &CommandRef::new("tool.brush")));
|
||||
|
||||
assert!(session.reset(&mut km, &save));
|
||||
assert_eq!(keys(&km, "file.save"), ["Cmd+S"]);
|
||||
session.reset_all(&mut km);
|
||||
assert!(km.overrides().is_empty());
|
||||
assert!(!session.is_modified(&km));
|
||||
|
||||
// One undo per action, back to the steal.
|
||||
for _ in 0..5 {
|
||||
assert!(session.undo(&mut km));
|
||||
}
|
||||
assert_eq!(keys(&km, "file.save"), ["Cmd+S", "Cmd+C"]);
|
||||
assert!(session.undo(&mut km));
|
||||
assert!(!session.can_undo());
|
||||
|
||||
session.redo(&mut km);
|
||||
session.cancel(&mut km);
|
||||
assert!(km.overrides().is_empty(), "cancel restores the state at open");
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
#![cfg(feature = "egui")]
|
||||
|
||||
use craft_keymap::egui::{Dispatcher, Hit, matches, platform};
|
||||
use craft_keymap::{Active, Bindable, Binding, Chord, CommandRef, Key, KeyInput, Keymap, Kind, Layout, Mods, Platform, Scope, Scopes, Trigger};
|
||||
use egui::{Event, InputState, Key as EguiKey, Modifiers};
|
||||
|
||||
fn chord(text: &str) -> Chord {
|
||||
Chord::parse(text).unwrap_or_else(|e| panic!("{text}: {e}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_browser_on_a_mac_gets_the_mac_keymap() {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_os(egui::os::OperatingSystem::from_user_agent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15"));
|
||||
assert_eq!(platform(&ctx), Platform::Mac);
|
||||
ctx.set_os(egui::os::OperatingSystem::from_user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64)"));
|
||||
assert_eq!(platform(&ctx), Platform::Windows);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_key_converts_both_ways() {
|
||||
for &key in Key::ALL {
|
||||
assert_eq!(Key::from_egui(key.to_egui()), Some(key), "{key}");
|
||||
}
|
||||
for k in [EguiKey::Copy, EguiKey::Cut, EguiKey::Paste, EguiKey::BrowserBack, EguiKey::ShiftLeft, EguiKey::IntlBackslash] {
|
||||
assert_eq!(Key::from_egui(k), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modifiers_and_shortcuts_follow_the_platform() {
|
||||
let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE };
|
||||
assert_eq!(Mods::from_egui(&ctrl, Platform::Windows), Mods::CMD);
|
||||
assert_eq!(Mods::from_egui(&Modifiers::CTRL, Platform::Mac), Mods::CTRL);
|
||||
assert_eq!(Mods::from_egui(&Modifiers::MAC_CMD, Platform::Mac), Mods::CMD);
|
||||
|
||||
assert!(matches(&chord("Ctrl+S"), EguiKey::S, &ctrl, Platform::Windows));
|
||||
assert!(matches(&chord("Cmd+S"), EguiKey::S, &ctrl, Platform::Windows));
|
||||
assert!(!matches(&chord("Cmd+S"), EguiKey::S, &Modifiers::CTRL, Platform::Mac));
|
||||
|
||||
let shortcut = chord("Cmd+Shift+Z").to_egui_shortcut();
|
||||
assert_eq!(shortcut.logical_key, EguiKey::Z);
|
||||
assert!(Modifiers { mac_cmd: true, command: true, shift: true, ..Modifiers::NONE }.matches_exact(shortcut.modifiers));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shifted_symbols_match_their_bindings() {
|
||||
let p = Platform::Windows;
|
||||
let shift = Modifiers::SHIFT;
|
||||
let none = Modifiers::NONE;
|
||||
let cmd = Modifiers { ctrl: true, command: true, ..Modifiers::NONE };
|
||||
let cmd_shift = Modifiers { shift: true, ..cmd };
|
||||
|
||||
// Shift+base matches the shifted key egui reports, but the base key alone does not.
|
||||
assert!(matches(&chord("Shift+;"), EguiKey::Colon, &shift, p));
|
||||
assert!(!matches(&chord("Shift+;"), EguiKey::Semicolon, &none, p));
|
||||
assert!(!matches(&chord(";"), EguiKey::Colon, &shift, p));
|
||||
assert!(matches(&chord("Shift+/"), EguiKey::Questionmark, &shift, p));
|
||||
assert!(matches(&chord("Cmd+Shift+]"), EguiKey::CloseCurlyBracket, &cmd_shift, p));
|
||||
assert!(matches(&chord("Shift+1"), EguiKey::Exclamationmark, &shift, p));
|
||||
// A shifted symbol bound directly matches while Shift is held to type it.
|
||||
assert!(matches(&chord("?"), EguiKey::Questionmark, &shift, p));
|
||||
assert!(matches(&chord(":"), EguiKey::Colon, &none, p));
|
||||
|
||||
// Zoom keys: `=` also matches `+`, with or without Shift; `+` matches Shift+`=`.
|
||||
assert!(matches(&chord("Cmd+="), EguiKey::Plus, &cmd, p));
|
||||
assert!(matches(&chord("Cmd+="), EguiKey::Plus, &cmd_shift, p));
|
||||
assert!(matches(&chord("Cmd+="), EguiKey::Equals, &cmd, p));
|
||||
assert!(matches(&chord("Cmd++"), EguiKey::Equals, &cmd_shift, p));
|
||||
assert!(matches(&chord("Cmd++"), EguiKey::Plus, &cmd_shift, p));
|
||||
assert!(!matches(&chord("Cmd++"), EguiKey::Equals, &cmd, p));
|
||||
assert!(!matches(&chord("Cmd+="), EguiKey::Plus, &none, p));
|
||||
assert!(!matches(&chord("Cmd+="), EguiKey::Minus, &cmd, p));
|
||||
}
|
||||
|
||||
const CTRL: Modifiers = Modifiers { ctrl: true, command: true, ..Modifiers::NONE };
|
||||
|
||||
fn dispatch_keymap() -> Keymap {
|
||||
let app = |id: &str, keys: &[&str]| keys.iter().fold(Bindable::new(id, id, Scope::app()), |e, k| e.with_default(Binding::parse(k).unwrap()));
|
||||
let tool = |id: &str| app(id, &["M"]).with_kind(Kind::Tool { group: Some("select".into()) });
|
||||
let catalog = vec![
|
||||
app("edit.copy", &["Cmd+C", "Cmd+Insert"]),
|
||||
app("edit.paste", &["Cmd+V", "Shift+Insert"]),
|
||||
app("edit.pasteInPlace", &["Cmd+Shift+V"]),
|
||||
app("edit.copyMerged", &["Cmd+Shift+C"]),
|
||||
app("app.quit", &["Cmd+Alt+Q"]),
|
||||
app("type.pageNumber", &["Cmd+Alt+Shift+N"]),
|
||||
app("view.refresh", &["Cmd+Alt+F5"]),
|
||||
app("file.save", &["Cmd+S"]),
|
||||
app("view.zoomIn", &["="]),
|
||||
app("help.find", &["Shift+;"]),
|
||||
app("tool.brush", &["B"]),
|
||||
app("app.loop", &["L"]),
|
||||
Bindable::new("timeline.loop", "Loop", Scope::new("Timeline").unwrap()).with_default(Binding::parse("L").unwrap()),
|
||||
tool("tool.marquee"),
|
||||
tool("tool.ellipse"),
|
||||
app("reveal.one", &["U"]),
|
||||
app("reveal.all", &["U U"]),
|
||||
];
|
||||
Keymap::new(catalog, Scopes::new().with_panel("Timeline"), Platform::Windows)
|
||||
}
|
||||
|
||||
fn press(key: EguiKey, modifiers: Modifiers) -> Event {
|
||||
Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers }
|
||||
}
|
||||
|
||||
fn frame(time: f64, modifiers: Modifiers, events: Vec<Event>) -> InputState {
|
||||
let mut input = InputState::default();
|
||||
input.time = time;
|
||||
input.modifiers = modifiers;
|
||||
input.events = events;
|
||||
input
|
||||
}
|
||||
|
||||
/// Dispatches one frame and returns the ids that ran and the events left.
|
||||
fn run(d: &mut Dispatcher, km: &Keymap, active: &Active, mut input: InputState) -> (Vec<String>, Vec<Event>) {
|
||||
let hits = d.dispatch(&mut input, km, active);
|
||||
(hits.into_iter().map(|h| h.command.id).collect(), input.events)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bound_press_runs_once_and_is_removed_with_its_text() {
|
||||
let km = dispatch_keymap();
|
||||
let events = vec![
|
||||
press(EguiKey::B, Modifiers::NONE),
|
||||
Event::Text("b".into()),
|
||||
Event::Key { key: EguiKey::B, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE },
|
||||
press(EguiKey::Q, Modifiers::NONE),
|
||||
Event::Text("q".into()),
|
||||
];
|
||||
let (ran, left) = run(&mut Dispatcher::new(), &km, &Active::NONE, frame(1.0, Modifiers::NONE, events));
|
||||
assert_eq!(ran, ["tool.brush"]);
|
||||
// The release and the unbound Q with its text stay.
|
||||
assert_eq!(left.len(), 3);
|
||||
assert!(matches!(left[0], Event::Key { key: EguiKey::B, pressed: false, .. }));
|
||||
assert!(matches!(left[1], Event::Key { key: EguiKey::Q, pressed: true, .. }));
|
||||
assert_eq!(left[2], Event::Text("q".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shifted_symbols_and_zoom_keys_reach_their_bindings() {
|
||||
let km = dispatch_keymap();
|
||||
let mut d = Dispatcher::new();
|
||||
let shift = Modifiers::SHIFT;
|
||||
let (ran, left) = run(&mut d, &km, &Active::NONE, frame(1.0, shift, vec![press(EguiKey::Colon, shift), Event::Text(":".into())]));
|
||||
assert_eq!(ran, ["help.find"]);
|
||||
assert!(left.is_empty());
|
||||
let (ran, _) = run(&mut d, &km, &Active::NONE, frame(2.0, Modifiers::NONE, vec![press(EguiKey::Plus, Modifiers::NONE)]));
|
||||
assert_eq!(ran, ["view.zoomIn"]);
|
||||
let (ran, _) = run(&mut d, &km, &Active::NONE, frame(3.0, shift, vec![press(EguiKey::Plus, shift)]));
|
||||
assert_eq!(ran, ["view.zoomIn"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipboard_events_stay_with_the_app_by_default() {
|
||||
let km = dispatch_keymap();
|
||||
let mut d = Dispatcher::new();
|
||||
// egui-winit sends these in place of the Ctrl+C and Ctrl+V presses.
|
||||
let events = vec![Event::Copy, Event::Paste("text".into())];
|
||||
let (ran, left) = run(&mut d, &km, &Active::NONE, frame(1.0, CTRL, events.clone()));
|
||||
assert!(ran.is_empty(), "{ran:?}");
|
||||
assert_eq!(left, events);
|
||||
// The web build sends the press and then the event: both stay.
|
||||
let events = vec![press(EguiKey::C, CTRL), Event::Copy, press(EguiKey::S, CTRL)];
|
||||
let (ran, left) = run(&mut d, &km, &Active::NONE, frame(2.0, CTRL, events.clone()));
|
||||
assert_eq!(ran, ["file.save"]);
|
||||
assert_eq!(left, events[..2]);
|
||||
// A clipboard press with no clipboard event after it is an ordinary press.
|
||||
let (ran, _) = run(&mut d, &km, &Active::NONE, frame(3.0, CTRL, vec![press(EguiKey::Insert, CTRL)]));
|
||||
assert_eq!(ran, ["edit.copy"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipboard_chords_with_more_modifiers_run_their_bindings() {
|
||||
let km = dispatch_keymap();
|
||||
let mut d = Dispatcher::new();
|
||||
let typing = Active { typing: true, ..Active::NONE };
|
||||
let ctrl_shift = Modifiers { shift: true, ..CTRL };
|
||||
// The desktop: egui-winit sends the Paste event in place of Ctrl+Shift+V.
|
||||
let mut input = frame(1.0, ctrl_shift, vec![Event::Paste("text".into())]);
|
||||
let hits = d.dispatch(&mut input, &km, &Active::NONE);
|
||||
let ran: Vec<_> = hits.iter().map(|h| (h.command.id.as_str(), h.pasted.as_deref())).collect();
|
||||
assert_eq!(ran, [("edit.pasteInPlace", Some("text"))]);
|
||||
assert!(input.events.is_empty());
|
||||
let (ran, left) = run(&mut d, &km, &typing, frame(2.0, ctrl_shift, vec![Event::Copy]));
|
||||
assert_eq!(ran, ["edit.copyMerged"]);
|
||||
assert!(left.is_empty());
|
||||
// Ctrl+Shift+X has no binding: the event stays.
|
||||
let (ran, left) = run(&mut d, &km, &Active::NONE, frame(3.0, ctrl_shift, vec![Event::Cut]));
|
||||
assert!(ran.is_empty());
|
||||
assert_eq!(left, [Event::Cut]);
|
||||
|
||||
// The web: the press decides for itself and its event, also while typing.
|
||||
for (time, active) in [(4.0, &Active::NONE), (5.0, &typing)] {
|
||||
let events = vec![press(EguiKey::C, ctrl_shift), Event::Copy];
|
||||
let (ran, left) = run(&mut d, &km, active, frame(time, ctrl_shift, events));
|
||||
assert_eq!(ran, ["edit.copyMerged"]);
|
||||
assert!(left.is_empty(), "{left:?}");
|
||||
}
|
||||
let events = vec![press(EguiKey::X, ctrl_shift), Event::Cut];
|
||||
let (ran, left) = run(&mut d, &km, &Active::NONE, frame(6.0, ctrl_shift, events.clone()));
|
||||
assert!(ran.is_empty());
|
||||
assert_eq!(left, events);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipboard_events_run_their_chords_outside_text_fields_when_turned_on() {
|
||||
let km = dispatch_keymap();
|
||||
let mut d = Dispatcher::new().with_clipboard_events(true);
|
||||
let mut input = frame(1.0, CTRL, vec![Event::Copy, Event::Paste("text".into())]);
|
||||
let hits = d.dispatch(&mut input, &km, &Active::NONE);
|
||||
let ran: Vec<_> = hits.iter().map(|h| (h.command.id.as_str(), h.pasted.as_deref())).collect();
|
||||
assert_eq!(ran, [("edit.copy", None), ("edit.paste", Some("text"))]);
|
||||
assert!(input.events.is_empty());
|
||||
|
||||
let typing = Active { typing: true, ..Active::NONE };
|
||||
let (ran, left) = run(&mut d, &km, &typing, frame(2.0, CTRL, vec![Event::Copy]));
|
||||
assert!(ran.is_empty());
|
||||
assert_eq!(left, [Event::Copy]);
|
||||
|
||||
// The web build sends the key press and the clipboard event it causes: one run each.
|
||||
for (time, key, mods, event, id) in [
|
||||
(3.0, EguiKey::C, CTRL, Event::Copy, "edit.copy"),
|
||||
(4.0, EguiKey::Insert, CTRL, Event::Copy, "edit.copy"),
|
||||
(5.0, EguiKey::Insert, Modifiers::SHIFT, Event::Paste("text".into()), "edit.paste"),
|
||||
] {
|
||||
let (ran, _) = run(&mut d, &km, &Active::NONE, frame(time, mods, vec![press(key, mods), event]));
|
||||
assert_eq!(ran, [id], "{key:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_web_paste_carries_its_text_and_takes_its_event() {
|
||||
let km = dispatch_keymap();
|
||||
let mut d = Dispatcher::new().with_clipboard_events(true);
|
||||
// The web build sends the Cmd+V press and then the Paste event with the clipboard text.
|
||||
let events = vec![press(EguiKey::V, CTRL), Event::Paste("text".into()), press(EguiKey::C, CTRL), Event::Copy];
|
||||
let mut input = frame(1.0, CTRL, events.clone());
|
||||
let mut seen = Vec::new();
|
||||
let hits = d.dispatch_filtered(&mut input, &km, &Active::NONE, |hit| {
|
||||
seen.push(hit.pasted.clone());
|
||||
true
|
||||
});
|
||||
let ran: Vec<_> = hits.iter().map(|h| (h.command.id.as_str(), h.pasted.as_deref())).collect();
|
||||
assert_eq!(ran, [("edit.paste", Some("text")), ("edit.copy", None)]);
|
||||
assert_eq!(seen, [Some("text".to_string()), None], "the filter sees the pasted text");
|
||||
assert!(input.events.is_empty(), "{:?}", input.events);
|
||||
|
||||
// A declined press leaves the press and its event in place, and the event does not run again.
|
||||
let mut input = frame(2.0, CTRL, events.clone());
|
||||
let hits = d.dispatch_filtered(&mut input, &km, &Active::NONE, |hit| hit.command.id != "edit.paste");
|
||||
let ran: Vec<_> = hits.iter().map(|h| h.command.id.as_str()).collect();
|
||||
assert_eq!(ran, ["edit.copy"]);
|
||||
assert_eq!(input.events, events[..2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_web_paste_runs_once_when_repeats_are_off() {
|
||||
let km = dispatch_keymap();
|
||||
let mut d = Dispatcher::new().with_clipboard_events(true);
|
||||
let repeat = Event::Key { key: EguiKey::V, physical_key: Some(EguiKey::V), pressed: true, repeat: true, modifiers: CTRL };
|
||||
let paste = || Event::Paste("text".into());
|
||||
let events = vec![press(EguiKey::V, CTRL), paste(), repeat.clone(), paste()];
|
||||
let (ran, left) = run(&mut d, &km, &Active::NONE, frame(1.0, CTRL, events));
|
||||
assert_eq!(ran, ["edit.paste"]);
|
||||
assert_eq!(left, [repeat, paste()], "the repeat and its event stay in egui's input");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declined_hits_leave_their_events_in_order() {
|
||||
let km = dispatch_keymap();
|
||||
let mut d = Dispatcher::new();
|
||||
let shift = Modifiers::SHIFT;
|
||||
let events = vec![
|
||||
press(EguiKey::B, Modifiers::NONE),
|
||||
Event::Text("b".into()),
|
||||
press(EguiKey::S, CTRL),
|
||||
press(EguiKey::Colon, shift),
|
||||
Event::Text(":".into()),
|
||||
press(EguiKey::Equals, Modifiers::NONE),
|
||||
];
|
||||
let mut input = frame(1.0, Modifiers::NONE, events.clone());
|
||||
let mut seen = Vec::new();
|
||||
let hits = d.dispatch_filtered(&mut input, &km, &Active::NONE, |hit| {
|
||||
seen.push((hit.command.id.clone(), hit.trigger.chord.to_string(), hit.exact));
|
||||
hit.command.id != "file.save" && hit.command.id != "tool.brush"
|
||||
});
|
||||
let s = |id: &str, chord: &str, exact| (id.to_string(), chord.to_string(), exact);
|
||||
assert_eq!(seen, [s("tool.brush", "B", true), s("file.save", "Cmd+S", true), s("help.find", "Shift+;", false), s("view.zoomIn", "=", true)]);
|
||||
let ran: Vec<_> = hits.iter().map(|h| h.command.id.as_str()).collect();
|
||||
assert_eq!(ran, ["help.find", "view.zoomIn"]);
|
||||
assert_eq!(input.events, events[..3], "the declined B keeps its text, and Ctrl+S stays in its place");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipboard_presses_stay_with_the_text_field() {
|
||||
let km = dispatch_keymap();
|
||||
let mut d = Dispatcher::new();
|
||||
let typing = Active { typing: true, ..Active::NONE };
|
||||
// The web build's Cmd+C press and its Copy event both reach the text field.
|
||||
let events = vec![press(EguiKey::C, CTRL), Event::Copy, press(EguiKey::Insert, CTRL)];
|
||||
let (ran, left) = run(&mut d, &km, &typing, frame(1.0, CTRL, events.clone()));
|
||||
assert!(ran.is_empty(), "{ran:?}");
|
||||
assert_eq!(left, events);
|
||||
let (ran, _) = run(&mut d, &km, &Active::NONE, frame(2.0, CTRL, vec![press(EguiKey::Insert, CTRL)]));
|
||||
assert_eq!(ran, ["edit.copy"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_press_that_types_text_stays_with_the_text_field() {
|
||||
let km = dispatch_keymap();
|
||||
let mut d = Dispatcher::new();
|
||||
let typing = Active { typing: true, ..Active::NONE };
|
||||
// A press the web build's text agent follows with the text it typed.
|
||||
let events = vec![press(EguiKey::B, Modifiers::NONE), Event::Text("b".into())];
|
||||
let (ran, left) = run(&mut d, &km, &typing, frame(1.0, Modifiers::NONE, events.clone()));
|
||||
assert!(ran.is_empty(), "{ran:?}");
|
||||
assert_eq!(left, events);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_alt_is_left_to_the_text_field_only_when_it_types() {
|
||||
let km = dispatch_keymap();
|
||||
let mut d = Dispatcher::new();
|
||||
let typing = Active { typing: true, ..Active::NONE };
|
||||
// AltGr+Q on a German layout types `@`: the browser on Windows reports Ctrl+Alt+Q and the text
|
||||
// agent sends the text after it.
|
||||
let alt_gr = Modifiers { alt: true, ..CTRL };
|
||||
let events = vec![press(EguiKey::Q, alt_gr), Event::Text("@".into())];
|
||||
let (ran, left) = run(&mut d, &km, &typing, frame(1.0, alt_gr, events.clone()));
|
||||
assert!(ran.is_empty(), "{ran:?}");
|
||||
assert_eq!(left, events);
|
||||
// A real Ctrl+Alt chord types nothing, so it runs while typing.
|
||||
let all = Modifiers { shift: true, ..alt_gr };
|
||||
let (ran, left) = run(&mut d, &km, &typing, frame(2.0, all, vec![press(EguiKey::N, all)]));
|
||||
assert_eq!(ran, ["type.pageNumber"]);
|
||||
assert!(left.is_empty());
|
||||
let (ran, _) = run(&mut d, &km, &typing, frame(3.0, alt_gr, vec![press(EguiKey::Q, alt_gr)]));
|
||||
assert_eq!(ran, ["app.quit"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_blocks_plain_keys_but_not_command_chords() {
|
||||
let km = dispatch_keymap();
|
||||
let mut d = Dispatcher::new();
|
||||
let typing = Active { typing: true, ..Active::NONE };
|
||||
let events = vec![press(EguiKey::B, Modifiers::NONE), Event::Text("b".into()), press(EguiKey::S, CTRL)];
|
||||
let (ran, left) = run(&mut d, &km, &typing, frame(1.0, CTRL, events));
|
||||
assert_eq!(ran, ["file.save"]);
|
||||
assert_eq!(left.len(), 2);
|
||||
assert_eq!(left[1], Event::Text("b".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_goes_to_the_text_field_and_save_still_runs() {
|
||||
let km = Keymap::new(
|
||||
vec![
|
||||
Bindable::new("edit.undo", "Undo", Scope::app()).with_default(Binding::parse("Cmd+Z").unwrap()),
|
||||
Bindable::new("file.save", "Save", Scope::app()).with_default(Binding::parse("Cmd+S").unwrap()),
|
||||
],
|
||||
Scopes::new(),
|
||||
Platform::Windows,
|
||||
);
|
||||
let typing = Active { typing: true, ..Active::NONE };
|
||||
let events = vec![press(EguiKey::Z, CTRL), press(EguiKey::S, CTRL)];
|
||||
let (ran, left) = run(&mut Dispatcher::new(), &km, &typing, frame(1.0, CTRL, events));
|
||||
assert_eq!(ran, ["file.save"]);
|
||||
assert_eq!(left, [press(EguiKey::Z, CTRL)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_focused_panel_wins_and_tool_groups_cycle() {
|
||||
let km = dispatch_keymap();
|
||||
let mut d = Dispatcher::new();
|
||||
let l = || frame(1.0, Modifiers::NONE, vec![press(EguiKey::L, Modifiers::NONE)]);
|
||||
assert_eq!(run(&mut d, &km, &Active::panel("Timeline"), l()).0, ["timeline.loop"]);
|
||||
assert_eq!(run(&mut d, &km, &Active::NONE, l()).0, ["app.loop"]);
|
||||
|
||||
let mut input = frame(2.0, Modifiers::NONE, vec![press(EguiKey::M, Modifiers::NONE)]);
|
||||
let hits = d.dispatch(&mut input, &km, &Active::NONE);
|
||||
let tools = vec![CommandRef::new("tool.marquee"), CommandRef::new("tool.ellipse")];
|
||||
let trigger = Trigger::single(chord("M"));
|
||||
let got: Vec<_> = hits.iter().map(|h: &Hit| (&h.command, &h.cycle, h.trigger, h.exact, h.pasted.as_deref())).collect();
|
||||
assert_eq!(got, [(&tools[0], &tools, trigger, true, None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_press_runs_the_double_binding() {
|
||||
let km = dispatch_keymap();
|
||||
let mut d = Dispatcher::new();
|
||||
let key = |d: &mut Dispatcher, k: EguiKey, t: f64| run(d, &km, &Active::NONE, frame(t, Modifiers::NONE, vec![press(k, Modifiers::NONE)])).0;
|
||||
let u = |d: &mut Dispatcher, t: f64| key(d, EguiKey::U, t);
|
||||
assert_eq!(u(&mut d, 1.0), ["reveal.one"]);
|
||||
assert_eq!(u(&mut d, 1.3), ["reveal.all"]);
|
||||
// The press after a double starts over.
|
||||
assert_eq!(u(&mut d, 1.5), ["reveal.one"]);
|
||||
assert_eq!(u(&mut d, 2.5), ["reveal.one"]);
|
||||
// B in between breaks the pair.
|
||||
key(&mut d, EguiKey::B, 2.6);
|
||||
assert_eq!(u(&mut d, 2.7), ["reveal.one"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_double_press_needs_both_presses_in_one_panel() {
|
||||
let km = Keymap::new(
|
||||
vec![
|
||||
Bindable::new("x.one", "One", Scope::new("X").unwrap()).with_default(Binding::parse("A").unwrap()),
|
||||
Bindable::new("y.one", "One", Scope::new("Y").unwrap()).with_default(Binding::parse("A").unwrap()),
|
||||
Bindable::new("y.two", "Two", Scope::new("Y").unwrap()).with_default(Binding::parse("A A").unwrap()),
|
||||
],
|
||||
Scopes::new().with_panel("X").with_panel("Y").with_panel_fallthrough(false),
|
||||
Platform::Windows,
|
||||
);
|
||||
let mut d = Dispatcher::new();
|
||||
let a = |d: &mut Dispatcher, panel, t| run(d, &km, &Active::panel(panel), frame(t, Modifiers::NONE, vec![press(EguiKey::A, Modifiers::NONE)])).0;
|
||||
assert_eq!(a(&mut d, "X", 1.0), ["x.one"]);
|
||||
assert_eq!(a(&mut d, "Y", 1.2), ["y.one"]);
|
||||
assert_eq!(a(&mut d, "Y", 1.4), ["y.two"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_presses_in_one_frame_make_a_double() {
|
||||
let km = dispatch_keymap();
|
||||
let mut d = Dispatcher::new();
|
||||
let u = press(EguiKey::U, Modifiers::NONE);
|
||||
let (ran, left) = run(&mut d, &km, &Active::NONE, frame(4.0, Modifiers::NONE, vec![u.clone(), u]));
|
||||
assert_eq!(ran, ["reveal.one", "reveal.all"]);
|
||||
assert!(left.is_empty(), "{left:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn key_repeats_run_only_when_turned_on() {
|
||||
let km = Keymap::new(
|
||||
vec![
|
||||
Bindable::new("nudge.right", "Nudge", Scope::app()).with_default(Binding::parse("Right").unwrap()),
|
||||
Bindable::new("jump.right", "Jump", Scope::app()).with_default(Binding::parse("Right Right").unwrap()),
|
||||
],
|
||||
Scopes::new(),
|
||||
Platform::Windows,
|
||||
);
|
||||
let held = |repeat: bool| Event::Key { key: EguiKey::ArrowRight, physical_key: None, pressed: true, repeat, modifiers: Modifiers::NONE };
|
||||
let events = || vec![held(false), held(true), held(true)];
|
||||
|
||||
let mut on = Dispatcher::new().with_repeat(true);
|
||||
let (ran, left) = run(&mut on, &km, &Active::NONE, frame(1.0, Modifiers::NONE, events()));
|
||||
assert_eq!(ran, ["nudge.right", "nudge.right", "nudge.right"]);
|
||||
assert!(left.is_empty());
|
||||
// Repeats neither made nor broke a double: the next press within the window is one.
|
||||
let (ran, _) = run(&mut on, &km, &Active::NONE, frame(1.3, Modifiers::NONE, vec![held(false)]));
|
||||
assert_eq!(ran, ["jump.right"]);
|
||||
|
||||
let (ran, left) = run(&mut Dispatcher::new(), &km, &Active::NONE, frame(1.0, Modifiers::NONE, events()));
|
||||
assert_eq!(ran, ["nudge.right"]);
|
||||
assert_eq!(left, [held(true), held(true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dispatcher_reads_presses_by_the_layout() {
|
||||
let app = |id: &str, key: &str| Bindable::new(id, id, Scope::app()).with_default(Binding::parse(key).unwrap());
|
||||
let km = Keymap::new(
|
||||
vec![app("edit.duplicate", "Cmd+Shift+D"), app("tab.next", "Cmd+Shift+]"), app("edit.comment", "Cmd+/")],
|
||||
Scopes::new(),
|
||||
Platform::Windows,
|
||||
);
|
||||
let at = |key, physical, modifiers| Event::Key { key, physical_key: Some(physical), pressed: true, repeat: false, modifiers };
|
||||
let ctrl_shift = Modifiers { shift: true, ..CTRL };
|
||||
|
||||
// Arabic 101: typing ي on the D key shows the layout is not Latin, so ⌃⇧D (which types ]) is
|
||||
// Ctrl+Shift+D.
|
||||
let mut d = Dispatcher::new();
|
||||
let typed = vec![at(EguiKey::D, EguiKey::D, Modifiers::NONE), Event::Text("ي".into())];
|
||||
run(&mut d, &km, &Active::NONE, frame(1.0, Modifiers::NONE, typed));
|
||||
assert!(!d.layout().is_latin());
|
||||
let (ran, _) = run(&mut d, &km, &Active::NONE, frame(2.0, ctrl_shift, vec![at(EguiKey::CloseBracket, EguiKey::D, ctrl_shift)]));
|
||||
assert_eq!(ran, ["edit.duplicate"]);
|
||||
|
||||
// German: ⇧7 types /, so Ctrl+Shift+7 runs Ctrl+/; the ü key's label is learned from typing.
|
||||
let mut d = Dispatcher::new();
|
||||
let typed = vec![at(EguiKey::OpenBracket, EguiKey::OpenBracket, Modifiers::NONE), Event::Text("ü".into())];
|
||||
run(&mut d, &km, &Active::NONE, frame(1.0, Modifiers::NONE, typed));
|
||||
assert_eq!(chord("Cmd+[").display_for(Platform::Windows, d.layout()), "Ctrl+Ü");
|
||||
let (ran, _) = run(&mut d, &km, &Active::NONE, frame(2.0, ctrl_shift, vec![at(EguiKey::Slash, EguiKey::Num7, ctrl_shift)]));
|
||||
assert_eq!(ran, ["edit.comment"]);
|
||||
|
||||
// German on egui-winit: AltGr+M types µ and AltGr+] types ~ with no modifiers reported, so
|
||||
// presses while right Alt is held teach nothing and Ctrl+Z stays Ctrl+Z on the Y position.
|
||||
let mut d = Dispatcher::new();
|
||||
let typed = vec![at(EguiKey::Plus, EguiKey::CloseBracket, Modifiers::NONE), Event::Text("+".into())];
|
||||
run(&mut d, &km, &Active::NONE, frame(1.0, Modifiers::NONE, typed));
|
||||
let right_alt =
|
||||
|pressed| Event::Key { key: EguiKey::AltRight, physical_key: Some(EguiKey::AltRight), pressed, repeat: false, modifiers: Modifiers::NONE };
|
||||
run(&mut d, &km, &Active::NONE, frame(2.0, Modifiers::NONE, vec![right_alt(true)]));
|
||||
let alt_graph = vec![
|
||||
at(EguiKey::M, EguiKey::M, Modifiers::NONE),
|
||||
Event::Text("µ".into()),
|
||||
at(EguiKey::CloseBracket, EguiKey::CloseBracket, Modifiers::NONE),
|
||||
Event::Text("~".into()),
|
||||
right_alt(false),
|
||||
];
|
||||
run(&mut d, &km, &Active::NONE, frame(3.0, Modifiers::NONE, alt_graph));
|
||||
assert!(d.layout().is_latin());
|
||||
assert_eq!(d.layout().char_at(Key::CloseBracket), Some('+'));
|
||||
assert_eq!(d.layout().resolve(&KeyInput::new(Mods::CMD).with_typed(Key::Z).with_physical(Key::Y)), Some(chord("Cmd+Z")));
|
||||
|
||||
// A layout the platform reports applies from the first press.
|
||||
let mut d = Dispatcher::new().with_layout(Layout::new().with_latin(false));
|
||||
let (ran, _) = run(&mut d, &km, &Active::NONE, frame(1.0, ctrl_shift, vec![at(EguiKey::CloseBracket, EguiKey::D, ctrl_shift)]));
|
||||
assert_eq!(ran, ["edit.duplicate"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn letters_follow_the_latin_layout_from_egui_winit_to_the_dispatcher() {
|
||||
let app = |id: &str, key: &str| Bindable::new(id, id, Scope::app()).with_default(Binding::parse(key).unwrap());
|
||||
let km = Keymap::new(vec![app("d", "Cmd+D"), app("e", "Cmd+E")], Scopes::new(), Platform::Linux);
|
||||
let at = |key, modifiers| Event::Key { key, physical_key: Some(EguiKey::D), pressed: true, repeat: false, modifiers };
|
||||
|
||||
// The QWERTY D key, as the suite's egui-winit reports it: on a layout that is not Latin, the
|
||||
// logical key is the Latin layout's letter (Dvorak types e there), and the text is Cyrillic.
|
||||
// (layout, logical key, text typed, platform report, command Ctrl runs)
|
||||
let cases = [
|
||||
("Dvorak + Russian", EguiKey::E, "в", Some(false), "e"),
|
||||
("QWERTY + Russian", EguiKey::D, "в", Some(false), "d"),
|
||||
("Dvorak", EguiKey::E, "e", Some(true), "e"),
|
||||
("QWERTY", EguiKey::D, "d", Some(true), "d"),
|
||||
];
|
||||
for (name, key, text, latin, expected) in cases {
|
||||
// The layout learned from typing.
|
||||
let mut d = Dispatcher::new();
|
||||
run(&mut d, &km, &Active::NONE, frame(1.0, Modifiers::NONE, vec![at(key, Modifiers::NONE), Event::Text(text.into())]));
|
||||
assert_eq!(Some(d.layout().is_latin()), latin, "{name}");
|
||||
let (ran, _) = run(&mut d, &km, &Active::NONE, frame(2.0, CTRL, vec![at(key, CTRL)]));
|
||||
assert_eq!(ran, [expected], "{name}, learned");
|
||||
|
||||
// The layout the platform reports, before anything is typed.
|
||||
let mut d = Dispatcher::new().with_layout(Layout::new().with_latin(latin == Some(true)));
|
||||
let (ran, _) = run(&mut d, &km, &Active::NONE, frame(1.0, CTRL, vec![at(key, CTRL)]));
|
||||
assert_eq!(ran, [expected], "{name}, reported");
|
||||
}
|
||||
}
|
||||
|
||||
/// `input` with the Latin layout characters the suite's egui-winit reports per physical key, set
|
||||
/// through serde because crates.io egui has no such field; `None` there.
|
||||
fn with_latin_layout_chars(mut input: InputState, chars: &[(EguiKey, char)]) -> Option<InputState> {
|
||||
let mut raw = serde_json::to_value(&input.raw).unwrap();
|
||||
raw.get("latin_layout_chars")?;
|
||||
raw["latin_layout_chars"] = serde_json::to_value(chars).unwrap();
|
||||
input.raw = serde_json::from_value(raw).unwrap();
|
||||
Some(input)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_without_a_latin_letter_runs_no_letter_binding() {
|
||||
let app = |id: &str, key: &str| Bindable::new(id, id, Scope::app()).with_default(Binding::parse(key).unwrap());
|
||||
let km = Keymap::new(vec![app("quit", "Cmd+Q"), app("quote", "Cmd+'"), app("j", "Cmd+J")], Scopes::new(), Platform::Linux);
|
||||
let at = |key, physical| Event::Key { key, physical_key: Some(physical), pressed: true, repeat: false, modifiers: CTRL };
|
||||
|
||||
// Dvorak + Russian. The QWERTY Q key types й, and Dvorak ' there: egui-winit reports the key
|
||||
// as ', and egui without a key for the character as its position, Q. The QWERTY C key types
|
||||
// с, and Dvorak j.
|
||||
let latin = [(EguiKey::Q, '\''), (EguiKey::C, 'j')];
|
||||
let cases = [(at(EguiKey::Quote, EguiKey::Q), "quote"), (at(EguiKey::Q, EguiKey::Q), "quote"), (at(EguiKey::J, EguiKey::C), "j")];
|
||||
for (press, expected) in cases {
|
||||
let mut d = Dispatcher::new().with_layout(Layout::new().with_latin(false));
|
||||
let Some(input) = with_latin_layout_chars(frame(1.0, CTRL, vec![press.clone()]), &latin) else {
|
||||
// crates.io egui reports no Latin layout, so the position decides: Ctrl+Q.
|
||||
let (ran, _) = run(&mut d, &km, &Active::NONE, frame(1.0, CTRL, vec![at(EguiKey::Q, EguiKey::Q)]));
|
||||
assert_eq!(ran, ["quit"]);
|
||||
return;
|
||||
};
|
||||
let (ran, _) = run(&mut d, &km, &Active::NONE, input);
|
||||
assert_eq!(ran, [expected], "{press:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,838 @@
|
||||
//! Import of synthetic shortcut sets written for these tests.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use craft_keymap::chord::foreign::ReadNote;
|
||||
use craft_keymap::chord::foreign::{Flavor, ForeignError};
|
||||
use craft_keymap::import::{
|
||||
Failed, FailedChange, MAX_IMPORT_ENTRIES, MAX_IMPORT_TEXT, MAX_KEYS_PER_ENTRY, MAX_SUGGESTIONS, NoChangeReason, SkipReason, Skipped,
|
||||
UnmatchedReason, normalize_label,
|
||||
};
|
||||
use craft_keymap::{
|
||||
Bindable, Binding, CommandRef, ContextRule, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportReport, Keymap, Kind, MAX_COMMANDS,
|
||||
NoneDefined, Overrides, Platform, Scope, Scopes, Start, plan, reserved,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
fn b(text: &str) -> Binding {
|
||||
Binding::parse(text).unwrap_or_else(|e| panic!("{text}: {e}"))
|
||||
}
|
||||
|
||||
fn bindings(texts: &[&str]) -> Vec<Binding> {
|
||||
texts.iter().map(|t| b(t)).collect()
|
||||
}
|
||||
|
||||
fn command(id: impl Into<CommandRef>, label: &str, path: &[&str], keys: &[&str]) -> Bindable {
|
||||
let mut out = Bindable::new(id, label, Scope::app());
|
||||
if !path.is_empty() {
|
||||
out = out.with_path(path.iter().map(|s| s.to_string()).collect());
|
||||
}
|
||||
keys.iter().fold(out, |e, k| e.with_default(b(k)))
|
||||
}
|
||||
|
||||
fn panel(name: &str) -> CommandRef {
|
||||
CommandRef::with_params("window.panel", json!({ "panel": name }))
|
||||
}
|
||||
|
||||
fn catalog() -> Vec<Bindable> {
|
||||
vec![
|
||||
command("file.new", "Document…", &["File", "New", "Document…"], &["Cmd+N"]),
|
||||
command("dialog.newDocument", "New Document Dialog", &[], &["Cmd+N"]),
|
||||
command("file.close", "Close", &["File", "Close"], &["Cmd+W"]),
|
||||
command("file.save", "Save", &["File", "Save"], &["Cmd+S"]),
|
||||
command("file.exit", "Exit", &["File", "Exit"], &[]),
|
||||
command("edit.paste", "Paste", &["Edit", "Paste"], &["Cmd+V"]),
|
||||
command("edit.clear", "Clear", &["Edit", "Clear"], &[]),
|
||||
command("edit.duplicate", "Duplicate", &["Edit", "Duplicate"], &["Cmd+Alt+Shift+D"]),
|
||||
command("edit.checkSpelling", "Check Spelling…", &["Edit", "Proofing", "Check Spelling…"], &[]),
|
||||
command("edit.pen", "Pen", &["Edit", "Preferences", "Pen"], &[]),
|
||||
command("app.palette", "Command Palette", &[], &["Cmd+Alt+K"]),
|
||||
command(panel("layers"), "Layers", &["Window", "Layers"], &["F7"]),
|
||||
command(panel("pages"), "Pages", &["Window", "Pages"], &["F12"]),
|
||||
command("view.guides", "Guides", &["View", "Grids & Guides", "Guides"], &["Cmd+;"]).toggle(),
|
||||
command("view.goToPage", "Go to Page…", &["View", "Go to Page…"], &["Cmd+J"]),
|
||||
command("view.zoomIn", "Zoom In", &["View", "Zoom In"], &["Cmd+="]),
|
||||
command("object.textFrameOptions", "Text Frame Options…", &["Object", "Text Frame Options…"], &["Cmd+B"]),
|
||||
command("type.break", "Break", &["Type", "Breaks", "Break"], &[]),
|
||||
command("type.columnBreak", "Insert Break", &["Type", "Column", "Insert Break"], &[]),
|
||||
command("type.frameBreak", "Insert Break", &["Type", "Frame", "Insert Break"], &[]),
|
||||
command("type.bold", "Bold", &["Type", "Style", "Bold"], &[]),
|
||||
command("type.italic", "Italic", &["Type", "Style", "Italic"], &[]),
|
||||
command("tool.pen", "Pen Tool", &[], &["P"]).with_kind(Kind::Tool { group: None }).with_alias("Pen"),
|
||||
command("tool.type", "Type Tool", &[], &["T"]).with_kind(Kind::Tool { group: None }),
|
||||
command("scripts.run", "Run Script", &[], &[]),
|
||||
]
|
||||
}
|
||||
|
||||
fn keymap(platform: Platform) -> Keymap {
|
||||
Keymap::new(catalog(), Scopes::new().with_context("Text"), platform).with_reserved(reserved::system(platform))
|
||||
}
|
||||
|
||||
fn key(flavor: Flavor, context: &str, text: &str) -> ForeignKey {
|
||||
ForeignKey::read(Some(context), text, flavor)
|
||||
}
|
||||
|
||||
fn entry(menu: Option<&str>, path: &[&str], keys: &[(&str, &str)], flavor: Flavor) -> ForeignEntry {
|
||||
keys.iter().fold(ForeignEntry::new(menu, path.iter().copied()), |e, (c, t)| e.with_key(key(flavor, c, t)))
|
||||
}
|
||||
|
||||
fn win(menu: &str, path: &[&str], keys: &[(&str, &str)]) -> ForeignEntry {
|
||||
entry(Some(menu), path, keys, Flavor::Windows)
|
||||
}
|
||||
|
||||
/// An InDesign-like Windows set, one entry per match rule or apply rule.
|
||||
fn windows_set() -> ForeignSet {
|
||||
let d = "Default";
|
||||
let entries = vec![
|
||||
win("File", &["New", "Document..."], &[(d, "Ctrl+N")]),
|
||||
win("File", &["Close"], &[(d, "Ctrl+W"), (d, "Ctrl+F4")]),
|
||||
win("File", &["Save"], &[(d, "Ctrl+Hyperspace")]),
|
||||
win("File", &["Exit"], &[(d, "Alt+F4")]),
|
||||
win("Edit", &["Paste"], &[(d, "Ctrl+E")]),
|
||||
win("Edit", &["Clear"], &[(d, "Ctrl+E")]),
|
||||
win("Edit", &["Duplicate"], &[]),
|
||||
win("Edit", &["Duplicate"], &[]),
|
||||
win("Edit", &["Spelling", "Check Spelling..."], &[(d, "Ctrl+Alt+K"), ("Text", "F7")]),
|
||||
win("Edit", &["Frobnicate Everything"], &[(d, "Ctrl+F12")]),
|
||||
win("Edit", &["Never Heard Of It"], &[]),
|
||||
win("Window", &["Layers"], &[(d, "F7")]),
|
||||
win("Window", &["Pages"], &[(d, "Shift+F12")]),
|
||||
win("View", &["Grids & Guides", "SHOW/HIDE Guides"], &[(d, "Ctrl+Alt+;")]),
|
||||
win("Layout", &["Go To Page"], &[(d, "Ctrl+Alt+J")]),
|
||||
win("Object", &["Text Frame", "Options"], &[(d, "Ctrl+Alt+B")]),
|
||||
win("Type", &["Insert", "Break"], &[(d, "Ctrl+Alt+Enter")]),
|
||||
win("Type", &["Insert Break"], &[(d, "Shift+Enter")]),
|
||||
win("Type", &["Style", "Bold"], &[("Text", "Shift+Ctrl+B")]),
|
||||
win("Type", &["Style", "Italic"], &[(d, "Ctrl+I"), ("Table", "Ctrl+Alt+I")]),
|
||||
win("Tools", &["Pen"], &[(d, "Shift+P")]).tool(),
|
||||
win("Tools", &["Zoom In"], &[(d, "Z")]).tool(),
|
||||
entry(None, &["Zoom In"], &[(d, "Ctrl+Alt+I")], Flavor::Windows),
|
||||
entry(None, &["Somewhere", "Zoom In"], &[(d, "Ctrl+F11")], Flavor::Windows),
|
||||
win("Scripts", &["Frobnicate"], &[(d, "Ctrl+Alt+R")]),
|
||||
];
|
||||
ForeignSet::new(entries).with_name("My Set")
|
||||
}
|
||||
|
||||
fn numpad_set() -> ForeignSet {
|
||||
ForeignSet::new(vec![win("Window", &["Layers"], &[("Default", "Num 7")]).at_line(2)])
|
||||
}
|
||||
|
||||
fn windows_options() -> ImportOptions {
|
||||
let mut remembered = BTreeMap::new();
|
||||
remembered.insert(ForeignEntry::new(Some("Scripts"), ["Frobnicate"]).remember_key(), CommandRef::new("scripts.run"));
|
||||
ImportOptions {
|
||||
contexts: vec![("default".into(), ContextRule::Home), ("TEXT".into(), ContextRule::HomeWithoutHomeEntry)],
|
||||
remembered,
|
||||
..ImportOptions::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn import_windows() -> (Keymap, ImportReport) {
|
||||
let mut km = keymap(Platform::Windows);
|
||||
let report = plan(&windows_set(), &km, &windows_options()).apply(&mut km);
|
||||
(km, report)
|
||||
}
|
||||
|
||||
fn has(km: &Keymap, id: impl Into<CommandRef>, texts: &[&str]) {
|
||||
let c = id.into();
|
||||
assert_eq!(km.bindings(&c), bindings(texts), "{}", c.key());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_normalize_for_matching() {
|
||||
assert_eq!(normalize_label("Check Spelling..."), "check spelling");
|
||||
assert_eq!(normalize_label("Check Spelling…"), "check spelling");
|
||||
assert_eq!(normalize_label("Grids && Guides"), "grids guides");
|
||||
assert_eq!(normalize_label("SHOW/HIDE Guides"), "show/hide guides");
|
||||
assert_eq!(normalize_label("Preferences: General…"), "preferences general");
|
||||
assert_eq!(normalize_label("ÄRGER"), "ärger");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_match_step_finds_its_command() {
|
||||
let (km, r) = import_windows();
|
||||
assert_eq!(r.set.as_deref(), Some("My Set"));
|
||||
// 1: full path, with `&`, case and spacing normalized, and Show/Hide dropped for a toggle.
|
||||
has(&km, "view.guides", &["Cmd+Alt+;"]);
|
||||
// 2: joined segments `Text Frame Options` in Object.
|
||||
has(&km, "object.textFrameOptions", &["Cmd+Alt+B"]);
|
||||
// 2 is ambiguous (two `Insert Break` in Type), 3 finds `Break`.
|
||||
has(&km, "type.break", &["Cmd+Alt+Enter"]);
|
||||
// 3: last segment in the menu, under another submenu.
|
||||
has(&km, "edit.checkSpelling", &["Cmd+Alt+K"]);
|
||||
// 4: the label anywhere; also with no menu for a one-segment path.
|
||||
has(&km, "view.goToPage", &["Cmd+Alt+J"]);
|
||||
has(&km, "view.zoomIn", &["Cmd+Alt+I"]);
|
||||
// 0: a remembered answer.
|
||||
has(&km, "scripts.run", &["Cmd+Alt+R"]);
|
||||
// A command with parameters, by its path.
|
||||
has(&km, panel("pages"), &["Shift+F12"]);
|
||||
// A tool entry matches the tool, not the command with the same label.
|
||||
has(&km, "tool.pen", &["Shift+P"]);
|
||||
has(&km, "edit.pen", &[]);
|
||||
|
||||
let unmatched: Vec<(&str, UnmatchedReason)> = r.unmatched.iter().map(|u| (u.item.as_str(), u.reason)).collect();
|
||||
assert_eq!(
|
||||
unmatched,
|
||||
[
|
||||
("Edit > Frobnicate Everything", UnmatchedReason::NoMatch),
|
||||
("Type > Insert Break", UnmatchedReason::Ambiguous),
|
||||
("Type > Style > Italic", UnmatchedReason::Context),
|
||||
("Tools > Zoom In", UnmatchedReason::Tool),
|
||||
("Somewhere > Zoom In", UnmatchedReason::NoMatch),
|
||||
]
|
||||
);
|
||||
assert_eq!(r.unmatched[2].keys, "Table: Ctrl+Alt+I");
|
||||
assert_eq!(r.unmatched_without_shortcut, 1);
|
||||
assert_eq!(r.unreadable.len(), 1);
|
||||
assert_eq!(r.unreadable[0].item, "File > Save");
|
||||
assert_eq!(r.unreadable[0].keys, "Default: Ctrl+Hyperspace");
|
||||
assert!(matches!(r.unreadable[0].reason, ForeignError::UnknownKey(_)));
|
||||
assert!(r.suggestions.is_empty(), "not asked for");
|
||||
assert_eq!(r.truncated, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_set_wins_and_the_report_says_how() {
|
||||
let (km, r) = import_windows();
|
||||
// Two keys for one command, both kept in order.
|
||||
has(&km, "file.close", &["Cmd+W", "Cmd+F4"]);
|
||||
// The Text context counts only without a Default key.
|
||||
has(&km, "type.bold", &["Cmd+Shift+B"]);
|
||||
has(&km, "type.italic", &["Cmd+I"]);
|
||||
has(&km, panel("layers"), &["F7"]);
|
||||
// A later entry takes a chord from an earlier one; the earlier command keeps what it had.
|
||||
has(&km, "edit.paste", &["Cmd+V"]);
|
||||
has(&km, "edit.clear", &["Cmd+E"]);
|
||||
let skipped: Vec<_> = r.skipped.iter().map(|s| (s.command.id.as_str(), s.shortcut.as_str(), s.kept_by.clone(), s.reason)).collect();
|
||||
assert_eq!(
|
||||
skipped,
|
||||
[("file.exit", "Alt+F4", None, SkipReason::Reserved), ("edit.paste", "Cmd+E", Some(CommandRef::new("edit.clear")), SkipReason::Taken)]
|
||||
);
|
||||
// Taken from a command outside the set; the twin keeps its shared default.
|
||||
has(&km, "app.palette", &[]);
|
||||
has(&km, "dialog.newDocument", &["Cmd+N"]);
|
||||
let cleared: Vec<_> = r.conflicts_cleared.iter().map(|c| (c.command.id.as_str(), c.label.as_str(), c.shortcut.as_str())).collect();
|
||||
assert_eq!(cleared, [("app.palette", "Command Palette", "Cmd+Alt+K")]);
|
||||
// None defined clears; an unreadable key leaves the command as it was.
|
||||
has(&km, "edit.duplicate", &[]);
|
||||
has(&km, "file.save", &["Cmd+S"]);
|
||||
// Bindings equal to the defaults leave no override.
|
||||
let o = km.overrides();
|
||||
assert_eq!(o.get("file.new"), None);
|
||||
assert_eq!(o.get(&panel("layers").key()), None);
|
||||
assert_eq!(o.get("edit.duplicate"), Some(&[][..]));
|
||||
assert_eq!(o.get("file.close"), Some(&["Cmd+W".to_string(), "Cmd+F4".to_string()][..]));
|
||||
|
||||
let changed: Vec<&str> = r.changed.iter().map(|c| c.command.id.as_str()).collect();
|
||||
assert_eq!(
|
||||
changed,
|
||||
[
|
||||
"file.close",
|
||||
"edit.clear",
|
||||
"edit.duplicate",
|
||||
"edit.checkSpelling",
|
||||
"window.panel",
|
||||
"view.guides",
|
||||
"view.goToPage",
|
||||
"object.textFrameOptions",
|
||||
"type.break",
|
||||
"type.bold",
|
||||
"type.italic",
|
||||
"tool.pen",
|
||||
"view.zoomIn",
|
||||
"scripts.run",
|
||||
]
|
||||
);
|
||||
assert_eq!(r.imported, changed.len());
|
||||
let close = &r.changed[0];
|
||||
assert_eq!((close.label.as_str(), close.item.as_str()), ("Close", "File > Close"));
|
||||
assert_eq!((close.from.clone(), close.to.clone()), (vec!["Cmd+W".to_string()], vec!["Cmd+W".to_string(), "Cmd+F4".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mac_set_reads_its_modifiers_and_scopes_text_keys() {
|
||||
let mut km = keymap(Platform::Mac);
|
||||
let mac = |menu: &str, path: &[&str], keys: &[(&str, &str)]| entry(Some(menu), path, keys, Flavor::Mac);
|
||||
let set = ForeignSet::new(vec![
|
||||
mac("File", &["Save"], &[("Default", "⇧⌘S")]),
|
||||
mac("Edit", &["Paste"], &[("Default", "Cmd+Ctrl+V")]),
|
||||
mac("Type", &["Style", "Italic"], &[("Text", "Shift+Cmd+I")]),
|
||||
mac("Type", &["Style", "Bold"], &[("Default", "Cmd+B"), ("Tables", "Cmd+Opt+B")]),
|
||||
])
|
||||
.with_name("Mac");
|
||||
let text = Scope::new("Text").unwrap();
|
||||
let options = ImportOptions {
|
||||
contexts: vec![("Default".into(), ContextRule::Home), ("Text".into(), ContextRule::Scope(text))],
|
||||
..ImportOptions::default()
|
||||
};
|
||||
let r = plan(&set, &km, &options).apply(&mut km);
|
||||
has(&km, "file.save", &["Cmd+Shift+S"]);
|
||||
has(&km, "edit.paste", &["Cmd+Ctrl+V"]);
|
||||
has(&km, "type.italic", &["Text: Cmd+Shift+I"]);
|
||||
has(&km, "type.bold", &["Cmd+B"]);
|
||||
has(&km, "object.textFrameOptions", &[]);
|
||||
assert_eq!(r.conflicts_cleared[0].command.id, "object.textFrameOptions");
|
||||
assert_eq!(r.unmatched.len(), 1);
|
||||
assert_eq!((r.unmatched[0].keys.as_str(), r.unmatched[0].reason), ("Tables: Cmd+Opt+B", UnmatchedReason::Context));
|
||||
assert_eq!(r.changed.iter().find(|c| c.command.id == "type.italic").map(|c| c.to.clone()), Some(vec!["Text: Cmd+Shift+I".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_and_none_defined_options() {
|
||||
let set = ForeignSet::new(vec![win("File", &["Close"], &[("Default", "Ctrl+Q")]), win("Edit", &["Duplicate"], &[])]);
|
||||
let user = || {
|
||||
let mut o = Overrides::new();
|
||||
o.insert("file.save", vec!["Cmd+Alt+S".into()]);
|
||||
o
|
||||
};
|
||||
let options = |start, none_defined| ImportOptions {
|
||||
contexts: vec![("Default".into(), ContextRule::Home)],
|
||||
start,
|
||||
none_defined,
|
||||
..ImportOptions::default()
|
||||
};
|
||||
|
||||
let mut km = keymap(Platform::Windows).with_overrides(user());
|
||||
plan(&set, &km, &options(Start::Current, NoneDefined::Keep)).apply(&mut km);
|
||||
has(&km, "file.save", &["Cmd+Alt+S"]);
|
||||
has(&km, "file.close", &["Cmd+Q"]);
|
||||
has(&km, "edit.duplicate", &["Cmd+Alt+Shift+D"]);
|
||||
|
||||
let mut km = keymap(Platform::Windows).with_overrides(user());
|
||||
let r = plan(&set, &km, &options(Start::Defaults, NoneDefined::Clear)).apply(&mut km);
|
||||
has(&km, "file.save", &["Cmd+S"]);
|
||||
has(&km, "file.close", &["Cmd+Q"]);
|
||||
has(&km, "edit.duplicate", &[]);
|
||||
assert_eq!(r.imported, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_change_keeps_its_shortcut_when_a_later_change_frees_room() {
|
||||
// Save's change finds the overrides full. Close's change then frees an entry, and Zoom In
|
||||
// takes Cmd+S. Removing Cmd+S from Save would fit now, but Save's import failed, so Save
|
||||
// keeps it and Zoom In stays as it was.
|
||||
let set = ForeignSet::new(vec![
|
||||
win("File", &["Save"], &[("Default", "Ctrl+Alt+S")]),
|
||||
win("File", &["Close"], &[("Default", "Ctrl+W")]),
|
||||
win("View", &["Zoom In"], &[("Default", "Ctrl+S")]),
|
||||
]);
|
||||
let mut o = Overrides::new();
|
||||
o.insert("file.close", vec!["Cmd+Q".into()]);
|
||||
o.insert("view.zoomIn", vec!["Cmd+Alt+Z".into()]);
|
||||
for n in 2..MAX_COMMANDS {
|
||||
o.insert(format!("junk.{n}"), vec!["Cmd+K".into()]);
|
||||
}
|
||||
assert_eq!(o.len(), MAX_COMMANDS);
|
||||
let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], ..ImportOptions::default() };
|
||||
let mut km = keymap(Platform::Windows).with_overrides(o);
|
||||
let r = plan(&set, &km, &options).apply(&mut km);
|
||||
has(&km, "file.save", &["Cmd+S"]);
|
||||
has(&km, "file.close", &["Cmd+W"]);
|
||||
has(&km, "view.zoomIn", &["Cmd+Alt+Z"]);
|
||||
let failed: Vec<(&str, FailedChange)> = r.failed.iter().map(|f| (f.command.id.as_str(), f.change)).collect();
|
||||
assert_eq!(failed, [("file.save", FailedChange::Bind), ("view.zoomIn", FailedChange::Bind)]);
|
||||
assert!(r.conflicts_cleared.is_empty(), "{:?}", r.conflicts_cleared);
|
||||
assert_eq!(r.imported, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changes_that_find_the_overrides_full_are_reported() {
|
||||
let set = ForeignSet::new(vec![
|
||||
win("File", &["Close"], &[("Default", "Ctrl+J")]),
|
||||
win("File", &["Save"], &[("Default", "Ctrl+Alt+S")]),
|
||||
win("Edit", &["Duplicate"], &[]),
|
||||
]);
|
||||
let full = || {
|
||||
let mut o = Overrides::new();
|
||||
o.insert("file.close", vec!["Cmd+Q".into()]);
|
||||
for n in 1..MAX_COMMANDS {
|
||||
o.insert(format!("junk.{n}"), vec!["Cmd+K".into()]);
|
||||
}
|
||||
assert_eq!(o.len(), MAX_COMMANDS);
|
||||
o
|
||||
};
|
||||
let options = |start| ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], start, ..ImportOptions::default() };
|
||||
|
||||
// file.close has an entry to rewrite, but taking Cmd+J from view.goToPage needs a new one, so
|
||||
// both stay as they were. The other changes each need a new entry too.
|
||||
let mut km = keymap(Platform::Windows).with_overrides(full());
|
||||
let r = plan(&set, &km, &options(Start::Current)).apply(&mut km);
|
||||
has(&km, "file.close", &["Cmd+Q"]);
|
||||
has(&km, "view.goToPage", &["Cmd+J"]);
|
||||
has(&km, "file.save", &["Cmd+S"]);
|
||||
has(&km, "edit.duplicate", &["Cmd+Alt+Shift+D"]);
|
||||
let rows = |failed: &[Failed]| -> Vec<(String, String, FailedChange, Vec<String>)> {
|
||||
failed.iter().map(|f| (f.command.id.clone(), f.label.clone(), f.change, f.shortcuts.clone())).collect()
|
||||
};
|
||||
let row = |id: &str, label: &str, change, shortcuts: &[&str]| {
|
||||
(id.to_string(), label.to_string(), change, shortcuts.iter().map(|s| s.to_string()).collect::<Vec<_>>())
|
||||
};
|
||||
assert_eq!(
|
||||
rows(&r.failed),
|
||||
[
|
||||
row("file.close", "Close", FailedChange::Bind, &["Cmd+J"]),
|
||||
row("file.save", "Save", FailedChange::Bind, &["Cmd+Alt+S"]),
|
||||
row("edit.duplicate", "Duplicate", FailedChange::Clear, &[]),
|
||||
]
|
||||
);
|
||||
assert_eq!(r.imported, 0);
|
||||
assert!(r.conflicts_cleared.is_empty());
|
||||
let v = serde_json::to_value(&r).unwrap();
|
||||
assert_eq!(
|
||||
v["failed"][1],
|
||||
json!({"command": {"id": "file.save", "params": null}, "label": "Save", "change": "bind", "shortcuts": ["Cmd+Alt+S"]})
|
||||
);
|
||||
|
||||
// Starting from the defaults drops the entries, so everything fits.
|
||||
let mut km = keymap(Platform::Windows).with_overrides(full());
|
||||
let r = plan(&set, &km, &options(Start::Defaults)).apply(&mut km);
|
||||
assert!(r.failed.is_empty(), "{:?}", r.failed);
|
||||
has(&km, "file.close", &["Cmd+J"]);
|
||||
has(&km, "view.goToPage", &[]);
|
||||
has(&km, "file.save", &["Cmd+Alt+S"]);
|
||||
has(&km, "edit.duplicate", &[]);
|
||||
|
||||
// A later entry whose change finds the overrides full leaves the chord with the earlier one.
|
||||
let set = ForeignSet::new(vec![win("File", &["Close"], &[("Default", "Ctrl+Alt+J")]), win("File", &["Save"], &[("Default", "Ctrl+Alt+J")])]);
|
||||
let mut km = keymap(Platform::Windows).with_overrides(full());
|
||||
let r = plan(&set, &km, &options(Start::Current)).apply(&mut km);
|
||||
has(&km, "file.close", &["Cmd+Alt+J"]);
|
||||
has(&km, "file.save", &["Cmd+S"]);
|
||||
assert_eq!(rows(&r.failed), [row("file.save", "Save", FailedChange::Bind, &["Cmd+Alt+J"])]);
|
||||
assert!(r.skipped.is_empty(), "{:?}", r.skipped);
|
||||
assert_eq!(r.imported, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_in_unknown_scopes_are_skipped_and_the_rest_apply() {
|
||||
let set = ForeignSet::new(vec![win("File", &["Close"], &[("Default", "Ctrl+Q"), ("Story", "Ctrl+K"), ("Text", "Ctrl+L")])]);
|
||||
let options = ImportOptions {
|
||||
contexts: vec![
|
||||
("Default".into(), ContextRule::Home),
|
||||
("Story".into(), ContextRule::Scope(Scope::new("Story").unwrap())),
|
||||
("Text".into(), ContextRule::Scope(Scope::new("Text").unwrap())),
|
||||
],
|
||||
..ImportOptions::default()
|
||||
};
|
||||
let mut km = keymap(Platform::Windows);
|
||||
let r = plan(&set, &km, &options).apply(&mut km);
|
||||
has(&km, "file.close", &["Cmd+Q", "Text: Cmd+L"]);
|
||||
let skipped: Vec<_> = r
|
||||
.skipped
|
||||
.iter()
|
||||
.map(|s: &Skipped| (s.command.id.as_str(), s.item.as_str(), s.line, s.shortcut.as_str(), s.kept_by.clone(), s.reason))
|
||||
.collect();
|
||||
assert_eq!(skipped, [("file.close", "File > Close", None, "Story: Cmd+K", None, SkipReason::UnknownScope)]);
|
||||
assert_eq!(serde_json::to_value(r.skipped[0].reason).unwrap(), "unknownScope");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggestions_are_reported_never_applied() {
|
||||
let mut km = keymap(Platform::Windows);
|
||||
let set = ForeignSet::new(vec![win("Edit", &["Chek Spelling Now"], &[("Default", "Ctrl+K")])]);
|
||||
let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], suggest: true, ..ImportOptions::default() };
|
||||
let p = plan(&set, &km, &options);
|
||||
assert!(p.commands.is_empty());
|
||||
let r = p.apply(&mut km);
|
||||
assert_eq!(r.suggestions.len(), 1);
|
||||
assert_eq!(r.suggestions[0].item, "Edit > Chek Spelling Now");
|
||||
assert!(r.suggestions[0].candidates.contains(&CommandRef::new("edit.checkSpelling")), "{:?}", r.suggestions);
|
||||
has(&km, "edit.checkSpelling", &[]);
|
||||
assert!(km.overrides().is_empty());
|
||||
assert_eq!(r.imported, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_the_reader_dropped_count_as_truncated() {
|
||||
let set = ForeignSet::new(vec![win("File", &["Close"], &[("Default", "Ctrl+Q")])]).with_truncated(7);
|
||||
assert_eq!(plan(&set, &keymap(Platform::Windows), &default_context()).report.truncated, 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_sets_are_capped_and_counted() {
|
||||
let mut km = keymap(Platform::Windows);
|
||||
let long: String = "ä€𝄞 x".repeat(MAX_IMPORT_TEXT);
|
||||
let mut big = ForeignEntry::new(Some(long.as_str()), std::iter::repeat_n(long.clone(), 100));
|
||||
for _ in 0..MAX_KEYS_PER_ENTRY + 10 {
|
||||
let trigger = Err(ForeignError::UnknownKey(long.clone()));
|
||||
big = big.with_key(ForeignKey { context: Some(long.clone()), text: long.clone(), trigger, notes: vec![ReadNote::Numpad; 1000] });
|
||||
}
|
||||
// Unmatched entries with keys, more than the suggestions take.
|
||||
let near = win("Edit", &["Chek Spelling Now"], &[("Default", "Ctrl+F12")]);
|
||||
let mut entries: Vec<ForeignEntry> = std::iter::repeat_n(near, MAX_SUGGESTIONS + 10).collect();
|
||||
entries.push(big);
|
||||
entries.push(win("Edit", &["Paste"], &[("Default", &long), ("Default", "Ctrl+\u{0}"), ("Default", "Win+E")]));
|
||||
// Entries without keys fill the set to the cap and 500 past it.
|
||||
let keyless = MAX_IMPORT_ENTRIES - entries.len();
|
||||
entries.extend(std::iter::repeat_n(ForeignEntry::new(None, Vec::<String>::new()), keyless + 500));
|
||||
let set = ForeignSet::new(entries).with_name(long.clone());
|
||||
let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], suggest: true, ..ImportOptions::default() };
|
||||
let r = plan(&set, &km, &options).apply(&mut km);
|
||||
assert_eq!(r.suggestions.len(), MAX_SUGGESTIONS);
|
||||
// The set name, entries and keys past the caps, and suggestions past the cap (with the big entry's).
|
||||
assert!(r.truncated >= 1 + 500 + 10 + 11, "{}", r.truncated);
|
||||
assert_eq!(r.set.as_ref().map(|s| s.chars().count()), Some(MAX_IMPORT_TEXT));
|
||||
let row = r.unmatched.iter().find(|u| u.item.starts_with('ä')).unwrap();
|
||||
assert!(row.item.chars().count() <= MAX_IMPORT_TEXT * 34, "item of capped segments");
|
||||
assert!(row.keys.chars().count() <= (2 * MAX_IMPORT_TEXT + 4) * MAX_KEYS_PER_ENTRY);
|
||||
assert_eq!(r.unreadable.len(), 1, "Paste's keys");
|
||||
has(&km, "edit.paste", &["Cmd+V"]);
|
||||
// Entries past the cap are left out.
|
||||
assert_eq!(r.unmatched_without_shortcut, keyless);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "worst-case timing; run with --ignored"]
|
||||
fn hostile_sets_finish_in_time() {
|
||||
// A full catalog whose labels share words with every unmatched entry below, so each
|
||||
// suggestion scores every command.
|
||||
let mut catalog = catalog();
|
||||
let filler = MAX_COMMANDS - catalog.len();
|
||||
catalog.extend((0..filler).map(|i| command(format!("filler.c{i}").as_str(), &format!("Filler Command {i}"), &[], &[])));
|
||||
let mut km = Keymap::new(catalog, Scopes::new().with_context("Text"), Platform::Windows).with_reserved(reserved::system(Platform::Windows));
|
||||
let long: String = "ä€𝄞 x".repeat(MAX_IMPORT_TEXT);
|
||||
// Odd entries have keys and long labels that match nothing, so they reach the suggestions:
|
||||
// words in the whole label, or two words and symbols, which score high enough to suggest.
|
||||
let wordy = "Filler Command ä€𝄞 ".repeat(MAX_IMPORT_TEXT / 8);
|
||||
let symbols = format!("Filler Command {}", "€𝄞 ".repeat(MAX_IMPORT_TEXT));
|
||||
let filler_entry = |i: usize| match i % 4 {
|
||||
1 => win("Edit", &[&symbols], &[("Default", "Ctrl+F12")]),
|
||||
3 => win("Edit", &[&format!("{wordy}{i}")], &[("Default", "Ctrl+F12")]),
|
||||
_ => win("Edit", &[&format!("Item {i}")], &[]),
|
||||
};
|
||||
let mut entries: Vec<ForeignEntry> = (0..MAX_IMPORT_ENTRIES + 500).map(filler_entry).collect();
|
||||
let mut big = ForeignEntry::new(Some(long.as_str()), std::iter::repeat_n(long.clone(), 100));
|
||||
for _ in 0..MAX_KEYS_PER_ENTRY + 10 {
|
||||
let trigger = Err(ForeignError::UnknownKey(long.clone()));
|
||||
big = big.with_key(ForeignKey { context: Some(long.clone()), text: long.clone(), trigger, notes: vec![ReadNote::Numpad; 1000] });
|
||||
}
|
||||
entries.insert(0, big);
|
||||
entries.insert(1, win("Edit", &["Paste"], &[("Default", &long), ("Default", "Ctrl+\u{0}"), ("Default", "Win+E")]));
|
||||
let set = ForeignSet::new(entries).with_name(long.clone());
|
||||
let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], suggest: true, ..ImportOptions::default() };
|
||||
let started = std::time::Instant::now();
|
||||
let r = plan(&set, &km, &options).apply(&mut km);
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(240), "{:?}", started.elapsed());
|
||||
// Read filler entries are those before the cap, after the two inserted ones.
|
||||
let read = MAX_IMPORT_ENTRIES - 2;
|
||||
let keyed = read / 2;
|
||||
assert!(!r.suggestions.is_empty() && r.suggestions.len() <= MAX_SUGGESTIONS, "{}", r.suggestions.len());
|
||||
assert!(r.truncated >= 500 + 10 + keyed + 1 - MAX_SUGGESTIONS, "{}", r.truncated);
|
||||
assert_eq!(r.set.as_ref().map(|s| s.chars().count()), Some(MAX_IMPORT_TEXT));
|
||||
let row = r.unmatched.iter().find(|u| u.item.starts_with('ä')).unwrap();
|
||||
assert!(row.item.chars().count() <= MAX_IMPORT_TEXT * 34, "item of capped segments");
|
||||
assert!(row.keys.chars().count() <= (2 * MAX_IMPORT_TEXT + 4) * MAX_KEYS_PER_ENTRY);
|
||||
assert_eq!(r.unreadable.len(), 1, "Paste's keys");
|
||||
has(&km, "edit.paste", &["Cmd+V"]);
|
||||
// Entries past the cap are left out.
|
||||
assert_eq!(r.unmatched_without_shortcut, read - keyed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_carry_source_lines_and_approximated_keys() {
|
||||
let mut km = keymap(Platform::Windows);
|
||||
let d = "Default";
|
||||
let set = ForeignSet::new(vec![
|
||||
win("Window", &["Layers"], &[(d, "Ctrl+Num 5"), (d, "Num 7")]).at_line(3),
|
||||
win("Window", &["Layers"], &[(d, "Shift+F7")]).at_line(4),
|
||||
win("Edit", &["Paste"], &[(d, "Ctrl+Num 5")]).at_line(5),
|
||||
win("Edit", &["Chek Spelling Now"], &[(d, "Ctrl+K")]).at_line(8),
|
||||
win("File", &["Save"], &[(d, "Ctrl+Hyperspace")]).at_line(9),
|
||||
]);
|
||||
let options = ImportOptions { contexts: vec![(d.into(), ContextRule::Home)], suggest: true, ..ImportOptions::default() };
|
||||
let r = plan(&set, &km, &options).apply(&mut km);
|
||||
// A keypad key binds the main key and is reported. Paste, a later entry, takes Cmd+5.
|
||||
has(&km, panel("layers"), &["7", "Shift+F7"]);
|
||||
has(&km, "edit.paste", &["Cmd+5"]);
|
||||
let approximated: Vec<_> = r.approximated.iter().map(|a| (a.item.as_str(), a.line, a.keys.as_str(), a.note)).collect();
|
||||
assert_eq!(
|
||||
approximated,
|
||||
[
|
||||
("Window > Layers", Some(3), "Default: Ctrl+Num 5, Default: Num 7", ReadNote::Numpad),
|
||||
("Edit > Paste", Some(5), "Default: Ctrl+Num 5", ReadNote::Numpad)
|
||||
]
|
||||
);
|
||||
// Merged entries report the first one's line.
|
||||
let layers = r.changed.iter().find(|c| c.command == panel("layers")).unwrap();
|
||||
assert_eq!(layers.line, Some(3));
|
||||
assert_eq!((r.skipped[0].item.as_str(), r.skipped[0].line), ("Window > Layers", Some(3)));
|
||||
assert_eq!(r.unmatched[0].line, Some(8));
|
||||
assert_eq!(r.suggestions[0].line, Some(8));
|
||||
assert_eq!(r.unreadable[0].line, Some(9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn report_json_uses_camel_case_names() {
|
||||
let mut km = keymap(Platform::Windows);
|
||||
let mut options = windows_options();
|
||||
options.suggest = true;
|
||||
let r = plan(&windows_set(), &km, &options).apply(&mut km);
|
||||
let v = serde_json::to_value(&r).unwrap();
|
||||
let names = |v: &serde_json::Value| v.as_object().unwrap().keys().cloned().collect::<Vec<_>>();
|
||||
let mut top = names(&v);
|
||||
top.sort();
|
||||
assert_eq!(
|
||||
top,
|
||||
[
|
||||
"approximated",
|
||||
"changed",
|
||||
"conflictsCleared",
|
||||
"failed",
|
||||
"imported",
|
||||
"matchedWithoutChange",
|
||||
"set",
|
||||
"skipped",
|
||||
"suggestions",
|
||||
"truncated",
|
||||
"unmatched",
|
||||
"unmatchedWithoutShortcut",
|
||||
"unreadable"
|
||||
]
|
||||
);
|
||||
let sorted = |v: &serde_json::Value| {
|
||||
let mut n = names(v);
|
||||
n.sort();
|
||||
n
|
||||
};
|
||||
assert_eq!(sorted(&v["changed"][0]), ["command", "from", "item", "label", "line", "to"]);
|
||||
assert_eq!(sorted(&v["conflictsCleared"][0]), ["command", "label", "shortcut"]);
|
||||
assert_eq!(sorted(&v["skipped"][1]), ["command", "item", "keptBy", "line", "reason", "shortcut"]);
|
||||
assert_eq!(v["skipped"][1]["keptBy"], json!({"id": "edit.clear", "params": null}));
|
||||
assert_eq!(v["skipped"][0]["reason"], "reserved");
|
||||
assert_eq!(sorted(&v["unmatched"][0]), ["item", "keys", "line", "reason"]);
|
||||
let reasons: Vec<&str> = v["unmatched"].as_array().unwrap().iter().filter_map(|u| u["reason"].as_str()).collect();
|
||||
assert_eq!(reasons, ["noMatch", "ambiguous", "context", "tool", "noMatch"]);
|
||||
assert_eq!(sorted(&v["unreadable"][0]), ["item", "keys", "line", "reason"]);
|
||||
assert_eq!(sorted(&v["suggestions"][0]), ["candidates", "item", "line"]);
|
||||
let mut approximated = ImportReport::default();
|
||||
approximated.approximated = plan(&numpad_set(), &km, &options).report.approximated;
|
||||
let a = serde_json::to_value(&approximated).unwrap();
|
||||
assert_eq!(sorted(&a["approximated"][0]), ["item", "keys", "line", "note"]);
|
||||
assert_eq!(a["approximated"][0]["note"], "numpad");
|
||||
assert_eq!(v["changed"][0]["from"], json!(["Cmd+W"]));
|
||||
}
|
||||
|
||||
fn import_into(catalog: Vec<Bindable>, entries: Vec<ForeignEntry>, options: &ImportOptions) -> (Keymap, ImportReport) {
|
||||
let mut km = Keymap::new(catalog, Scopes::new(), Platform::Windows);
|
||||
let report = plan(&ForeignSet::new(entries), &km, options).apply(&mut km);
|
||||
(km, report)
|
||||
}
|
||||
|
||||
fn default_context() -> ImportOptions {
|
||||
ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], ..ImportOptions::default() }
|
||||
}
|
||||
|
||||
fn unmatched(r: &ImportReport) -> Vec<(&str, UnmatchedReason)> {
|
||||
r.unmatched.iter().map(|u| (u.item.as_str(), u.reason)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_menu_entries_match_by_path_end_or_label() {
|
||||
let catalog = vec![
|
||||
command("type.allCaps", "All Caps", &["Panels", "Character", "All Caps"], &[]),
|
||||
command("pages.overrideAll", "Override All Parent Items", &["Pages", "Override All Parent Page Items"], &[]),
|
||||
command("paragraph.justification", "Justification…", &[], &[]),
|
||||
command("swatches.new", "New Swatch", &["Swatches", "New Swatch"], &[]),
|
||||
command("gradient.new", "New Swatch", &["Gradient", "New Swatch"], &[]),
|
||||
command("character.smallCaps", "Small Caps", &[], &[]).with_alias("Character: Small Caps"),
|
||||
// The app has Paragraph and Color panels.
|
||||
command(panel("paragraph"), "Paragraph", &["Window", "Paragraph"], &[]),
|
||||
command(panel("color"), "Color", &["Window", "Color"], &[]),
|
||||
];
|
||||
let d = "Default";
|
||||
let panel_entry = |path: &[&str], key: &str| entry(None, path, &[(d, key)], Flavor::Windows).in_panel_menu();
|
||||
let entries = vec![
|
||||
// The end of a path, label last.
|
||||
panel_entry(&["Character", "All Caps"], "Ctrl+F1"),
|
||||
// The end of a path whose last segment differs from the label.
|
||||
panel_entry(&["Pages", "Override All Parent Page Items"], "Ctrl+F2"),
|
||||
// The last segment alone, as one command's label, for a panel the app has.
|
||||
panel_entry(&["Paragraph", "Justification..."], "Ctrl+F3"),
|
||||
// The last segment alone matches nothing for a panel the app lacks.
|
||||
panel_entry(&["History", "Justification..."], "Ctrl+F8"),
|
||||
// The panel picks one of two commands with the label.
|
||||
panel_entry(&["Swatches", "New Swatch"], "Ctrl+F4"),
|
||||
// The joined segments as an alias.
|
||||
panel_entry(&["Character", "Small Caps"], "Ctrl+F5"),
|
||||
// No path end fits and the label alone fits two commands.
|
||||
panel_entry(&["Color", "New Swatch"], "Ctrl+F6"),
|
||||
// Without the mark, a path with no menu matches only a whole catalog path.
|
||||
entry(None, &["Character", "All Caps"], &[(d, "Ctrl+F7")], Flavor::Windows),
|
||||
];
|
||||
let (km, r) = import_into(catalog, entries, &default_context());
|
||||
has(&km, "type.allCaps", &["Cmd+F1"]);
|
||||
has(&km, "pages.overrideAll", &["Cmd+F2"]);
|
||||
has(&km, "paragraph.justification", &["Cmd+F3"]);
|
||||
has(&km, "swatches.new", &["Cmd+F4"]);
|
||||
has(&km, "character.smallCaps", &["Cmd+F5"]);
|
||||
has(&km, "gradient.new", &[]);
|
||||
assert_eq!(
|
||||
unmatched(&r),
|
||||
[
|
||||
("History > Justification...", UnmatchedReason::NoMatch),
|
||||
("Color > New Swatch", UnmatchedReason::Ambiguous),
|
||||
("Character > All Caps", UnmatchedReason::NoMatch)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aliases_match_like_labels() {
|
||||
let catalog = vec![
|
||||
command("app.quit", "Quit DesignCraft", &["File", "Quit DesignCraft"], &[]).with_alias("Exit"),
|
||||
command("app.preferences", "Preferences…", &["Edit", "Preferences…"], &[]).with_alias("Preferences: General…"),
|
||||
command("type.bold", "Bold", &["Type", "Style", "Bold"], &[]).with_alias("Apply bold"),
|
||||
command("edit.paste", "Paste", &["Edit", "Paste"], &[]).with_alias("Einfügen"),
|
||||
];
|
||||
let d = "Default";
|
||||
let entries = vec![
|
||||
win("File", &["Exit"], &[(d, "Ctrl+Q")]),
|
||||
win("Edit", &["Preferences", "General..."], &[(d, "Ctrl+K")]),
|
||||
entry(None, &["Apply Bold"], &[(d, "Ctrl+Shift+B")], Flavor::Windows),
|
||||
win("Bearbeiten", &["Einfügen"], &[(d, "Ctrl+Shift+V")]),
|
||||
];
|
||||
let (km, r) = import_into(catalog, entries, &default_context());
|
||||
has(&km, "app.quit", &["Cmd+Q"]);
|
||||
has(&km, "app.preferences", &["Cmd+K"]);
|
||||
has(&km, "type.bold", &["Cmd+Shift+B"]);
|
||||
has(&km, "edit.paste", &["Cmd+Shift+V"]);
|
||||
assert!(r.unmatched.is_empty(), "{:?}", r.unmatched);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_paths_match_like_menu_paths() {
|
||||
let catalog = vec![
|
||||
command("object.color", "Apply Color", &["Object", "Apply Color"], &[]),
|
||||
command("color.applyColor", "Apply Color", &[], &[]).with_import_path(vec!["Tools".into(), "Apply Color".into()]),
|
||||
];
|
||||
let d = "Default";
|
||||
let entries = vec![win("Tools", &["Apply Color"], &[(d, "Ctrl+,")])];
|
||||
let (km, r) = import_into(catalog, entries, &default_context());
|
||||
has(&km, "color.applyColor", &["Cmd+,"]);
|
||||
has(&km, "object.color", &[]);
|
||||
assert!(r.unmatched.is_empty(), "{:?}", r.unmatched);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_and_hide_are_read_off_only_for_toggles() {
|
||||
let catalog = vec![
|
||||
command(panel("conveyor"), "Conveyor", &["Window", "Conveyor"], &[]),
|
||||
command("view.rulers", "Rulers", &["View", "Rulers"], &[]).toggle(),
|
||||
command("view.frameEdges", "Show Frame Edges", &["View", "Extras", "Show Frame Edges"], &[]).toggle(),
|
||||
command("view.hiddenCharacters", "Show Hidden Characters", &["Type", "Show Hidden Characters"], &[]),
|
||||
];
|
||||
let d = "Default";
|
||||
let entries = vec![
|
||||
// Not a toggle: the name must fit as written.
|
||||
win("View", &["Extras", "Hide Conveyor"], &[(d, "Ctrl+F1")]),
|
||||
// One toggle for both of the source's items.
|
||||
win("View", &["Show Rulers"], &[(d, "Ctrl+R")]),
|
||||
win("View", &["Hide Rulers"], &[(d, "Ctrl+Shift+R")]),
|
||||
win("View", &["Extras", "Hide Frame Edges"], &[(d, "Ctrl+H")]),
|
||||
// Exact names match any command.
|
||||
win("Type", &["Show Hidden Characters"], &[(d, "Ctrl+Alt+I")]),
|
||||
win("Type", &["Hide Hidden Characters"], &[(d, "Ctrl+Alt+H")]),
|
||||
];
|
||||
let (km, r) = import_into(catalog, entries, &default_context());
|
||||
has(&km, panel("conveyor"), &[]);
|
||||
has(&km, "view.rulers", &["Cmd+R", "Cmd+Shift+R"]);
|
||||
has(&km, "view.frameEdges", &["Cmd+H"]);
|
||||
has(&km, "view.hiddenCharacters", &["Cmd+Alt+I"]);
|
||||
assert_eq!(
|
||||
unmatched(&r),
|
||||
[("View > Extras > Hide Conveyor", UnmatchedReason::NoMatch), ("Type > Hide Hidden Characters", UnmatchedReason::NoMatch)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_entries_with_keys_to_bind_count_toward_suggestions() {
|
||||
let catalog = vec![command("edit.checkSpelling", "Check Spelling…", &["Edit", "Check Spelling…"], &[])];
|
||||
let d = "Default";
|
||||
// Twice the cap of unmatched entries without keys, or with keys only in a skipped context,
|
||||
// before one with a key.
|
||||
let mut entries: Vec<ForeignEntry> = (0..MAX_SUGGESTIONS)
|
||||
.flat_map(|i| [win("Edit", &[&format!("Nothing {i}")], &[]), win("Edit", &[&format!("Tables {i}")], &[("Table", "Ctrl+T")])])
|
||||
.collect();
|
||||
entries.push(win("Edit", &["Chek Spelling Now"], &[(d, "Ctrl+K"), ("Table", "Ctrl+T")]));
|
||||
let options = ImportOptions {
|
||||
contexts: vec![(d.into(), ContextRule::Home), ("Table".into(), ContextRule::Skip)],
|
||||
suggest: true,
|
||||
..ImportOptions::default()
|
||||
};
|
||||
let (_, r) = import_into(catalog, entries, &options);
|
||||
assert_eq!(r.unmatched_without_shortcut, 2 * MAX_SUGGESTIONS);
|
||||
assert_eq!(r.unmatched.len(), 1);
|
||||
assert_eq!(r.unmatched[0].keys, "Default: Ctrl+K", "keys in a skipped context are left out");
|
||||
assert_eq!(r.suggestions.len(), 1);
|
||||
assert_eq!(r.suggestions[0].candidates, [CommandRef::new("edit.checkSpelling")]);
|
||||
assert_eq!(r.truncated, 0);
|
||||
}
|
||||
|
||||
fn pages_catalog() -> Vec<Bindable> {
|
||||
vec![
|
||||
command("app.newDocumentDialog", "New Document…", &["File", "New Document…"], &["Cmd+N"]),
|
||||
command("layout.pages.insert", "Insert Pages…", &["Layout", "Pages", "Insert Pages…"], &["Cmd+Shift+P"]),
|
||||
command("file.close", "Close", &["File", "Close"], &["Cmd+W"]),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_menu_entries_without_keys_change_nothing() {
|
||||
let none = |path: &[&str]| ForeignEntry::new(None, path.iter().copied()).in_panel_menu();
|
||||
let entries = vec![
|
||||
// The app has no History panel, so the last segment alone does not match.
|
||||
none(&["History", "New Document"]),
|
||||
// A path end matches, but without keys the command keeps its shortcuts.
|
||||
none(&["Pages", "Insert Pages..."]),
|
||||
// The same for the last segment alone, with a panel the app has.
|
||||
none(&["Pages", "New Document"]),
|
||||
];
|
||||
let (km, r) = import_into(pages_catalog(), entries, &default_context());
|
||||
has(&km, "app.newDocumentDialog", &["Cmd+N"]);
|
||||
has(&km, "layout.pages.insert", &["Cmd+Shift+P"]);
|
||||
assert!(r.changed.is_empty(), "{:?}", r.changed);
|
||||
assert_eq!(r.unmatched_without_shortcut, 1);
|
||||
let rows: Vec<(&str, &str, NoChangeReason)> =
|
||||
r.matched_without_change.iter().map(|m| (m.item.as_str(), m.command.id.as_str(), m.reason)).collect();
|
||||
assert_eq!(
|
||||
rows,
|
||||
[
|
||||
("Pages > Insert Pages...", "layout.pages.insert", NoChangeReason::PanelMenu),
|
||||
("Pages > New Document", "app.newDocumentDialog", NoChangeReason::PanelMenu)
|
||||
]
|
||||
);
|
||||
let v = serde_json::to_value(&r).unwrap();
|
||||
let mut fields: Vec<String> = v["matchedWithoutChange"][0].as_object().unwrap().keys().cloned().collect();
|
||||
fields.sort();
|
||||
assert_eq!(fields, ["command", "item", "label", "line", "reason"]);
|
||||
assert_eq!(v["matchedWithoutChange"][0]["reason"], "panelMenu");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_without_keys_never_clears_keys_another_entry_gives() {
|
||||
let d = "Default";
|
||||
let keyed = || win("Layout", &["Pages", "Insert Pages..."], &[(d, "Ctrl+Alt+P")]);
|
||||
let keyless = || win("Layout", &["Insert Pages..."], &[]);
|
||||
for entries in [vec![keyed(), keyless()], vec![keyless(), keyed()]] {
|
||||
let (km, _) = import_into(pages_catalog(), entries, &default_context());
|
||||
has(&km, "layout.pages.insert", &["Cmd+Alt+P"]);
|
||||
}
|
||||
|
||||
// A panel-menu entry without keys, and the menu entry with the command's keys.
|
||||
let entries = vec![
|
||||
ForeignEntry::new(None, ["Pages", "Insert Pages..."]).in_panel_menu(),
|
||||
win("Layout", &["Pages", "Insert Pages..."], &[(d, "Ctrl+Shift+P")]),
|
||||
];
|
||||
let (km, r) = import_into(pages_catalog(), entries, &default_context());
|
||||
has(&km, "layout.pages.insert", &["Cmd+Shift+P"]);
|
||||
assert_eq!(r.matched_without_change.len(), 1);
|
||||
|
||||
// The later entry still takes the chord from another command; the entry without keys does
|
||||
// not clear the command that lost it.
|
||||
let entries = vec![keyless(), keyed(), win("File", &["Close"], &[(d, "Ctrl+Alt+P")])];
|
||||
let (km, r) = import_into(pages_catalog(), entries, &default_context());
|
||||
has(&km, "file.close", &["Cmd+Alt+P"]);
|
||||
has(&km, "layout.pages.insert", &["Cmd+Shift+P"]);
|
||||
assert_eq!(r.skipped.iter().map(|s| (s.command.id.as_str(), s.reason)).collect::<Vec<_>>(), [("layout.pages.insert", SkipReason::Taken)]);
|
||||
}
|
||||
@@ -0,0 +1,665 @@
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use craft_keymap::{
|
||||
Active, AssignError, Bindable, Binding, Chord, CommandRef, ConflictKind, DropReason, Key, Keymap, Kind, Lookup, MAX_BINDINGS, MAX_COMMANDS,
|
||||
MAX_CONFLICTS, Mods, Overrides, Platform, Policy, Problem, Scope, Scopes, Trigger, TypingRule, reserved,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
fn chord(text: &str) -> Chord {
|
||||
Chord::parse(text).unwrap_or_else(|e| panic!("{text}: {e}"))
|
||||
}
|
||||
|
||||
fn scope(name: &str) -> Scope {
|
||||
Scope::new(name).unwrap()
|
||||
}
|
||||
|
||||
fn b(text: &str) -> Binding {
|
||||
Binding::parse(text).unwrap_or_else(|e| panic!("{text}: {e}"))
|
||||
}
|
||||
|
||||
fn cmd(id: &str) -> CommandRef {
|
||||
CommandRef::new(id)
|
||||
}
|
||||
|
||||
fn app(id: &str, keys: &[&str]) -> Bindable {
|
||||
keys.iter().fold(Bindable::new(id, id, Scope::app()), |e, k| e.with_default(b(k)))
|
||||
}
|
||||
|
||||
fn in_scope(id: &str, home: &str, keys: &[&str]) -> Bindable {
|
||||
keys.iter().fold(Bindable::new(id, id, scope(home)), |e, k| e.with_default(b(k)))
|
||||
}
|
||||
|
||||
fn run(id: &str) -> Lookup {
|
||||
Lookup::Run(cmd(id))
|
||||
}
|
||||
|
||||
fn scopes() -> Scopes {
|
||||
Scopes::new().with_panel("Timeline").with_panel("Composition").with_share("Timeline", "Composition").with_context("Text")
|
||||
}
|
||||
|
||||
fn press(km: &Keymap, text: &str, active: &Active) -> Lookup {
|
||||
km.lookup(&chord(text), false, active)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_keys_are_canonical_whatever_the_map_order() {
|
||||
let c = CommandRef::with_params("window.panel", json!({"z": [1, "a b"], "panel": "layers"}));
|
||||
assert_eq!(c.key(), r#"window.panel {"panel":"layers","z":[1,"a b"]}"#);
|
||||
assert_eq!(CommandRef::parse_key(&c.key()), Some(c));
|
||||
assert_eq!(CommandRef::with_params("edit.copy", json!({})).key(), "edit.copy");
|
||||
assert_eq!(CommandRef::parse_key("x {bad"), None);
|
||||
assert_eq!(CommandRef::parse_key(&"x".repeat(300)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_picks_the_nearest_scope() {
|
||||
let catalog = vec![
|
||||
app("edit.copy", &["Cmd+C"]),
|
||||
in_scope("timeline.copy", "Timeline", &["Cmd+C"]),
|
||||
app("file.bake", &["Cmd+B"]),
|
||||
in_scope("text.bold", "Text", &["Cmd+B", "Cmd+I"]),
|
||||
in_scope("timeline.loop", "Timeline", &["L"]),
|
||||
];
|
||||
let km = Keymap::new(catalog.clone(), scopes(), Platform::Mac);
|
||||
let text = ["Text"];
|
||||
assert_eq!(press(&km, "Cmd+C", &Active::NONE), run("edit.copy"));
|
||||
assert_eq!(press(&km, "Cmd+C", &Active::panel("Timeline")), run("timeline.copy"));
|
||||
assert_eq!(press(&km, "Cmd+C", &Active::panel("Composition")), run("timeline.copy"), "sharing panel");
|
||||
assert_eq!(press(&km, "Cmd+C", &Active::panel("Effects")), run("edit.copy"));
|
||||
assert_eq!(press(&km, "Cmd+B", &Active::panel("Timeline")), run("file.bake"));
|
||||
assert_eq!(press(&km, "Cmd+B", &Active { panel: Some("Timeline"), contexts: &text, typing: false }), run("text.bold"));
|
||||
assert_eq!(press(&km, "Cmd+I", &Active::NONE), Lookup::None, "inactive context");
|
||||
assert_eq!(press(&km, "L", &Active::panel("Effects")), run("timeline.loop"), "fallthrough");
|
||||
assert_eq!(km.lookup(&chord("L"), true, &Active::panel("Timeline")), Lookup::None, "double press is its own trigger");
|
||||
|
||||
let strict = Keymap::new(catalog, scopes().with_panel_fallthrough(false), Platform::Mac);
|
||||
assert_eq!(press(&strict, "L", &Active::panel("Effects")), Lookup::None);
|
||||
assert_eq!(press(&strict, "L", &Active::panel("Timeline")), run("timeline.loop"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_rules_decide_what_fires_in_a_text_field() {
|
||||
let catalog = vec![app("tool.brush", &["B"]), app("edit.copy", &["Cmd+C"]), app("help", &["F1"]), app("view.alt", &["Alt+V"])];
|
||||
let typing = Active { panel: None, contexts: &[], typing: true };
|
||||
let cases = [
|
||||
(TypingRule::PlainKeysWait, [false, true, true, true]),
|
||||
(TypingRule::CommandKeysOnly, [false, true, true, false]),
|
||||
(TypingRule::AllWait, [false, false, false, false]),
|
||||
];
|
||||
for (rule, fires) in cases {
|
||||
let km = Keymap::new(catalog.clone(), Scopes::new(), Platform::Windows).with_typing_rule(rule);
|
||||
for ((key, id), fire) in [("B", "tool.brush"), ("Cmd+C", "edit.copy"), ("F1", "help"), ("Alt+V", "view.alt")].into_iter().zip(fires) {
|
||||
let want = if fire { run(id) } else { Lookup::None };
|
||||
assert_eq!(press(&km, key, &typing), want, "{rule:?} {key}");
|
||||
assert_eq!(press(&km, key, &Active::NONE), run(id), "{rule:?} {key} not typing");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_editing_chords_go_to_the_text_field_under_every_rule() {
|
||||
let catalog = vec![app("edit.undo", &["Cmd+Z"]), app("file.save", &["Cmd+S"]), app("nav.word", &["Alt+Left"]), app("nav.start", &["Cmd+Home"])];
|
||||
let typing = Active { typing: true, ..Active::NONE };
|
||||
for rule in [TypingRule::PlainKeysWait, TypingRule::CommandKeysOnly] {
|
||||
for platform in [Platform::Mac, Platform::Windows] {
|
||||
let km = Keymap::new(catalog.clone(), Scopes::new(), platform).with_typing_rule(rule);
|
||||
assert_eq!(press(&km, "Cmd+Z", &typing), Lookup::None, "{rule:?} {platform:?}");
|
||||
assert_eq!(press(&km, "Cmd+Z", &Active::NONE), run("edit.undo"));
|
||||
assert_eq!(press(&km, "Cmd+S", &typing), run("file.save"), "{rule:?} {platform:?}");
|
||||
}
|
||||
}
|
||||
// Word and line keys follow the platform.
|
||||
let mac = Keymap::new(catalog.clone(), Scopes::new(), Platform::Mac);
|
||||
let windows = Keymap::new(catalog.clone(), Scopes::new(), Platform::Windows);
|
||||
assert_eq!(press(&mac, "Alt+Left", &typing), Lookup::None);
|
||||
assert_eq!(press(&windows, "Alt+Left", &typing), run("nav.word"));
|
||||
assert_eq!(press(&windows, "Ctrl+Home", &typing), Lookup::None);
|
||||
assert_eq!(press(&mac, "Cmd+Home", &typing), run("nav.start"));
|
||||
|
||||
// A binding in an active context takes the chord from the field.
|
||||
let catalog = vec![app("edit.undo", &["Cmd+Z"]), app("text.undo", &["Text: Cmd+Z"])];
|
||||
let km = Keymap::new(catalog, scopes(), Platform::Windows);
|
||||
let editing = Active { contexts: &["Text"], typing: true, ..Active::NONE };
|
||||
assert_eq!(press(&km, "Cmd+Z", &editing), run("text.undo"));
|
||||
assert_eq!(press(&km, "Cmd+Z", &typing), Lookup::None);
|
||||
assert!(!TypingRule::PlainKeysWait.fires(&chord("Ctrl+Z"), Platform::Linux));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bindings_of_an_active_context_fire_while_typing_under_every_rule() {
|
||||
let catalog = vec![
|
||||
app("text.bold", &["Text: Cmd+B", "Text: B"]),
|
||||
app("file.bake", &["Cmd+B"]),
|
||||
in_scope("timeline.cut", "Timeline", &["Cmd+K"]),
|
||||
app("file.save", &["Cmd+S"]),
|
||||
];
|
||||
let editing = Active { panel: Some("Timeline"), contexts: &["Text"], typing: true };
|
||||
let elsewhere = Active { contexts: &[], ..editing };
|
||||
let km = Keymap::new(catalog, scopes(), Platform::Mac).with_typing_rule(TypingRule::AllWait);
|
||||
assert_eq!(press(&km, "Cmd+B", &editing), run("text.bold"));
|
||||
assert_eq!(press(&km, "B", &editing), run("text.bold"));
|
||||
assert_eq!(press(&km, "Cmd+K", &editing), Lookup::None, "panel bindings wait");
|
||||
assert_eq!(press(&km, "Cmd+S", &editing), Lookup::None, "app bindings wait");
|
||||
assert_eq!(press(&km, "Cmd+B", &elsewhere), Lookup::None, "the app binding waits when the context is not active");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tools_of_one_group_cycle_and_keep_their_shared_key() {
|
||||
let tool = |id: &str, group: &str| app(id, &["B"]).with_kind(Kind::Tool { group: Some(group.into()) });
|
||||
let mut km =
|
||||
Keymap::new(vec![tool("tool.brush", "brush"), tool("tool.pencil", "brush"), tool("tool.mixer", "brush")], Scopes::new(), Platform::Mac);
|
||||
assert_eq!(press(&km, "B", &Active::NONE), Lookup::Cycle(vec![cmd("tool.brush"), cmd("tool.pencil"), cmd("tool.mixer")]));
|
||||
assert!(km.conflicts().is_empty());
|
||||
|
||||
km.clear(&cmd("tool.mixer"));
|
||||
let done = km.assign(&cmd("tool.mixer"), b("B"), Policy::Steal).unwrap();
|
||||
assert!(done.taken_from.is_empty());
|
||||
assert_eq!(km.bindings(&cmd("tool.brush")), vec![b("B")]);
|
||||
|
||||
let mixed = Keymap::new(vec![tool("tool.brush", "brush"), app("layer.bake", &["B"]), tool("tool.pencil", "brush")], Scopes::new(), Platform::Mac);
|
||||
assert_eq!(press(&mixed, "B", &Active::NONE), run("tool.brush"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steal_keep_and_refuse() {
|
||||
let catalog = vec![app("edit.copy", &["Cmd+C"]), app("edit.duplicate", &["Cmd+D"]), in_scope("timeline.copy", "Timeline", &[])];
|
||||
let mut km = Keymap::new(catalog, scopes(), Platform::Mac);
|
||||
let dup = cmd("edit.duplicate");
|
||||
|
||||
let err = km.assign(&dup, b("Cmd+C"), Policy::Refuse).unwrap_err();
|
||||
let AssignError::Taken(holders) = err else { panic!("{err:?}") };
|
||||
assert_eq!(holders[0].command, cmd("edit.copy"));
|
||||
assert_eq!(km.bindings(&dup), vec![b("Cmd+D")]);
|
||||
|
||||
let done = km.assign(&dup, b("Cmd+C"), Policy::Keep).unwrap();
|
||||
assert_eq!(done.clashes.len(), 1);
|
||||
assert_eq!(km.bindings(&cmd("edit.copy")), vec![b("Cmd+C")]);
|
||||
assert_eq!(km.bindings(&dup), vec![b("Cmd+D"), b("Cmd+C")]);
|
||||
|
||||
km.reset_all();
|
||||
let done = km.assign(&dup, b("Cmd+C"), Policy::Steal).unwrap();
|
||||
assert_eq!(done.taken_from[0].command, cmd("edit.copy"));
|
||||
assert!(km.bindings(&cmd("edit.copy")).is_empty());
|
||||
assert_eq!(km.overrides().get("edit.copy"), Some(&[][..]));
|
||||
assert_eq!(press(&km, "Cmd+C", &Active::NONE), run("edit.duplicate"));
|
||||
|
||||
// A panel binding shadows the application one; nothing is taken.
|
||||
let done = km.assign(&cmd("timeline.copy"), b("Cmd+D"), Policy::Refuse).unwrap();
|
||||
assert!(done.taken_from.is_empty() && done.clashes.is_empty());
|
||||
assert_eq!(km.assign(&cmd("nope"), b("Cmd+D"), Policy::Steal), Err(AssignError::UnknownCommand));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twins_keep_their_shared_default_key() {
|
||||
let mut km = Keymap::new(vec![app("file.close", &["Cmd+W"]), app("sequence.close", &["Cmd+W"])], Scopes::new(), Platform::Mac);
|
||||
km.clear(&cmd("sequence.close"));
|
||||
let done = km.assign(&cmd("sequence.close"), b("Cmd+W"), Policy::Refuse).unwrap();
|
||||
assert!(done.taken_from.is_empty());
|
||||
assert_eq!(km.bindings(&cmd("file.close")), vec![b("Cmd+W")]);
|
||||
assert!(km.overrides().is_empty(), "back to the defaults");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_a_command_frees_its_panel_copies() {
|
||||
// filmcraft#1333: New Bin holds Cmd+B in the application and in the Project panel.
|
||||
let catalog = vec![app("project.newBin", &["Cmd+B", "Project: Cmd+B"]), app("clip.bold", &[])];
|
||||
let mut km = Keymap::new(catalog, Scopes::new().with_panel("Project"), Platform::Mac);
|
||||
assert_eq!(press(&km, "Cmd+B", &Active::panel("Project")), run("project.newBin"));
|
||||
assert!(km.clear(&cmd("project.newBin")));
|
||||
assert!(km.bindings(&cmd("project.newBin")).is_empty());
|
||||
assert_eq!(press(&km, "Cmd+B", &Active::panel("Project")), Lookup::None);
|
||||
assert!(km.assign(&cmd("clip.bold"), b("Project: Cmd+B"), Policy::Refuse).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_chords_are_refused() {
|
||||
let catalog = vec![app("view.next", &[])];
|
||||
let mut mac = Keymap::new(catalog.clone(), Scopes::new(), Platform::Mac).with_reserved(reserved::system(Platform::Mac));
|
||||
let err = mac.assign(&cmd("view.next"), b("Cmd+Tab"), Policy::Steal).unwrap_err();
|
||||
assert_eq!(err, AssignError::Reserved(Trigger::parse("Cmd+Tab").unwrap()));
|
||||
|
||||
let mut win = Keymap::new(catalog.clone(), Scopes::new(), Platform::Windows).with_reserved(reserved::system(Platform::Windows));
|
||||
assert!(matches!(win.assign(&cmd("view.next"), b("Ctrl+Alt+Delete"), Policy::Steal), Err(AssignError::Reserved(_))));
|
||||
assert!(reserved::system(Platform::Linux).contains(&chord("Cmd+Alt+F12")));
|
||||
|
||||
let mut o = Overrides::new();
|
||||
o.insert("view.next", vec!["Alt+F4".into()]);
|
||||
let linux = Keymap::new(catalog, Scopes::new(), Platform::Linux).with_reserved(reserved::system(Platform::Linux)).with_overrides(o);
|
||||
assert!(linux.bindings(&cmd("view.next")).is_empty());
|
||||
assert_eq!(linux.problems(), vec![Problem::Reserved { key: "view.next".into(), text: "Alt+F4".into() }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflicts_tell_clashes_from_shadows() {
|
||||
let catalog = vec![
|
||||
app("edit.copy", &["Cmd+C"]),
|
||||
app("color.copy", &["Cmd+C"]),
|
||||
in_scope("timeline.copy", "Timeline", &["Cmd+C"]),
|
||||
in_scope("text.cut", "Text", &["Cmd+X"]),
|
||||
app("edit.cut", &["Cmd+X"]),
|
||||
app("edit.find", &["Cmd+F"]),
|
||||
in_scope("tab.find", "Effects", &["Cmd+F"]),
|
||||
in_scope("render.find", "Render", &["Cmd+R"]),
|
||||
in_scope("effects.render", "Effects", &["Cmd+R"]),
|
||||
];
|
||||
let mut km = Keymap::new(catalog, scopes(), Platform::Mac);
|
||||
let summary = |km: &Keymap| -> Vec<(String, String, String, ConflictKind, bool)> {
|
||||
km.conflicts().into_iter().map(|c| (c.chord.to_string(), c.a.0.id, c.b.0.id, c.kind, c.in_defaults)).collect()
|
||||
};
|
||||
let s = |a: &str, x: &str, y: &str, k, d| (a.to_string(), x.to_string(), y.to_string(), k, d);
|
||||
let mut want = vec![
|
||||
s("Cmd+C", "edit.copy", "color.copy", ConflictKind::Clash, true),
|
||||
s("Cmd+C", "edit.copy", "timeline.copy", ConflictKind::Shadow, true),
|
||||
s("Cmd+C", "color.copy", "timeline.copy", ConflictKind::Shadow, true),
|
||||
s("Cmd+X", "text.cut", "edit.cut", ConflictKind::Shadow, true),
|
||||
s("Cmd+F", "edit.find", "tab.find", ConflictKind::Shadow, true),
|
||||
// Fallthrough: in a third panel the two tie.
|
||||
s("Cmd+R", "render.find", "effects.render", ConflictKind::Shadow, true),
|
||||
];
|
||||
let sort = |mut v: Vec<(String, String, String, ConflictKind, bool)>| {
|
||||
v.sort();
|
||||
v
|
||||
};
|
||||
assert_eq!(sort(summary(&km)), sort(want.clone()));
|
||||
|
||||
km.assign(&cmd("edit.find"), b("Cmd+D"), Policy::Steal).unwrap();
|
||||
km.assign(&cmd("edit.cut"), b("Cmd+D"), Policy::Keep).unwrap();
|
||||
want.push(s("Cmd+D", "edit.cut", "edit.find", ConflictKind::Clash, false));
|
||||
assert_eq!(sort(summary(&km)), sort(want.clone()));
|
||||
|
||||
let order: Vec<_> = summary(&km).into_iter().map(|(c, a, b, ..)| (c, a, b)).collect();
|
||||
let chords: Vec<Trigger> = km.conflicts().iter().map(|c| c.chord).collect();
|
||||
assert!(chords.is_sorted(), "{order:?}");
|
||||
let c = |x: &str, y: &str| order.iter().position(|(_, a, b)| a == x && b == y);
|
||||
assert!(c("edit.copy", "color.copy") < c("edit.copy", "timeline.copy"), "{order:?}");
|
||||
assert!(c("edit.copy", "timeline.copy") < c("color.copy", "timeline.copy"), "{order:?}");
|
||||
|
||||
// One command's conflicts, with that command as `a`.
|
||||
let with = |id: &str| -> Vec<(String, String, ConflictKind)> {
|
||||
km.conflicts_with(&cmd(id)).into_iter().map(|c| (c.chord.to_string(), c.b.0.id, c.kind)).collect()
|
||||
};
|
||||
let w = |chord: &str, other: &str, kind| (chord.to_string(), other.to_string(), kind);
|
||||
assert_eq!(with("edit.copy"), [w("Cmd+C", "color.copy", ConflictKind::Clash), w("Cmd+C", "timeline.copy", ConflictKind::Shadow)]);
|
||||
assert_eq!(with("edit.cut"), [w("Cmd+X", "text.cut", ConflictKind::Shadow), w("Cmd+D", "edit.find", ConflictKind::Clash)]);
|
||||
assert!(with("nope").is_empty());
|
||||
for entry in km.catalog() {
|
||||
let id = entry.command.id.as_str();
|
||||
let mut direct: Vec<_> =
|
||||
km.conflicts_with(&entry.command).into_iter().map(|c| (c.chord, c.a.0.id, c.b.0.id, c.kind, c.in_defaults)).collect();
|
||||
let mut filtered: Vec<_> = km
|
||||
.conflicts()
|
||||
.into_iter()
|
||||
.filter(|c| c.a.0.id == id || c.b.0.id == id)
|
||||
.map(|c| {
|
||||
if c.a.0.id == id {
|
||||
(c.chord, c.a.0.id, c.b.0.id, c.kind, c.in_defaults)
|
||||
} else {
|
||||
(c.chord, c.b.0.id, c.a.0.id, c.kind, c.in_defaults)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
direct.sort();
|
||||
filtered.sort();
|
||||
assert_eq!(direct, filtered, "{id}");
|
||||
}
|
||||
|
||||
let strict = Keymap::new(km.catalog().to_vec(), scopes().with_panel_fallthrough(false), Platform::Mac);
|
||||
assert!(!strict.conflicts().iter().any(|c| c.chord.to_string() == "Cmd+R"));
|
||||
}
|
||||
|
||||
/// `commands` commands, each with 16 bindings on one chord in 16 panels.
|
||||
fn crowded(commands: usize, scopes: Scopes, kind: Kind) -> (Keymap, Overrides) {
|
||||
let catalog: Vec<Bindable> = (0..commands).map(|n| app(&format!("c.{n}"), &[]).with_kind(kind.clone())).collect();
|
||||
let mut o = Overrides::new();
|
||||
for n in 0..commands {
|
||||
assert!(o.insert(format!("c.{n}"), (1..=MAX_BINDINGS).map(|p| format!("P{p}: K")).collect()));
|
||||
}
|
||||
(Keymap::new(catalog, scopes, Platform::Mac), o)
|
||||
}
|
||||
|
||||
fn panels(n: usize) -> Scopes {
|
||||
(1..=n).fold(Scopes::new(), |s, p| s.with_panel(&format!("P{p}")))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crowded_chords_are_capped() {
|
||||
// Panels the app never registered are not bound.
|
||||
let (km, o) = crowded(2, Scopes::new(), Kind::Command);
|
||||
let km = km.with_overrides(o);
|
||||
assert!(km.conflicts().is_empty());
|
||||
assert!(km.bindings(&cmd("c.0")).is_empty());
|
||||
assert_eq!(km.overrides().get("c.0").map(<[String]>::len), Some(MAX_BINDINGS), "kept verbatim");
|
||||
assert!(km.problems().contains(&Problem::UnknownScope { key: "c.0".into(), text: "P1: K".into() }));
|
||||
|
||||
// Registered panels that never share: 32 commands make 16 × 496 pairs, capped.
|
||||
let (km, o) = crowded(32, panels(MAX_BINDINGS).with_panel_fallthrough(false), Kind::Command);
|
||||
assert_eq!(km.with_overrides(o).conflicts().len(), MAX_CONFLICTS);
|
||||
|
||||
// Tools of one group: no conflicts.
|
||||
let (km, o) = crowded(32, panels(MAX_BINDINGS), Kind::Tool { group: None });
|
||||
assert!(km.with_overrides(o).conflicts().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "worst-case timing; run with --ignored"]
|
||||
fn crowded_chords_stay_fast() {
|
||||
let limit = Duration::from_secs(8);
|
||||
|
||||
// Panels the app never registered are not bound.
|
||||
let (km, o) = crowded(MAX_COMMANDS, Scopes::new(), Kind::Command);
|
||||
let km = km.with_overrides(o);
|
||||
let t = Instant::now();
|
||||
assert!(km.conflicts().is_empty());
|
||||
assert!(t.elapsed() < limit, "{:?}", t.elapsed());
|
||||
assert!(km.bindings(&cmd("c.0")).is_empty());
|
||||
assert_eq!(km.overrides().get("c.0").map(<[String]>::len), Some(MAX_BINDINGS), "kept verbatim");
|
||||
assert!(km.problems().contains(&Problem::UnknownScope { key: "c.0".into(), text: "P1: K".into() }));
|
||||
|
||||
// Registered panels that never share: many conflicts, capped.
|
||||
let (km, o) = crowded(MAX_COMMANDS, panels(MAX_BINDINGS).with_panel_fallthrough(false), Kind::Command);
|
||||
let km = km.with_overrides(o);
|
||||
let t = Instant::now();
|
||||
assert_eq!(km.conflicts().len(), MAX_CONFLICTS);
|
||||
assert!(t.elapsed() < limit, "{:?}", t.elapsed());
|
||||
|
||||
// Tools of one group: no conflicts, and no pair is compared.
|
||||
let (km, o) = crowded(MAX_COMMANDS, panels(MAX_BINDINGS), Kind::Tool { group: None });
|
||||
let km = km.with_overrides(o);
|
||||
let t = Instant::now();
|
||||
assert!(km.conflicts().is_empty());
|
||||
assert!(t.elapsed() < limit, "{:?}", t.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assigning_many_commands_stays_fast() {
|
||||
let catalog: Vec<Bindable> = (0..MAX_COMMANDS).map(|n| app(&format!("c.{n}"), &[])).collect();
|
||||
let mut km = Keymap::new(catalog, panels(MAX_BINDINGS), Platform::Mac);
|
||||
let list: Vec<Binding> = (1..=MAX_BINDINGS).map(|p| b(&format!("P{p}: K"))).collect();
|
||||
let t = Instant::now();
|
||||
for n in 0..MAX_COMMANDS {
|
||||
let done = km.set_bindings(&cmd(&format!("c.{n}")), list.clone(), Policy::Steal).unwrap();
|
||||
assert_eq!(done.taken_from.len(), if n == 0 { 0 } else { MAX_BINDINGS });
|
||||
}
|
||||
assert!(t.elapsed() < Duration::from_secs(8), "{:?}", t.elapsed());
|
||||
assert_eq!(km.bindings(&cmd(&format!("c.{}", MAX_COMMANDS - 1))), list);
|
||||
assert!(km.bindings(&cmd("c.0")).is_empty());
|
||||
assert_eq!(press(&km, "K", &Active::panel("P3")), run(&format!("c.{}", MAX_COMMANDS - 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binding_text_round_trips_for_every_key() {
|
||||
let panel = scope("Timeline");
|
||||
for &key in Key::ALL {
|
||||
for mods in [Mods::NONE, Mods { cmd: true, ctrl: true, alt: true, shift: true }] {
|
||||
let chord = Chord::new(mods, key);
|
||||
for trigger in [Trigger::single(chord), Trigger::double(chord)] {
|
||||
for binding in [Binding::new(trigger), Binding::in_scope(trigger, panel.clone())] {
|
||||
let text = binding.to_string();
|
||||
assert_eq!(Binding::parse(&text).as_ref(), Ok(&binding), "{text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(Binding::parse(": :"), Ok(Binding::new(Trigger::double(Chord::plain(Key::Colon)))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_names_with_outer_whitespace_are_refused() {
|
||||
for name in [" Timeline", "Timeline ", "\u{a0}Timeline", ""] {
|
||||
assert_eq!(Scope::new(name), None, "{name:?}");
|
||||
}
|
||||
assert_eq!(Scope::new("Time line").map(|s| s.to_string()).as_deref(), Some("Time line"));
|
||||
assert_eq!(Binding::parse(" Timeline : K").map(|b| b.scope), Ok(Some(scope("Timeline"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_are_refused_when_the_overrides_are_full() {
|
||||
let catalog = vec![app("edit.copy", &["Cmd+C"]), app("edit.duplicate", &["Cmd+D"]), app("edit.cut", &[])];
|
||||
let mut o = Overrides::new();
|
||||
o.insert("edit.cut", vec!["Cmd+X".into()]);
|
||||
for n in 1..MAX_COMMANDS {
|
||||
o.insert(format!("junk.{n}"), vec![]);
|
||||
}
|
||||
assert_eq!(o.len(), MAX_COMMANDS);
|
||||
let mut km = Keymap::new(catalog, Scopes::new(), Platform::Mac).with_overrides(o.clone());
|
||||
let (copy, dup, cut) = (cmd("edit.copy"), cmd("edit.duplicate"), cmd("edit.cut"));
|
||||
|
||||
assert_eq!(km.assign(&dup, b("Cmd+K"), Policy::Steal), Err(AssignError::Full));
|
||||
assert_eq!(km.set_bindings(&dup, vec![], Policy::Steal), Err(AssignError::Full));
|
||||
assert!(!km.clear(©));
|
||||
assert!(!km.remove(©, &b("Cmd+C")));
|
||||
// Taking Cmd+C from edit.copy would need an entry for it too.
|
||||
assert_eq!(km.assign(&cut, b("Cmd+C"), Policy::Steal), Err(AssignError::Full));
|
||||
assert_eq!(km.bindings(©), vec![b("Cmd+C")]);
|
||||
assert_eq!(km.bindings(&cut), vec![b("Cmd+X")]);
|
||||
assert_eq!(km.overrides(), &o);
|
||||
|
||||
// Commands that have an entry still change, and back to the defaults frees one.
|
||||
assert!(km.assign(&cut, b("Cmd+Shift+X"), Policy::Steal).is_ok());
|
||||
assert!(km.reset(&cut));
|
||||
assert!(km.assign(&dup, b("Cmd+K"), Policy::Steal).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bindings_in_unknown_scopes_are_refused() {
|
||||
let catalog = vec![app("edit.copy", &["Cmd+C"]), in_scope("timeline.mark", "Timeline", &["M"])];
|
||||
let mut km = Keymap::new(catalog, Scopes::new().with_context("Text"), Platform::Mac);
|
||||
let copy = cmd("edit.copy");
|
||||
assert_eq!(km.assign(©, b("Nowhere: Cmd+K"), Policy::Steal), Err(AssignError::UnknownScope(scope("Nowhere"))));
|
||||
assert!(km.assign(©, b("Timeline: Cmd+K"), Policy::Steal).is_ok(), "a catalog scope");
|
||||
assert!(km.assign(©, b("Text: Cmd+K"), Policy::Steal).is_ok(), "a registered scope");
|
||||
|
||||
let mut o = Overrides::new();
|
||||
o.insert("edit.copy", vec!["Nowhere: Cmd+K".into(), "Cmd+J".into()]);
|
||||
km.set_overrides(o);
|
||||
assert_eq!(km.bindings(©), vec![b("Cmd+J")]);
|
||||
assert_eq!(km.problems(), vec![Problem::UnknownScope { key: "edit.copy".into(), text: "Nowhere: Cmd+K".into() }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_entries_keep_the_defaults() {
|
||||
let catalog = vec![app("edit.copy", &["Cmd+C"]), app("edit.paste", &["Cmd+V"])];
|
||||
let mut o = Overrides::new();
|
||||
o.insert("edit.copy", vec!["Cmd+Nope".into()]);
|
||||
o.insert("edit.paste", vec![]);
|
||||
let mut km = Keymap::new(catalog, Scopes::new(), Platform::Mac).with_overrides(o);
|
||||
assert_eq!(km.bindings(&cmd("edit.copy")), vec![b("Cmd+C")]);
|
||||
assert!(km.bindings(&cmd("edit.paste")).is_empty());
|
||||
assert_eq!(km.overrides().get("edit.copy"), Some(&["Cmd+Nope".to_string()][..]), "verbatim");
|
||||
assert!(km.reset(&cmd("edit.copy")));
|
||||
assert_eq!(km.overrides().get("edit.copy"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_with_nothing_usable_keep_the_defaults() {
|
||||
let catalog = vec![app("edit.copy", &["Cmd+C"]), app("edit.cut", &["Cmd+X"]), app("edit.paste", &["Cmd+V"]), app("edit.undo", &["Cmd+Z"])];
|
||||
let mut o = Overrides::new();
|
||||
o.insert("edit.copy", vec!["Nowhere: Cmd+K".into()]);
|
||||
o.insert("edit.cut", vec!["Alt+F4".into()]);
|
||||
o.insert("edit.paste", vec!["Nowhere: Cmd+K".into(), "Alt+F4".into(), "Cmd+J".into()]);
|
||||
o.insert("edit.undo", vec![]);
|
||||
let km = Keymap::new(catalog, Scopes::new(), Platform::Linux).with_reserved(reserved::system(Platform::Linux)).with_overrides(o);
|
||||
assert_eq!(km.bindings(&cmd("edit.copy")), vec![b("Cmd+C")], "only an unknown scope");
|
||||
assert_eq!(km.bindings(&cmd("edit.cut")), vec![b("Cmd+X")], "only a reserved chord");
|
||||
assert_eq!(km.bindings(&cmd("edit.paste")), vec![b("Cmd+J")]);
|
||||
assert!(km.bindings(&cmd("edit.undo")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overrides_hold_only_what_differs_from_the_defaults() {
|
||||
let catalog = vec![app("edit.copy", &["Cmd+C"]), in_scope("timeline.mark", "Timeline", &["M"])];
|
||||
let mut km = Keymap::new(catalog, scopes(), Platform::Mac);
|
||||
let copy = cmd("edit.copy");
|
||||
km.assign(©, b("Timeline: Cmd+K"), Policy::Steal).unwrap();
|
||||
assert_eq!(km.overrides().get("edit.copy"), Some(&["Cmd+C".to_string(), "Timeline: Cmd+K".to_string()][..]));
|
||||
assert_eq!(km.bindings(©)[1], Binding::in_scope(Trigger::parse("Cmd+K").unwrap(), scope("Timeline")));
|
||||
assert!(km.remove(©, &b("Timeline: Cmd+K")));
|
||||
assert!(km.overrides().is_empty());
|
||||
|
||||
km.set_bindings(&cmd("timeline.mark"), vec![b("Timeline: M")], Policy::Steal).unwrap();
|
||||
assert!(km.overrides().is_empty(), "the home scope written out is the same binding");
|
||||
km.set_bindings(©, vec![b("Cmd+Shift+C")], Policy::Steal).unwrap();
|
||||
assert!(km.reset(©));
|
||||
assert!(km.overrides().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_keep_the_texts_this_build_cannot_use() {
|
||||
let catalog = vec![app("file.quit", &["Cmd+Q"]), app("file.close", &["Cmd+W"]), app("file.save", &["Cmd+S"])];
|
||||
let mut o = Overrides::new();
|
||||
o.insert("file.quit", vec!["Cmd+Q".into(), "Cmd+FutureKey".into(), "Nowhere: Cmd+J".into()]);
|
||||
let mut km = Keymap::new(catalog.clone(), scopes(), Platform::Mac).with_overrides(o);
|
||||
let quit = cmd("file.quit");
|
||||
let texts = |km: &Keymap| km.overrides().get("file.quit").map(<[String]>::to_vec);
|
||||
let strings = |t: &[&str]| Some(t.iter().map(|s| s.to_string()).collect::<Vec<_>>());
|
||||
|
||||
km.assign(&quit, b("Cmd+W"), Policy::Steal).unwrap();
|
||||
assert_eq!(texts(&km), strings(&["Cmd+Q", "Cmd+W", "Cmd+FutureKey", "Nowhere: Cmd+J"]));
|
||||
km.assign(&cmd("file.save"), b("Cmd+Q"), Policy::Steal).unwrap();
|
||||
assert_eq!(texts(&km), strings(&["Cmd+W", "Cmd+FutureKey", "Nowhere: Cmd+J"]), "taken by a Steal");
|
||||
let reloaded = Keymap::new(catalog, scopes(), Platform::Mac).with_overrides(km.overrides().clone());
|
||||
assert_eq!(reloaded.bindings(&quit), vec![b("Cmd+W")]);
|
||||
|
||||
// An entry of only such texts would load as the defaults, so a cleared command drops them.
|
||||
assert!(km.clear(&quit));
|
||||
assert_eq!(texts(&km), strings(&[]));
|
||||
assert!(km.reset(&quit));
|
||||
assert_eq!(texts(&km), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_override_equal_to_the_defaults_on_this_platform_is_not_stored() {
|
||||
let mut km = Keymap::new(vec![app("file.save", &["Cmd+S"])], Scopes::new(), Platform::Windows);
|
||||
km.set_bindings(&cmd("file.save"), vec![b("Ctrl+S")], Policy::Steal).unwrap();
|
||||
assert!(km.overrides().is_empty());
|
||||
assert_eq!(press(&km, "Ctrl+S", &Active::NONE), run("file.save"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_text_in_the_map_form_removes_the_shortcut() {
|
||||
let catalog = vec![app("edit.copy", &["Cmd+C"]), app("edit.paste", &["Cmd+V"]), app("edit.cut", &["Cmd+X"])];
|
||||
let o: Overrides = serde_json::from_str(r#"{"edit.copy": "", "edit.paste": [""], "edit.cut": "Cmd+K"}"#).unwrap();
|
||||
assert!(o.load_notes().is_empty(), "{:?}", o.load_notes());
|
||||
let km = Keymap::new(catalog.clone(), Scopes::new(), Platform::Mac).with_overrides(o);
|
||||
assert!(km.bindings(&cmd("edit.copy")).is_empty(), "a removed default stays removed");
|
||||
assert!(km.bindings(&cmd("edit.paste")).is_empty());
|
||||
assert_eq!(km.bindings(&cmd("edit.cut")), vec![b("Cmd+K")]);
|
||||
assert!(km.problems().is_empty());
|
||||
|
||||
let saved = serde_json::to_string(km.overrides()).unwrap();
|
||||
let again = Keymap::new(catalog, Scopes::new(), Platform::Mac).with_overrides(serde_json::from_str(&saved).unwrap());
|
||||
assert!(again.bindings(&cmd("edit.copy")).is_empty(), "{saved}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overrides_write_the_map_form_unless_a_command_has_several_keys() {
|
||||
let mut o = Overrides::new();
|
||||
o.insert("edit.copy", vec!["Cmd+K".into()]);
|
||||
o.insert("edit.paste", vec![]);
|
||||
let text = serde_json::to_string(&o).unwrap();
|
||||
assert_eq!(text, r#"{"edit.copy":"Cmd+K","edit.paste":""}"#, "older builds read one text per command");
|
||||
assert_eq!(serde_json::from_str::<Overrides>(&text).unwrap(), o);
|
||||
|
||||
o.insert("edit.cut", vec!["Cmd+X".into(), "Shift+Delete".into()]);
|
||||
let text = serde_json::to_string(&o).unwrap();
|
||||
assert!(text.starts_with(r#"[{"command":"edit.copy","keys":["Cmd+K"]},"#), "{text}");
|
||||
assert_eq!(serde_json::from_str::<Overrides>(&text).unwrap(), o);
|
||||
|
||||
// A blank text is kept verbatim (it loads as the defaults), which the map form cannot say.
|
||||
let mut blank = Overrides::new();
|
||||
blank.insert("edit.copy", vec![" ".into()]);
|
||||
let text = serde_json::to_string(&blank).unwrap();
|
||||
assert!(text.starts_with('['), "{text}");
|
||||
assert_eq!(serde_json::from_str::<Overrides>(&text).unwrap(), blank);
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct Prefs {
|
||||
#[serde(with = "craft_keymap::keymap::overrides_list")]
|
||||
shortcuts: Overrides,
|
||||
}
|
||||
let mut single = Overrides::new();
|
||||
single.insert("edit.copy", vec!["Cmd+K".into()]);
|
||||
let text = serde_json::to_string(&Prefs { shortcuts: single }).unwrap();
|
||||
assert_eq!(text, r#"{"shortcuts":[{"command":"edit.copy","keys":["Cmd+K"]}]}"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_folds_into_cmd_off_macos() {
|
||||
let catalog = vec![app("edit.cut", &["Cmd+X"]), app("mac.cut", &["Ctrl+X"])];
|
||||
let win = Keymap::new(catalog.clone(), Scopes::new(), Platform::Windows);
|
||||
let mac = Keymap::new(catalog, Scopes::new(), Platform::Mac);
|
||||
let conflicts = win.conflicts();
|
||||
assert_eq!(conflicts.len(), 1);
|
||||
assert_eq!((conflicts[0].kind, conflicts[0].chord.to_string()), (ConflictKind::Clash, "Cmd+X".to_string()));
|
||||
assert!(mac.conflicts().is_empty());
|
||||
assert_eq!(press(&win, "Ctrl+X", &Active::NONE), run("edit.cut"));
|
||||
assert_eq!(press(&mac, "Ctrl+X", &Active::NONE), run("mac.cut"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_overrides_load_without_panic_and_report_problems() {
|
||||
let mut doc = serde_json::Map::new();
|
||||
for i in 0..(MAX_COMMANDS + 100) {
|
||||
doc.insert(format!("junk.{i}"), json!(["Cmd+Z"]));
|
||||
}
|
||||
doc.insert("edit.copy".into(), json!(["Cmd+Nope", "x".repeat(10_000), 7, "Shift+C"]));
|
||||
doc.insert("a".into(), json!(["Shift+A"]));
|
||||
doc.insert("é".repeat(300), json!([]));
|
||||
doc.insert("b".into(), json!({"deep": [[[[1]]]]}));
|
||||
let o: Overrides = serde_json::from_value(serde_json::Value::Object(doc)).unwrap();
|
||||
assert!(o.len() <= MAX_COMMANDS);
|
||||
|
||||
let km = Keymap::new(vec![app("edit.copy", &["Cmd+C"]), app("a", &[])], Scopes::new(), Platform::Linux).with_overrides(o.clone());
|
||||
assert_eq!(km.bindings(&cmd("edit.copy")), vec![b("Shift+C")]);
|
||||
assert_eq!(km.overrides().get("edit.copy"), Some(&["Cmd+Nope".to_string(), "Shift+C".to_string()][..]), "verbatim");
|
||||
let problems = km.problems();
|
||||
assert!(problems.iter().any(|p| matches!(p, Problem::TooManyCommands { .. })));
|
||||
assert!(problems.contains(&Problem::Dropped { key: "edit.copy".into(), reason: DropReason::TextTooLong }));
|
||||
assert!(problems.contains(&Problem::Dropped { key: "edit.copy".into(), reason: DropReason::NotText }));
|
||||
assert!(problems.iter().any(|p| matches!(p, Problem::Dropped { reason: DropReason::KeyTooLong, .. })));
|
||||
assert!(problems.iter().any(|p| matches!(p, Problem::BadBinding { text, .. } if text == "Cmd+Nope")));
|
||||
assert!(problems.iter().any(|p| matches!(p, Problem::UnknownCommand { key } if key == "junk.0")));
|
||||
|
||||
let text = serde_json::to_string(&o).unwrap();
|
||||
let again: Overrides = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(again, o);
|
||||
assert!(text.starts_with(r#"[{"command":"a","keys":["Shift+A"]},"#), "{}", &text[..80]);
|
||||
assert!(serde_json::from_str::<Overrides>(r#"{"x": {"y": 1}, "z": true, "w": null, "v": "Cmd+V"}"#).is_ok());
|
||||
let items: Overrides =
|
||||
serde_json::from_str(r#"[{"command": "v", "keys": "Cmd+V"}, {"command": "x"}, {"keys": []}, 3, [], {"command": "y", "keys": [1]}]"#).unwrap();
|
||||
assert_eq!(items.iter().collect::<Vec<_>>(), [("v", &["Cmd+V".to_string()][..]), ("y", &[][..])]);
|
||||
assert_eq!(items.load_notes().len(), 5);
|
||||
|
||||
let twice: Overrides = serde_json::from_str(r#"[{"command": "v", "keys": ["Cmd+V"]}, {"command": "v", "keys": []}]"#).unwrap();
|
||||
assert_eq!(twice.get("v"), Some(&["Cmd+V".to_string()][..]), "the first entry stays");
|
||||
assert_eq!(twice.load_notes(), [Problem::DuplicateKey { key: "v".into() }]);
|
||||
for text in [r#""x""#, "5", "true", "null"] {
|
||||
let o: Overrides = serde_json::from_str(text).unwrap();
|
||||
assert!(o.is_empty(), "{text}");
|
||||
assert_eq!(o.load_notes(), [Problem::Dropped { key: String::new(), reason: DropReason::NotAList }], "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_removes_hand_written_variants_of_a_key() {
|
||||
let layers = CommandRef::with_params("window.panel", json!({"panel": "layers"}));
|
||||
let catalog = vec![Bindable::new(layers.clone(), "Layers", Scope::app()).with_default(b("F7"))];
|
||||
let load = || {
|
||||
let mut o = Overrides::new();
|
||||
o.insert(r#"window.panel {"panel":"layers"}"#, vec!["Cmd+L".into()]);
|
||||
o.insert(r#"window.panel { "panel": "layers" }"#, vec!["Cmd+K".into()]);
|
||||
Keymap::new(catalog.clone(), Scopes::new(), Platform::Mac).with_overrides(o)
|
||||
};
|
||||
let mut km = load();
|
||||
assert_eq!(km.bindings(&layers), vec![b("Cmd+L")], "the canonical entry wins");
|
||||
km.reset(&layers);
|
||||
assert!(km.overrides().is_empty(), "{:?}", km.overrides());
|
||||
|
||||
// Setting the defaults drops the entries too.
|
||||
let mut km = load();
|
||||
km.set_bindings(&layers, vec![b("F7")], Policy::Steal).unwrap();
|
||||
assert!(km.overrides().is_empty(), "{:?}", km.overrides());
|
||||
let again = Keymap::new(catalog.clone(), Scopes::new(), Platform::Mac).with_overrides(km.overrides().clone());
|
||||
assert_eq!(again.bindings(&layers), vec![b("F7")]);
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
use craft_keymap::{Chord, Key, KeyInput, Layout, Mods, Platform};
|
||||
|
||||
fn chord(text: &str) -> Chord {
|
||||
Chord::parse(text).unwrap_or_else(|e| panic!("{text}: {e}"))
|
||||
}
|
||||
|
||||
/// A press as egui reports it at the US position `physical`: the modifiers held and the logical
|
||||
/// key, which is the physical key when the character typed has no key (`ф`, `é`, `ข`).
|
||||
fn at(reported: &str, physical: Key) -> KeyInput {
|
||||
let c = chord(reported);
|
||||
KeyInput::new(c.mods).with_typed(c.key).with_physical(physical)
|
||||
}
|
||||
|
||||
fn texts(chords: &[Chord]) -> Vec<String> {
|
||||
chords.iter().map(Chord::to_string).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_layout_resolves_presses_by_the_rule() {
|
||||
let latin = Layout::new();
|
||||
let other = Layout::new().with_latin(false);
|
||||
let rows: &[(&str, &Layout, KeyInput, &str)] = &[
|
||||
// Russian: letters type Cyrillic, which egui reports as the physical key.
|
||||
("Russian ⌘С", &other, at("Cmd+C", Key::C), "Cmd+C"),
|
||||
("Russian ⌘Х", &other, at("Cmd+[", Key::OpenBracket), "Cmd+["),
|
||||
("Russian / key types .", &other, at("Cmd+.", Key::Slash), "Cmd+."),
|
||||
("Russian ⇧7 types ?", &other, at("Shift+?", Key::Num7), "?"),
|
||||
// Arabic 101: ⇧D types ].
|
||||
("Arabic ⌃⇧D", &other, at("Cmd+Shift+]", Key::D), "Cmd+Shift+D"),
|
||||
("Arabic ⌃V", &other, at("Cmd+V", Key::V), "Cmd+V"),
|
||||
// Hebrew: Q types /, W types ', the / position types ..
|
||||
("Hebrew ⌃Q", &other, at("Cmd+/", Key::Q), "Cmd+Q"),
|
||||
("Hebrew ⌃W", &other, at("Cmd+'", Key::W), "Cmd+W"),
|
||||
("Hebrew / key types .", &other, at("Cmd+.", Key::Slash), "Cmd+."),
|
||||
// Greek: Q types ;.
|
||||
("Greek ⌃Q", &other, at("Cmd+;", Key::Q), "Cmd+Q"),
|
||||
("Greek ⌃Z", &other, at("Cmd+Z", Key::Z), "Cmd+Z"),
|
||||
// Dvorak + Russian, as the suite's egui-winit reports them: the Latin layout's character
|
||||
// for each key. Dvorak types ' on the Q position, which egui reports as Q or as '.
|
||||
("Dvorak + Russian ⌃С", &other, at("Cmd+J", Key::C).with_latin('j'), "Cmd+J"),
|
||||
("Dvorak + Russian ⌃Й", &other, at("Cmd+Q", Key::Q).with_latin('\''), "Cmd+'"),
|
||||
("Dvorak + Russian ⌃Й as '", &other, at("Cmd+'", Key::Q).with_latin('\''), "Cmd+'"),
|
||||
("Dvorak + Russian / key types .", &other, at("Cmd+.", Key::Slash).with_latin('z'), "Cmd+Z"),
|
||||
// Dvorak + Hebrew: the Q position types / and has no Dvorak letter.
|
||||
("Dvorak + Hebrew ⌃Q", &other, at("Cmd+/", Key::Q).with_latin('\''), "Cmd+/"),
|
||||
// Thai Kedmanee: 2 types /, - types ข, D types ก.
|
||||
("Thai 2 key types /", &other, at("Cmd+/", Key::Num2), "Cmd+/"),
|
||||
("Thai - key types ข", &other, at("Cmd+-", Key::Minus), "Cmd+-"),
|
||||
("Thai ⌃D", &other, at("Cmd+D", Key::D), "Cmd+D"),
|
||||
// AZERTY.
|
||||
("AZERTY A", &latin, at("Cmd+A", Key::Q), "Cmd+A"),
|
||||
("AZERTY M", &latin, at("Cmd+M", Key::Semicolon), "Cmd+M"),
|
||||
("AZERTY M key types ,", &latin, at("Cmd+,", Key::M), "Cmd+,"),
|
||||
("AZERTY & key", &latin, at("Cmd+1", Key::Num1), "Cmd+1"),
|
||||
("AZERTY ⇧& types 1", &latin, at("Cmd+Shift+1", Key::Num1), "Cmd+Shift+1"),
|
||||
("AZERTY 6 key types -", &latin, at("Cmd+-", Key::Num6), "Cmd+-"),
|
||||
("AZERTY ⇧; types .", &latin, at("Shift+.", Key::Comma), "."),
|
||||
// Dvorak.
|
||||
("Dvorak O", &latin, at("Cmd+O", Key::S), "Cmd+O"),
|
||||
("Dvorak ⇧O keeps Shift", &latin, at("Cmd+Shift+O", Key::S), "Cmd+Shift+O"),
|
||||
("Dvorak Q key types '", &latin, at("Cmd+'", Key::Q), "Cmd+'"),
|
||||
("Dvorak W key types ,", &latin, at("Cmd+,", Key::W), "Cmd+,"),
|
||||
// QWERTZ (German).
|
||||
("QWERTZ ⇧⌘7 types /", &latin, at("Cmd+Shift+/", Key::Num7), "Cmd+/"),
|
||||
("QWERTZ Z", &latin, at("Cmd+Z", Key::Y), "Cmd+Z"),
|
||||
("QWERTZ ⇧ß types ?", &latin, at("Cmd+Shift+?", Key::Minus), "Cmd+?"),
|
||||
("QWERTZ + key", &latin, at("Cmd++", Key::CloseBracket), "Cmd++"),
|
||||
("QWERTZ ⇧, types ;", &latin, at("Cmd+Shift+;", Key::Comma), "Cmd+;"),
|
||||
// US.
|
||||
("US ⇧;", &latin, at("Shift+:", Key::Semicolon), ":"),
|
||||
("US ⇧⌘=", &latin, at("Cmd+Shift++", Key::Equals), "Cmd++"),
|
||||
("US ⇧- types _, which has no key", &latin, at("Shift+-", Key::Minus), "Shift+-"),
|
||||
// macOS "Dvorak – QWERTY ⌘": with ⌘ held the layout's ⌘ table is QWERTY, while the
|
||||
// logical key egui reports is Dvorak's K.
|
||||
("Dvorak – QWERTY ⌘ ⌘V", &latin, at("Cmd+K", Key::V).with_latin('v'), "Cmd+V"),
|
||||
// A Shift level the platform reports wins over the inference.
|
||||
("reported Shift level", &latin, at("Cmd+Shift+/", Key::Num7).with_shift_needed(false), "Cmd+Shift+/"),
|
||||
];
|
||||
for (name, layout, input, want) in rows {
|
||||
assert_eq!(layout.resolve(input).map(|c| c.to_string()).as_deref(), Some(*want), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reported_cases_match_only_the_chord_the_press_means() {
|
||||
let p = Platform::Windows;
|
||||
let arabic = Layout::new().with_latin(false);
|
||||
let ctrl_shift_d = at("Cmd+Shift+]", Key::D);
|
||||
assert!(arabic.matches(&chord("Ctrl+Shift+D"), &ctrl_shift_d, p));
|
||||
assert!(!arabic.matches(&chord("Ctrl+Shift+]"), &ctrl_shift_d, p), "Arabic Ctrl+Shift+D must not run Ctrl+Shift+]");
|
||||
|
||||
let dvorak_russian_q = at("Cmd+Q", Key::Q).with_latin('\'');
|
||||
assert!(!Layout::new().with_latin(false).matches(&chord("Ctrl+Q"), &dvorak_russian_q, p), "Dvorak + Russian й must not quit");
|
||||
|
||||
let qwerty_cmd = at("Cmd+K", Key::V).with_latin('v');
|
||||
assert!(Layout::new().matches(&chord("Cmd+V"), &qwerty_cmd, Platform::Mac));
|
||||
assert!(!Layout::new().matches(&chord("Cmd+K"), &qwerty_cmd, Platform::Mac), "⌘V must not open the command palette");
|
||||
|
||||
let german = Layout::new();
|
||||
let slash = at("Cmd+Shift+/", Key::Num7);
|
||||
assert_eq!(texts(&german.candidates(&slash)), ["Cmd+/", "Cmd+Shift+7"]);
|
||||
assert!(german.matches(&chord("⌘/"), &slash, Platform::Mac));
|
||||
// A US-written ⌘? binding is reached with German's ⇧ß, not with ⇧7.
|
||||
assert!(!german.matches(&chord("Cmd+Shift+/"), &slash, p));
|
||||
assert_eq!(texts(&german.candidates(&at("Cmd+Shift+?", Key::Minus))), ["Cmd+?", "Cmd+Shift+/"]);
|
||||
// German Ctrl+; is Ctrl+Shift+, and must not run a Ctrl+Shift+, (font size) binding.
|
||||
let semicolon = at("Cmd+Shift+;", Key::Comma);
|
||||
assert!(german.matches(&chord("Ctrl+;"), &semicolon, p));
|
||||
assert!(!german.matches(&chord("Ctrl+Shift+,"), &semicolon, p));
|
||||
|
||||
// AZERTY's 6 key types -: Ctrl+- first, then Ctrl+6.
|
||||
assert_eq!(texts(&Layout::new().candidates(&at("Cmd+-", Key::Num6))), ["Cmd+-", "Cmd+6"]);
|
||||
// Zoom keys: + also runs =, and Shift+= runs +.
|
||||
assert_eq!(texts(&Layout::new().candidates(&at("Cmd+Shift++", Key::Equals))), ["Cmd++", "Cmd+Shift+=", "Cmd+="]);
|
||||
assert_eq!(texts(&Layout::new().candidates(&KeyInput::new(Mods::SHIFT).with_typed(Key::Equals))), ["Shift+=", "+"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_decides_whether_the_layout_is_latin() {
|
||||
let mut layout = Layout::new();
|
||||
assert!(layout.is_latin(), "nothing known counts as Latin");
|
||||
let ctrl_shift_d = at("Cmd+Shift+]", Key::D);
|
||||
// Read as punctuation until the layout is known: ] needs Shift on the D key.
|
||||
assert_eq!(layout.resolve(&ctrl_shift_d), Some(chord("Cmd+]")));
|
||||
|
||||
layout.observe(Key::D, Mods::NONE, "ي");
|
||||
assert!(!layout.is_latin());
|
||||
assert_eq!(layout.resolve(&ctrl_shift_d), Some(chord("Cmd+Shift+D")));
|
||||
|
||||
// Punctuation on a letter key says nothing: Hebrew Q and Dvorak Q both type a symbol.
|
||||
layout.observe(Key::Q, Mods::NONE, "/");
|
||||
assert!(!layout.is_latin());
|
||||
layout.observe(Key::A, Mods::SHIFT, "A");
|
||||
assert!(layout.is_latin());
|
||||
layout.observe(Key::W, Mods::NONE, "ς");
|
||||
assert!(!layout.is_latin());
|
||||
layout.observe(Key::S, Mods::CMD, "s");
|
||||
assert!(!layout.is_latin(), "a command chord teaches nothing");
|
||||
layout.observe(Key::S, Mods::NONE, "š");
|
||||
assert!(layout.is_latin(), "Latin letters beyond ASCII count as Latin");
|
||||
layout.observe(Key::M, Mods::NONE, "µ");
|
||||
assert!(layout.is_latin(), "Latin-1 symbols that count as letters say nothing");
|
||||
|
||||
// What the platform reports wins.
|
||||
let mut reported = Layout::new().with_latin(false);
|
||||
reported.observe(Key::A, Mods::NONE, "a");
|
||||
assert!(!reported.is_latin());
|
||||
reported.set_latin(None);
|
||||
assert!(reported.is_latin());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dvorak_shift_punctuation_never_runs_its_position() {
|
||||
// Dvorak's , key sits on W and types < with Shift, which egui has no key for, so egui
|
||||
// reports the press as W.
|
||||
let ctrl_shift_lt = at("Cmd+Shift+W", Key::W);
|
||||
let mut dvorak = Layout::new();
|
||||
assert_eq!(dvorak.resolve(&ctrl_shift_lt), Some(chord("Cmd+Shift+W")), "nothing known yet");
|
||||
|
||||
dvorak.observe(Key::S, Mods::NONE, "o");
|
||||
assert_eq!(dvorak.resolve(&ctrl_shift_lt), Some(chord("Cmd+Shift+W")), "the W position is unseen");
|
||||
dvorak.observe(Key::W, Mods::NONE, ",");
|
||||
assert_eq!(dvorak.resolve(&ctrl_shift_lt), None);
|
||||
assert!(!dvorak.matches(&chord("Ctrl+Shift+W"), &ctrl_shift_lt, Platform::Windows));
|
||||
// Without Shift, and for letters typed where they sit (Dvorak's A) or elsewhere, presses
|
||||
// resolve as before.
|
||||
assert_eq!(dvorak.resolve(&at("Cmd+W", Key::W)), Some(chord("Cmd+W")));
|
||||
dvorak.observe(Key::A, Mods::NONE, "a");
|
||||
assert_eq!(dvorak.resolve(&at("Cmd+Shift+A", Key::A)), Some(chord("Cmd+Shift+A")));
|
||||
assert_eq!(dvorak.resolve(&at("Cmd+Shift+O", Key::S)), Some(chord("Cmd+Shift+O")));
|
||||
|
||||
// AZERTY: A is moved, but the unseen E position still runs Ctrl+Shift+E.
|
||||
let mut azerty = Layout::new();
|
||||
azerty.observe(Key::Q, Mods::NONE, "a");
|
||||
assert_eq!(azerty.resolve(&at("Cmd+Shift+E", Key::E)), Some(chord("Cmd+Shift+E")));
|
||||
|
||||
// QWERTY: a position typing its own letter keeps the position fallback.
|
||||
let mut qwerty = Layout::new();
|
||||
qwerty.observe(Key::S, Mods::NONE, "s");
|
||||
qwerty.observe(Key::W, Mods::SHIFT, "W");
|
||||
assert_eq!(qwerty.resolve(&ctrl_shift_lt), Some(chord("Cmd+Shift+W")));
|
||||
assert_eq!(qwerty.resolve(&at("Cmd+Shift+E", Key::E)), Some(chord("Cmd+Shift+E")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layout_switch_forgets_what_letter_positions_typed() {
|
||||
// On Dvorak the W position types `,`; after a switch to QWERTY, Ctrl+Shift+W is W again.
|
||||
let ctrl_shift_w = at("Cmd+Shift+W", Key::W);
|
||||
let mut layout = Layout::new().with_latin(true);
|
||||
layout.observe(Key::W, Mods::NONE, ",");
|
||||
assert_eq!(layout.resolve(&ctrl_shift_w), None);
|
||||
layout.set_latin(Some(true));
|
||||
assert_eq!(layout.resolve(&ctrl_shift_w), None, "the same report is the same layout");
|
||||
|
||||
// Dvorak, then Russian, then QWERTY, as the platform reports them.
|
||||
layout.set_latin(Some(false));
|
||||
layout.set_latin(Some(true));
|
||||
assert_eq!(layout.resolve(&ctrl_shift_w), Some(chord("Cmd+Shift+W")));
|
||||
|
||||
// An app that learns of a switch itself.
|
||||
let mut unreported = Layout::new();
|
||||
unreported.observe(Key::W, Mods::NONE, ",");
|
||||
assert_eq!(unreported.resolve(&ctrl_shift_w), None);
|
||||
unreported.forget_letters();
|
||||
assert_eq!(unreported.resolve(&ctrl_shift_w), Some(chord("Cmd+Shift+W")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_show_the_layouts_own_punctuation() {
|
||||
let mut german = Layout::new().with_char(Key::OpenBracket, 'ü').with_char(Key::Slash, '-').with_char(Key::CloseBracket, '+');
|
||||
german.observe(Key::Minus, Mods::NONE, "ß");
|
||||
let label = |layout: &Layout, text: &str, p| chord(text).display_for(p, layout);
|
||||
assert_eq!(label(&german, "Cmd+[", Platform::Windows), "Ctrl+Ü");
|
||||
assert_eq!(label(&german, "Cmd+[", Platform::Mac), "⌘Ü");
|
||||
// German types - at the / position, so Ctrl+- shows -; its + key types a key of its own.
|
||||
assert_eq!(label(&german, "Cmd+-", Platform::Windows), "Ctrl+-");
|
||||
assert_eq!(label(&german, "Cmd+]", Platform::Windows), "Ctrl+]");
|
||||
assert_eq!(label(&german, "Cmd+Z", Platform::Windows), "Ctrl+Z");
|
||||
assert_eq!(label(&german, "Cmd+1", Platform::Windows), "Ctrl+1");
|
||||
|
||||
let russian = Layout::new().with_latin(false).with_char(Key::OpenBracket, 'х');
|
||||
assert_eq!(label(&russian, "Cmd+[", Platform::Linux), "Ctrl+Х");
|
||||
assert_eq!(label(&russian, "Cmd+C", Platform::Linux), "Ctrl+C");
|
||||
assert_eq!(craft_keymap::Trigger::double(chord("[")).display_for(Platform::Linux, &russian), "Х Х");
|
||||
assert_eq!(label(&Layout::new(), "Cmd+[", Platform::Linux), "Ctrl+[");
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
use craft_keymap::{
|
||||
Bindable, Binding, CommandRef, ContextRule, Flavor, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, Keymap, MAX_SETS, Overrides, Platform,
|
||||
Policy, ProfileError, Profiles, Scope, Scopes, SetProblem, Start, plan,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
fn b(text: &str) -> Binding {
|
||||
Binding::parse(text).unwrap_or_else(|e| panic!("{text}: {e}"))
|
||||
}
|
||||
|
||||
fn keymap() -> Keymap {
|
||||
let catalog = vec![
|
||||
Bindable::new("file.save", "Save", Scope::app()).with_path(vec!["File".into(), "Save".into()]).with_default(b("Cmd+S")),
|
||||
Bindable::new("edit.copy", "Copy", Scope::app()).with_path(vec!["Edit".into(), "Copy".into()]).with_default(b("Cmd+C")),
|
||||
Bindable::new(CommandRef::with_params("window.panel", json!({"panel": "layers"})), "Layers", Scope::app()).with_default(b("F7")),
|
||||
Bindable::new("timeline.loop", "Loop", Scope::new("Timeline").unwrap()).with_default(b("L")),
|
||||
];
|
||||
Keymap::new(catalog, Scopes::new().with_panel("Timeline"), Platform::Mac)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profiles_copy_built_ins_on_edit_and_round_trip_as_json() {
|
||||
let mut classic = Overrides::new();
|
||||
classic.insert("edit.copy", vec!["Cmd+Shift+C".into()]);
|
||||
let builtins = [("Craft", Overrides::new()), ("Classic", classic.clone())];
|
||||
let mut p = Profiles::default();
|
||||
assert_eq!(p.active_name(&builtins), "Craft");
|
||||
|
||||
let mut edited = Overrides::new();
|
||||
edited.insert("edit.copy", vec![]);
|
||||
assert_eq!(p.store(edited.clone(), &builtins, "Custom"), Ok(Some("Custom".into())));
|
||||
assert_eq!(p.active_name(&builtins), "Custom");
|
||||
assert_eq!(p.store(Overrides::new(), &builtins, "Custom"), Ok(None), "a user set is edited in place");
|
||||
assert!(p.active_overrides(&builtins).is_empty());
|
||||
|
||||
p.select("Classic", &builtins).unwrap();
|
||||
assert_eq!(p.active_overrides(&builtins), &classic);
|
||||
assert_eq!(p.store(classic.clone(), &builtins, "Custom"), Ok(None), "no change, no copy");
|
||||
assert_eq!(p.store(edited.clone(), &builtins, "Custom"), Ok(Some("Custom 2".into())));
|
||||
assert_eq!(builtins[1].1, classic);
|
||||
|
||||
let exported = p.export("Custom 2", &builtins).unwrap();
|
||||
assert_eq!(p.import(&exported, &builtins), Ok("Custom 3".into()));
|
||||
assert_eq!(p.active_overrides(&builtins), &edited);
|
||||
|
||||
assert_eq!(p.delete("Classic", &builtins), Err(ProfileError::BuiltIn));
|
||||
assert_eq!(p.rename("Custom 3", "classic", &builtins), Err(ProfileError::NameTaken));
|
||||
assert_eq!(p.rename("Custom 3", "Mine", &builtins), Ok("Mine".into()));
|
||||
assert_eq!(p.active(), "Mine");
|
||||
assert_eq!(p.save_as(&"x".repeat(65), Overrides::new(), &builtins), Err(ProfileError::BadName));
|
||||
p.delete("Mine", &builtins).unwrap();
|
||||
assert_eq!(p.active_name(&builtins), "Craft");
|
||||
|
||||
let wrong = exported.replace("craft-keymap", "other");
|
||||
assert_eq!(p.import(&wrong, &builtins), Err(ProfileError::WrongFormat));
|
||||
let newer = exported.replace("\"version\": 1", "\"version\": 2");
|
||||
assert_eq!(p.import(&newer, &builtins), Err(ProfileError::NewerVersion(2)));
|
||||
|
||||
let text = serde_json::to_string(&p).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Profiles>(&text).unwrap(), p);
|
||||
let junk: Profiles = serde_json::from_str(r#"{"active": 5, "sets": {"": {}, "ok": {"a": ["A"]}, "bad": 3}}"#).unwrap();
|
||||
assert_eq!(junk.sets().keys().collect::<Vec<_>>(), ["ok"]);
|
||||
let junk: Profiles =
|
||||
serde_json::from_str(r#"{"sets": [{"name": "ok", "overrides": [{"command": "a", "keys": ["A"]}, 4]}, {"name": ""}, 7]}"#).unwrap();
|
||||
assert_eq!(junk.sets()["ok"].get("a"), Some(&["A".to_string()][..]));
|
||||
assert!(text.contains(r#""overrides":[{"command":"edit.copy","keys":[]}]"#), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_keeps_a_set_whose_name_differs_only_in_case() {
|
||||
let builtins = [("Craft", Overrides::new())];
|
||||
let mut p: Profiles = serde_json::from_str(r#"{"sets": {"Mine": {"a": "A"}, "mine": {"b": "B"}}}"#).unwrap();
|
||||
assert_eq!(p.rename("Mine", "mine", &builtins), Err(ProfileError::NameTaken));
|
||||
assert_eq!(p.sets()["mine"].get("b"), Some(&["B".to_string()][..]));
|
||||
assert_eq!(p.rename("Mine", "MINE", &builtins), Err(ProfileError::NameTaken));
|
||||
p.delete("mine", &builtins).unwrap();
|
||||
assert_eq!(p.rename("Mine", "MINE", &builtins), Ok("MINE".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sets_that_are_not_a_list_or_map_load_as_none() {
|
||||
for text in [r#"{"active": "Mine", "sets": 5}"#, r#"{"active": "Mine", "sets": null}"#, r#"{"active": "Mine", "sets": "x"}"#] {
|
||||
let p: Profiles = serde_json::from_str(text).unwrap_or_else(|e| panic!("{text}: {e}"));
|
||||
assert!(p.sets().is_empty(), "{text}");
|
||||
assert_eq!(p.active(), "Mine", "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_user_set_named_like_a_new_built_in_keeps_its_edits() {
|
||||
let mut mine = Overrides::new();
|
||||
mine.insert("edit.copy", vec!["Cmd+K".into()]);
|
||||
let mut p = Profiles::default();
|
||||
p.save_as("Classic", mine.clone(), &[("Craft", Overrides::new())]).unwrap();
|
||||
|
||||
// An update adds a built-in of that name.
|
||||
let mut classic = Overrides::new();
|
||||
classic.insert("edit.copy", vec!["Cmd+Shift+C".into()]);
|
||||
let builtins = [("Craft", Overrides::new()), ("Classic", classic.clone())];
|
||||
assert_eq!(p.active_overrides(&builtins), &mine, "the user set is what the name reads");
|
||||
|
||||
let mut edited = mine.clone();
|
||||
edited.insert("edit.paste", vec![]);
|
||||
assert_eq!(p.store(edited.clone(), &builtins, "Custom"), Ok(Some("Classic 2".into())));
|
||||
assert_eq!(p.active_name(&builtins), "Classic 2");
|
||||
assert_eq!(p.active_overrides(&builtins), &edited);
|
||||
assert_eq!(p.get("Classic", &builtins), Some(&classic));
|
||||
assert_eq!(builtins[1].1, classic);
|
||||
|
||||
let mut q: Profiles =
|
||||
serde_json::from_value(json!({"active": "CRAFT", "sets": [{"name": "CRAFT", "overrides": {"edit.copy": "Cmd+K"}}]})).unwrap();
|
||||
assert!(q.reconcile(&builtins));
|
||||
assert_eq!(q.active_name(&builtins), "CRAFT 2");
|
||||
assert_eq!(q.active_overrides(&builtins), &mine);
|
||||
assert!(!q.reconcile(&builtins));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exported_set_imports_as_a_new_set_with_the_same_keymap() {
|
||||
let mut km = keymap();
|
||||
km.assign(&"file.save".into(), b("Cmd+Alt+S"), Policy::Steal).unwrap();
|
||||
km.assign(&CommandRef::with_params("window.panel", json!({"panel": "layers"})), b("Timeline: Cmd+L"), Policy::Steal).unwrap();
|
||||
km.clear(&"edit.copy".into());
|
||||
let builtins = [("Craft", Overrides::new())];
|
||||
let mut p = Profiles::default();
|
||||
p.save_as("Mine", km.overrides().clone(), &builtins).unwrap();
|
||||
|
||||
let text = p.export("Mine", &builtins).unwrap();
|
||||
assert_eq!(p.import(&text, &builtins), Ok("Mine 2".into()));
|
||||
assert_eq!(p.active(), "Mine 2");
|
||||
|
||||
let mut again = keymap();
|
||||
again.set_overrides(p.active_overrides(&builtins).clone());
|
||||
for bindable in km.catalog() {
|
||||
assert_eq!(again.bindings(&bindable.command), km.bindings(&bindable.command), "{}", bindable.command.key());
|
||||
}
|
||||
assert_eq!(again.overrides(), km.overrides());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_copies_built_in_and_user_sets() {
|
||||
let mut classic = Overrides::new();
|
||||
classic.insert("edit.copy", vec!["Cmd+Shift+C".into()]);
|
||||
let builtins = [("Craft", Overrides::new()), ("Classic", classic.clone())];
|
||||
let mut p = Profiles::default();
|
||||
|
||||
assert_eq!(p.duplicate("Classic", "Classic", &builtins), Ok("Classic 2".into()));
|
||||
assert_eq!(p.active(), "Classic 2");
|
||||
assert_eq!(p.active_overrides(&builtins), &classic);
|
||||
assert_eq!(p.duplicate("Classic 2", " Mine ", &builtins), Ok("Mine".into()));
|
||||
assert_eq!(p.duplicate("Mine", "mine", &builtins), Ok("mine 2".into()), "names compare without case");
|
||||
assert_eq!(p.duplicate("Nope", "X", &builtins), Err(ProfileError::NotFound));
|
||||
assert_eq!(p.duplicate("Craft", "", &builtins), Err(ProfileError::BadName));
|
||||
|
||||
while p.sets().len() < MAX_SETS {
|
||||
p.duplicate("Craft", "Spare", &builtins).unwrap();
|
||||
}
|
||||
assert_eq!(p.duplicate("Craft", "Spare", &builtins), Err(ProfileError::TooMany));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_foreign_set_imports_as_a_new_set_and_leaves_the_keymap_alone() {
|
||||
let km = keymap();
|
||||
let read = |text: &str| ForeignKey::read(Some("Default"), text, Flavor::Mac);
|
||||
let set = ForeignSet::new(vec![ForeignEntry::new(Some("File"), ["Save"]).with_key(read("Cmd+Shift+S"))]).with_name("Other App");
|
||||
let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], start: Start::Defaults, ..ImportOptions::default() };
|
||||
let planned = plan(&set, &km, &options);
|
||||
let builtins = [("Craft", Overrides::new())];
|
||||
let mut p = Profiles::default();
|
||||
|
||||
let (name, report) = p.import_plan(&planned, &km, None, &builtins).unwrap();
|
||||
assert_eq!(name, "Other App");
|
||||
assert_eq!(report.changed.len(), 1);
|
||||
assert!(km.overrides().is_empty());
|
||||
assert_eq!(p.active(), "Other App");
|
||||
let mut imported = keymap();
|
||||
imported.set_overrides(p.active_overrides(&builtins).clone());
|
||||
assert_eq!(imported.bindings(&"file.save".into()), [b("Cmd+Shift+S")]);
|
||||
|
||||
let (name, _) = p.import_plan(&planned, &km, Some("Craft"), &builtins).unwrap();
|
||||
assert_eq!(name, "Craft 2", "a built-in's name is not reused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_lists_the_sets_it_drops_and_the_store_has_a_version() {
|
||||
let text = r#"{"version": 2, "active": "ok", "sets": [
|
||||
{"name": "ok", "overrides": {}}, {"name": " pad ", "overrides": {}}, {"name": "ok", "overrides": {"a": "A"}}, {"name": "bad", "overrides": 3}
|
||||
]}"#;
|
||||
let p: Profiles = serde_json::from_str(text).unwrap();
|
||||
assert_eq!(p.sets().keys().collect::<Vec<_>>(), ["ok"]);
|
||||
assert!(p.sets()["ok"].is_empty(), "the first of two sets with one name stays");
|
||||
let name = |n: &str| n.to_string();
|
||||
assert_eq!(
|
||||
p.problems(),
|
||||
[
|
||||
SetProblem::NewerVersion(2),
|
||||
SetProblem::BadName { name: name(" pad ") },
|
||||
SetProblem::Duplicate { name: name("ok") },
|
||||
SetProblem::BadOverrides { name: name("bad") }
|
||||
]
|
||||
);
|
||||
|
||||
let many: Vec<_> = (0..MAX_SETS + 3).map(|i| json!({"name": format!("s{i}"), "overrides": {}})).collect();
|
||||
let p: Profiles = serde_json::from_value(json!({ "sets": many })).unwrap();
|
||||
assert_eq!((p.sets().len(), p.problems()), (MAX_SETS, &[SetProblem::TooMany { ignored: 3 }][..]));
|
||||
|
||||
assert_eq!(serde_json::to_value(&p).unwrap()["version"], 1);
|
||||
let unversioned: Profiles = serde_json::from_str(r#"{"active": "x", "sets": []}"#).unwrap();
|
||||
assert!(unversioned.problems().is_empty());
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_keymap::{Bindable, Binding, CommandRef, DropReason, Keymap, Overrides, Platform, Policy, Problem, Profiles, Scope, Scopes};
|
||||
use craft_settings::{Location, OpenOptions, Probe, Settings, SettingsStore};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
|
||||
#[derive(Serialize, Deserialize, Default, Clone, PartialEq, Debug)]
|
||||
#[serde(default)]
|
||||
struct Prefs {
|
||||
general: General,
|
||||
#[serde(with = "craft_keymap::keymap::overrides_list")]
|
||||
shortcuts: Overrides,
|
||||
profiles: Profiles,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Default, Clone, PartialEq, Debug)]
|
||||
#[serde(default)]
|
||||
struct General {
|
||||
language: String,
|
||||
}
|
||||
|
||||
impl Settings for Prefs {
|
||||
const APP_ID: &'static str = "keymaptest";
|
||||
const SCHEMA_VERSION: u32 = 1;
|
||||
}
|
||||
|
||||
fn open(dir: &std::path::Path) -> SettingsStore<Prefs> {
|
||||
let probe = Probe { env: Box::new(|_| None), exe_dir: None, platform_config_dir: None };
|
||||
let options = OpenOptions::new(Location::Dir(dir.to_path_buf())).probe(probe).debounce(Duration::from_millis(10));
|
||||
let (store, report) = SettingsStore::open_with(options);
|
||||
assert!(report.section_errors.is_empty(), "{report:?}");
|
||||
store
|
||||
}
|
||||
|
||||
fn keymap(overrides: Overrides) -> Keymap {
|
||||
let catalog = vec![
|
||||
Bindable::new(CommandRef::with_params("window.panel", json!({"panel": "layers"})), "Layers", Scope::app()),
|
||||
Bindable::new("text.bold", "Bold", Scope::app()),
|
||||
Bindable::new("edit.copy", "Copy", Scope::app()).with_default(Binding::parse("Cmd+C").unwrap()),
|
||||
Bindable::new("edit.paste", "Paste", Scope::app()).with_default(Binding::parse("Cmd+V").unwrap()),
|
||||
];
|
||||
Keymap::new(catalog, Scopes::new().with_context("Text"), Platform::Mac).with_overrides(overrides)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overrides_round_trip_through_craft_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut km = keymap(Overrides::new());
|
||||
let layers = CommandRef::with_params("window.panel", json!({"panel": "layers"}));
|
||||
km.assign(&layers, Binding::parse("Cmd+Shift+L").unwrap(), Policy::Steal).unwrap();
|
||||
km.assign(&"text.bold".into(), Binding::parse("Text: Cmd+B").unwrap(), Policy::Steal).unwrap();
|
||||
km.clear(&"edit.copy".into());
|
||||
|
||||
let mut store = open(tmp.path());
|
||||
store.update(|p| {
|
||||
p.shortcuts = km.overrides().clone();
|
||||
p.profiles.save_as("Mine", km.overrides().clone(), &[]).unwrap();
|
||||
p.profiles.save_as("Spare", Overrides::new(), &[]).unwrap();
|
||||
});
|
||||
store.flush().unwrap();
|
||||
|
||||
// A hand edit: one text that does not parse, one value that is not a list.
|
||||
let path = tmp.path().join("config.toml");
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let edit = r#"shortcuts = [{ command = "edit.paste", keys = ["Cmd+Nope"] }, { command = "edit.cut", keys = 5 }, "#;
|
||||
assert!(text.contains("shortcuts = ["), "{text}");
|
||||
std::fs::write(&path, text.replacen("shortcuts = [", edit, 1)).unwrap();
|
||||
|
||||
let mut store = open(tmp.path());
|
||||
let mut km = keymap(store.get().shortcuts.clone());
|
||||
assert_eq!(km.bindings(&layers), vec![Binding::parse("Cmd+Shift+L").unwrap()]);
|
||||
assert_eq!(km.bindings(&"text.bold".into()), vec![Binding::parse("Text: Cmd+B").unwrap()]);
|
||||
assert!(km.bindings(&"edit.copy".into()).is_empty());
|
||||
assert_eq!(km.bindings(&"edit.paste".into()), vec![Binding::parse("Cmd+V").unwrap()], "nothing readable: the defaults");
|
||||
assert_eq!(km.overrides().get("edit.paste"), Some(&["Cmd+Nope".to_string()][..]));
|
||||
let problems = km.problems();
|
||||
assert!(problems.contains(&Problem::Dropped { key: "edit.cut".into(), reason: DropReason::NotAList }), "{problems:?}");
|
||||
assert!(problems.iter().any(|p| matches!(p, Problem::BadBinding { text, .. } if text == "Cmd+Nope")), "{problems:?}");
|
||||
assert_eq!(store.get().profiles.sets().len(), 2);
|
||||
|
||||
store.update(|p| p.general.language = "de".into());
|
||||
store.flush().unwrap();
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(text.contains("keys = [\"Cmd+Nope\"]"), "{text}");
|
||||
assert!(
|
||||
text.contains(r#"command = "window.panel {\"panel\":\"layers\"}""#) || text.contains(r#"command = 'window.panel {"panel":"layers"}'"#),
|
||||
"{text}"
|
||||
);
|
||||
assert_eq!(open(tmp.path()).get().shortcuts, store.get().shortcuts);
|
||||
|
||||
// Removals reach the file.
|
||||
km.reset(&layers);
|
||||
store.update(|p| {
|
||||
p.shortcuts = km.overrides().clone();
|
||||
p.profiles.delete("Spare", &[]).unwrap();
|
||||
});
|
||||
store.flush().unwrap();
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let line = text.lines().find(|l| l.starts_with("shortcuts = ")).unwrap();
|
||||
assert!(!line.contains("window.panel") && !text.contains("Spare"), "{text}");
|
||||
let reloaded = open(tmp.path());
|
||||
assert!(keymap(reloaded.get().shortcuts.clone()).bindings(&layers).is_empty());
|
||||
assert_eq!(reloaded.get().profiles.sets().keys().collect::<Vec<_>>(), ["Mine"]);
|
||||
assert_eq!(reloaded.get().profiles.sets()["Mine"].get("text.bold"), Some(&["Text: Cmd+B".to_string()][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hand_written_array_of_tables_and_map_forms_load() {
|
||||
for text in [
|
||||
"schema_version = 1\n\n[[shortcuts]]\ncommand = \"edit.copy\"\nkeys = [\"Cmd+K\"]\n\n[[shortcuts]]\ncommand = \"edit.paste\"\nkeys = []\n",
|
||||
"schema_version = 1\n\n[shortcuts]\n\"edit.copy\" = [\"Cmd+K\"]\n\"edit.paste\" = []\n",
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::write(tmp.path().join("config.toml"), text).unwrap();
|
||||
let km = keymap(open(tmp.path()).get().shortcuts.clone());
|
||||
assert_eq!(km.bindings(&"edit.copy".into()), vec![Binding::parse("Cmd+K").unwrap()], "{text}");
|
||||
assert!(km.bindings(&"edit.paste".into()).is_empty(), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shortcuts_value_that_is_not_a_list_loads_as_no_overrides() {
|
||||
for value in ["\"x\"", "5", "true"] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let text = format!("schema_version = 1\nshortcuts = {value}\n\n[general]\nlanguage = \"de\"\n");
|
||||
std::fs::write(tmp.path().join("config.toml"), text).unwrap();
|
||||
let store = open(tmp.path());
|
||||
assert!(store.get().shortcuts.is_empty(), "{value}");
|
||||
assert_eq!(store.get().general.language, "de", "{value}");
|
||||
let problems = keymap(store.get().shortcuts.clone()).problems();
|
||||
assert_eq!(problems, vec![Problem::Dropped { key: String::new(), reason: DropReason::NotAList }], "{value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sets_value_that_is_not_a_list_keeps_the_rest_of_the_profiles() {
|
||||
for value in ["\"x\"", "5", "true"] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let text = format!("schema_version = 1\n\n[profiles]\nactive = \"Mine\"\nsets = {value}\n");
|
||||
std::fs::write(tmp.path().join("config.toml"), text).unwrap();
|
||||
let store = open(tmp.path());
|
||||
assert_eq!(store.get().profiles.active(), "Mine", "{value}");
|
||||
assert!(store.get().profiles.sets().is_empty(), "{value}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Deterministic app-supplied fonts for dialog tests, including their first layout pass.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use egui::{FontData, FontDefinitions, FontId};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
// Assets from craft-fonts b076417b5880bd4154bd22f00695b1d28c6bea83. Keep the
|
||||
// input outside this repository; do not fall back to machine-installed fonts.
|
||||
const INPUTS: [(&str, &str, &str); 2] = [
|
||||
("keymap-symbols", "fonts/noto-sans-symbols/NotoSansSymbols.ttf", "f7e7e04b4a24b6c78893d50cbfd2b2f6cae49617ab047bfef668d252adb128f7"),
|
||||
(
|
||||
"keymap-symbols-2",
|
||||
"fonts/noto-sans-symbols-2/NotoSansSymbols2-Regular.ttf",
|
||||
"7d5fb73b7ca67a6798101741f5d280a3d016a56a197afcd4199dbb57b4b82a21",
|
||||
),
|
||||
];
|
||||
|
||||
fn definitions() -> FontDefinitions {
|
||||
static FONTS: OnceLock<FontDefinitions> = OnceLock::new();
|
||||
FONTS
|
||||
.get_or_init(|| {
|
||||
let root = PathBuf::from(std::env::var_os("CRAFT_FONTS_DIR").unwrap_or_else(|| {
|
||||
panic!("UI tests require absolute CRAFT_FONTS_DIR at craft-fonts b076417b5880bd4154bd22f00695b1d28c6bea83; see README.md")
|
||||
}));
|
||||
assert!(root.is_absolute(), "CRAFT_FONTS_DIR must be absolute: {}", root.display());
|
||||
let mut fonts = FontDefinitions::default();
|
||||
assert!(fonts.font_data.contains_key("Hack"), "UI tests require egui default_fonts");
|
||||
for (name, relative, expected) in INPUTS {
|
||||
let path = root.join(relative);
|
||||
let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("required font {}: {e}", path.display()));
|
||||
assert_eq!(format!("{:x}", Sha256::digest(&bytes)), expected, "unreviewed font input: {}", path.display());
|
||||
fonts.font_data.insert(name.into(), Arc::new(FontData::from_owned(bytes)));
|
||||
}
|
||||
for family in fonts.families.values_mut() {
|
||||
for name in ["keymap-symbols", "keymap-symbols-2", "Hack"] {
|
||||
if !family.iter().any(|existing| existing == name) {
|
||||
family.push(name.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
fonts
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub fn configure(ctx: &egui::Context) {
|
||||
ctx.set_fonts(definitions());
|
||||
}
|
||||
|
||||
/// All printable ASCII plus the key symbols, dialog icons and accented pseudolocale
|
||||
/// repertoire. Direction marks are intentionally invisible, rather than drawn glyphs.
|
||||
pub fn assert_coverage(ctx: &egui::Context) {
|
||||
const SYMBOLS: &str = "×·—“”…‹›←↑→↓↩↺⇥⇧⌃⌘⌥⌦⌫⎋⏎⌨▾⚠✕⟦⟧ÅÉØáëïöüÜ";
|
||||
ctx.fonts_mut(|fonts| {
|
||||
for font in [FontId::proportional(16.0), FontId::monospace(16.0)] {
|
||||
for c in (' '..='~').chain(SYMBOLS.chars()) {
|
||||
assert!(fonts.has_glyph(&font, c), "test font {:?} lacks {c} (U+{:04X})", font.family, u32::from(c));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,156 @@
|
||||
//! The catalog the dialog tests and screenshots use.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::BTreeSet;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_keymap::ui::{PLURALS, STRINGS, Text};
|
||||
use craft_keymap::{Bindable, Binding, Key, Keymap, Kind, Platform, Scope, Scopes};
|
||||
|
||||
fn binding(text: &str) -> Binding {
|
||||
Binding::parse(text).unwrap_or_else(|e| panic!("{text}: {e}"))
|
||||
}
|
||||
|
||||
pub fn fixture(platform: Platform) -> Keymap {
|
||||
let tool = Kind::Tool { group: Some("Marquee".into()) };
|
||||
let path = |p: &[&str]| p.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
let timeline = Scope::new("Timeline").unwrap_or_else(Scope::app);
|
||||
let catalog = vec![
|
||||
Bindable::new("file.save", "Save", Scope::app()).with_path(path(&["File", "Save"])).with_default(binding("Cmd+S")),
|
||||
Bindable::new("file.saveAs", "Save As…", Scope::app()).with_path(path(&["File", "Save As…"])).with_default(binding("Cmd+Shift+S")),
|
||||
Bindable::new("file.export", "Export…", Scope::app()).with_path(path(&["File", "Export…"])).with_default(binding("Cmd+E")),
|
||||
Bindable::new("object.front", "Bring to Front", Scope::app()).with_path(path(&["Object", "Arrange", "Bring to Front"])),
|
||||
Bindable::new("tool.marquee", "Marquee Tool", Scope::app()).with_kind(tool.clone()).with_default(binding("M")),
|
||||
Bindable::new("tool.ellipse", "Elliptical Marquee Tool", Scope::app()).with_kind(tool).with_default(binding("M")),
|
||||
Bindable::new("timeline.loop", "Loop", timeline).with_default(binding("L")),
|
||||
Bindable::new("type.bold", "Bold", Scope::app()).with_default(binding("Text: Cmd+B")),
|
||||
];
|
||||
Keymap::new(catalog, Scopes::new().with_panel("Timeline").with_context("Text"), platform)
|
||||
}
|
||||
|
||||
/// `km` with a command whose label and menu path are far too long for a row.
|
||||
#[allow(dead_code)]
|
||||
pub fn with_long_label(km: Keymap) -> Keymap {
|
||||
let long = "Distribute Selected Objects Evenly Along the Active Guide Path and Keep Their Spacing".to_string();
|
||||
let mut catalog = km.catalog().to_vec();
|
||||
catalog.insert(
|
||||
3,
|
||||
Bindable::new("object.distribute", long.as_str(), Scope::app())
|
||||
.with_path(vec!["Object".into(), "Arrange and Distribute Along a Path".into(), long.clone()])
|
||||
.with_default(binding("Cmd+Alt+Shift+D"))
|
||||
.with_default(binding("Ctrl+Alt+Shift+F12")),
|
||||
);
|
||||
Keymap::new(catalog, Scopes::new().with_panel("Timeline").with_context("Text"), km.platform())
|
||||
}
|
||||
|
||||
/// A pseudo translation: every string about 40 % longer, accented, between right-to-left marks and
|
||||
/// in `⟦…⟧`, so text drawn without the marks never went through [`Text`]. Placeholders stay as
|
||||
/// they are. Labels and path parts are marked too. Looked-up dialog strings missing from
|
||||
/// `STRINGS` or `PLURALS` are collected in `unlisted`.
|
||||
#[allow(dead_code)]
|
||||
#[derive(Default)]
|
||||
pub struct Pseudo {
|
||||
pub unlisted: Rc<RefCell<BTreeSet<String>>>,
|
||||
/// Lay the dialog out right to left.
|
||||
pub rtl: bool,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
impl Pseudo {
|
||||
pub fn mark(source: &str) -> String {
|
||||
let mut out = String::from("⟦\u{200F}");
|
||||
let mut in_placeholder = false;
|
||||
let mut letters = 0;
|
||||
for c in source.chars() {
|
||||
match c {
|
||||
'{' => in_placeholder = true,
|
||||
'}' => in_placeholder = false,
|
||||
_ => {}
|
||||
}
|
||||
let accented = match c {
|
||||
_ if in_placeholder => c,
|
||||
'a' => 'á',
|
||||
'e' => 'ë',
|
||||
'i' => 'ï',
|
||||
'o' => 'ö',
|
||||
'u' => 'ü',
|
||||
'A' => 'Å',
|
||||
'E' => 'É',
|
||||
'O' => 'Ø',
|
||||
_ => c,
|
||||
};
|
||||
if !in_placeholder && c.is_alphabetic() {
|
||||
letters += 1;
|
||||
}
|
||||
out.push(accented);
|
||||
}
|
||||
out.extend(std::iter::repeat_n('~', letters * 2 / 5));
|
||||
out.push_str("\u{200F}⟧");
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Text for Pseudo {
|
||||
fn ui<'a>(&'a self, source: &'a str) -> Cow<'a, str> {
|
||||
if !STRINGS.contains(&source) {
|
||||
self.unlisted.borrow_mut().insert(source.to_string());
|
||||
}
|
||||
Pseudo::mark(source).into()
|
||||
}
|
||||
|
||||
fn plural(&self, n: u64, one: &str, other: &str) -> String {
|
||||
if !PLURALS.contains(&(one, other)) {
|
||||
self.unlisted.borrow_mut().insert(format!("{one}|{other}"));
|
||||
}
|
||||
Pseudo::mark(if n == 1 { one } else { other }).replace("{n}", &n.to_string())
|
||||
}
|
||||
|
||||
fn command<'a>(&'a self, b: &'a Bindable) -> Cow<'a, str> {
|
||||
Pseudo::mark(&b.label).into()
|
||||
}
|
||||
|
||||
fn segment<'a>(&'a self, s: &'a str) -> Cow<'a, str> {
|
||||
Pseudo::mark(s).into()
|
||||
}
|
||||
|
||||
/// Key names spelled out in words (Escape, Space), on every platform.
|
||||
fn key(&self, k: Key, _p: Platform) -> Option<String> {
|
||||
let name = k.to_string();
|
||||
name.chars().any(|c| c.is_ascii_lowercase()).then(|| Pseudo::mark(&name))
|
||||
}
|
||||
|
||||
fn rtl(&self) -> bool {
|
||||
self.rtl
|
||||
}
|
||||
}
|
||||
|
||||
/// English laid out right to left, to look at the mirrored layout.
|
||||
#[allow(dead_code)]
|
||||
pub struct EnglishRtl;
|
||||
|
||||
impl Text for EnglishRtl {
|
||||
fn ui<'a>(&'a self, source: &'a str) -> Cow<'a, str> {
|
||||
source.into()
|
||||
}
|
||||
|
||||
fn plural(&self, n: u64, one: &str, other: &str) -> String {
|
||||
(if n == 1 { one } else { other }).replace("{n}", &n.to_string())
|
||||
}
|
||||
|
||||
fn rtl(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The words stay in English order; spaces at either end change sides, as in a right-to-left
|
||||
/// paragraph.
|
||||
fn visual(&self, s: &str) -> String {
|
||||
let core = s.trim();
|
||||
if core.is_empty() {
|
||||
return s.to_string();
|
||||
}
|
||||
let start = s.len() - s.trim_start().len();
|
||||
let end = s.trim_end().len();
|
||||
format!("{}{core}{}", &s[end..], &s[..start])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
#![cfg(feature = "snapshot")]
|
||||
//! Screenshots of the Keyboard Shortcuts dialog for review, not a golden comparison. With
|
||||
//! `CRAFT_KEYMAP_SNAPSHOT_DIR` set, writes PNGs of a few states in light and dark at 1× and 2×;
|
||||
//! without it the test does nothing.
|
||||
//!
|
||||
//! `CRAFT_KEYMAP_SNAPSHOT_DIR=/tmp/shots cargo test -p craft-keymap --features snapshot --test ui_snapshot`
|
||||
//!
|
||||
//! Uses the same hash-verified `CRAFT_FONTS_DIR` input as ui_dialog (see README.md).
|
||||
//! Fonts are installed before the first layout pass; missing glyphs remain errors.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use craft_keymap::ui::{DialogState, English, Options, ShortcutsDialog, Text};
|
||||
use craft_keymap::{ContextRule, Flavor, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, Keymap, Overrides, Platform, Profiles};
|
||||
use egui::{Key as EguiKey, Modifiers, Theme, Vec2};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use ui_fixture::{EnglishRtl, Pseudo, fixture, with_long_label};
|
||||
|
||||
#[path = "support/fonts.rs"]
|
||||
mod test_fonts;
|
||||
mod ui_fixture;
|
||||
|
||||
struct Fx {
|
||||
km: Keymap,
|
||||
text: Box<dyn Text>,
|
||||
options: Options,
|
||||
state: DialogState,
|
||||
sets: Option<(Profiles, Vec<(&'static str, Overrides)>)>,
|
||||
}
|
||||
|
||||
impl Fx {
|
||||
fn dialog(&mut self) -> (ShortcutsDialog<'_>, &mut DialogState) {
|
||||
let Fx { km, text, options, state, sets } = self;
|
||||
let d = ShortcutsDialog::new(km, &**text).options(options);
|
||||
let d = match sets {
|
||||
Some((p, b)) => d.sets(p, b),
|
||||
None => d,
|
||||
};
|
||||
(d, state)
|
||||
}
|
||||
}
|
||||
|
||||
/// A named state of the dialog: window size and what to do before the picture.
|
||||
struct Case {
|
||||
name: &'static str,
|
||||
size: Vec2,
|
||||
platform: Platform,
|
||||
/// Show named sets.
|
||||
sets: bool,
|
||||
/// Show the on-screen keyboard.
|
||||
keyboard: bool,
|
||||
words: Words,
|
||||
/// Add a command with a very long label and name the user set at length.
|
||||
long: bool,
|
||||
act: fn(&mut Harness<'_, Fx>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Words {
|
||||
English,
|
||||
/// English laid out right to left.
|
||||
Rtl,
|
||||
/// The pseudo translation of the tests, left to right.
|
||||
Pseudo,
|
||||
}
|
||||
|
||||
impl Case {
|
||||
const fn new(name: &'static str, width: f32, height: f32, act: fn(&mut Harness<'_, Fx>)) -> Case {
|
||||
Case { name, size: Vec2::new(width, height), platform: Platform::Mac, sets: false, keyboard: false, words: Words::English, long: false, act }
|
||||
}
|
||||
|
||||
const fn windows(mut self) -> Case {
|
||||
self.platform = Platform::Windows;
|
||||
self
|
||||
}
|
||||
|
||||
const fn sets(mut self) -> Case {
|
||||
self.sets = true;
|
||||
self
|
||||
}
|
||||
|
||||
const fn keyboard(mut self) -> Case {
|
||||
self.keyboard = true;
|
||||
self
|
||||
}
|
||||
|
||||
const fn words(mut self, words: Words) -> Case {
|
||||
self.words = words;
|
||||
self
|
||||
}
|
||||
|
||||
const fn long(mut self) -> Case {
|
||||
self.long = true;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
fn foreign_review(h: &mut Harness<'_, Fx>) {
|
||||
let read = |text: &str| ForeignKey::read(Some("Default"), text, Flavor::Windows);
|
||||
let set = ForeignSet::new(vec![
|
||||
ForeignEntry::new(Some("File"), ["Save"]).with_key(read("Ctrl+Alt+S")).at_line(3),
|
||||
ForeignEntry::new(Some("File"), ["Frobnicate"]).with_key(read("Ctrl+F")).at_line(4),
|
||||
ForeignEntry::new(Some("File"), ["Export…"]).with_key(read("Ctrl+Blorp")).at_line(5),
|
||||
ForeignEntry::new(Some("Object"), ["Arrange", "Bring to Front"]).with_key(read("Num 7")).at_line(6),
|
||||
ForeignEntry::new(Some("File"), ["Sve Az"]).with_key(read("Ctrl+F9")).at_line(7),
|
||||
])
|
||||
.with_name("Theirs");
|
||||
let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], suggest: true, ..ImportOptions::default() };
|
||||
let (d, state) = h.state_mut().dialog();
|
||||
d.review_import(state, set, options);
|
||||
h.run();
|
||||
}
|
||||
|
||||
fn click(h: &mut Harness<'_, Fx>, label: &str) {
|
||||
h.get_by_label(label).click();
|
||||
h.run();
|
||||
}
|
||||
|
||||
fn select(h: &mut Harness<'_, Fx>, label: &str) {
|
||||
h.get_by_label(label).click();
|
||||
h.run();
|
||||
}
|
||||
|
||||
const CASES: &[Case] = &[
|
||||
Case::new("selected", 1000.0, 640.0, |h| select(h, "Save As…")),
|
||||
Case::new("conflict", 1000.0, 640.0, |h| {
|
||||
click(h, "Export…: ⌘E");
|
||||
h.key_press_modifiers(Modifiers::COMMAND, EguiKey::S);
|
||||
h.run();
|
||||
}),
|
||||
Case::new("recording", 1000.0, 640.0, |h| click(h, "Save: Ctrl+S")).windows(),
|
||||
Case::new("narrow", 560.0, 640.0, |h| select(h, "Save")),
|
||||
Case::new("sets", 1000.0, 640.0, |h| {
|
||||
click(h, "Save: ⌘S");
|
||||
h.key_press(EguiKey::F2);
|
||||
h.run();
|
||||
click(h, "New Set…");
|
||||
})
|
||||
.sets(),
|
||||
Case::new("sets-narrow", 560.0, 640.0, |h| click(h, "More")).sets(),
|
||||
Case::new("keyboard", 1100.0, 720.0, |h| {
|
||||
click(h, "Save As…");
|
||||
click(h, "⌘ Command");
|
||||
click(h, "⌘S: Save");
|
||||
})
|
||||
.keyboard(),
|
||||
Case::new("keyboard-windows", 860.0, 640.0, |h| click(h, "L: Loop (Timeline)")).windows().keyboard(),
|
||||
Case::new("review", 1000.0, 640.0, foreign_review).sets(),
|
||||
Case::new("long", 1000.0, 640.0, |h| {
|
||||
let state = &mut h.state_mut().state;
|
||||
state.select(&craft_keymap::CommandRef::from("object.distribute"));
|
||||
h.run();
|
||||
})
|
||||
.sets()
|
||||
.long(),
|
||||
Case::new("long-narrow", 560.0, 640.0, |h| {
|
||||
h.state_mut().state.select(&craft_keymap::CommandRef::from("object.distribute"));
|
||||
h.run();
|
||||
})
|
||||
.sets()
|
||||
.long(),
|
||||
Case::new("rtl", 1000.0, 640.0, |h| {
|
||||
click(h, "Export…: ⌘E");
|
||||
h.key_press_modifiers(Modifiers::COMMAND, EguiKey::S);
|
||||
h.run();
|
||||
})
|
||||
.sets()
|
||||
.long()
|
||||
.words(Words::Rtl),
|
||||
Case::new("rtl-narrow", 560.0, 640.0, |h| select(h, "Bold")).words(Words::Rtl).long(),
|
||||
Case::new("rtl-keyboard", 1100.0, 720.0, |h| click(h, "L: Loop (Timeline)")).keyboard().words(Words::Rtl),
|
||||
Case::new("rtl-review", 1000.0, 640.0, foreign_review).sets().words(Words::Rtl),
|
||||
Case::new("pseudo", 1100.0, 720.0, |h| {
|
||||
h.state_mut().state.select(&craft_keymap::CommandRef::from("file.save"));
|
||||
h.run();
|
||||
})
|
||||
.sets()
|
||||
.keyboard()
|
||||
.long()
|
||||
.words(Words::Pseudo),
|
||||
Case::new("pseudo-narrow", 560.0, 640.0, |h| {
|
||||
h.state_mut().state.select(&craft_keymap::CommandRef::from("object.distribute"));
|
||||
h.run();
|
||||
})
|
||||
.sets()
|
||||
.long()
|
||||
.words(Words::Pseudo),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn dialog_screenshots() {
|
||||
let Some(dir) = std::env::var_os("CRAFT_KEYMAP_SNAPSHOT_DIR").map(PathBuf::from) else { return };
|
||||
std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
|
||||
// `CRAFT_KEYMAP_SNAPSHOT_ONLY=keyboard` renders only the cases whose name starts with it.
|
||||
let only = std::env::var("CRAFT_KEYMAP_SNAPSHOT_ONLY").unwrap_or_default();
|
||||
for case in CASES.iter().filter(|c| c.name.starts_with(&only)) {
|
||||
for (theme_name, theme) in [("light", Theme::Light), ("dark", Theme::Dark)] {
|
||||
for scale in [1.0, 2.0] {
|
||||
let sets = case.sets.then(|| {
|
||||
let mut p = Profiles::default();
|
||||
let builtins = vec![("Fixture Defaults", Overrides::new())];
|
||||
if case.long {
|
||||
let name = "My Shortcuts for Long Evenings of Retouching Photographs";
|
||||
if let Err(e) = p.save_as(name, Overrides::new(), &builtins).and_then(|n| p.select(&n, &builtins)) {
|
||||
panic!("{name}: {e}");
|
||||
}
|
||||
}
|
||||
(p, builtins)
|
||||
});
|
||||
let options = Options::default().with(|o| o.keyboard = case.keyboard);
|
||||
let km = if case.long { with_long_label(fixture(case.platform)) } else { fixture(case.platform) };
|
||||
let text: Box<dyn Text> = match case.words {
|
||||
Words::English => Box::new(English),
|
||||
Words::Rtl => Box::new(EnglishRtl),
|
||||
Words::Pseudo => Box::new(Pseudo::default()),
|
||||
};
|
||||
let fx = Fx { km, text, options, state: DialogState::new(), sets };
|
||||
let mut h = Harness::builder()
|
||||
.with_size(case.size)
|
||||
.with_pixels_per_point(scale)
|
||||
.with_theme(theme)
|
||||
.with_context_setup(test_fonts::configure)
|
||||
.wgpu()
|
||||
.build_ui_state(
|
||||
|ui, fx: &mut Fx| {
|
||||
test_fonts::assert_coverage(ui.ctx());
|
||||
egui::Frame::central_panel(ui.style()).show(ui, |ui| {
|
||||
let (d, state) = fx.dialog();
|
||||
d.ui(ui, state);
|
||||
});
|
||||
},
|
||||
fx,
|
||||
);
|
||||
h.run();
|
||||
(case.act)(&mut h);
|
||||
let image = h.render().unwrap_or_else(|e| panic!("render {}: {e}", case.name));
|
||||
let path = dir.join(format!("shortcuts-{}-{theme_name}@{scale}x.png", case.name));
|
||||
image.save(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Portable regressions adapted from PdfCraft 7437bde378f43856eada40af25b983812e615e8a (MIT OR Apache-2.0).
|
||||
//! Portable regressions adapted from PdfCraft 7437bde378f43856eada40af25b983812e615e8a and
|
||||
//! a2ec27b4775f53c40cad3456936d9406611e3a8d (MIT OR Apache-2.0).
|
||||
#![cfg(feature = "raster")]
|
||||
use craft_pdf::{
|
||||
open_slice,
|
||||
@@ -269,3 +270,161 @@ fn tiff_predictor_packed_rgb_image_renders_every_row() {
|
||||
assert_eq!(pixel(10), &[255, 0, 0, 255]);
|
||||
assert_eq!(pixel(30), &[0, 255, 0, 255]);
|
||||
}
|
||||
|
||||
// An 8 x 4 all-black Group 4 stream, hand-encoded from ITU-T T.6: one horizontal-mode row
|
||||
// (white 0, black 8), three V0 rows, then EOFB.
|
||||
const ALL_BLACK_8X4: [u8; 6] = [0x26, 0xa2, 0xfe, 0x00, 0x20, 0x02];
|
||||
|
||||
fn fax_page(space: &str, params: &str) -> Pixels {
|
||||
let content = "q 20 0 0 20 5 5 cm /Im1 Do Q";
|
||||
let mut pdf = format!(
|
||||
"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents 4 0 R /Resources << /XObject << /Im1 5 0 R >> >> >> endobj
|
||||
4 0 obj << /Length {} >> stream
|
||||
{content}
|
||||
endstream endobj
|
||||
5 0 obj << /Type /XObject /Subtype /Image /Width 8 /Height 4 /ColorSpace {space} /BitsPerComponent 1 /Filter /CCITTFaxDecode /DecodeParms << /K -1 /Columns 8 {params} >> /Length {} >> stream\n",
|
||||
content.len(),
|
||||
ALL_BLACK_8X4.len()
|
||||
)
|
||||
.into_bytes();
|
||||
pdf.extend_from_slice(&ALL_BLACK_8X4);
|
||||
pdf.extend_from_slice(b"\nendstream endobj\ntrailer << /Root 1 0 R >>\n%%EOF");
|
||||
render(&pdf)
|
||||
}
|
||||
|
||||
fn pixel(page: &Pixels, x: u32, y: u32) -> &[u8] {
|
||||
let i = ((y * page.width + x) * 4) as usize;
|
||||
&page.rgba[i..i + 4]
|
||||
}
|
||||
|
||||
/// Scanners and fax services write Group 4 pages with `/Rows 0`, which ISO 32000-2 Table 11
|
||||
/// defines as "height not predetermined" (the default), not as zero rows.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), test)]
|
||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
||||
fn group4_fax_with_rows_zero_decodes_to_the_image_height() {
|
||||
for rows in ["", "/Rows 4", "/Rows 0"] {
|
||||
let page = fax_page("/DeviceGray", rows);
|
||||
assert_eq!(pixel(&page, 15, 24), &[0, 0, 0, 255], "{rows:?}: the fax image paints black");
|
||||
assert_eq!(pixel(&page, 1, 38), &[255, 255, 255, 255], "{rows:?}: outside the image stays white");
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft #3308: a fax image whose `/Rows` is below its `/Height` is decoded to its height.
|
||||
/// `/BlackIs1` turns the fixture white, so rows left undecoded show as black. Also through an
|
||||
/// `/Indexed` color space, the filter's other output path.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), test)]
|
||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
||||
fn group4_fax_with_rows_below_its_height_decodes_to_the_image_height() {
|
||||
for (space, rows) in [("/DeviceGray", "/Rows 2"), ("[/Indexed /DeviceRGB 1 <000000FFFFFF>]", "/Rows 2"), ("/DeviceGray", "/Rows 4")] {
|
||||
let page = fax_page(space, &format!("{rows} /BlackIs1 true"));
|
||||
for y in [17, 22, 27, 32] {
|
||||
assert_eq!(pixel(&page, 15, y), &[255, 255, 255, 255], "{space} {rows}: image row at y {y} is decoded");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft ledger hayro-interpret P2 (#3178): a shaded Type 3 glyph clips to its `/FontBBox` in
|
||||
/// device space at every position, not to the glyph-space box.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), test)]
|
||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
||||
fn shaded_type3_glyph_draws_at_multiple_positions() {
|
||||
let content = "BT /F 30 Tf 1 0 0 1 50 70 Tm (A) Tj 1 0 0 1 220 70 Tm (A) Tj ET";
|
||||
let glyph = "100 0 d0 0 0 100 100 re W n /S sh";
|
||||
let pdf = format!(
|
||||
"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 150] /Resources << /Font << /F 5 0 R >> >> /Contents 4 0 R >> endobj
|
||||
4 0 obj << /Length {} >> stream
|
||||
{content}
|
||||
endstream endobj
|
||||
5 0 obj << /Type /Font /Subtype /Type3 /FontBBox [0 0 100 100] /FontMatrix [0.01 0 0 0.01 0 0] /CharProcs << /A 6 0 R >> /Encoding << /Differences [65 /A] >> /FirstChar 65 /LastChar 65 /Widths [100] /Resources << /Shading << /S 7 0 R >> >> >> endobj
|
||||
6 0 obj << /Length {} >> stream
|
||||
{glyph}
|
||||
endstream endobj
|
||||
7 0 obj << /ShadingType 2 /ColorSpace /DeviceRGB /Coords [0 0 100 0] /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> /Extend [true true] >> endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF",
|
||||
content.len(),
|
||||
glyph.len()
|
||||
);
|
||||
let page = render(pdf.as_bytes());
|
||||
for x in [65, 235] {
|
||||
let px = pixel(&page, x, 65);
|
||||
assert!(px[0] < 240 && px[2] < 240 && px[1] < 10, "glyph at {x}: {px:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft ledger hayro-interpret (26) extension: comma-below letters in non-embedded standard
|
||||
/// fonts are the letter with the font's comma under it, apart from the letter and inside the
|
||||
/// descender, whichever name the font gives them (`/scommaaccent`, `/Kcedilla`, `/uni0219`).
|
||||
#[cfg_attr(not(target_arch = "wasm32"), test)]
|
||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
||||
fn comma_below_letters_in_standard_fonts_draw_a_comma_under_the_letter() {
|
||||
let pairs = [
|
||||
("s", "uni0219"),
|
||||
("t", "uni021B"),
|
||||
("T", "uni021A"),
|
||||
("K", "uni0136"),
|
||||
("k", "kcedilla"),
|
||||
("G", "uni0122"),
|
||||
("G", "Gcedilla"),
|
||||
("R", "uni0156"),
|
||||
("s", "scommaaccent"),
|
||||
("S", "Scommaaccent"),
|
||||
("t", "tcommaaccent"),
|
||||
("T", "Tcommaaccent"),
|
||||
("k", "kcommaaccent"),
|
||||
("K", "Kcommaaccent"),
|
||||
("l", "lcommaaccent"),
|
||||
("L", "Lcommaaccent"),
|
||||
("n", "ncommaaccent"),
|
||||
("N", "Ncommaaccent"),
|
||||
("r", "rcommaaccent"),
|
||||
("R", "Rcommaaccent"),
|
||||
("G", "Gcommaaccent"),
|
||||
];
|
||||
let letters: Vec<&str> = pairs.iter().flat_map(|(base, accented)| [*base, *accented]).collect();
|
||||
let (size, baseline) = (40u32, 60u32);
|
||||
for font in ["Helvetica", "Times-Roman", "Courier", "Helvetica-BoldOblique"] {
|
||||
let mut content = String::new();
|
||||
for i in 0..letters.len() {
|
||||
content.push_str(&format!("BT /F1 {size} Tf {} {} Td <{:02X}> Tj ET\n", 10 + 40 * i, 80 - baseline, 1 + i));
|
||||
}
|
||||
let differences = letters.iter().map(|n| format!("/{n}")).collect::<Vec<_>>().join(" ");
|
||||
let pdf = format!(
|
||||
"%PDF-1.4
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 {} 80] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >> endobj
|
||||
4 0 obj << /Length {} >> stream
|
||||
{content}endstream endobj
|
||||
5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /{font}
|
||||
/Encoding << /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences [1 {differences}] >> >> endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF",
|
||||
20 + 40 * letters.len(),
|
||||
content.len()
|
||||
);
|
||||
let p = render(pdf.as_bytes());
|
||||
// The rows (y down) of the i-th letter that have dark pixels.
|
||||
let ink_rows = |i: u32| -> Vec<u32> {
|
||||
(0..p.height).filter(|&y| ((8 + 40 * i)..(48 + 40 * i).min(p.width)).any(|x| pixel(&p, x, y)[0] < 128)).collect()
|
||||
};
|
||||
for (pair, (_, name)) in pairs.iter().enumerate() {
|
||||
let (base, accented) = (ink_rows(2 * pair as u32), ink_rows(2 * pair as u32 + 1));
|
||||
let (Some(&base_bottom), Some(&bottom)) = (base.last(), accented.last()) else {
|
||||
panic!("{font} {name}: draws nothing ({} rows of its base letter)", base.len());
|
||||
};
|
||||
assert!(bottom > base_bottom + 2, "{font} {name}: a mark hangs below the letter ({bottom} vs {base_bottom})");
|
||||
assert!(
|
||||
(base_bottom + 1..bottom).any(|y| !accented.contains(&y)),
|
||||
"{font} {name}: the mark is apart from the letter, a comma and not a cedilla"
|
||||
);
|
||||
assert!(bottom < baseline + size * 3 / 10, "{font} {name}: the comma stays within the descender ({bottom})");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Text contracts adapted from PdfCraft a2ec27b4775f53c40cad3456936d9406611e3a8d (MIT OR Apache-2.0):
|
||||
//! Annex D.2 alias codes, glyph names outside the Adobe Glyph List, and `/ToUnicode` identity names.
|
||||
#![cfg(feature = "interpret")]
|
||||
#![allow(clippy::unwrap_used, clippy::panic)]
|
||||
|
||||
use craft_pdf::interpret::{
|
||||
BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask, TransformExt,
|
||||
font::Glyph,
|
||||
};
|
||||
use hayro_cmap::BfString;
|
||||
use kurbo::{Affine, BezPath, Rect};
|
||||
|
||||
/// The text of each glyph drawn, `None` where the font gives none.
|
||||
#[derive(Default)]
|
||||
struct TextDevice {
|
||||
glyphs: Vec<Option<String>>,
|
||||
}
|
||||
|
||||
impl Device<'_> for TextDevice {
|
||||
fn set_soft_mask(&mut self, _: Option<SoftMask<'_>>) {}
|
||||
fn set_blend_mode(&mut self, _: BlendMode) {}
|
||||
fn draw_path(&mut self, _: &BezPath, _: Affine, _: &Paint<'_>, _: &PathDrawMode) {}
|
||||
fn push_clip_path(&mut self, _: &ClipPath) {}
|
||||
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {}
|
||||
fn draw_glyph(&mut self, glyph: &Glyph<'_>, _: Affine, _: Affine, _: &Paint<'_>, _: &GlyphDrawMode) {
|
||||
self.glyphs.push(glyph.as_unicode().map(|text| match text {
|
||||
BfString::Char(c) => c.to_string(),
|
||||
BfString::String(s) => s,
|
||||
}));
|
||||
}
|
||||
fn draw_image(&mut self, _: Image<'_, '_>, _: Affine) {}
|
||||
fn pop_clip_path(&mut self) {}
|
||||
fn pop_transparency_group(&mut self) {}
|
||||
}
|
||||
|
||||
/// The glyph texts of a one-page PDF whose font `/F1` is object 5; `extra` holds further objects.
|
||||
fn glyph_texts(font: &str, extra: &str, content: &[u8]) -> Vec<Option<String>> {
|
||||
let mut pdf = format!(
|
||||
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >> endobj\n\
|
||||
4 0 obj << /Length {} >> stream\n",
|
||||
content.len()
|
||||
)
|
||||
.into_bytes();
|
||||
pdf.extend_from_slice(content);
|
||||
pdf.extend_from_slice(format!("\nendstream endobj\n5 0 obj {font} endobj\n{extra}trailer << /Root 1 0 R >>\n%%EOF\n").as_bytes());
|
||||
let pdf = craft_pdf::open_slice(&pdf, None).unwrap();
|
||||
let page = &pdf.pages()[0];
|
||||
let cache = InterpreterCache::new();
|
||||
let mut context =
|
||||
Context::new(page.initial_transform(true).to_kurbo(), Rect::new(0.0, 0.0, 300.0, 300.0), &cache, page.xref(), InterpreterSettings::default());
|
||||
let mut device = TextDevice::default();
|
||||
craft_pdf::interpret_page(page, &mut context, &mut device).unwrap();
|
||||
device.glyphs
|
||||
}
|
||||
|
||||
fn helvetica_texts(encoding: &str, content: &[u8]) -> Vec<String> {
|
||||
let font = format!("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding {encoding} >>");
|
||||
glyph_texts(&font, "", content).into_iter().map(|text| text.unwrap_or_default()).collect()
|
||||
}
|
||||
|
||||
/// PdfCraft ledger hayro-interpret (30): WinAnsiEncoding gives 0xAD and 0xA0 the glyph names
|
||||
/// `hyphen` and `space`, and MacRomanEncoding gives 0xCA `space` (Annex D.2), so they read as the
|
||||
/// ordinary hyphen and space rather than U+00AD and U+00A0. A `/Differences` entry naming
|
||||
/// `sfthyphen` or `nbspace` keeps its glyph list value.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), test)]
|
||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
||||
fn the_annex_d2_alias_codes_read_as_an_ordinary_hyphen_and_space() {
|
||||
assert_eq!(
|
||||
helvetica_texts("/WinAnsiEncoding", b"BT /F1 20 Tf 20 150 Td (a\xadb\xa0c) Tj ET"),
|
||||
["a", "-", "b", " ", "c"],
|
||||
"WinAnsi 0xAD and 0xA0"
|
||||
);
|
||||
assert_eq!(helvetica_texts("/MacRomanEncoding", b"BT /F1 20 Tf 20 150 Td (a\xcab) Tj ET"), ["a", " ", "b"], "MacRoman 0xCA");
|
||||
assert_eq!(
|
||||
helvetica_texts(
|
||||
"<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences [88 /sfthyphen 89 /nbspace] >>",
|
||||
b"BT /F1 20 Tf 20 150 Td (aXbYc) Tj ET"
|
||||
),
|
||||
["a", "\u{ad}", "b", "\u{a0}", "c"],
|
||||
"a named glyph keeps its glyph list value"
|
||||
);
|
||||
}
|
||||
|
||||
/// PdfCraft ledger hayro-interpret P6 (#3169, #3170): ligature (`f_i`) and suffixed
|
||||
/// (`hyphen.case`) names read by the glyph list specification's full mapping. A name that only
|
||||
/// numbers the glyph (`C39`, `c251`), a ZapfDingbats name (`a12`) and a name with no meaning
|
||||
/// left (`foo`) read as nothing.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), test)]
|
||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
||||
fn glyph_names_outside_the_glyph_list_still_read_as_text() {
|
||||
let encoding = "<< /Type /Encoding /Differences [30 /f_i /f_l 2 /hyphen.case 39 /C39 97 /c251 174 /C174 \
|
||||
88 /a12 /foo /uni00660069 61 /C39.sc 233 /C1] >>";
|
||||
let texts = helvetica_texts(encoding, b"BT /F1 20 Tf 20 150 Td (\x1e\x1f\x02'a\xaeXYZ=\xe9) Tj ET");
|
||||
assert_eq!(texts, ["fi", "fl", "-", "", "", "", "", "", "fi", "", ""]);
|
||||
}
|
||||
|
||||
/// PdfCraft ledger hayro-interpret P6: the `uni` and `u` forms take uppercase hex digits only.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), test)]
|
||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
||||
fn glyph_names_with_lowercase_hex_read_as_nothing() {
|
||||
let encoding = "<< /Type /Encoding /Differences [65 /uni20ac0308 /uni20AC0308 /u1040c.alt /u1040C.alt /f_uni20ac /f_uni20AC] >>";
|
||||
let texts = helvetica_texts(encoding, b"BT /F1 20 Tf 20 150 Td (ABCDEF) Tj ET");
|
||||
assert_eq!(texts, ["", "\u{20ac}\u{308}", "", "\u{1040c}", "f", "f\u{20ac}"]);
|
||||
}
|
||||
|
||||
/// PdfCraft ledger hayro-interpret (44): `/ToUnicode /Identity-H` (a name, not a CMap stream)
|
||||
/// reads two-byte codes as their Unicode values. Controls (a DEL and a C1 control) are not text.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), test)]
|
||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
||||
fn identity_to_unicode_names_give_text() {
|
||||
for name in ["Identity-H", "Identity-V"] {
|
||||
let font = format!(
|
||||
"<< /Type /Font /Subtype /Type0 /BaseFont /RobotoMono-Regular /Encoding /Identity-H /DescendantFonts [6 0 R] /ToUnicode /{name} >>"
|
||||
);
|
||||
let cid = "6 0 obj << /Type /Font /Subtype /CIDFontType2 /BaseFont /RobotoMono-Regular \
|
||||
/CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /DW 600 /CIDToGIDMap /Identity >> endobj\n";
|
||||
let texts = glyph_texts(&font, cid, b"BT /F1 12 Tf 20 200 Td <005A00FC0072006900630068002020AC007F0085> Tj ET");
|
||||
let texts: Vec<String> = texts.into_iter().map(|text| text.unwrap_or_default()).collect();
|
||||
assert_eq!(texts, ["Z", "\u{fc}", "r", "i", "c", "h", " ", "\u{20ac}", "", ""], "{name}");
|
||||
}
|
||||
}
|
||||
@@ -7,11 +7,11 @@ test_root=$(mktemp -d "${TMPDIR:-/tmp}/craft-pdf-backends.XXXXXX")
|
||||
trap 'rm -rf "$test_root"' EXIT
|
||||
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$root/target}"
|
||||
patches=()
|
||||
for backend in hayro hayro-interpret hayro-syntax hayro-jbig2; do
|
||||
for backend in hayro hayro-interpret hayro-syntax hayro-jbig2 hayro-cmap hayro-postscript; do
|
||||
cp -R "$root/vendor/$backend" "$test_root/$backend"
|
||||
patches+=(--config "patch.crates-io.$backend.path=\"$test_root/$backend\"")
|
||||
done
|
||||
for backend in hayro-syntax hayro-interpret hayro hayro-jbig2; do
|
||||
for backend in hayro-syntax hayro-interpret hayro hayro-jbig2 hayro-cmap hayro-postscript; do
|
||||
cargo test --manifest-path "$test_root/$backend/Cargo.toml" --lib "${patches[@]}"
|
||||
done
|
||||
cargo test --manifest-path "$test_root/hayro-syntax/Cargo.toml" --doc "${patches[@]}"
|
||||
|
||||
Vendored
+57
@@ -6,6 +6,25 @@ The upstream [patch ledger](https://github.com/storytold/pdfcraft/blob/7437bde37
|
||||
describes the inherited patches. Source manifests record every transferred Git blob and
|
||||
SHA-256 alongside the local hash. The source manifests themselves are not self-hashed.
|
||||
|
||||
`hayro-cmap` 0.1.0 is transferred from [PdfCraft revision a2ec27b4775f53c40cad3456936d9406611e3a8d](https://github.com/storytold/pdfcraft/tree/a2ec27b4775f53c40cad3456936d9406611e3a8d/vendor/hayro-cmap)
|
||||
with its malformed-CMap patch (PdfCraft #3177): bad `bfchar` or `bfrange` entries, an
|
||||
unresolvable `usecmap` and an unparseable tail are skipped instead of discarding the whole
|
||||
CMap. Its tests `tests::bad_bfchar_entry_is_skipped` and `tests::unresolvable_usecmap_is_skipped`
|
||||
come with it. One local patch: a binary `usecmap` counts against the 16-level nesting limit
|
||||
as a text one does, so a self-referencing binary CMap stops instead of overflowing the stack.
|
||||
Consuming workspaces need a `hayro-cmap` patch entry beside the other Hayro entries.
|
||||
|
||||
`hayro-postscript` 0.1.0 is the crates.io package (upstream revision
|
||||
a2354aebaf86f5ab13e5fd6b6b0521306488bf9d), the PostScript token scanner `hayro-cmap` uses
|
||||
to parse the CMap streams PDFs embed. One local patch: the scanner, which does not parse
|
||||
dictionaries yet, skips runs of `<<` and `>>` in a loop and returns the next object, instead
|
||||
of recursing once per delimiter, so a long run of `<` or `>` bytes no longer overflows the
|
||||
stack. Tests: `object::tests::long_open_dict_run_does_not_overflow`,
|
||||
`object::tests::long_close_dict_run_does_not_overflow`, `object::tests::dict_delimiters_are_skipped`
|
||||
and `object::tests::nested_dict_delimiters_are_skipped`. Its `SOURCE.json` records the
|
||||
registry hashes. Consuming workspaces need a `hayro-postscript` patch entry beside the other
|
||||
Hayro entries.
|
||||
|
||||
The shared snapshot adds immutable per-document ordinary decode limits, threaded through
|
||||
initial xrefs, object streams, fallback and repair. Existing constructors retain their
|
||||
previous default. Known-size image budgets and streaming content budgets remain distinct.
|
||||
@@ -58,6 +77,44 @@ Hostile-input bounds (CodeRabbit findings):
|
||||
- An xref-stream `/W` type field wider than one byte is read at its full width (big-endian)
|
||||
instead of only its first byte, and `/W[0]` over 8 bytes is refused like `/W[1]`.
|
||||
A dash array over 256 entries strokes solid.
|
||||
- An xref-stream subsection running past object number `i32::MAX` is refused instead of
|
||||
overflowing or turning negative.
|
||||
- A CID font's `/W2` run that starts past CID 65535 is skipped as in `/W`, instead of
|
||||
overflowing and discarding the whole table.
|
||||
- CCITT images: `ccitt_size_ok` (inherited PdfCraft ledger item 2) allows at most 2^20
|
||||
columns and 2^28 pixels (columns × rows) before the decoder allocates. A `/Columns` past
|
||||
`u32::MAX` is refused rather than wrapped to a small width. `/Rows` follows PdfCraft (17)
|
||||
and (19): `/Rows 0` or a value below `/Height` decodes to the image height, and decoding
|
||||
still stops where the data ends.
|
||||
|
||||
Reader limits from the [PdfCraft revision a2ec27b4775f53c40cad3456936d9406611e3a8d ledger](https://github.com/storytold/pdfcraft/blob/a2ec27b4775f53c40cad3456936d9406611e3a8d/vendor/README.md),
|
||||
by its item ids: hayro-interpret (31), its overflow part: the largest 32-bit Type 0 sample is
|
||||
computed in 64 bits instead of overflowing `2_u32.pow(32)`. The flat sample array that (31)
|
||||
also brings is a performance change and is not part of this set. hayro-syntax (7), (22) and
|
||||
(25) are covered by the local bounds above: ASCII85 output stops at the decode limit,
|
||||
object-stream indexes are parsed once with checked offsets, and direct objects nest at most
|
||||
64 levels, stricter than PdfCraft's 128. Test:
|
||||
`function::type0::tests::thirty_two_bit_samples_do_not_overflow`.
|
||||
|
||||
Rendering fixes from the same [PdfCraft revision a2ec27b4775f53c40cad3456936d9406611e3a8d ledger](https://github.com/storytold/pdfcraft/blob/a2ec27b4775f53c40cad3456936d9406611e3a8d/vendor/README.md),
|
||||
by its item ids, each marked `PdfCraft patch` in the source: hayro-syntax (17) and (19), CCITT
|
||||
`/Rows 0` or fewer `/Rows` than `/Height` decode to the image height; (20), spaces or tabs
|
||||
between `stream` and its line break; the `EI` extension of (4), `EI` followed by a delimiter
|
||||
ends an inline image; (23), bytes above 0x7F after an `EI` candidate don't reject it; the
|
||||
unledgered #3565 fix, a doubled sign (`--280`) is one number in both read and skip, beside the
|
||||
local zero-tolerance sign tokens; and the `base_dimensions` one-point floor after `/UserUnit`.
|
||||
Their unit tests come with them; the CCITT raster tests are adapted in `tests/upstream_raster.rs`.
|
||||
Text fixes from the same ledger in hayro-interpret: (30), the Annex D.2 alias codes (WinAnsi
|
||||
0xA0 and 0xAD, MacRoman 0xCA) read as an ordinary space and hyphen unless `/Differences` names
|
||||
them; (44), a `/ToUnicode /Identity-H` or `/Identity-V` name reads two-byte codes as Unicode;
|
||||
(P6), glyph names outside the Adobe Glyph List (`f_i`, `hyphen.case`, `uniXXXXXXXX`) read by
|
||||
the glyph list specification's full mapping; (P8), a substitute without a spacing character
|
||||
draws its ordinary space; (P2), a Type 3 glyph's `/FontBBox` is taken to device space before it
|
||||
bounds the glyph's clip and shadings; and the extension of (26), comma-below letters (ș ț ķ ļ ņ
|
||||
ŗ Ģ) in the standard-font stand-ins are built from the font's comma. The text contracts are
|
||||
adapted in `tests/upstream_text.rs` and the Type 3 and comma-below raster tests in
|
||||
`tests/upstream_raster.rs`. (P8)'s PdfCraft test needs a Japanese substitute font and is not
|
||||
ported.
|
||||
|
||||
This remains the patched 0.7 backend. It retains the existing Bradford Lab conversion,
|
||||
floating component precision and codec versions, rather than claiming full 0.8
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "alloc-no-stdlib"
|
||||
version = "2.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
|
||||
|
||||
[[package]]
|
||||
name = "alloc-stdlib"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli"
|
||||
version = "8.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
"brotli-decompressor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli-decompressor"
|
||||
version = "5.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa"
|
||||
Vendored
+87
@@ -0,0 +1,87 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2024"
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
authors = ["Laurenz Stampfl <laurenz.stampfl@gmail.com>"]
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "A parser for CMap files."
|
||||
readme = "README.md"
|
||||
license = "Apache-2.0 OR MIT"
|
||||
repository = "https://github.com/LaurenzV/hayro"
|
||||
resolver = "2"
|
||||
|
||||
[features]
|
||||
default = ["embed-cmaps"]
|
||||
embed-cmaps = [
|
||||
"std",
|
||||
"dep:brotli",
|
||||
]
|
||||
std = []
|
||||
|
||||
[lib]
|
||||
name = "hayro_cmap"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies.brotli]
|
||||
version = "8"
|
||||
features = [
|
||||
"std",
|
||||
"std",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.hayro-postscript]
|
||||
version = "0.1.0"
|
||||
default-features = false
|
||||
|
||||
[lints.clippy]
|
||||
collection_is_never_read = "warn"
|
||||
dbg_macro = "warn"
|
||||
debug_assert_with_mut_call = "warn"
|
||||
default_trait_access = "warn"
|
||||
doc_markdown = "warn"
|
||||
fn_to_numeric_cast_any = "warn"
|
||||
infinite_loop = "warn"
|
||||
large_stack_arrays = "warn"
|
||||
mismatching_type_param_order = "warn"
|
||||
negative_feature_names = "warn"
|
||||
redundant_feature_names = "warn"
|
||||
same_functions_in_if_condition = "warn"
|
||||
semicolon_if_nothing_returned = "warn"
|
||||
todo = "warn"
|
||||
too_many_arguments = "allow"
|
||||
unseparated_literal_suffix = "warn"
|
||||
use_self = "warn"
|
||||
wildcard_dependencies = "warn"
|
||||
|
||||
[lints.rust]
|
||||
elided_lifetimes_in_paths = "warn"
|
||||
keyword_idents_2024 = "forbid"
|
||||
missing_docs = "warn"
|
||||
non_ascii_idents = "forbid"
|
||||
non_local_definitions = "forbid"
|
||||
trivial_numeric_casts = "warn"
|
||||
unnameable_types = "warn"
|
||||
unreachable_pub = "warn"
|
||||
unsafe_op_in_unsafe_fn = "forbid"
|
||||
unused_import_braces = "warn"
|
||||
unused_lifetimes = "warn"
|
||||
unused_macro_rules = "warn"
|
||||
unused_qualifications = "warn"
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
description = "A parser for CMap files."
|
||||
authors = { workspace = true }
|
||||
edition = { workspace = true }
|
||||
repository = { workspace = true }
|
||||
license = { workspace = true }
|
||||
|
||||
[features]
|
||||
default = ["embed-cmaps"]
|
||||
std = []
|
||||
# Embed the 61 predefined cmaps into the binary. Adds about ~250KB of brotli-encoded data.
|
||||
embed-cmaps = ["std", "dep:brotli"]
|
||||
|
||||
[dependencies]
|
||||
hayro-postscript = { workspace = true }
|
||||
brotli = { workspace = true, optional = true, features = ["std"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
Vendored
+177
@@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
Copyright (c) The Hayro Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
# hayro-cmap
|
||||
|
||||
[](https://crates.io/crates/hayro-cmap)
|
||||
[](https://docs.rs/hayro-cmap)
|
||||
|
||||
<!-- cargo-rdme start -->
|
||||
|
||||
A parser for cmap files, as they are found in PDFs.
|
||||
|
||||
This crate provides a parser for CMap files and allows you to
|
||||
- Map character codes from text-showing operators to CID identifiers.
|
||||
- Map CIDs to Unicode characters or strings.
|
||||
|
||||
### Safety
|
||||
This crate forbids unsafe code via a crate-level attribute.
|
||||
|
||||
<!-- cargo-rdme end -->
|
||||
|
||||
## License
|
||||
Licensed under either of
|
||||
|
||||
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
|
||||
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
|
||||
|
||||
at your option.
|
||||
Vendored
+98
@@ -0,0 +1,98 @@
|
||||
{
|
||||
"crate": "hayro-cmap",
|
||||
"source_repository": "https://github.com/storytold/pdfcraft",
|
||||
"source_revision": "a2ec27b4775f53c40cad3456936d9406611e3a8d",
|
||||
"source_directory": "vendor/hayro-cmap",
|
||||
"files": [
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"source_sha256": "b0ffb94a754c7254ecbead6649fa7877b6875531f9af8c62f7c28e1b11c5a391",
|
||||
"source_git_blob": "b19a6c70fe633320e822a370fa242f32b7e0f914",
|
||||
"sha256": "b0ffb94a754c7254ecbead6649fa7877b6875531f9af8c62f7c28e1b11c5a391"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"source_sha256": "7066550c610db3cb13df3c955f5737dccc3d9d24b6b680e9f633ecfadb82bf86",
|
||||
"source_git_blob": "3818d177b6dcc5c0d754bc3ecf1a3422476c7e2f",
|
||||
"sha256": "7066550c610db3cb13df3c955f5737dccc3d9d24b6b680e9f633ecfadb82bf86"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.toml.orig",
|
||||
"source_sha256": "9bcaf09fca4f5880318ba762cf07d5d269c458bb06f0b6409ae0879b2e564be3",
|
||||
"source_git_blob": "59f5c99d3f5082e9f5064055da016aed0d4fcf35",
|
||||
"sha256": "9bcaf09fca4f5880318ba762cf07d5d269c458bb06f0b6409ae0879b2e564be3"
|
||||
},
|
||||
{
|
||||
"path": "LICENSE-APACHE",
|
||||
"source_sha256": "0cec06e0e55fbc3dc5cee4fca9b607f66cb8f4e4dbcf3b3c013594dd156732e9",
|
||||
"source_git_blob": "4947287f7b5ccb5d1e8b7b2d3aa5d89f322c160d",
|
||||
"sha256": "0cec06e0e55fbc3dc5cee4fca9b607f66cb8f4e4dbcf3b3c013594dd156732e9"
|
||||
},
|
||||
{
|
||||
"path": "LICENSE-MIT",
|
||||
"source_sha256": "51b50e6120c344dcc146bbd6375ca1c78e079d97c8bea76e67a53d6ff0efebac",
|
||||
"source_git_blob": "ae3742de4e9ccb463cb46f05fe3ca0ec23fbb0d2",
|
||||
"sha256": "51b50e6120c344dcc146bbd6375ca1c78e079d97c8bea76e67a53d6ff0efebac"
|
||||
},
|
||||
{
|
||||
"path": "README.md",
|
||||
"source_sha256": "167f3ef1e830520bcc45359a21e513069e75a42393722accca9f56822f1dcc82",
|
||||
"source_git_blob": "bc93f93daa6b750afd709e2bcdfa2b2518b6e6a5",
|
||||
"sha256": "167f3ef1e830520bcc45359a21e513069e75a42393722accca9f56822f1dcc82"
|
||||
},
|
||||
{
|
||||
"path": "assets/LICENSE.txt",
|
||||
"source_sha256": "742665db9c8e1bc72603c6d319ca3e90b83bd6d95202f0cd4ef11068a07a9c29",
|
||||
"source_git_blob": "2552cc990c12f85cdc50ef3c5185061a8c64e326",
|
||||
"sha256": "742665db9c8e1bc72603c6d319ca3e90b83bd6d95202f0cd4ef11068a07a9c29"
|
||||
},
|
||||
{
|
||||
"path": "assets/README.md",
|
||||
"source_sha256": "61a2206d48aa4bac7dfc39416b0526fd994d0173897666f231f5c370cc06f646",
|
||||
"source_git_blob": "4cedb1ff6d3c6d0b44e5cf20f749fb470bc8de01",
|
||||
"sha256": "61a2206d48aa4bac7dfc39416b0526fd994d0173897666f231f5c370cc06f646"
|
||||
},
|
||||
{
|
||||
"path": "assets/cmaps.brotli",
|
||||
"source_sha256": "ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46",
|
||||
"source_git_blob": "ba74bd32fc71bb274e3e7e5c36bafaf89b9d6815",
|
||||
"sha256": "ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46"
|
||||
},
|
||||
{
|
||||
"path": "src/bcmap/embedded.rs",
|
||||
"source_sha256": "c1e18cf9fa5c413fe87bbc69394f2b8f0a7f6b5cda30b926665d0596ea79691b",
|
||||
"source_git_blob": "0f5c241a0e278da6e3eefe72fe3925ce7e177f57",
|
||||
"sha256": "c1e18cf9fa5c413fe87bbc69394f2b8f0a7f6b5cda30b926665d0596ea79691b"
|
||||
},
|
||||
{
|
||||
"path": "src/bcmap/huffman.rs",
|
||||
"source_sha256": "9b1f4ba036f8b6e9011b2fb9c1d80f6b34ba4c1be3c101b9678a8b49a8d352ea",
|
||||
"source_git_blob": "b6e8e9ab5d9fcdf831ceedaa7f620bd9d5e7ac8c",
|
||||
"sha256": "9b1f4ba036f8b6e9011b2fb9c1d80f6b34ba4c1be3c101b9678a8b49a8d352ea"
|
||||
},
|
||||
{
|
||||
"path": "src/bcmap/mod.rs",
|
||||
"source_sha256": "38dafbd8fcb5ca6f647d70d02cdb5af532ea7f2a3ac3f7ac8d1dea23abc93058",
|
||||
"source_git_blob": "997bc00d85db1504c63cf56e3cb157410ebdb0bb",
|
||||
"sha256": "3d0ea5e34bc92c40a250923ecb71b48571100bba5cc4664ea2c46d51086fe6be"
|
||||
},
|
||||
{
|
||||
"path": "src/bcmap/reader.rs",
|
||||
"source_sha256": "343b20170f8445258fb564f4f5387f66df804920d73886981f0db8829562d1cf",
|
||||
"source_git_blob": "25d6639104148a9123044c2c092a9bee5c889fd3",
|
||||
"sha256": "343b20170f8445258fb564f4f5387f66df804920d73886981f0db8829562d1cf"
|
||||
},
|
||||
{
|
||||
"path": "src/lib.rs",
|
||||
"source_sha256": "d666b3d8e4d37fc06c299a60ab9748ae17badcea271ff2cf864dcee76e27648c",
|
||||
"source_git_blob": "fb42ff37ec9ccece66d33d1888bd25963cbf1171",
|
||||
"sha256": "d6b9c6fa8de00942dd4cdfbd43578d3e53f8a3a6cf1e3563b345a9f6f35bc5e8"
|
||||
},
|
||||
{
|
||||
"path": "src/parse.rs",
|
||||
"source_sha256": "1999127f05b59bdd55e2a7349dafc0b2213238201da37f7c35cd698996f2dc6b",
|
||||
"source_git_blob": "a936209275ffca797912dec052dc03ddb0d2dce4",
|
||||
"sha256": "1999127f05b59bdd55e2a7349dafc0b2213238201da37f7c35cd698996f2dc6b"
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
Copyright 1990-2023 Adobe. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
Neither the name of Adobe nor the names of its contributors may be
|
||||
used to endorse or promote products derived from this software without
|
||||
specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
See https://github.com/LaurenzV/cmap-resources/tree/hayro for information on how this blob was generated and how
|
||||
it can be parsed.
|
||||
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user