Compare commits

..
Author SHA1 Message Date
dependabot[bot] 62518dc0aa ci(deps): bump the actions group across 1 directory with 3 updates
Bumps the actions group with 3 updates in the / directory: [step-security/harden-runner](https://github.com/step-security/harden-runner), [storytold/craft-common-actions/actions/checkout-craft-fonts](https://github.com/storytold/craft-common-actions) and [storytold/craft-common-actions/actions/checkout-craft-i18n](https://github.com/storytold/craft-common-actions).


Updates `step-security/harden-runner` from 2.22.4 to 2.23.0
- [Release notes](https://github.com/step-security/harden-runner/releases)
- [Commits](https://github.com/step-security/harden-runner/compare/1d88384fd173af6ecb012dfd0264a306b711241a...aebdcf6156ab6691adf63218240e476564a1ed4c)

Updates `storytold/craft-common-actions/actions/checkout-craft-fonts` from f5141455aac7b2eb4708aa259d8ffcdf10fde939 to be00e5ccd18b68e950c8a08532f2230e7c3d0cba
- [Commits](https://github.com/storytold/craft-common-actions/compare/f5141455aac7b2eb4708aa259d8ffcdf10fde939...be00e5ccd18b68e950c8a08532f2230e7c3d0cba)

Updates `storytold/craft-common-actions/actions/checkout-craft-i18n` from f5141455aac7b2eb4708aa259d8ffcdf10fde939 to be00e5ccd18b68e950c8a08532f2230e7c3d0cba
- [Commits](https://github.com/storytold/craft-common-actions/compare/f5141455aac7b2eb4708aa259d8ffcdf10fde939...be00e5ccd18b68e950c8a08532f2230e7c3d0cba)

---
updated-dependencies:
- dependency-name: step-security/harden-runner
  dependency-version: 2.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
- dependency-name: storytold/craft-common-actions/actions/checkout-craft-fonts
  dependency-version: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
  dependency-type: direct:production
  dependency-group: actions
- dependency-name: storytold/craft-common-actions/actions/checkout-craft-i18n
  dependency-version: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
  dependency-type: direct:production
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-26 01:55:10 +00:00
skylar taylor-barrick 765abcc790 Switch on supervised nightlies on the nightly-signer branch (#7839)
Supervised nightly switch-on, merged under Skylar's explicit Nightly 758 override after green CI, CodeRabbit on this head with no open threads, Sonar passing, and an independent adversarial review with no blockers.
2026-11-25 19:52:59 -06:00
Martin BallandClaude Opus 5.5 a44dc74fc0 #7822: Spec, plan and ADR for closing document windows (#7840)
Agreed rules for every close path (window close, File › Close, quit, one-document hosts, automation), who owns the Save prompt, and the order of work: craft-libs hidden root and test kit, repin, then the WordCraft fix. Adds Document window and Save prompt to the glossary.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 00:19:22 +00:00
skylar taylor-barrick 77a530b179 Use the shared nightly launcher template (#7829)
Renders the plain nightly tar's launcher from craft-common-actions' shared template.

Independent check: dylanmtaylor compared all 14 app launcher PRs byte for byte with the template rendered from the registry (https://github.com/storytold/craft-common-actions/pull/367#issuecomment-7172085284); this head was re-checked against craft-common-actions main 88148a5.
2026-11-25 16:17:53 -06:00
Martin BallandClaude Opus 5.5 4e00d00779 ROADMAP: remove a stray branch-name line from the progress log (#6917)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:48:59 +00:00
Lucas Batista Vargas 26b1d89ad2 fix(dialogs): restore table style dialog v0.18.1 layout, preview, and alignment test (#7317) (#7645) 2026-11-25 18:04:13 +00:00
Lucas Batista Vargas a272715194 test(windows): restore #117 window title test and cover root promotion (#7702) 2026-11-25 15:38:40 +00:00
Lucas Batista Vargas ff90488655 test(credits): cover Models table refit in narrowed About dialog (#7646) 2026-11-25 15:38:34 +00:00
Lucas Batista Vargas bc629b7a4f test(control_server): adapt params.token / params.key auth test post-#7101 (#7729) (#7629) 2026-11-25 15:38:28 +00:00
Lucas Batista Vargas 954750790b Dialogs: restore modal shake/nudge animation on backdrop clicks (#7321) (#7332) 2026-11-25 15:38:22 +00:00
Lucas Batista Vargas f587bcb95a fix(keytips): record ribbon menu_button commands and restore language test (#7317) (#7612) 2026-11-25 15:38:16 +00:00
Lucas Batista Vargas b068e1a538 refactor(ui-egui): unify command_input cache loop and test keytip cache behaviour (#7764) (#7573) 2026-11-25 15:38:10 +00:00
Lucas Batista Vargas 9ab9f2f874 Accessibility: return keyboard focus to page on dialog dismissal from non-canvas controls (#7458) (#7467) 2026-11-25 15:38:04 +00:00
Lucas Batista Vargas 231a09761c test(keytips): adapt long QAT multi-digit badge test to craft Keytips (#7733) (#7626) 2026-11-25 15:37:58 +00:00
Lucas Batista Vargas dc12b22371 test(objects): adapt nothing_to_snap_to post-#7101 (#7749) (#7618) 2026-11-25 15:37:50 +00:00
Lucas Batista Vargas b77c55c028 test(dialogs): adapt escape_in_the_browser_leaves_the_dialog_under_it_open post-#7101 (#7754) (#7617) 2026-11-25 15:37:43 +00:00
Lucas Batista Vargas 09465c9fc4 test(ribbon): adapt Styles gallery RTL reading-order test post-#7101 (#7753) (#7616) 2026-11-25 15:37:37 +00:00
Lucas Batista Vargas c8ecea24cf test(file_dialogs): adapt entries_expose_names_selection_and_picking post-#7101 (#7317) (#7613) 2026-11-25 15:37:32 +00:00
Lucas Batista Vargas 2a09d78972 test(keys): restore the_ignored_paste_uses_up_its_paste_modifiers test (#7317) (#7609) 2026-11-25 15:37:26 +00:00
Lucas Batista Vargas b163c0568d test(file_browser): restore a_dialog_closing_into_the_browser_leaves_it_the_keyboard test (#7317) (#7604) 2026-11-25 15:37:20 +00:00
Lucas Batista Vargas 8ed5ddd47b test(ui-egui): restore the_tab_strip_buttons_have_names test (#7317, #1110) (#7577) 2026-11-25 15:37:13 +00:00
Lucas Batista Vargas ea8f665f20 test(ui-egui): restore focus_and_full_screen_view_ask_for_full_screen_once_per_change (#1678) (#7576) 2026-11-25 15:37:06 +00:00
Lucas Batista Vargas c30777bf2a test(ui-egui): restore command_filter_narrows_the_picker_and_add_works test (#7317) (#7574) 2026-11-25 15:36:59 +00:00
Lucas Batista Vargas 34b79b33db test(ui-egui): restore the_ribbon_boxes_name_themselves_for_a_screen_reader test (#7317, #3172) (#7569) 2026-11-25 15:36:53 +00:00
Lucas Batista Vargas f89c52c428 test(ui-egui): restore the_print_button_leads_the_settings_and_is_the_primary_action (#2958) (#7568) 2026-11-25 15:36:47 +00:00
Lucas Batista Vargas 4da5534eb8 test(ui-egui): restore the_plus_button_adds_a_row test (#7317) (#7563) 2026-11-25 15:36:41 +00:00
Lucas Batista Vargas afe332b225 test(engine): restore copy_format_web_alias_respects_user_removal_and_reassignment test (#7317) (#7562) 2026-11-25 15:36:29 +00:00
Lucas Batista Vargas 3ebf69481a test(ui-egui): restore caret_colour_is_not_worked_out_while_the_caret_is_hidden (#299) (#7561) 2026-11-25 15:36:22 +00:00
Lucas Batista Vargas ab014b8fe5 test(engine): restore f11_is_full_screen_and_alt_f1_walks_fields test (#980) (#7317) (#7559) 2026-11-25 15:36:16 +00:00
Lucas Batista Vargas 7951466b8b test(ui-egui): restore a_bordered_table_shows_no_gridlines (#5967) (#7554) 2026-11-25 15:36:08 +00:00
Lucas Batista Vargas d26c7375ff test(ui-egui): restore read_aloud_player_closes_from_title_bar (#1885) (#7553) 2026-11-25 15:35:57 +00:00
Lucas Batista Vargas e3b742f75a test(ui-egui): restore the_full_screen_button_reports_the_commands_own_enabled_state (#7317) (#7552) 2026-11-25 15:35:50 +00:00
Lucas Batista Vargas f847159a29 System clipboard: restore test for empty copy preserving clipboard state (#7317) (#7544) 2026-11-25 15:35:44 +00:00
Lucas Batista Vargas 9409b2fd79 Tests: restore title_stem_omits_nul_from_each_title_source (#7317) (#7543) 2026-11-25 15:35:38 +00:00
Lucas Batista Vargas e2f001b946 Dialogs: restore AutoCorrect filter and Compare options tests (#7317) (#7542) 2026-11-25 15:35:32 +00:00
Lucas Batista Vargas dc5d27cded Default apps: restore test for xdg-mime word types and exclusion of plain text (#7317) (#7541) 2026-11-25 15:35:25 +00:00
Lucas Batista Vargas c56825487f Dialogs insert: restore test for Document Information fields in Field dialog (#7317) (#7537) 2026-11-25 15:35:19 +00:00
Lucas Batista Vargas 4343683da8 Icons: restore test for fitOnePage painting through the SVG registry (#7317) (#7534) 2026-11-25 15:35:12 +00:00
Lucas Batista Vargas 1f65a8e588 Window geometry: restore test for clamping or dropping insane values (#7317) (#7533) 2026-11-25 15:35:06 +00:00
Lucas Batista Vargas bfc160809c Font download: restore test for short window opt-out and close buttons (#7317) (#7530) 2026-11-25 15:35:00 +00:00
Lucas Batista Vargas 3639389be3 Paste picture: restore test for refusing hostile clipboard pictures and files (#7317) (#7529) 2026-11-25 15:34:54 +00:00
Lucas Batista Vargas 37d03a1eb4 Chrome: restore test for clicking AutoSave label to toggle (#3370) (#7317) (#7528) 2026-11-25 15:34:48 +00:00
Lucas Batista Vargas 7fa77df595 DOCX settings merge trials: zoom round-trips and the mail-merge source id (#7524) 2026-11-25 15:34:42 +00:00
Dylan M. Taylor c179a31619 packaging(linux): support co-installable nightly packages (#7746)
Linux nightly packaging by @dylanmtaylor, with the per-app Nightly flavor commits stacked on his branch.

Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
2026-11-24 19:00:35 -06:00
Lucas Batista Vargas 6e92d33e07 UI: cache command metadata, hints and keytip tables between idle frames (#7674) (#7719) 2026-11-24 21:51:04 +00:00
Lucas Batista Vargas 4d7100a7f8 test(fonts): adapt installed Arabic font isolation test post-#7101 (#7734) (#7627) 2026-11-24 17:03:26 +00:00
Lucas Batista Vargas 920d9342e7 test(chrome): adapt AutoSave knob RTL mirroring test to craft Switch (#7730) (#7630)
* test(chrome): adapt AutoSave knob RTL mirroring test to craft Switch (#7730)

* test(chrome): drive AutoSave RTL test via ui.language and root_env
2026-11-24 17:03:20 +00:00
Lucas Batista Vargas c11504affa Ribbon: align Table Design › Table Style Options checkboxes in two columns (#7691) (#7695)
* Ribbon: align Table Style Options checkboxes in two columns (#7691)

* Ribbon: widen Table Style Options column gutter while keeping tight rows
2026-11-24 17:03:14 +00:00
Lucas Batista Vargas 604ad56f0a fix(keytips): show legacy menu key hint under slim screen bar without ribbon (#7731) (#7628) 2026-11-24 14:26:12 +00:00
Lucas Batista Vargas 852330e928 fix(chrome): return canvas focus after picking an Undo History row (#7726) (#7632) 2026-11-24 14:25:57 +00:00
Lucas Batista Vargas b5fb29b539 test(dialogs): restore RTL Page Setup oversized margin test (#7722) (#7637)
Closes #7722. Part of #7317.
2026-11-24 14:25:41 +00:00
Lucas Batista Vargas 012d0dd875 test(control_server): adapt per-connection token auth test post-#7101 (#7720) (#7631) 2026-11-24 14:25:28 +00:00
Lucas Batista Vargas 352042d41f Canvas: size Web Layout from PageView's side gutter instead of rail width (#7687) (#7701) 2026-11-24 11:50:56 +00:00
Lucas Batista Vargas 4f6cc31af6 test(dialogs): verify Customize Keyboard empty shortcuts list shows None (#7317) (#7644) 2026-11-24 11:50:50 +00:00
Lucas Batista Vargas 58e52bc962 test(dialogs): restore the_title_bar_close_box_is_the_whole_corner test (#7317) (#7638) 2026-11-24 11:50:45 +00:00
122 changed files with 10385 additions and 391 deletions
+16
View File
@@ -0,0 +1,16 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
+107
View File
@@ -0,0 +1,107 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/wordcraft",
"repository_id": 1408489772,
"producer_workflow_id": 429734489,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "wordcraft-nightly-20261124",
"repository": "storytold/wordcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 380135788,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_wordcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_wordcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
+227
View File
@@ -0,0 +1,227 @@
name: Nightly build check
# Builds the unsigned WordCraft Nightly the way the producer does (packaging/linux/nightly.sh,
# packaging/windows/package.ps1 -Nightly, packaging/macos/nightly.sh) and checks each archive as the
# Launcher unpacks it. No secrets and no environment: the real Nightly is signed by the shared
# release-ref signer (craft-common-actions), which calls packaging/macos/nightly-sign.sh and the
# app's sign.ps1.
on:
# The platform runners are shared with release builds: pull requests run this only with the
# `full-ci` label, never by changed paths. `labeled` so adding it starts a run.
pull_request:
types: [opened, synchronize, reopened, labeled]
workflow_dispatch:
permissions:
contents: read
# A newer push to a labelled PR cancels its older run. Any event that will not build (no `full-ci`
# label, or another label added) gets a group of its own, so it never cancels a real build.
concurrency:
group: nightly-build-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
linux:
name: Nightly tar (x86_64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: ubuntu-latest
timeout-minutes: 120
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install the system libraries the GUI links
run: sudo apt-get update && sudo apt-get install -y pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
- name: Prepare a Nightly identity for this commit
shell: bash
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "WORDCRAFT_BUILD_SHA=$sha"
echo "WORDCRAFT_BUILD_DATE=$date"
echo "WORDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
echo "WORDCRAFT_BUILD_CHANNEL=nightly-v1"
echo "CARGO_TARGET_DIR=$RUNNER_TEMP/nightly-targets"
echo "DIST=$RUNNER_TEMP/nightly-dist"
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts"
echo "CRAFT_FONTS_REQUIRED=1"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly tar
run: bash packaging/linux/nightly.sh --arch x86_64
- name: Check the tar as the Launcher unpacks it, and ask its version
shell: bash
run: |
set -euo pipefail
work="$RUNNER_TEMP/nightly-check"
mkdir -p "$work"
archive="$DIST/wordcraft-$WORDCRAFT_VERSION-linux-x86_64-nightly.tar.gz"
# The launcher and the GUI it starts, the icon and the notices; the embedded fonts'
# OFL-*.txt licences appear when the build has CRAFT_FONTS_DIR.
core="$(tar -tzf "$archive" | sort | grep -Ev '^OFL-[A-Za-z0-9_.-]+\.txt$' | tr '\n' ' ')"
[ "$core" = "ATTRIBUTION.md LICENSE-APACHE LICENSE-MIT NOTICE README.md wordcraft wordcraft-bin wordcraft-nightly.png " ] \
|| { echo "unexpected members: $core"; exit 1; }
tar -xzf "$archive" -C "$work"
[ -x "$work/wordcraft" ] && [ ! -L "$work/wordcraft" ]
[ "$(stat -c %a "$work/wordcraft")" = 755 ]
[ -x "$work/wordcraft-bin" ] && [ ! -L "$work/wordcraft-bin" ]
mkdir -p "$work/home" "$work/profile"
chmod 700 "$work/home" "$work/profile"
out="$(env -i HOME="$work/home" PATH=/usr/bin:/bin "$work/wordcraft" --version 2>"$work/stderr")" \
|| { cat "$work/stderr"; exit 1; }
[ ! -s "$work/stderr" ]
[ "$out" = "WordCraft $WORDCRAFT_VERSION (nightly-v1)" ]
out="$(env -i HOME="$work/home" PATH=/usr/bin:/bin "$work/wordcraft" --launch-profile nightly-v1 --profile-root "$work/profile" --version)"
[ "$out" = "WordCraft $WORDCRAFT_VERSION (nightly-v1)" ]
[ "$(head -c 2 "$work/wordcraft")" = '#!' ]
echo "==> verified (unsigned): $out"
- name: Keep the unsigned archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: wordcraft-nightly-linux-x86_64-unsigned
path: ${{ runner.temp }}/nightly-dist/wordcraft-${{ env.WORDCRAFT_VERSION }}-linux-x86_64-nightly.tar.gz
if-no-files-found: error
retention-days: 7
compression-level: 0
windows:
name: Nightly ZIP (x86_64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: windows-latest
timeout-minutes: 150
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
defaults:
run:
shell: pwsh
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
targets: x86_64-pc-windows-msvc
- name: Prepare a Nightly identity for this commit
shell: bash
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "WORDCRAFT_BUILD_SHA=$sha"
echo "WORDCRAFT_BUILD_DATE=$date"
echo "WORDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
echo "WORDCRAFT_BUILD_CHANNEL=nightly-v1"
echo "CARGO_TARGET_DIR=$RUNNER_TEMP/nightly-targets"
echo "DIST=$RUNNER_TEMP/nightly-dist"
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts"
echo "CRAFT_FONTS_REQUIRED=1"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly intermediate
run: ./packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly -Target x86_64-pc-windows-msvc -TargetDir $env:CARGO_TARGET_DIR -Dist $env:DIST
- name: Run the packaging contracts (no signing material)
run: ./packaging/windows/nightly-package-tests.ps1 -FixtureRoot $env:RUNNER_TEMP
- name: Run the signing contracts (dummy keys, no signing)
run: ./packaging/windows/nightly-signing-tests.ps1 -FixtureRoot $env:RUNNER_TEMP
- name: Keep the unsigned intermediate
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: wordcraft-nightly-windows-x86_64-unsigned
path: ${{ runner.temp }}/nightly-dist/wordcraft-${{ env.WORDCRAFT_VERSION }}-windows-x86_64-nightly.unsigned.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
macos:
name: Nightly .app (aarch64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: macos-15
timeout-minutes: 120
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
targets: aarch64-apple-darwin
- name: Prepare a Nightly identity for this commit
shell: bash
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "WORDCRAFT_BUILD_SHA=$sha"
echo "WORDCRAFT_BUILD_DATE=$date"
echo "WORDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
echo "WORDCRAFT_BUILD_CHANNEL=nightly-v1"
echo "CARGO_TARGET_DIR=$RUNNER_TEMP/nightly-targets"
echo "DIST=$RUNNER_TEMP/nightly-dist"
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts"
echo "CRAFT_FONTS_REQUIRED=1"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly bundle
run: bash packaging/macos/nightly.sh --arch aarch64
- name: Check the archive and the bundle version
run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$DIST/wordcraft-$WORDCRAFT_VERSION-macos-aarch64-nightly.zip"
- name: Keep the unsigned archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: wordcraft-nightly-macos-aarch64-unsigned
path: ${{ runner.temp }}/nightly-dist/wordcraft-${{ env.WORDCRAFT_VERSION }}-macos-aarch64-nightly.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
+72
View File
@@ -0,0 +1,72 @@
name: Dispatch release-ref nightly
# Transport only, never authorization. No checkout, payload parsing or release environment.
on:
workflow_run:
workflows: [WordCraft unsigned nightly]
types: [completed]
branches: [main]
permissions: {}
jobs:
dispatch:
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
if: >-
false && github.repository == 'storytold/wordcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Dispatch only the exact completed producer run and attempt
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import json
import os
import urllib.request
def require(value, message):
if not value:
raise RuntimeError(message)
# These filters reduce noise; the protected signer-branch validator repeats admission
# against authenticated API metadata and required attestation/quality evidence.
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/wordcraft', 'wrong repository')
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
event = json.load(stream)
require(event.get('action') == 'completed', 'producer is not complete')
require(event.get('repository', {}).get('full_name') == 'storytold/wordcraft', 'wrong event repository')
producer = event.get('workflow_run', {})
require(producer.get('head_repository', {}).get('full_name') == 'storytold/wordcraft', 'foreign producer')
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
require(producer.get('head_branch') == 'main', 'wrong producer branch')
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
run_id, attempt = producer.get('id'), producer.get('run_attempt')
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
}}).encode('utf-8')
request = urllib.request.Request(
'https://api.github.com/repos/storytold/wordcraft/actions/workflows/nightly-sign.yml/dispatches',
data=body, method='POST', headers={
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'wordcraft-nightly-dispatch'
})
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise RuntimeError('dispatch redirects are forbidden')
# One bounded request, no retry: duplicate transport is not publication authority.
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
require(response.status == 204, 'dispatch was not accepted')
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
+45
View File
@@ -0,0 +1,45 @@
name: WordCraft release-ref nightly signer
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
on:
workflow_dispatch:
inputs:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: wordcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
if: >-
github.repository == 'storytold/wordcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: wordcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment (which trusts release and
# nightly-signer) and export keys in its signing step.
+34
View File
@@ -0,0 +1,34 @@
name: WordCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
on:
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/wordcraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: wordcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
+26 -3
View File
@@ -5,9 +5,9 @@ name: Packaging lint
on:
push:
branches: [main, release]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
pull_request:
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
workflow_dispatch:
permissions:
@@ -28,7 +28,7 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -49,3 +49,26 @@ jobs:
- name: Build and check non-executable installer fixtures
shell: pwsh
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
nightly-source-contract:
name: Nightly source contracts (no build or signing)
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Enforce nightly serialization and synthetic packaging contracts
run: python3 packaging/nightly-tests.py
- name: Check the Arch Nightly handoff launcher (no build)
run: bash packaging/linux/nightly-arch-tar-test.sh
- name: Render and run the Nightly tar launcher (no build)
run: bash packaging/linux/nightly-package-test.sh
- name: Check the flat Nightly tar's shared template launcher (no build)
run: bash packaging/linux/nightly-tar-launch-test.sh
+4
View File
@@ -8,3 +8,7 @@ plan/
/.claude/
/target-*/
/craft-fonts/
/.nightly-tools
/.nightly-input
/craft-i18n
__pycache__/
-69
View File
@@ -1,69 +0,0 @@
# Accessibility
Source: `standards/app-accessibility.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib/blob/main/standards/app-accessibility.md); do not edit this copy directly. Propose changes to the shared statement in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib).
We want people who use screen readers, braille displays, screen magnifiers, voice control, high contrast, large text, reduced motion, or keyboard navigation to be able to get their work done in the Craft applications.
## Supported environments and how accessibility works
The Craft applications draw their own interface in Rust with `egui` and expose accessibility information through **AccessKit**:
- **Windows:** UI Automation (for tools such as NVDA, JAWS, and Narrator)
- **macOS:** NSAccessibility (VoiceOver)
- **Linux and FreeBSD:** AT-SPI (Orca)
- **Web (WebAssembly):** Browser accessibility tree in modern evergreen browsers
- **Display and motion:** Light and dark themes, along with ongoing work to honour system high-contrast, text-scaling, and reduced-motion settings
- **Headless and command-line workflows:** Most Craft applications also ship a command-line and automation binary (`<app>-cli`) that can inspect and edit documents from a terminal without using the graphical interface; see [This application](#this-application) below
**Current status:** The Craft suite is in early-alpha development. We use WCAG 2.2 and W3C's [WCAG2ICT](https://www.w3.org/TR/wcag2ict-22/) as practical reference points for user needs ([RFC-0014](https://github.com/storytold/craft-contrib/blob/main/rfcs/0014-accessibility.md)), while manual testing with assistive technologies across every tool and surface is still in progress.
## Known limitations and workarounds
Shared framework improvements are tracked in [storytold/craft-libs#437](https://github.com/storytold/craft-libs/issues/437). Current suite-wide gaps include:
- **Custom drawn surfaces (canvases, pages, grids, timelines, node graphs, and layer lists):** Some custom-painted views do not yet publish complete `AccessKit` nodes, caret bounds for magnifiers, or editable states (for example, `AccessKit`'s Windows adapter reporting `Document` nodes as read-only, which can prevent typing echo in screen readers). *Workaround:* Use structured inspector panels where available, or run headless commands through `<app>-cli` when a task does not need direct canvas interaction.
- **Focus in menus, toolbars, and dialogs:** Some popups, menus, or keyboard access-key overlays may leave focus in the underlying document or not yet restore focus cleanly when dismissed. *Workaround:* Press `Escape` to close open popups, `Alt` or `F10` for menu/toolbar navigation, and `F6` to move between major regions where supported.
- **Unannounced state changes:** Shortcuts or background tasks that change state away from focus do not yet consistently announce updates through a live region.
- **Pointer-heavy interactions:** Certain timeline, node-wiring, or object-placement gestures do not yet have non-dragging keyboard alternatives.
See [This application](#this-application) below for repository-specific links and details.
## Reporting an accessibility barrier
If you run into an accessibility barrier, please open an issue using the link in [This application](#this-application) below (or let us know in the [ArtCraft Discord](https://discord.gg/artcraft) if GitHub's issue form gets in the way).
- **No personal disclosure needed:** You never have to disclose a disability or explain why you use assistive technology.
- **Screenshots and recordings are optional:** Plain-text descriptions are always welcome and sufficient.
- **Helpful details to share (when convenient):**
- What you were trying to do, what happened, and what you expected
- Application version (or commit) and operating system or browser
- Input method, display settings, or assistive technology and version (for example, NVDA, JAWS, Narrator, VoiceOver, Orca, screen magnifier, high contrast, text scaling, or keyboard-only)
## How we respond
- **Triage and labels:** Maintainers and triagers label barrier reports with `accessibility` and set priority during triage based on impact—barriers that block a core workflow are treated as high-priority bugs, and barriers that risk losing work are critical.
- **Assistive-technology verification (`needs screen reader test`):** Pull requests that fix a reported assistive-technology barrier or add custom accessibility-tree or focus behaviour are labelled `needs screen reader test` so someone using assistive technology can verify a build and share what they observed; if the barrier remains, we reopen the issue.
## Note for contributors and coding agents
`ACCESSIBILITY.md` is a user-facing overview, **not** an extra rule set or audit checklist for coding agents:
- **Follow `AGENTS.md` and [`standards/accessibility.md`](https://github.com/storytold/craft-contrib/blob/main/standards/accessibility.md) for engineering work,** and keep every pull request scoped strictly to its issue. Do not widen an unrelated change to audit or rework surrounding UI.
- **Design for the actual user need—do not overbuild or apply naive readings of standards.** Accessibility guidelines exist to support real workflows and give flexible ways to meet them. Understand what a criterion genuinely requires in context before changing UI: for example, a button whose label or icon is legible and whose focus or selection ring already has clear contrast does **not** need its resting fill or border restyled to hit a 3:1 ratio, and inherently spatial or freehand tools should not have artificial keyboard grids bolted onto them.
- **Preserve visual design and shared primitives.** Use shared theme tokens and shared widgets from `storytold/craft-libs` instead of inventing one-off styling, contrast overrides, focus shims, or live-region scaffolding inside an application.
- **Be candid in pull requests.** Automated accessibility-tree checks never prove a change works with a real screen reader; describe only what was actually verified.
## Ownership
Maintained by the `craft-app-team` maintainers in [`storytold`](https://github.com/storytold). Shared updates belong in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib); repository-specific facts follow below.
## This application
**WordCraft** (`storytold/wordcraft`) is an open-source word processor written in pure Rust.
- **Published application builds:** macOS, Windows, Linux, FreeBSD, and Web (WebAssembly)
- **Command-line and automation interface:** `wordcraft-cli` provides headless terminal and automation access for scripted workflows without the graphical interface
- **Report an accessibility barrier:** [Open an issue in `storytold/wordcraft`](https://github.com/storytold/wordcraft/issues/new)
- **Tracked accessibility issues:** [Open issues labelled `accessibility` in `storytold/wordcraft`](https://github.com/storytold/wordcraft/issues?q=is%3Aissue+state%3Aopen+label%3Aaccessibility)
- **Pull requests awaiting assistive-technology verification:** [Pull requests labelled `needs screen reader test` in `storytold/wordcraft`](https://github.com/storytold/wordcraft/pulls?q=is%3Apr+label%3A%22needs+screen+reader+test%22)
- **Contributor and agent rules for this repository:** [`AGENTS.md`](AGENTS.md)
+6
View File
@@ -26,6 +26,12 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.wordcraft.svg` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
| `assets/app-icon/hicolor/48x48/apps/ai.storyteller.wordcraft.png` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.wordcraft.png` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
| `assets/app-icon/wordcraft-nightly.png` | WordCraft contributors | derived from `assets/app-icon/hicolor/256x256/apps/ai.storyteller.wordcraft.png` by `packaging/nightly-icons.py` (nightly field `#232c67`); input hashes and the recipe are in `assets/app-icon/nightly-provenance.json` | MIT OR Apache-2.0 | Nightly 256 px render; the icon the Linux Nightly tar ships |
| `assets/app-icon/wordcraft-nightly-1024.png` | WordCraft contributors | derived from `assets/app-icon/wordcraft-1024.png` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | 1024 px master the Nightly `.icns` is generated from |
| `assets/app-icon/wordcraft-nightly.ico` | WordCraft contributors | derived from `assets/app-icon/wordcraft.ico` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | Windows Nightly icon (16-256 px), embedded by `apps/wordcraft/build.rs` into the Nightly executable only |
| `assets/app-icon/wordcraft-nightly.icns` | WordCraft contributors | derived from `assets/app-icon/wordcraft.icns` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | macOS Nightly bundle icon (`CFBundleIconFile wordcraft-nightly`) |
| `assets/app-icon/nightly-provenance.json` | WordCraft contributors | original work for this repository | MIT OR Apache-2.0 | The exact inputs, palette and transform that produced the Nightly icon set |
| `assets/app-icon/README.md` | WordCraft contributors | original description of this repository's own icon artwork | MIT OR Apache-2.0 | Names the master, the sizes and the regeneration steps |
| `assets/fonts/Inter-Medium.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
| `assets/fonts/Inter-Regular.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
| `assets/fonts/Inter-SemiBold.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
Generated
+6
View File
@@ -6442,6 +6442,9 @@ dependencies = [
"raw-window-handle",
"wasm-bindgen",
"wasm-bindgen-futures",
"wayland-backend",
"wayland-client",
"wayland-protocols",
"web-sys",
"windows-sys 0.61.2",
]
@@ -8970,10 +8973,13 @@ dependencies = [
"eframe",
"egui",
"log",
"rfd",
"serde_json",
"tempfile",
"thiserror 2.0.21",
"winit",
"winresource",
"winsafe",
"wordcraft-control-key",
"wordcraft-doc",
"wordcraft-engine",
+13
View File
@@ -66,3 +66,16 @@ _Avoid_: Tofu, box, notdef character
A picture the document refers to that the output cannot include: its part is absent, its data
cannot be decoded, its format is unsupported, or it is linked from outside the file.
_Avoid_: Broken image, dropped image
## Windows
**Document window**:
A top-level window showing one open document. A document can be shown in several document windows
at once (View › New Window); each window shows exactly one.
_Avoid_: Viewport (that is the framework's surface), root window, tab
**Save prompt**:
The question "Save changes?" asked when the last document window showing a document with unsaved
changes is about to close. It belongs to that window and appears there; while it is up, the other
windows wait.
_Avoid_: Close guard, save dialog, unsaved-changes dialog
-1
View File
@@ -167,7 +167,6 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
- 2026-11-17: File formats, codecs and protocols now come from the shared libraries (storytold/craft-libs#778): legacy code pages (craft-codepage, #6785), plain-text encoding detection (craft-mime, #6950), the ZIP entry-count guard (craft-zip, #6948), Read Aloud's Speech Dispatcher wire format (craft-ssip, #6951), picture probes for clipboard DIBs, JPEG memory, PNG and WebP (craft-image-codecs, #6949, #6955) and the MCP stdio server (craft-mcp-server, #6956), all with craft-libs pinned at main `93dac78c` (#6954, #6960). Opening documents and pictures behaves as before, except that large non-interleaved JPEGs are refused sooner (a 4:4:4 picture from about 60 Mpx, was 67 Mpx), invalid PNGs are refused more strictly, a lossless WebP's transparency is now seen, and MCP clients get tool errors for unknown or mistyped arguments and a 1,000-message batch cap (docs/mcp.md). The old code stays as test-only references the shared code is checked against.
- 2026-11-15: Get the Missing Fonts. A document opened from a file that is missing fonts their publisher gives away (Microsoft's Aptos family, the default in recent Word documents; Cascadia Code and Mono) brings up a box naming each font, the font drawn instead, the publisher's download page and how to install the download, with Don't show this again. `font.missing` reports the same page, so agents get it without the box. WordCraft links to the page only; it downloads and bundles nothing.
- 2026-10-30: Track Changes: a list item deleted whole, text and paragraph mark, shows its number as deleted text, in the deletion's colour and with its mark (struck through by default, or caret, #, bold, italic, underline), and hides it with No Markup or when Track Changes Options hide deletions (#4828). Readiness unchanged.
fix/6146-touchpad-scroll-speed
- 2026-11-09: Touchpad and mouse-wheel scroll speed settings (#6146): scales Wayland touchpad point input by default (4×) so two-finger scrolling matches desktop speed rather than crawling 1:1, and scales mouse wheel line distance; File › Options › Advanced › Scrolling; commands ui.scrollSpeed and ui.touchpadScrollSpeed.
- 2026-11-15: Layout: from Word 2013's layout (compatibility mode 15), balancing the columns before a continuous break keeps the last two, three or five lines of a paragraph that began on the page before together, keeps a two- or three-line paragraph that begins the last page whole, and holds a paragraph with keep lines together (or keep with next) whole in the first column when the strict rules fit. Synthetic tests also cover a footnote and a float (#6821); mode 14 splits them as before. Readiness estimates unchanged.
+13
View File
@@ -897,8 +897,21 @@ fn parity_markdown(p: &Value) -> String {
s
}
/// The Launcher's Nightly bootstrap belongs to the desktop app: a CLI must not accept it, in the
/// separate-token or `=` form, so a mis-routed launch fails loudly instead of editing stable data.
fn launcher_profile_flag(args: &[OsString]) -> bool {
args.iter().any(|arg| {
let arg = arg.to_string_lossy();
arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=")
})
}
fn main() -> ExitCode {
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
if launcher_profile_flag(&args) {
eprintln!("wordcraft-cli: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
return ExitCode::from(2);
}
// Language packs installed in the suite's font store are used; `proof.installPack` installs
// only while the person has turned downloading on in the app.
wordcraft_engine::packs::use_font_store(false);
+17
View File
@@ -1,6 +1,23 @@
use super::*;
use std::io::Read;
/// The desktop app's Nightly bootstrap is never a CLI option, in either spelling.
#[test]
fn the_launcher_profile_bootstrap_is_refused_in_both_forms() {
for argv in [
&["--launch-profile", "nightly-v1", "--profile-root", "/nightly/profiles/wordcraft", "--version"][..],
&["--launch-profile=nightly-v1", "--profile-root=/nightly/profiles/wordcraft"][..],
&["--profile-root", "/nightly/profiles/wordcraft"][..],
] {
let argv: Vec<std::ffi::OsString> = argv.iter().map(std::ffi::OsString::from).collect();
assert!(launcher_profile_flag(&argv), "{argv:?}");
}
for argv in [&["--version"][..], &["proof.check", "--launch-profiles"][..], &["--profile-roots"][..]] {
let argv: Vec<std::ffi::OsString> = argv.iter().map(std::ffi::OsString::from).collect();
assert!(!launcher_profile_flag(&argv), "{argv:?}");
}
}
fn args(values: &[&str]) -> Vec<String> {
values.iter().map(|value| (*value).into()).collect()
}
+6
View File
@@ -25,6 +25,9 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "
egui = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
# The nightly launch profile's refusal dialog (a native message box, like the app's other OS errors).
rfd = { workspace = true }
thiserror = { workspace = true }
# The suite's shared libraries: the runtime hooks (`ui`, `ui-app`), file dialogs, the control
# channel's arguments, the GPU choice, printing, settings and window placement, the OS appearance
# reader and the system clipboard.
@@ -68,3 +71,6 @@ xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
# The update helper: a copy of this program started with `--finish-update`
# (`craft::update::self_update::finish`).
craft = { workspace = true, features = ["update"] }
# The nightly Windows identity: an explicit AppUserModelID, so Nightly gets its own taskbar
# button instead of sharing the stable app's (#16335's rule for the suite).
winsafe = { version = "=0.0.29", default-features = false, features = ["user", "shell"] }
+43 -5
View File
@@ -1,25 +1,63 @@
//! Windows only: embed the app icon and version info (VERSIONINFO) into `wordcraft.exe`, so it
//! shows in Explorer, the taskbar, the Start menu and Alt-Tab.
//!
//! On every other target this does nothing. A missing resource compiler is a warning, so a
//! cross-compile from macOS or Linux still links, unless `WORDCRAFT_REQUIRE_WINRES=1` turns it
//! The build channel (`WORDCRAFT_BUILD_CHANNEL`) is decided here, before any code is compiled: a
//! nightly-v1 build gets its own cfg, its own icon and its exact feed version in VERSIONINFO.
//! On every other target this does nothing but that. A missing resource compiler is a warning, so
//! a cross-compile from macOS or Linux still links, unless `WORDCRAFT_REQUIRE_WINRES=1` turns it
//! into an error (for release builds).
#[path = "src/build_channel.rs"]
mod build_channel;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=WORDCRAFT_BUILD_CHANNEL");
println!("cargo:rustc-check-cfg=cfg(wordcraft_nightly_v1)");
let nightly = match std::env::var("WORDCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=wordcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported WORDCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
println!("cargo:rerun-if-changed=../../assets/app-icon/wordcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/wordcraft-nightly.ico");
println!("cargo:rerun-if-env-changed=WORDCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=WORDCRAFT_VERSION");
let built_version = if nightly {
match std::env::var("WORDCRAFT_VERSION") {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit WORDCRAFT_VERSION feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=WORDCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut res = winresource::WindowsResource::new();
res.set_icon("../../assets/app-icon/wordcraft.ico")
.set("ProductName", "WordCraft")
.set("FileDescription", "WordCraft word processor")
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "WordCraft Nightly" } else { "WordCraft" })
.set("FileDescription", if nightly { "WordCraft Nightly word processor" } else { "WordCraft word processor" })
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) the WordCraft authors. MIT OR Apache-2.0.")
.set("OriginalFilename", "wordcraft.exe")
.set("InternalName", "wordcraft");
if nightly {
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
res.set("ProductVersion", &built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("WORDCRAFT_REQUIRE_WINRES").is_some() {
eprintln!("embedding Windows resources failed: {e}");
+54
View File
@@ -0,0 +1,54 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/wordcraft-nightly.ico" } else { "../../assets/app-icon/wordcraft.ico" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/wordcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/wordcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.18.1-nightly.20261124.17.1.gabcdef012345"));
for invalid in [
"",
"0.18.1",
"0.18.1-nightly",
"0.18.1-nightly.20261124",
"0.18.1-nightly.20261124.17.1.gABCDEF012345",
"0.18.1-nightly.20261124.17.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.18.1-nightly.20261124.1.1.gabcdef012345",
"0.18.1-nightly.20261124.1.1.gabcdef012345/other",
"0.18.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
+72
View File
@@ -0,0 +1,72 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub const COMPILED: BuildFlavor = if cfg!(wordcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open WordCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable WordCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
/// The Launcher's version line: `WordCraft <version> (nightly-v1)` for a nightly build.
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("WordCraft {stable} (nightly-v1)"),
}
}
/// A plain `--version` / `-V`: the only arguments, answered before any startup work.
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.18.1"), "0.18.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.18.1"), "WordCraft 0.18.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
+163
View File
@@ -123,4 +123,167 @@ mod tests {
assert!(supplied.exists());
let _ = std::fs::remove_dir_all(&dir);
}
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
fn boot() -> (u16, Receiver<ControlRequest>, Control) {
let options = ControlOptions { token: Some(TOKEN.to_string()), ..ControlOptions::default() };
let (rx, control) = start(&options, 0, host(), None).unwrap();
let port = control.listening.addr.port();
(port, rx, control)
}
/// Answer the next request that reaches the UI with `ok`, and return it.
fn answer(rx: &Receiver<ControlRequest>) -> ControlRequest {
let req = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
let _ = req.reply.send(serde_json::json!({"ok": true, "result": {}}));
req
}
/// One connection, several lines.
struct Conn(std::io::BufReader<std::net::TcpStream>, std::net::TcpStream);
impl Conn {
fn open(port: u16) -> Self {
let s = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
s.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap();
Self(std::io::BufReader::new(s.try_clone().unwrap()), s)
}
fn send(&mut self, line: &str) {
use std::io::Write;
writeln!(self.1, "{line}").unwrap();
}
fn recv(&mut self) -> serde_json::Value {
use std::io::BufRead;
let mut r = String::new();
let n = self.0.read_line(&mut r).expect("read reply line");
assert!(n > 0, "unexpected EOF while waiting for reply");
serde_json::from_str(&r).expect("reply is valid JSON")
}
fn call(&mut self, line: &str) -> serde_json::Value {
self.send(line);
self.recv()
}
/// The server closed the connection.
fn closed(&mut self) -> bool {
use std::io::BufRead;
let mut r = String::new();
match self.0.read_line(&mut r) {
Ok(0) => true,
Err(e) => matches!(
e.kind(),
std::io::ErrorKind::ConnectionReset
| std::io::ErrorKind::ConnectionAborted
| std::io::ErrorKind::NotConnected
| std::io::ErrorKind::BrokenPipe
),
_ => false,
}
}
}
/// Post-#7101 adaptation of `the_key_on_each_request` (#124, tracked under #7317 / #7720):
/// `craft::automation::server` replaced the legacy per-request `"key"` field with one-time
/// per-connection token authentication (`docs/control-protocol.md`, Token).
#[test]
fn a_connection_authenticates_once_with_the_token_and_unauthenticated_requests_are_refused() {
let (port, rx, control) = boot();
// Authenticate once per connection with `params.token`.
let mut c = Conn::open(port);
let auth_resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#));
assert_eq!(auth_resp, serde_json::json!({"id": 1, "ok": true, "result": {"authenticated": true}}));
// Subsequent requests on the authenticated connection carry no token and reach the UI.
c.send(r#"{"id":7,"method":"document.inspect","params":{"text":true}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"text": true})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(7)));
c.send(r#"{"id":8,"method":"document.inspect","params":{"text":false}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"text": false})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(8)));
drop(c);
// An unauthenticated connection is refused and closed without reaching the UI.
let mut unauth = Conn::open(port);
let r = unauth.call(r#"{"id":9,"method":"document.inspect"}"#);
assert_eq!(r, serde_json::json!({"id": 9, "ok": false, "error": "authentication required"}));
assert!(unauth.closed());
assert!(rx.try_recv().is_err(), "unauthenticated request must not reach the UI");
drop(unauth);
// Legacy pre-#7101 per-request `"key"` does not bypass `auth` and closes the connection.
let mut legacy = Conn::open(port);
let r = legacy.call(&format!(r#"{{"id":10,"key":"{TOKEN}","method":"document.inspect","params":{{"text":true}}}}"#));
assert_eq!(r, serde_json::json!({"id": 10, "ok": false, "error": "authentication required"}));
assert!(legacy.closed());
assert!(rx.try_recv().is_err(), "legacy per-request key must not reach the UI");
drop(legacy);
control.shut_down();
}
/// Post-#7101 adaptation of `params_key_is_only_a_secret_for_auth` (#124, tracked under #7317 / #7729):
/// `craft::automation::server` replaced legacy `"key"` / `params.key` secrets with one-time
/// per-connection `auth` using `params.token` (`docs/control-protocol.md`, Token).
#[test]
fn params_token_is_only_a_secret_for_auth() {
let (port, rx, control) = boot();
// Neither `params.token` on a non-`auth` method nor legacy `params.key` on
// `document.inspect` or `auth` authenticates.
for (id, line) in [
(1, format!(r#"{{"id":1,"method":"document.inspect","params":{{"token":"{TOKEN}"}}}}"#)),
(2, format!(r#"{{"id":2,"method":"document.inspect","params":{{"key":"{TOKEN}"}}}}"#)),
(3, format!(r#"{{"id":3,"method":"auth","params":{{"key":"{TOKEN}"}}}}"#)),
] {
let mut c = Conn::open(port);
assert_eq!(c.call(&line), serde_json::json!({"id": id, "ok": false, "error": "authentication required"}));
assert!(c.closed());
}
assert!(rx.try_recv().is_err(), "refused requests must not reach the UI");
// Authenticate once with `params.token`; `params.key` and `params.token` on subsequent
// non-`auth` methods are forwarded untouched as ordinary parameters.
let mut c = Conn::open(port);
let auth_resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#));
assert_eq!(auth_resp, serde_json::json!({"id": 1, "ok": true, "result": {"authenticated": true}}));
c.send(r#"{"id":2,"method":"ui.key","params":{"key":"Enter"}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("ui.key", &serde_json::json!({"key": "Enter"})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(2)));
c.send(r#"{"id":3,"method":"document.inspect","params":{"token":"ordinary"}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"token": "ordinary"})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(3)));
drop(c);
control.shut_down();
}
/// Post-#7101 adaptation of `a_wrong_key_is_refused_and_closed` (#124, tracked under #7317):
/// wrong, short, and long `params.token` values are refused and close the connection without
/// reaching the UI.
#[test]
fn a_wrong_token_is_refused_and_closed() {
let (port, rx, control) = boot();
let wrong = TOKEN.replace('0', "1");
let long = format!("{TOKEN}0");
for token in ["nope", wrong.as_str(), &TOKEN[..63], long.as_str()] {
let mut c = Conn::open(port);
let resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{token}"}}}}"#));
assert_eq!(resp, serde_json::json!({"id": 1, "ok": false, "error": "authentication required"}), "{token}");
assert!(c.closed(), "{token}");
}
assert!(rx.try_recv().is_err(), "refused auth attempts must not reach the UI");
control.shut_down();
}
}
+17
View File
@@ -54,6 +54,23 @@ pub fn identity() -> AppIdentity {
mod tests {
use super::*;
/// Every type the button claims is included in identity, and plain text/Markdown are never claimed.
#[test]
fn xdg_mime_sets_every_word_type_in_one_call() {
let id = identity();
assert_eq!(id.desktop_id, "ai.storyteller.wordcraft.desktop");
assert_eq!(id.registered_name, "WordCraft");
for t in [
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/msword",
"application/rtf",
"application/vnd.oasis.opendocument.text",
] {
assert!(id.mime_types.iter().any(|a| a == t), "{t}");
}
assert!(!id.mime_types.iter().any(|a| a == "text/plain" || a == "text/markdown"), "plain text and Markdown are never claimed");
}
/// Every type the button claims is one the desktop entry declares, or desktops ignore it.
#[test]
fn the_desktop_entry_declares_every_claimed_type() {
+211
View File
@@ -0,0 +1,211 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, preferences, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old settings-folder resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path) -> Result<PathBuf, String> {
crate::profile_root::validate(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref(), crate::profile_root::probe_writable)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\wordcraft" } else { "/nightly-data/profiles/wordcraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--control", "7981", "a.docx"]), args(&["--", "--launch-profile", "file.docx"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "letter with spaces.docx"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "letter with spaces.docx"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--sample", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse(argv).is_err());
}
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--sample", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+191 -22
View File
@@ -14,9 +14,16 @@
#[cfg(target_os = "linux")]
mod appimage_env;
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod control_server;
mod default_apps;
mod launch_profile;
mod nightly_session;
mod prefs;
mod process_identity;
mod profile_root;
mod region;
use std::path::PathBuf;
@@ -58,6 +65,9 @@ struct App {
spool: Spool,
/// The control server, when `--control` started one; it removes the token file it made.
control: Option<control_server::Control>,
/// The app binary's last step as the app leaves, run once at the end of `finish` (a Nightly
/// quit ends the process inside AppKit's terminate, after eframe's `on_exit`).
exit: Option<Box<dyn FnOnce()>>,
}
impl App {
@@ -95,7 +105,12 @@ impl App {
if let Some(control) = self.control.take() {
control.shut_down();
}
self.app.start_pending_update();
if !launch_profile::current().is_nightly() {
self.app.start_pending_update();
}
if let Some(exit) = self.exit.take() {
exit();
}
}
}
@@ -202,10 +217,12 @@ type MakeDefault = Box<dyn Fn() -> Result<DefaultApp, DefaultAppError>>;
/// What the app takes from its host beyond the runtime: File › Print through the system spooler,
/// personal templates (#2852, made on first save in `Templates` in the settings folder), and making
/// WordCraft the default app for Word documents (#295; macOS has no way to, so no button there).
fn services(spool: Spool, intake: FileIntake) -> Services {
fn services(spool: Spool, intake: FileIntake, nightly: bool) -> Services {
// Nightly never claims the stable app's file associations: the button would rewrite the same
// OS registration the stable WordCraft owns.
#[cfg(any(unix, windows))]
let make_default_app =
(!cfg!(target_os = "macos")).then(|| -> MakeDefault { Box::new(|| craft::platform::default_app::make_default(&default_apps::identity())) });
let make_default_app = (!cfg!(target_os = "macos") && !nightly)
.then(|| -> MakeDefault { Box::new(|| craft::platform::default_app::make_default(&default_apps::identity())) });
#[cfg(not(any(unix, windows)))]
let make_default_app: Option<MakeDefault> = None;
Services {
@@ -258,9 +275,9 @@ fn build_sha() -> &'static str {
/// The arguments as text, and apart the files whose names aren't valid Unicode, such as a Latin-1
/// one (#1440). A `--control` port, a token or a token file that isn't is an error.
fn text_args() -> (Vec<String>, Vec<std::path::PathBuf>) {
fn text_args(arguments: Vec<std::ffi::OsString>) -> (Vec<String>, Vec<std::path::PathBuf>) {
let (mut args, mut files) = (Vec::new(), Vec::new());
for (i, a) in std::env::args_os().skip(1).enumerate() {
for (i, a) in arguments.into_iter().enumerate() {
match a.into_string() {
Ok(a) => args.push(a),
Err(a) if args.last().is_some_and(|p| matches!(p.as_str(), "--control" | "--control-token" | "--control-token-file")) => {
@@ -318,18 +335,96 @@ fn complain(message: std::fmt::Arguments<'_>) {
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("wordcraft: {message}\n"));
}
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
process_identity::initialize(
build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1,
wordcraft_ui_egui::os_window::id_for(wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1),
)
}
/// Tell the person why a Launcher launch was refused, with a native message box on a desktop
/// session (a Launcher start has no terminal to read standard error from).
fn report_launch_profile_error(error: &str) {
complain(format_args!("launch profile: {error}"));
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if let Err(identity) = initialize_nightly_process_identity() {
complain(format_args!("launch profile: {identity}"));
return;
}
let _ = rfd::MessageDialog::new()
.set_title("WordCraft Nightly")
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Select the immutable launch profile before any startup service or side effect.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// The trusted Launcher protocol is decided before logging, crash handling, the update helper,
// fonts, preferences or the settings folder.
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
let line = build_flavor::version(build_flavor::COMPILED, env!("WORDCRAFT_BUILT_VERSION"));
let _ = std::io::Write::write_all(&mut std::io::stdout(), format!("{line}\n").as_bytes());
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| launch_profile::prepare(launch, launch_profile::validate_root))
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let identity = if early.profile.is_nightly() {
wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1
} else {
wordcraft_ui_egui::os_window::LaunchIdentity::Stable
};
if let Err(error) = launch_profile::install(early.profile).and_then(|()| wordcraft_ui_egui::os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
// One data root for everything the app keeps: preferences, window place, logs, recovery,
// fonts, templates, dictionaries and control token files all come from it.
if let Some(root) = launch_profile::current().root()
&& let Err(error) = wordcraft_control_key::use_settings_dir(root.to_path_buf())
{
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
}
/// Parses the command line, installs logging and the panic hook, restores preferences and window
/// geometry, opens requested documents or the Start screen, starts the control server when
/// asked, and runs the eframe event loop.
fn main() -> eframe::Result {
// Windows: the print helper is a copy of this program that runs one job in its own process.
// It reads only its own job folder, so it runs before the launch profile is parsed: a Nightly
// wants a profile on every start, and the helper must print without one.
#[cfg(windows)]
if let Some(code) = craft::print::spool::isolated::helper_main() {
std::process::exit(code);
}
let Some(arguments) = prepare_launch() else { return Ok(()) };
// Windows: the update helper is a copy of this program started with `--finish-update`.
// A Nightly never updates itself: the Launcher owns its updates.
#[cfg(windows)]
if let Some(result) = craft::update::self_update::finish(&wordcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
if !launch_profile::current().is_nightly()
&& let Some(result) = craft::update::self_update::finish(&wordcraft_ui_egui::UPDATE_APP, &arguments)
{
std::process::exit(i32::from(result.is_err()));
}
// Linux: before anything reads another program's AppImage variables, or a thread starts (#5653).
@@ -352,7 +447,7 @@ fn main() -> eframe::Result {
let mut flags = ControlOptions::default();
let mut files = Vec::new();
let mut sample = false;
let (args, other_files) = text_args();
let (args, other_files) = text_args(arguments);
// Only macOS (Finder / LaunchServices) adds these; elsewhere `-NS…` could be a real file name.
let args = if cfg!(target_os = "macos") { without_launch_args(args) } else { args };
let mut bad_control: Option<Option<String>> = None;
@@ -388,6 +483,7 @@ fn main() -> eframe::Result {
},
"--sample" => sample = true,
"--version" => {
// A nightly build reported its channel line before this parser ran.
println!("wordcraft {} ({})", env!("CARGO_PKG_VERSION"), build_sha());
return Ok(());
}
@@ -422,6 +518,13 @@ fn main() -> eframe::Result {
complain(format_args!("--control needs a port number from 1 to 65535, got \"0\""));
std::process::exit(2);
}
// Nightly runs the Launcher's documents only: no control server, token file or automation
// switch, and none inherited from a stable launch's environment.
if launch_profile::current().is_nightly() && (control.port.is_some() || control.token.is_some() || control.token_file.is_some()) {
complain(format_args!("a WordCraft Nightly window does not start a control server; open documents through ArtCraft Launcher"));
std::process::exit(2);
}
let nightly = launch_profile::current().is_nightly();
let settings_dir = wordcraft_control_key::settings_dir();
// The log file lives in the settings directory, next to the preferences; opened after the
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
@@ -440,10 +543,16 @@ fn main() -> eframe::Result {
None => logger.stderr_only(),
}
}
// A Nightly window always carries its own id; a stable one keeps the Flatpak sandbox's id
// when it runs inside one (so docks match the flatpak's desktop file).
let app_id = match launch_profile::current().root() {
Some(_) => wordcraft_ui_egui::os_window::app_id().to_string(),
None => std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| wordcraft_ui_egui::os_window::APP_ID.to_string()),
};
let mut options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("WordCraft")
.with_app_id("ai.storyteller.wordcraft")
.with_title(wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()))
.with_app_id(app_id)
.with_inner_size([1440.0, 920.0])
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
.with_drag_and_drop(true)
@@ -504,9 +613,33 @@ fn main() -> eframe::Result {
let _apple_events = craft::platform::open::apple_events::install(sender);
#[cfg(not(target_os = "macos"))]
drop(sender);
// Nightly's own health record: one owner per profile, cleared only by a controlled return.
let (nightly_record, health_unavailable) = match nightly_session::Session::begin_with_health(
launch_profile::current().root(),
env!("WORDCRAFT_BUILT_VERSION"),
option_env!("WORDCRAFT_BUILD_SHA"),
) {
Ok(pair) => pair,
Err(error) => {
log::warn!("Nightly session health is unavailable: {error}");
(None, launch_profile::current().is_nightly())
}
};
let session_health_warning: Option<String> = health_unavailable.then(|| {
"WordCraft Nightly could not record session health in its private profile. You can still edit, but abnormal-exit detection is unavailable."
.to_string()
});
let previous_nightly_unclean = nightly_record.as_ref().is_some_and(nightly_session::Session::previous_unclean);
let nightly_watch: nightly_session::Shared = Arc::new(Mutex::new(nightly_record));
let unclean_notice_shown = Arc::new(std::sync::atomic::AtomicBool::new(false));
// The window body and its exit hook each take a clone of the flag; the return path keeps the
// other, so a start that created no window can still finish the record.
let session_for_exit = nightly_watch.clone();
let noticed_for_exit = unclean_notice_shown.clone();
let noticed_in_window = unclean_notice_shown.clone();
let exit_settings = settings.clone();
let result = eframe::run_native(
"WordCraft",
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
options,
Box::new(move |cc| {
let ctx = cc.egui_ctx.clone();
@@ -528,7 +661,7 @@ fn main() -> eframe::Result {
);
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
.app_id("ai.storyteller.wordcraft")
.app_id(wordcraft_ui_egui::os_window::app_id())
.system(SystemReader::start(wake))
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
.placement(placement);
@@ -547,19 +680,31 @@ fn main() -> eframe::Result {
prefs::load_user_dictionary(&mut session, &settings, path);
}
let spool = Spool::new(host.jobs_shared().clone());
let mut app = WordApp::new(session, services(spool.clone(), intake)).with_host(host).with_settings(settings.clone());
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
// the region check below reads the saved region the settings apply.
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
app = app.with_fallback_chooser(true);
}
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
if nightly {
// The Launcher installs Nightly; Help › Check for Updates says so instead.
app.use_launcher_updates();
} else {
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
}
}
// Language packs from the suite's font store; an Install click is the person's own.
wordcraft_engine::packs::use_font_store(true);
// Nightly keeps its own store in the profile, so a pack installed there is not a
// change to the stable apps' shared fonts.
match launch_profile::current().root() {
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
None => {
wordcraft_engine::packs::use_font_store(true);
}
}
// A region chosen in File › Options replaces the system's for the first blank
// document too (#838).
if !sample && app.session.prefs.region.is_some() {
@@ -576,7 +721,8 @@ fn main() -> eframe::Result {
}
}
let mut control_server = None;
if let Some(port) = control.port
if !nightly
&& let Some(port) = control.port
&& let Some((rx, started)) =
control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
{
@@ -598,9 +744,32 @@ fn main() -> eframe::Result {
for f in other_files {
open_non_unicode(&mut app, &f);
}
Ok(Box::new(App { app, panels, drops, settings, spool, control: control_server }))
// The personal agent files, the session record and the control token all live in the
// profile; the app's own services are built with the nightly rule in mind.
if let Some(warning) = &session_health_warning {
app.status_long(warning.clone());
}
if previous_nightly_unclean {
app.status_long(
"The previous WordCraft Nightly session did not finish normally. You can report a problem from Help › About. No diagnostics have been sent.",
);
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
}
Ok(Box::new(App {
app,
panels,
drops,
settings,
spool,
control: control_server,
exit: Some(Box::new(move || {
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
})),
}))
}),
);
// The exit hook has run; this is the no-op fallback for a start that created no window.
nightly_session::finish_once(&nightly_watch, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
// The app is dropped by now: whatever it saved on the way out is in the store.
if let Err(e) = exit_settings.lock().flush() {
log::warn!("preferences: {e}");
@@ -802,8 +971,8 @@ mod smoke {
let (intake, sender) = FileIntake::new(Wake::new(|| {}));
let drops = intake.sender();
let session = Session::new(wordcraft_doc::Document::new());
let app = WordApp::new(session, services(spool.clone(), intake)).with_host(host).with_settings(settings.clone());
Run { app: App { app, panels, drops, settings, spool, control: None }, frames, ctx, sender }
let app = WordApp::new(session, services(spool.clone(), intake, false)).with_host(host).with_settings(settings.clone());
Run { app: App { app, panels, drops, settings, spool, control: None, exit: None }, frames, ctx, sender }
}
/// One frame as eframe runs it: the input hook once, the logic once, the UI per pass.
+266
View File
@@ -0,0 +1,266 @@
//! App-private Nightly session health, not telemetry or a Launcher protocol.
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
use std::fs::{File, OpenOptions};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// Write `bytes` to `path` through a fresh temporary file in the same folder and a rename: the
/// destination entry is replaced, never followed, so a link planted at `path` is not written
/// through. The file is synced and the folder is synced after the rename.
fn write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let directory = path.parent().ok_or_else(|| io::Error::other("the session record has no folder"))?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let temporary = directory.join(format!(".{name}.{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
let mut file = OpenOptions::new().write(true).create_new(true).open(&temporary)?;
let written = std::io::Write::write_all(&mut file, bytes).and_then(|()| file.sync_all());
drop(file);
if let Err(error) = written {
let _ = std::fs::remove_file(&temporary);
return Err(error);
}
if let Err(error) = std::fs::rename(&temporary, path) {
let _ = std::fs::remove_file(&temporary);
return Err(error);
}
if let Ok(directory) = File::open(directory) {
let _ = directory.sync_all();
}
Ok(())
}
/// The owner's session, shared by the app's exit hook (macOS: a quit ends the process inside
/// AppKit's terminate) and the code after the event loop.
pub type Shared = Arc<Mutex<Option<Session>>>;
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(unclean_notice_shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
impl Session {
/// The warning belongs to this window: a busy secondary has no health-record coverage,
/// while Stable and a lease-owning Nightly window preserve their existing result.
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version, commit)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
/// `None` is stable or another owner of this profile. Neither case touches the record.
/// The supplied root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit.filter(|value| !value.is_empty()),
}))?;
write_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
/// Controlled return. If an earlier session's interruption was detected but no window showed
/// it yet, the record is left for the next owner to report; otherwise this is [`Self::complete`].
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Controlled event-loop completion includes a handled startup error, not only exit 0.
/// An unwind, abort, forced exit or killed process never calls this method.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path =
std::env::temp_dir().join(format!("wordcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
#[test]
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
assert!(!warning);
let first = first.unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unimportant = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
assert!(!unimportant.previous_unclean());
drop(unimportant); // Unwind/abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
// The window never started: no notice was shown.
let failed = Session::begin(Some(&fixture.0), "startup-failed", None).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
// The next start still sees the interruption and shows it.
let next = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
assert!(!clean.previous_unclean());
clean.finish(false).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
// The exit hook (macOS quit: the only path that runs there).
finish_once(&shared, false);
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
assert!(!successor.previous_unclean());
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
finish_once(&shared, false);
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
successor.complete().unwrap();
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
assert!(watch.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
}
#[test]
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
assert!(data["commit"].is_null(), "missing provenance must not be invented");
watch.complete().unwrap();
}
#[test]
#[cfg(unix)]
fn reserved_state_aliases_do_not_modify_external_files() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
}
+4 -2
View File
@@ -15,9 +15,11 @@ use wordcraft_ui_egui::prefs::{Prefs, import_legacy_window, legacy_ui_json};
/// The most of an old `ui.json` read for its window entry; the file is a few kilobytes.
const LEGACY_LIMIT: u64 = 8 << 20;
/// Whether this run reads and writes preferences. `WORDCRAFT_NO_PREFS` turns them off.
/// Whether this run reads and writes preferences. `WORDCRAFT_NO_PREFS` turns them off; a Nightly
/// profile always keeps its own, so an inherited developer switch cannot leave the app with no
/// preferences folder at all.
pub fn enabled() -> bool {
std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
crate::launch_profile::current().is_nightly() || std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
}
/// `custom-dictionary.txt` in the settings folder: the words Add to Dictionary kept (#40).
+70
View File
@@ -0,0 +1,70 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
use std::sync::OnceLock;
#[derive(Clone, Debug, thiserror::Error)]
pub enum IdentityError {
#[error("{0}")]
Configuration(String),
}
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
.map_err(IdentityError::Configuration)
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
}
+535
View File
@@ -0,0 +1,535 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
//!
//! WordCraft keeps all of its user state in one settings folder (`wordcraft_control_key::settings_dir`):
//! `config.toml`, `window.json`, `logs/`, `recovery/`, `fonts/`, `Templates/`,
//! `custom-dictionary.txt` and the control token files. The suite's shared font store
//! (`Craft Fonts` / `craft-fonts`, which also holds installed Language packs) is the one other
//! per-user folder the app writes, and Nightly points it at the profile too
//! (`wordcraft_engine::packs::use_font_store_in`). Every stable location of either is fenced here.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
/// The app id of the nightly Flatpak this build ships in (`packaging/linux/flatpak-bundle.sh`).
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.wordcraft.nightly";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("WordCraft")))
.collect::<Result<Vec<_>, _>>()?;
// The suite's shared font store and the MSI's default per-user and per-machine folders.
roots.push(required_base(env, "LOCALAPPDATA")?.join("Craft Fonts"));
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("WordCraft"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("WordCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("wordcraft")))
.collect::<Result<Vec<_>, _>>()?;
// The shared font store (fonts and Language packs) and the native packages' locations.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join("craft-fonts"));
roots.extend(["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.wordcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/WordCraft"),
library.join("Caches/WordCraft"),
library.join("Caches/ai.storyteller.wordcraft"),
library.join("Preferences/WordCraft"),
library.join("Preferences/ai.storyteller.wordcraft.plist"),
library.join("Saved Application State/ai.storyteller.wordcraft.savedState"),
library.join("Application Support/Craft Fonts"),
home.join("Applications/WordCraft.app"),
PathBuf::from("/Applications/WordCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
Ok(child)
}
/// Every existing entry directly in the profile (`config.toml`, `logs`, `recovery`, `fonts`,
/// `Templates`, `window.json` and so on) must resolve inside it, so a link there cannot point
/// Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
Ok(())
}
/// The app's exclusive create probe: a file only this process can have made, created and removed.
pub fn probe_writable(dir: &Path) -> std::io::Result<()> {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let probe = dir.join(format!(".nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
}
/// The writable hook is injected so filesystem boundary tests exercise the real policy without
/// starting the app or creating the profile of the person running them.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
// The developer switch that points a run at any folder: Nightly's folder comes from the Launcher.
if env("WORDCRAFT_PROFILE_DIR").is_some_and(|v| !v.is_empty()) {
return Err("nightly-v1 cannot be combined with WORDCRAFT_PROFILE_DIR".into());
}
// These rows are native tar/app-bundle launches, not a Flatpak package. Inheriting a Flatpak
// runtime could point another profile at the stable app's token files; the nightly Flatpak
// itself (`packaging/linux/flatpak-bundle.sh`) is the one sandbox this build ships in.
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
&& id != NIGHTLY_FLATPAK_ID
{
return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into());
}
let chosen = canonical_future(root)?;
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
// Existing aliases under the profile must not redirect its own subfolders elsewhere.
entries_stay_inside(&chosen)?;
// Recovery can read, adopt and sweep entries; a link there must never leave the profile.
private_subdirectory(&chosen, "recovery", "recovery folder")?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
private_subdirectory(&confirmed, "recovery", "recovery folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("wordcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/wordcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|dir| {
let probe = dir.join("exclusive-test-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
},
)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
fn linux_fences_the_settings_folders_font_store_and_packages_but_allows_the_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("wordcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let fonts = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap()).join("craft-fonts");
std::fs::create_dir_all(fonts.join("language-packs")).unwrap();
for candidate in [fonts.clone(), fonts.join("nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
for package in ["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"] {
assert!(fixture.check(Platform::Linux, &PathBuf::from(package)).is_err());
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
let nightly = data.join("ArtCraftLauncher/nightly/profiles/wordcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn linux_fences_the_stable_flatpak_data_folder() {
let fixture = Fixture::new();
let flatpak = fixture.home().join(".var/app/ai.storyteller.wordcraft");
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert!(!flatpak.exists());
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
// Inside the Nightly Flatpak, XDG_DATA_HOME is this app's own persistent data folder, so
// the launcher's profile lands there rather than on the discarded sandbox home.
let nightly = fixture.home().join(".var/app/ai.storyteller.wordcraft.nightly/data/wordcraft-nightly");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
}
#[test]
fn mac_fences_the_app_library_subtrees_the_shared_font_store_and_the_whole_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/WordCraft Nightly.app/Contents/MacOS/WordCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/WordCraft",
"Caches/WordCraft",
"Caches/ai.storyteller.wordcraft",
"Preferences/WordCraft",
"Saved Application State/ai.storyteller.wordcraft.savedState",
"Application Support/Craft Fonts",
] {
let stable = library.join(suffix);
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/wordcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
}
#[test]
fn windows_roaming_local_font_store_and_install_fences_remain_active() {
let fixture = Fixture::new();
let mut fixture = fixture;
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("WordCraft");
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
let fonts = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Craft Fonts");
assert!(fixture.check(Platform::Windows, &fonts.join("nightly")).unwrap_err().contains("overlap"));
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
let per_user = local.join("Programs").join("ArtCraft").join("WordCraft");
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
let base = fixture.root.join(format!("machine {key}"));
fixture.env.insert(key.into(), base.clone().into_os_string());
let machine = base.join("ArtCraft").join("WordCraft");
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
assert!(!machine.exists());
}
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("wordcraft");
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not WordCraft's install");
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/wordcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("recovery"), platform));
assert!(overlaps(&root.join("recovery"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("wordcraft-other"), platform));
}
}
#[cfg(unix)]
#[test]
fn recovery_and_entry_aliases_cannot_leave_the_profile_and_stable_bytes_stay_untouched() {
let fixture = Fixture::new();
let stable = fixture.home().join(".config/wordcraft/recovery");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join("recovery")).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "recovery must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
}
for name in ["logs", "fonts", "config.toml"] {
let private = fixture.root.join(format!("nightly-entry-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_err(), "{name} must not lead outside the profile");
}
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn a_recovery_alias_inside_the_profile_keeps_it_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
std::fs::create_dir_all(&recovery).unwrap();
std::os::unix::fs::symlink(&recovery, private.join("recovery")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
assert_eq!(std::fs::canonicalize(private.join("recovery")).unwrap(), recovery);
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/wordcraft");
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
fixture.env.remove("XDG_CACHE_HOME");
fixture.env.insert("WORDCRAFT_PROFILE_DIR".into(), fixture.home().join("custom-stable").into_os_string());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("WORDCRAFT_PROFILE_DIR"));
fixture.env.remove("WORDCRAFT_PROFILE_DIR");
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.wordcraft".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
fixture.env.remove("FLATPAK_ID");
// The nightly Flatpak is the one sandbox this build ships in, so its own id is accepted.
let flatpak_profile = fixture.home().join("nightly/flatpak-profile");
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
assert_eq!(fixture.check(Platform::Linux, &flatpak_profile).unwrap(), flatpak_profile);
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
assert!(!candidate.exists());
}
#[test]
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
let fixture = Fixture::new();
let file = fixture.home().join("not-a-directory");
std::fs::write(&file, b"do not replace me").unwrap();
assert!(fixture.check(Platform::Linux, &file).is_err());
assert_eq!(std::fs::read(file).unwrap(), b"do not replace me");
let candidate = fixture.home().join("nightly");
let calls = std::cell::Cell::new(0);
let result = validate_for(
Platform::Linux,
&candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
calls.set(calls.get() + 1);
Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal"))
},
);
assert!(result.unwrap_err().contains("not writable"));
assert_eq!(calls.get(), 1);
assert!(!fixture.home().join(".config/wordcraft").exists());
}
#[cfg(unix)]
#[test]
fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() {
use std::os::unix::fs::symlink;
let fixture = Fixture::new();
let stable = fixture.home().join(".config/wordcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("sentinel"), b"untouched").unwrap();
let alias = fixture.home().join("alias");
symlink(&stable, &alias).unwrap();
assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap"));
let missing = fixture.home().join("missing-target");
let dangling = fixture.home().join("dangling");
symlink(&missing, &dangling).unwrap();
assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err());
assert!(!missing.exists());
assert!(!stable.join("nightly").exists());
assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched");
}
}
+39
View File
@@ -0,0 +1,39 @@
# WordCraft app icon
A **page and pen**: a sheet of paper with a folded corner and ruled lines, with a fountain pen
lying across its lower right, on the app's blue field. It is drawn in the canvas palette the app's
own artwork uses (`#3b5bdb` field, `#efe9dc` paper, `#0b0b0c` ink).
`wordcraft.svg` is the canonical master: a full-bleed 512-unit tile with a rounded square
(`rx=112`) and no border. Windows and Linux use the tile as it is; the macOS renders sit on
Apple's grid, an 824/1024 body with a transparent margin.
## Files
- `wordcraft.svg`: canonical master (also the hicolor scalable icon).
- `wordcraft-1024.png`: 1024 px full-bleed render.
- `wordcraft-macos-512.png`: the padded macOS render (Dock, window icon; embedded by the app).
- `wordcraft.icns`: macOS bundle icon (`CFBundleIconFile`), padded frames.
- `wordcraft.ico`: Windows icon, 16–256 px, embedded in `wordcraft.exe` by
`apps/wordcraft/build.rs`.
- `hicolor/<size>/apps/ai.storyteller.wordcraft.png` (16–512) and `hicolor/scalable/...svg`:
Linux icon theme.
## Regenerate
Replace `wordcraft.svg`, then run `packaging/icons.sh`. It needs `resvg`, plus `iconutil` on macOS;
`cargo run -p xtask -- ico` packs the Windows icon.
## Nightly channel
The Nightly icons keep the drawing, its alpha and the macOS padding exactly as the stable renders
have them. Only the background contribution changes: from the app blue to the deeper Nightly
background `#232c67`. There is no letter badge, crescent or other mark; the app and the Launcher
name the channel in text.
`packaging/nightly-icons.py` derives the four files from the committed stable renders (the `.ico`
frames, the `.icns` slots, the 256 px hicolor render and the padded 512 px macOS master) and
records their hashes in [`nightly-provenance.json`](nightly-provenance.json). `--check` re-derives
them and compares. The three smallest macOS slots (16, 32 and 64 px) are box-filtered from the
padded master; every other frame is the same size as the stable frame it comes from, so nothing is
upscaled. The stable files are not modified.
+72
View File
@@ -0,0 +1,72 @@
{
"title": "WordCraft nightly deep-background icons",
"author": "@skylartaylor",
"license": "MIT OR Apache-2.0",
"source_commit": null,
"inputs": [
{
"path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.wordcraft.png",
"sha256": "7c1791408282d01e8c5d0cb1f4080971eaa412c60518694a1cec1e60b23c7406",
"purpose": "Windows/Linux native256 master"
},
{
"path": "assets/app-icon/wordcraft.ico",
"sha256": "53a23dcf66260f44d87d4d143d633395f3e967f391eda47e6e9cc3a52f820225",
"purpose": "nine full-bleed frames, 16-256 px"
},
{
"path": "assets/app-icon/wordcraft.icns",
"sha256": "02ac9dcb7ee06858416c7ef70ca2b359cad38dbef4a0b526bb1f28953d90170f",
"purpose": "padded macOS frames, 32-1024 px"
},
{
"path": "assets/app-icon/wordcraft-macos-512.png",
"sha256": "5a8a4476c1fb67123f803a8ab7a7a0dbd9912675ae54d695c17e74454913ceae",
"purpose": "padded macOS master (box-filtered down to the 16/32/64 px slots, never upscaled)"
}
],
"method": {
"kind": "derived from the project-owned stable renders by a committed, reproducible script",
"original_palette": {
"ink": "#0b0b0c",
"paper": "#efe9dc",
"background": "#3b5bdb"
},
"nightly_background": "#232c67",
"transform": "Decompose every pixel in the stable three-colour palette (ink, paper, background) and rebuild it with the Nightly background, keeping the ink and paper weights, alpha and padding. Clamped and renormalised where an antialiased pixel falls outside the triangle. No crescent, letter or badge.",
"generator": "packaging/nightly-icons.py",
"generator_sha256": "7a31bc6d3a00d991cf4fd6b1f2ce06b3bdc9201525d207ba84a935a877ee8e4a",
"reproduce": "python3 packaging/nightly-icons.py --check"
},
"outputs": {
"assets/app-icon/wordcraft-nightly.png": "43a002255f6db703599de99224cd47274905b8742d92f91d0f7c41c8cb5656e2",
"assets/app-icon/wordcraft-nightly.ico": "f4bb314bb6c8c131c7250e441407be5e22e645579881f0a80fe7bd963adda54a",
"assets/app-icon/wordcraft-nightly-1024.png": "36e21d31b852ac222c787ee27af45667882353eb9b1c3bfb62a9038c17843b25",
"assets/app-icon/wordcraft-nightly.icns": "0b359aa7f07fda079298a97215da207486ca092bbe9c6b277a5de3d3fbc4f9ef"
},
"ico_frame_sizes": [
16,
20,
24,
32,
40,
48,
64,
128,
256
],
"icns_png_slots": {
"icp4": 16,
"icp5": 32,
"icp6": 64,
"ic07": 128,
"ic08": 256,
"ic13": 256,
"ic09": 512,
"ic14": 512,
"ic10": 1024,
"ic11": 32,
"ic12": 64
},
"validation": "Every output is re-derived from the committed inputs by the committed script (--check) and compared by SHA-256; the frames' pixel dimensions and the containers' members are checked while deriving; the foreground and padding were compared visually against the stable renders. Native Explorer/Finder qualification is unrun."
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

+33 -1
View File
@@ -4,14 +4,34 @@
use std::path::{Path, PathBuf};
/// The folder the desktop app chose before any of its state was read: a Launcher-selected
/// Nightly profile (`launch_profile`). Set once, at startup, before the first [`settings_dir`]
/// call; tests and the CLI leave it unset.
static CHOSEN: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
/// Point [`settings_dir`] at `dir` for this process. Fails when a folder was already chosen.
pub fn use_settings_dir(dir: PathBuf) -> Result<(), String> {
CHOSEN.set(dir).map_err(|_| "the settings folder was already selected".into())
}
/// The app's settings folder (preferences, logs, token files): macOS
/// `~/Library/Application Support/WordCraft`, Windows `%APPDATA%\WordCraft`, otherwise
/// `$XDG_CONFIG_HOME/wordcraft` or `~/.config/wordcraft`.
/// `WORDCRAFT_PROFILE_DIR` overrides the entire folder for isolated runs.
/// A folder chosen by the app through [`use_settings_dir`] wins: it is a launch decision, not
/// an environment variable a child or a wrapper might have inherited. `WORDCRAFT_PROFILE_DIR`
/// overrides the entire folder for isolated runs otherwise.
pub fn settings_dir() -> Option<PathBuf> {
if let Some(path) = CHOSEN.get() {
return Some(path.clone());
}
if let Some(path) = std::env::var_os("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
return Some(PathBuf::from(path));
}
platform_settings_dir()
}
/// The platform's own folder, when nothing chose one (see [`settings_dir`]).
fn platform_settings_dir() -> Option<PathBuf> {
if cfg!(target_os = "macos") {
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
} else if cfg!(windows) {
@@ -67,6 +87,18 @@ mod tests {
assert_eq!(parse_instance_id("app=ai.storyteller.wordcraft\n"), None);
}
#[test]
fn a_chosen_folder_wins_over_the_environment() {
// The chosen folder is process-wide and set once, so this test only reads the rule when
// nothing chose one (the crate's own tests and the CLI never do).
if CHOSEN.get().is_none() {
assert_eq!(settings_dir(), super::platform_settings_dir());
assert!(use_settings_dir(PathBuf::from("/chosen/profile")).is_ok());
assert_eq!(settings_dir().as_deref(), Some(std::path::Path::new("/chosen/profile")));
assert!(use_settings_dir(PathBuf::from("/other")).is_err(), "the folder is selected once");
}
}
#[test]
fn key_file_per_instance() {
let dir = Path::new("/settings/wordcraft");
+42 -1
View File
@@ -110,7 +110,17 @@ fn unmodelled_settings_survive_a_save_and_owned_ones_follow_the_model() {
assert!(!s.contains("trackRevisions"), "{s}");
assert_eq!(s.matches("compatibilityMode").count(), 1, "{s}");
assert!(s.contains("mailMerge"), "{s}");
assert!(text(&files, "word/_rels/settings.xml.rels").contains("file:///__wordcraft_missing_source__/letters.xlsx"));
let rel_id = s
.split("<w:dataSource")
.nth(1)
.and_then(|after| after.split("r:id=\"").nth(1))
.and_then(|after| after.split('"').next())
.expect("dataSource r:id");
let rels = text(&files, "word/_rels/settings.xml.rels");
let expected_rel = format!(
r#"<Relationship Id="{rel_id}" Type="{REL}/mailMergeSource" Target="file:///__wordcraft_missing_source__/letters.xlsx" TargetMode="External"/>"#
);
assert!(rels.contains(&expected_rel), "missing matching relationship for {rel_id}: {rels}");
// The privacy options are the model's (#1062): written once each, and gone when turned off.
assert_eq!(s.matches("removePersonalInformation").count(), 1, "{s}");
assert_eq!(s.matches("removeDateAndTime").count(), 1, "{s}");
@@ -132,6 +142,37 @@ fn unmodelled_settings_survive_a_save_and_owned_ones_follow_the_model() {
assert_eq!(text(&save(&again), "word/settings.xml"), s);
}
#[test]
fn changed_zoom_survives_merged_settings_and_reads_back_as_page_width() {
let old_zoom = r#"<w:zoom w:percent="120"/>"#;
let updated_zoom = r#"<w:zoom w:val="bestFit" w:percent="145"/>"#;
for original in [SETTINGS.to_string(), SETTINGS.replace(old_zoom, "")] {
let mut doc = wordcraft_docx::read(&with_settings(&original)).unwrap();
assert!(doc.passthrough.contains_key("wordcraft:settings.orig"));
doc.settings.zoom = Some(wordcraft_doc::Zoom { percent: 145, fit: Some(wordcraft_doc::ZoomFit::PageWidth) });
let bytes = wordcraft_docx::write(&doc).unwrap();
let settings = text(&unzip(&bytes), "word/settings.xml");
assert_eq!(settings.matches("<w:zoom ").count(), 1, "{settings}");
assert!(settings.contains(updated_zoom), "{settings}");
// The retained root and unrelated child bytes still belong to the original file.
let root_end = original.find("><w:").unwrap() + 1;
assert!(settings.starts_with(&original[..root_end]), "{settings}");
for kept in [
r#"<w:proofState w:spelling="clean" w:grammar="clean"/>"#,
r#"<w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars>"#,
r#"<w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids>"#,
] {
assert!(settings.contains(kept), "{kept} lost: {settings}");
}
assert!(pos(&settings, "<w:zoom ") < pos(&settings, "<w:proofState"));
let again = wordcraft_docx::read(&bytes).unwrap();
let zoom = again.settings.zoom.unwrap();
assert_eq!(zoom.percent, 145);
assert!(matches!(zoom.fit, Some(wordcraft_doc::ZoomFit::PageWidth)));
assert_eq!(text(&save(&again), "word/settings.xml"), settings);
}
}
#[test]
fn settings_written_by_wordcraft_keep_no_original() {
let doc = wordcraft_doc::Document::new();
+28
View File
@@ -927,4 +927,32 @@ mod shortcut_tests {
}
}
}
#[test]
fn copy_format_web_alias_respects_user_removal_and_reassignment() {
use craft_keymap::{Binding, Chord, CommandRef, Overrides, Policy};
let mut commands = super::super::registry().all().to_vec();
commands.iter_mut().find(|c| c.id == "edit.copyFormat").unwrap().shortcut = copy_format_shortcut(true);
let registry = Registry::new(commands);
let mut keymap = crate::keymap::registry_keymap(&registry, &Overrides::default());
let copy_cmd = CommandRef::new("edit.copyFormat");
let bold_cmd = CommandRef::new("format.bold");
let chord = Chord::parse("Mod+Alt+Shift+C").unwrap();
let binding = Binding::parse("Mod+Alt+Shift+C").unwrap();
assert!(keymap.bindings(&copy_cmd).iter().any(|b| b.trigger.chord == chord));
assert!(keymap.remove(&copy_cmd, &binding));
assert_eq!(keymap.holder(&chord), None);
keymap.assign(&bold_cmd, binding, Policy::Steal).unwrap();
assert_eq!(keymap.holder(&chord).as_ref().map(|c| c.id.as_str()), Some("format.bold"));
assert_eq!(keymap.holder(&Chord::parse("Mod+Shift+C").unwrap()).as_ref().map(|c| c.id.as_str()), Some("edit.copyFormat"));
let overrides = keymap.overrides().clone();
let restored = crate::keymap::registry_keymap(&registry, &overrides);
assert_eq!(restored.holder(&chord).as_ref().map(|c| c.id.as_str()), Some("format.bold"));
assert_eq!(restored.holder(&Chord::parse("Mod+Shift+C").unwrap()).as_ref().map(|c| c.id.as_str()), Some("edit.copyFormat"));
}
}
+22
View File
@@ -398,6 +398,28 @@ mod tests {
assert!(!page_text(&mut s).contains("{ AUTHOR }"));
}
/// #980: F11 is full screen, as people expect of a desktop app; the field walk keeps Word's
/// other keys, Alt+F1 and Alt+Shift+F1 (and Shift+F11).
#[test]
fn f11_is_full_screen_and_alt_f1_walks_fields() {
let s = Session::new(wordcraft_doc::Document::new());
let keymap = crate::keymap::registry_keymap(&s.registry, s.keymap());
let chord = |c: &str| craft_keymap::Chord::parse(c).unwrap();
let key = |k: &str| keymap.holder(&chord(k)).map(|c| c.id);
assert_eq!(key("F11").as_deref(), Some("view.fullScreen"));
assert_eq!(key("Alt+F1").as_deref(), Some("fields.next"));
assert_eq!(key("Alt+Shift+F1").as_deref(), Some("fields.previous"));
assert_eq!(key("Shift+F11").as_deref(), Some("fields.previous"));
assert_eq!(key("Mod+F11").as_deref(), Some("fields.lock"));
let shortcut = s.registry.get("view.fullScreen").map(|c| c.shortcut);
if cfg!(target_os = "macos") {
assert_eq!(shortcut, Some("Mod+Ctrl+F / F11"));
assert_eq!(key("Mod+Ctrl+F").as_deref(), Some("view.fullScreen"));
} else {
assert_eq!(shortcut, Some("F11"));
}
}
/// Editing a code changes the instruction and the result; lock keeps a result through updates;
/// unlink turns the field into its text in one undo step; Alt+F1/Shift+F11 walk the fields.
#[test]
+2
View File
@@ -102,6 +102,8 @@ impl WordApp {
command_catalog_lang: "",
key_overrides: Default::default(),
command_states: Default::default(),
command_states_cache: None,
keytip_cache: None,
fonts_frames: 0,
clipboard_published: false,
printing: Default::default(),
+184 -26
View File
@@ -1,7 +1,7 @@
//! The app's side of the framework command runtime: the catalog of commands and their default
//! chords, the per-frame state (enabled, checked, hint) and the running of what the runtime fired.
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use craft::keymap::Overrides;
@@ -83,6 +83,62 @@ fn with_word_chords(catalog: AppCatalog) -> AppCatalog {
.fold(catalog, |catalog, command| catalog.replace_defaults(command.id(), Vec::new()))
}
/// Precomputed command references, translated hints, and last gate results for
/// [`WordApp::command_input`], rebuilt when the engine registry or interface language changes.
///
/// Every command's gate predicate still runs on every frame so enabled/disabled state is never
/// stale; only the per-frame `CATALOG.lines()` parsing, `i18n` hint formatting, and full
/// `CommandStates` map rebuild are skipped when nothing changed.
pub(crate) struct CommandStatesCache {
registry: Arc<wordcraft_engine::Registry>,
lang: &'static str,
/// `(id, location, label, prebuilt CommandRef, last (enabled, reason))` for every registered
/// engine command, in registry order.
registered: Vec<(&'static str, &'static str, &'static str, CommandRef, Option<(bool, Option<&'static str>)>)>,
/// `(id, prebuilt CommandRef, last enabled)` for gated `ui.*` commands.
ui_commands: Vec<(&'static str, CommandRef, Option<bool>)>,
/// `(id, prebuilt CommandRef, last enabled)` for unimplemented Word catalog commands.
unimplemented: Vec<(&'static str, CommandRef, Option<bool>)>,
/// Precomputed `CommandRef` and last enabled state for `ui.dialog {"name": "commands"}`.
commands_dialog: (CommandRef, Option<bool>),
/// Translated fallback hint shared by all unimplemented catalog commands.
unavailable_hint: Option<Arc<str>>,
/// Cached translated hints by `(spec index, disabled reason)` for the current language.
hints: HashMap<(usize, Option<&'static str>), Option<Arc<str>>>,
}
impl CommandStatesCache {
fn new(registry: Arc<wordcraft_engine::Registry>, lang: &'static str) -> Self {
let registered = registry.all().iter().map(|spec| (spec.id, spec.location, spec.label, CommandRef::new(spec.id), None)).collect();
let ui_commands = ["ui.collapseRibbon", "ui.resetInterfaceSize", "ui.print", "ui.printSubmit"]
.into_iter()
.chain(GATED_UI_COMMANDS.iter().map(|(id, _)| *id))
.map(|id| (id, CommandRef::new(id), None))
.collect();
let unimplemented = unimplemented_catalog_commands(&registry).map(|(id, _)| (id, CommandRef::new(id), None)).collect();
let commands_dialog = (CommandRef::with_params("ui.dialog", json!({"name": "commands"})), None);
let unavailable_hint = crate::widgets::command_hint("", "", Some("")).map(Arc::from);
CommandStatesCache { registry, lang, registered, ui_commands, unimplemented, commands_dialog, unavailable_hint, hints: HashMap::new() }
}
fn matches(&self, registry: &Arc<wordcraft_engine::Registry>, lang: &'static str) -> bool {
self.lang == lang && Arc::ptr_eq(&self.registry, registry)
}
fn hint_for(&mut self, idx: usize, location: &str, label: &str, reason: Option<&'static str>) -> Option<Arc<str>> {
self.hints.entry((idx, reason)).or_insert_with(|| crate::widgets::command_hint(location, label, reason).map(Arc::from)).clone()
}
}
/// Gate check for a command known to live in `app.session.registry` (skips the extra registry lookup).
fn gate_registered(app: &WordApp, id: &str) -> (bool, Option<&'static str>) {
if !app.has_document() && !super::commands::works_without_document(id) {
return (false, None);
}
let reason = app.session.why_disabled(id);
(reason.is_none(), reason)
}
impl WordApp {
/// The app's commands as the keymap knows them: every engine command with its default
/// chords, then the interface commands. The interface commands come last because a tie in the
@@ -177,36 +233,78 @@ impl WordApp {
if let Some(catalog) = self.catalog() {
input = input.catalog(catalog);
}
let mut states = CommandStates::new();
for spec in registry.all() {
let (enabled, reason) = gate(self, spec.id); // A toggle's checked state is bound at its ribbon button, not here.
let mut state = CommandState::new().enabled(enabled);
if let Some(hint) = crate::widgets::command_hint(spec.location, spec.label, reason) {
state = state.hint(hint);
let lang = crate::i18n::current().code();
let (mut cache, fresh_cache) = match self.command_states_cache.take() {
Some(cache) if cache.matches(&registry, lang) => (cache, false),
_ => (CommandStatesCache::new(registry, lang), true),
};
// Re-evaluate every command's gate without allocating on idle frames. A fresh cache has
// `None` in every `last` slot, so the same compare pass collects every entry for it.
let mut reg_changes: Vec<(usize, bool, Option<&'static str>)> = Vec::new();
for (i, &(id, _, _, _, last)) in cache.registered.iter().enumerate() {
let current = gate_registered(self, id);
if last != Some(current) {
reg_changes.push((i, current.0, current.1));
}
states.set(CommandRef::new(spec.id), state);
}
// Print acts on the document, so with none open it is off like the engine's commands (#1129); a command with
// no state here resolves as enabled.
let ids = ["ui.collapseRibbon", "ui.resetInterfaceSize", "ui.print", "ui.printSubmit"]
.into_iter()
.chain(GATED_UI_COMMANDS.iter().map(|(id, _)| *id));
for id in ids {
states.set(CommandRef::new(id), CommandState::new().enabled(command_enabled(self, id)));
}
let unavailable_hint: Option<Arc<str>> = crate::widgets::command_hint("", "", Some("")).map(Arc::from);
for (id, _) in unimplemented_catalog_commands(&registry) {
let mut state = CommandState::new().enabled(command_enabled(self, id));
if let Some(hint) = unavailable_hint.as_ref() {
state = state.hint(Arc::clone(hint));
let mut ui_changes: Vec<(usize, bool)> = Vec::new();
for (i, &(id, _, last)) in cache.ui_commands.iter().enumerate() {
let enabled = command_enabled(self, id);
if last != Some(enabled) {
ui_changes.push((i, enabled));
}
states.set(CommandRef::new(id), state);
}
let commands = CommandRef::with_params("ui.dialog", json!({"name": "commands"}));
states.set(commands, CommandState::new().enabled(command_enabled(self, "ui.dialog")));
if *self.command_states != states {
self.command_states.edit(|kept| *kept = states);
let mut unimpl_changes: Vec<(usize, bool)> = Vec::new();
for (i, &(id, _, last)) in cache.unimplemented.iter().enumerate() {
let enabled = command_enabled(self, id);
if last != Some(enabled) {
unimpl_changes.push((i, enabled));
}
}
let dialog_enabled = command_enabled(self, "ui.dialog");
let dialog_changed = cache.commands_dialog.1 != Some(dialog_enabled);
let any_changed = !reg_changes.is_empty() || !ui_changes.is_empty() || !unimpl_changes.is_empty() || dialog_changed;
if fresh_cache || any_changed {
let apply = |kept: &mut CommandStates| {
for (i, enabled, reason) in reg_changes {
let (_, location, label, _, _) = cache.registered[i];
cache.registered[i].4 = Some((enabled, reason));
let mut state = CommandState::new().enabled(enabled);
if let Some(hint) = cache.hint_for(i, location, label, reason) {
state = state.hint(hint);
}
kept.set(cache.registered[i].3.clone(), state);
}
for (i, enabled) in ui_changes {
cache.ui_commands[i].2 = Some(enabled);
kept.set(cache.ui_commands[i].1.clone(), CommandState::new().enabled(enabled));
}
for (i, enabled) in unimpl_changes {
cache.unimplemented[i].2 = Some(enabled);
let mut state = CommandState::new().enabled(enabled);
if let Some(hint) = cache.unavailable_hint.as_ref() {
state = state.hint(Arc::clone(hint));
}
kept.set(cache.unimplemented[i].1.clone(), state);
}
if dialog_changed {
cache.commands_dialog.1 = Some(dialog_enabled);
kept.set(cache.commands_dialog.0.clone(), CommandState::new().enabled(dialog_enabled));
}
};
if fresh_cache {
let mut states = CommandStates::new();
apply(&mut states);
if *self.command_states != states {
self.command_states.edit(|kept| *kept = states);
}
} else {
self.command_states.edit(apply);
}
}
self.command_states_cache = Some(cache);
input.states(&self.command_states)
}
@@ -321,4 +419,64 @@ mod tests {
);
}
}
/// Cached `command_input()` keeps steady-state idle calls zero-change while immediately reflecting
/// table/context transitions and document-open state changes.
#[test]
fn command_input_cache_tracks_state_transitions_and_is_noop_when_idle() {
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), Default::default());
let _ = app.command_input();
let rev_after_first = app.command_states.revision();
assert!(
!app.command_states.get(&CommandRef::new("table.deleteRow")).unwrap().is_enabled(),
"table.deleteRow starts disabled outside a table"
);
assert!(app.command_states.get(&CommandRef::new("format.bold")).unwrap().is_enabled(), "format.bold starts enabled");
// Repeated idle calls must not mutate `command_states` or bump its revision.
for _ in 0..5 {
let _ = app.command_input();
}
assert_eq!(app.command_states.revision(), rev_after_first, "idle frames leave command_states revision untouched");
// Entering a table enables `table.deleteRow` immediately on the next `command_input()`.
app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
let _ = app.command_input();
let rev_after_table = app.command_states.revision();
assert_ne!(rev_after_table, rev_after_first, "state change bumps command_states revision");
assert!(app.command_states.get(&CommandRef::new("table.deleteRow")).unwrap().is_enabled(), "table.deleteRow is enabled inside a table");
// Closing the document disables document commands immediately.
app.no_document = Some(app.session.document_id());
let _ = app.command_input();
assert!(!app.command_states.get(&CommandRef::new("format.bold")).unwrap().is_enabled(), "format.bold disables when no document is open");
// Dropping the cache and rebuilding from scratch must produce the exact same `CommandStates`.
let incremental = (*app.command_states).clone();
app.command_states_cache = None;
let _ = app.command_input();
assert_eq!(*app.command_states, incremental, "incremental cache matches full rebuild exactly");
// Swapping the registry rebuilds `command_states` cleanly and drops commands that are no
// longer registered.
app.no_document = None;
let full_registry = app.session.registry.clone();
app.session.registry = std::sync::Arc::new(wordcraft_engine::Registry::new(vec![wordcraft_engine::CommandSpec::new(
"test.ephemeral",
"Ephemeral",
"Home",
|_, _| Ok(json!({})),
)]));
let _ = app.command_input();
assert!(
app.command_states.get(&CommandRef::new("test.ephemeral")).is_some_and(|s| s.is_enabled()),
"custom registry command is published when registered"
);
app.session.registry = full_registry;
let _ = app.command_input();
assert!(
app.command_states.get(&CommandRef::new("test.ephemeral")).is_none(),
"swapping back to the default registry clears removed commands from command_states"
);
}
}
+4
View File
@@ -181,6 +181,7 @@ impl WordApp {
/// Close prompt `id` from outside and drop the answer that leaves behind.
pub(crate) fn close_prompt(&mut self, id: DialogId) {
if let Some(ctx) = self.ctx.clone() {
crate::dialogs::chrome::forget_nudge(&ctx, id);
self.dialog_host.cancel_by_id(&ctx, id);
}
let _ = self.dialog_host.take_by_id::<UnsavedChangesDialog>(id);
@@ -191,6 +192,9 @@ impl WordApp {
pub(crate) fn pump_close_prompt(&mut self) {
let Some(id) = self.closing.as_ref().and_then(|c| c.prompt) else { return };
let Some(result) = self.dialog_host.take_by_id::<UnsavedChangesDialog>(id) else { return };
if let Some(ctx) = self.ctx.as_ref() {
crate::dialogs::chrome::forget_nudge(ctx, id);
}
if let Some(closing) = self.closing.as_mut() {
closing.prompt = None;
}
+141
View File
@@ -158,4 +158,145 @@ mod tests {
let missing = missing_glyphs(&stack, &FontRef::proportional(), samples, false);
assert!(missing.is_empty(), "symbols without a glyph: {missing:#?}");
}
/// An installed Arabic font is asked for only when Arabic text needs one (and no embedded
/// Arabic face covers it): neither installing the UI font stack for English/CJK/Arabic nor
/// triggering CJK on-demand fallback ever asks for an Arabic system font, and Arabic on-demand
/// fallback never asks for a CJK system font.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn the_installed_arabic_font_is_asked_for_by_arabic_alone() {
use std::path::PathBuf;
use std::sync::Mutex;
use craft::host::Wake;
use craft::i18n::Han;
use craft::ui::fonts::{FontCandidates, on_demand_registered};
struct RecordingCandidates {
scripts: Mutex<Vec<String>>,
}
impl RecordingCandidates {
fn new() -> Arc<Self> {
Arc::new(Self { scripts: Mutex::new(Vec::new()) })
}
fn scripts(&self) -> Vec<String> {
self.scripts.lock().map(|guard| guard.clone()).unwrap_or_default()
}
}
impl FontCandidates for RecordingCandidates {
fn files(&self, script: &str, han: Option<Han>) -> Vec<PathBuf> {
if let Ok(mut scripts) = self.scripts.lock() {
scripts.push(script.to_owned());
}
SystemCandidates.files(script, han)
}
fn covers(&self, data: &[u8], c: char) -> Option<u32> {
SystemCandidates.covers(data, c)
}
fn pending(&self) -> bool {
SystemCandidates.pending()
}
fn wake_when_ready(&self, wake: Wake) {
SystemCandidates.wake_when_ready(wake);
}
}
let paint = |ctx: &egui::Context, text: &str| {
for _ in 0..6 {
ctx.run_ui(egui::RawInput::default(), |ui| {
ui.label(text);
})
.drop_without_applying_deltas();
}
};
let is_cjk_script = |script: &str| matches!(script, "Hani" | "Hira" | "Kana" | "Hang" | "Bopo");
let en = Lang::EN;
let ja = crate::i18n::fixture_lang("ja", "\tHome\tホーム\n");
let ar = crate::i18n::fixture_lang("ar", "\tHome\tالرئيسية\n");
// Installing the production `ui_fonts` stack and painting Latin text never requests or
// loads an installed Arabic or CJK system font up front.
for lang in [en, ja, ar] {
let ctx = egui::Context::default();
let spy = RecordingCandidates::new();
ui_fonts(lang).on_demand(Arc::clone(&spy) as Arc<dyn FontCandidates>).install(&ctx);
assert!(on_demand_registered(&ctx).is_empty(), "{}: installing ui_fonts reads no system font eagerly", lang.code());
assert!(spy.scripts().is_empty(), "{}: installing ui_fonts requests no system font candidates", lang.code());
paint(&ctx, "Hello");
assert!(on_demand_registered(&ctx).is_empty(), "{}: Latin UI text reads no system font", lang.code());
assert!(spy.scripts().is_empty(), "{}: Latin UI text requests no system font candidates", lang.code());
}
let embedded_arabic: Vec<String> = CRAFT_FONTS.iter().filter(|f| f.has_script("Arab")).map(EmbeddedFace::name).collect();
let ar_ctx = egui::Context::default();
let ar_stack = ui_fonts(ar).install(&ar_ctx);
let en_stack = ui_fonts(en).stack();
let ja_stack = ui_fonts(ja).stack();
if !embedded_arabic.is_empty() {
assert!(
ar_stack.chain(&FontRef::proportional()).first().is_some_and(|name| embedded_arabic.contains(name)),
"Arabic UI leads with its embedded Arabic face"
);
assert!(
!en_stack.chain(&FontRef::proportional()).first().is_some_and(|name| embedded_arabic.contains(name)),
"English UI does not lead with an Arabic face"
);
assert!(
!ja_stack.chain(&FontRef::proportional()).first().is_some_and(|name| embedded_arabic.contains(name)),
"CJK UI does not lead with an Arabic face"
);
paint(&ar_ctx, "مرحبا");
assert!(ar_ctx.fonts_mut(|f| f.has_glyph(&egui::FontId::proportional(14.0), 'ع')), "embedded Arabic face draws Arabic text");
assert!(on_demand_registered(&ar_ctx).is_empty(), "no installed Arabic system font is read when an embedded Arabic face covers Arabic");
} else {
paint(&ar_ctx, "مرحبا");
let registered = on_demand_registered(&ar_ctx);
let arabic_candidates = SystemCandidates.files("Arab", None);
assert!(!registered.is_empty() || cfg!(not(any(target_os = "macos", windows))), "macOS and Windows ship an installed Arabic font");
if !registered.is_empty() {
assert_eq!(registered.len(), 1, "Arabic text registers one installed Arabic face");
assert!(arabic_candidates.contains(&registered[0].1), "registered face {:?} came from Arabic system candidates", registered[0].1);
assert!(ar_ctx.fonts_mut(|f| f.has_glyph(&egui::FontId::proportional(14.0), 'ع')), "installed Arabic system font draws Arabic text");
}
}
// CJK on-demand lookup through `ui_fonts` never asks for an Arabic system font (U+3400 is
// CJK Extension A, outside embedded catalog subsets, so it exercises CJK on-demand lookup
// even in builds with `CRAFT_FONTS_DIR`).
let cjk_spy = RecordingCandidates::new();
let cjk_ctx = egui::Context::default();
ui_fonts(ja).on_demand(Arc::clone(&cjk_spy) as Arc<dyn FontCandidates>).install(&cjk_ctx);
paint(&cjk_ctx, "日本語 㐀");
let cjk_scripts = cjk_spy.scripts();
assert!(!cjk_scripts.iter().any(|s| s == "Arab"), "CJK fallback never asks for an Arabic font: {cjk_scripts:?}");
if !cjk_ctx.fonts_mut(|f| f.has_glyph(&egui::FontId::proportional(14.0), '\u{3400}')) || !on_demand_registered(&cjk_ctx).is_empty() {
assert!(cjk_scripts.iter().any(|s| is_cjk_script(s)), "uncovered CJK text asks for CJK candidates: {cjk_scripts:?}");
}
// Arabic on-demand lookup when no embedded Arabic face is present asks for Arabic alone
// and never triggers a CJK system-font lookup.
let ar_spy = RecordingCandidates::new();
let ar_no_embed_ctx = egui::Context::default();
if embedded_arabic.is_empty() {
ui_fonts(ar).on_demand(Arc::clone(&ar_spy) as Arc<dyn FontCandidates>).install(&ar_no_embed_ctx);
} else {
UiFonts::new(&I18nScripts)
.languages(&["en", "ja", "ar"])
.ui_language(ar.code())
.on_demand(Arc::clone(&ar_spy) as Arc<dyn FontCandidates>)
.install(&ar_no_embed_ctx);
}
paint(&ar_no_embed_ctx, "مرحبا");
let ar_scripts = ar_spy.scripts();
assert!(ar_scripts.iter().any(|s| s == "Arab"), "Arabic text without an embedded Arabic face asks for Arab: {ar_scripts:?}");
assert!(!ar_scripts.iter().any(|s| is_cjk_script(s)), "Arabic fallback never asks for a CJK font: {ar_scripts:?}");
}
}
+16 -8
View File
@@ -81,6 +81,7 @@ impl WordApp {
let mode = self.screen_mode();
let dropped = self.ribbon_dropped;
let key = self.windows.window_key();
let ribbon_out = std::cell::RefCell::new(None);
let shell = AppShell::new(key)
.mode_set(ScreenModeSet::Document)
.screen_mode(Bind::given(mode))
@@ -94,12 +95,12 @@ impl WordApp {
// tabs and collapsed every one of them.
.top(Slot::new("ribbonDrop").drops().size(SlotSize::Content), |ui, _cx, app: &mut WordApp| {
if !stale(app) {
ribbon_slot(app, ui);
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
}
})
.top(Slot::new("ribbon").size(SlotSize::Content), |ui, _cx, app: &mut WordApp| {
if !stale(app) {
ribbon_slot(app, ui);
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
}
})
// As tall as the bar: a failure's line under the message puts Install below the first line, and a slot of
@@ -132,6 +133,11 @@ impl WordApp {
self.follow_screen_mode(out.screen_mode);
}
self.ribbon_dropped = out.dropped;
// Keytips run outside the ribbon slots so legacy sequences and their hint still work when
// no ribbon shows (Focus, Full Screen View) and anchor under the slim screen bar.
let ribbon = ribbon_out.into_inner().unwrap_or_else(ribbon::no_ribbon);
let screen_bar = out.regions.slots.iter().find(|(slot, _)| *slot == "screenBar").map(|(_, rect)| *rect);
crate::keytips::show(ui, self, &ribbon, screen_bar);
out.regions
}
@@ -145,20 +151,22 @@ impl WordApp {
// PLAN: assumed `updates_ui::run(app: &mut WordApp)` (shell-w13, sh.A20) opens the updater's dialogs on the host.
updates_ui::run(self);
crate::dialogs::host::prepare(self);
let had_dialogs = !self.dialog_host.is_empty();
self.dialog_host.run(ui);
crate::dialogs::host::settle(self, ctx);
crate::dialogs::chrome::apply_modal_nudge(self, ui);
if moved(self) {
return;
}
if had_dialogs && self.dialog_host.is_empty() && !self.file_dialog_open() && !self.ui.backstage {
self.canvas.focus_page(ctx);
self.canvas.focus_pending = true;
self.canvas.focus_page_after_pass();
ctx.request_repaint();
}
self.refocus_after_chrome_click(ctx, regions);
if let Some(url) = self.canvas.open_url.take() {
ctx.open_url(egui::OpenUrl::new_tab(url));
}
}
}
/// The ribbon, then its keytips, in a top slot: the keytips read what the ribbon recorded this pass.
fn ribbon_slot(app: &mut WordApp, ui: &mut egui::Ui) {
let out = ribbon::show(app, ui);
crate::keytips::show(ui, app, &out);
}
+29 -4
View File
@@ -156,6 +156,10 @@ pub struct CanvasState {
pub(crate) read_force_reflow: bool,
/// Web Layout's width follows the window once a drag has settled, not on every frame of it.
web_viewport: reading::Settle,
/// Side gutter the last `PageView` pass laid pages out with (`PageSpacing::side`), in screen points.
pub(crate) page_side: Option<f32>,
/// `PageView`'s side gutter changed since the last Web Layout pass, so Web Layout must reflow at once.
web_force_reflow: bool,
/// First text position on the column currently leading the reading view, captured from the last
/// pass's layout. Survives changing page sizes, even when the caret stays elsewhere.
pub(crate) read_first_visible: Option<Pos>,
@@ -405,6 +409,8 @@ impl Default for CanvasState {
nav_to_caret: false,
read_force_reflow: false,
web_viewport: Default::default(),
page_side: None,
web_force_reflow: false,
read_first_visible: None,
dragging: false,
column_drag: None,
@@ -465,16 +471,19 @@ fn update_viewport(app: &mut WordApp, full: Rect, metrics: &ReadingMetrics, side
// Without an anchor (Read Mode was just entered) the view starts at the caret.
app.canvas.scroll_to_caret |= reflow_anchor.is_none();
}
app.canvas.web_force_reflow = false;
} else {
if app.session.view.mode == wordcraft_layout::ViewMode::Web {
// Web Layout wraps to the work area (#1876).
let scale = app.session.view.zoom.clamp(0.1, 5.0) * PX_PER_PT;
// The page view keeps its side gutter (the rail width) clear on both sides of a page, so the page
// The page view keeps its side gutter (`PageSpacing::side`) clear on both sides of a page, so the page
// fits the window only when its width leaves that room.
let w = web_layout_width((full.width() - 2.0 * side).max(0.0), scale);
let changed = (app.session.view.web_width - w).abs() > 0.5;
// At once on entry or a zoom (the viewport holds still), after a window drag has settled.
if app.canvas.web_viewport.apply(full.size(), ctx.input(|i| i.time), changed, false) {
let forced = std::mem::take(&mut app.canvas.web_force_reflow);
// At once on entry, a zoom, or a page-spacing change (the viewport holds still), after a window drag
// has settled.
if app.canvas.web_viewport.apply(full.size(), ctx.input(|i| i.time), changed, forced) {
app.session.view.web_width = w;
// The pixel offset no longer points at the same text: keep the caret's line in view.
app.canvas.scroll_to_caret = true;
@@ -483,6 +492,7 @@ fn update_viewport(app: &mut WordApp, full: Rect, metrics: &ReadingMetrics, side
}
} else {
app.canvas.web_viewport.leave();
app.canvas.web_force_reflow = false;
}
app.canvas.read_force_reflow = false;
app.canvas.read_first_visible = None;
@@ -732,7 +742,8 @@ fn show_reading(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: R
pub fn show(app: &mut WordApp, ui: &mut Ui) {
let full = ui.available_rect_before_wrap();
let Some(metrics) = reading_metrics::read(ui) else { return };
let layout = prepare_layout(app, full, &metrics, Env::of(ui).tokens.size.rail.width, ui.ctx());
let side = app.canvas.page_side.unwrap_or(0.0);
let layout = prepare_layout(app, full, &metrics, side, ui.ctx());
if app.session.view.read_mode {
show_reading(app, ui, &layout, full, &metrics);
} else {
@@ -871,6 +882,20 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
});
let caret = caret_after.or(caret);
app.canvas.page_keys = source.into_keys();
let side = out.spacing.side as f32;
if side.is_finite() {
let side = side.max(0.0);
if app.canvas.page_side.is_none_or(|prev| (prev - side).abs() > 0.01) {
app.canvas.page_side = Some(side);
if app.session.view.mode == wordcraft_layout::ViewMode::Web {
app.canvas.web_force_reflow = true;
ui.ctx().request_discard("page view side gutter changed");
if !ui.ctx().will_discard() {
ui.ctx().request_repaint();
}
}
}
}
// This pass's own input changed the document under the pages it drew: run the pass again, so the frame that
// delivers a key paints its text (production laid out and painted in the one pass) rather than the next frame.
if ran && !Arc::ptr_eq(&laid_before, &app.session.layout()) {
+18
View File
@@ -253,6 +253,24 @@ fn drawing_over_the_pages_follows_the_read_mode_page_color() {
assert_eq!(blank(&a), Rgb::WHITE, "the paper under the raster, not the page color");
}
/// #299: the caret's colour is worked out only when the caret is drawn: with text selected
/// there is no caret, so the page's draw list isn't built for it.
#[test]
fn caret_colour_is_not_worked_out_while_the_caret_is_hidden() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello WordCraft")), Default::default());
a.run("select.text", json!({"text": "Hello"})).unwrap();
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
h.run_steps(4);
assert!(h.state().canvas.caret_bg.is_none(), "no caret, no colour lookup");
}
/// Show revisions in balloons: a document whose only revision is a deletion gets the markup
/// area for its balloon; the other modes have nothing to show there, and neither does the view
/// while the Comments pane is open.
@@ -260,6 +260,19 @@ fn table_gridlines_skip_edges_a_border_draws() {
);
}
/// #5967: a new table has borders on every edge, so it shows no gridline at all; with its
/// borders removed every edge shows one.
#[test]
fn a_bordered_table_shows_no_gridlines() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.table", json!({"rows": 2, "cols": 3})).unwrap();
assert!(a.session.view.table_gridlines, "View Gridlines is on by default");
let segs = |a: &mut WordApp| gridline_segments(&a.session.layout().pages[0], true, None).len();
assert_eq!(segs(&mut a), 0);
a.run("table.borders", json!({"kind": "none"})).unwrap();
assert_eq!(segs(&mut a), 6 * 4, "every edge of the six cells");
}
/// The drawing grid the page shows starts at the text area's top left, stays inside it, spaces
/// its lines by the settings the same both ways or differently across and down, and falls back
/// to the spec's 1/8 inch for a missing spacing.
+3 -4
View File
@@ -3,7 +3,6 @@
use craft::behavior::IconId;
use craft::ui::buttons::IconButton;
use craft::ui::contract::{BodyCx, Props as _, Show as _, TooltipSpec};
use craft::ui::runtime::inspect;
use egui::Ui;
use serde_json::json;
@@ -11,9 +10,9 @@ use super::Screen;
use crate::WordApp;
/// Fills the screen-bar slot. Focus: a `more` button that drops the ribbon down over the page. Immersive: the
/// command search field. The bar is an inspected region, where the keytips hang their hint while no ribbon shows.
/// command search field.
pub(crate) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, app: &mut WordApp) {
inspect::record(ui, crate::keytips::screen_bar_region(), |ui| match Screen::of(&app.session.view) {
match Screen::of(&app.session.view) {
Screen::Focus => {
let out = IconButton::new(IconId::new("wordcraft.more"))
.label(tl!("Show the ribbon").to_string())
@@ -27,5 +26,5 @@ pub(crate) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, app: &mut WordApp) {
_ => {
super::search::show(app, ui, false);
}
});
}
}
+151
View File
@@ -76,6 +76,34 @@ fn new_app() -> WordApp {
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default())
}
/// A saved .docx (so AutoSave can cover it) in the harness.
fn autosave_harness() -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf) {
let dir = std::env::temp_dir().join(format!("wordcraft-ui-autosave-label-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("draft.docx");
let mut a = new_app();
a.run("text.insert", json!({"text": "Hello"})).unwrap();
a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap();
assert!(a.autosaves(), "a saved .docx is covered by AutoSave");
let h = harness(a);
(h, dir)
}
/// #3370: clicking the AutoSave switch label toggles AutoSave on and off.
#[test]
fn clicking_the_autosave_label_toggles_autosave() {
let (mut h, dir) = autosave_harness();
assert!(h.state().autosaves());
h.get_by_label("AutoSave").click();
crate::test_harness::frames(&mut h, 2);
assert!(!h.state().autosaves(), "clicking the text turns AutoSave off");
h.get_by_label("AutoSave").click();
crate::test_harness::frames(&mut h, 2);
assert!(h.state().autosaves(), "and clicking it again turns it back on");
let _ = std::fs::remove_dir_all(&dir);
}
/// #701: the arrow beside Undo lists the session's undo steps, newest first; clicking the third
/// row undoes three steps at once.
#[test]
@@ -103,6 +131,39 @@ fn undo_list_matches_the_session_and_undoes_up_to_the_clicked_row() {
assert_eq!(h.query_all_by_role(Role::ListBoxOption).count(), 0, "the list closes");
}
/// #3040: clicking a row in the Undo History popover undoes the step and returns keyboard focus
/// to the document so typing continues immediately.
#[test]
fn undo_list_row_returns_focus_to_the_document() {
use egui::accesskit::Role;
let mut a = new_app();
a.run("text.insert", json!({"text": "Hello"})).unwrap();
assert_eq!(a.session.undo_history().len(), 1);
let mut h = harness(a);
assert!(h.state().canvas.focused(&h.ctx), "canvas starts focused");
let arrow = h.get_by_label("Undo History").rect().center();
click_at(&mut h, arrow, egui::PointerButton::Primary);
assert_eq!(h.query_all_by_role(Role::ListBoxOption).count(), 1, "the arrow opens the Undo list");
assert!(!h.state().canvas.focused(&h.ctx), "the open Undo list holds the keyboard");
let row = h.get_by_role_and_label(Role::ListBoxOption, "Typing").rect().center();
click_at(&mut h, row, egui::PointerButton::Primary);
assert_eq!(h.query_all_by_role(Role::ListBoxOption).count(), 0, "picking a row closes the Undo list");
assert!(h.state().session.undo_history().is_empty(), "the step was undone");
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body), "", "the undone text is gone");
assert!(h.state().canvas.focused(&h.ctx), "the row click returns focus to the document");
h.event(egui::Event::Text("!".into()));
crate::test_harness::frames(&mut h, 2);
assert_eq!(
h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body),
"!",
"typing reaches the document immediately after picking an Undo list row"
);
}
/// #1975: the zoom percentage gains and loses digits (9% → 100% → 500%); the controls to its
/// left must not shift with it.
#[test]
@@ -437,6 +498,96 @@ fn status_bar_texts_stop_before_the_controls_in_a_narrow_window() {
assert!(painted_on_row_of(&wide, focus).iter().any(|(t, _)| t == "Track Changes: On"), "a wide window shows everything");
}
/// Finds the painted track and knob rects inside a rendered `craft::ui::choice::Switch`.
/// `Switch` sets `PARTS = false` and exposes only its `Role::Switch` node and toggled state, so
/// the thumb position is read from the unblurred filled shapes painted inside the switch rect.
fn switch_track_and_knob(shapes: &[egui::epaint::ClippedShape], switch_rect: egui::Rect) -> (egui::Rect, egui::Rect) {
fn filled_rects(shape: &egui::Shape, inside: egui::Rect, out: &mut Vec<egui::Rect>) {
match shape {
egui::Shape::Vec(children) => children.iter().for_each(|c| filled_rects(c, inside, out)),
egui::Shape::Rect(r) if r.blur_width == 0.0 && r.fill != egui::Color32::TRANSPARENT && inside.contains_rect(r.rect) => {
out.push(r.rect);
}
_ => {}
}
}
let mut rects = Vec::new();
for clipped in shapes {
filled_rects(&clipped.shape, switch_rect.expand(1.0), &mut rects);
}
let track = rects
.iter()
.copied()
.filter(|r| r.width() > r.height())
.max_by(|a, b| a.area().total_cmp(&b.area()))
.unwrap_or_else(|| panic!("expected painted switch track inside {switch_rect:?}: {rects:?}"));
let knob = rects
.iter()
.copied()
.filter(|r| track.contains_rect(*r) && r.width() < track.width())
.max_by(|a, b| a.area().total_cmp(&b.area()))
.unwrap_or_else(|| panic!("expected painted switch knob inside track {track:?}: {rects:?}"));
(track, knob)
}
/// The AutoSave switch renders its knob on the right when on and on the left when off in a
/// left-to-right interface, and mirrors through `WordApp::root_env()` for an Arabic interface.
#[test]
fn the_autosave_knob_sits_right_when_on_and_mirrors_right_to_left() {
use craft::i18n::Direction;
use egui::accesskit::{Role, Toggled};
struct ResetLang;
impl Drop for ResetLang {
fn drop(&mut self) {
crate::i18n::apply_language(crate::i18n::Lang::EN);
}
}
let _reset = ResetLang;
let mut a = new_app();
a.ui.animations = crate::theme::Animations::Off;
a.ui.language = "en".into();
// Mark the document as saved here without touching disk (`session.dirty` stays false).
let path = std::path::PathBuf::from("draft.docx");
a.session.path = Some(path.clone());
a.autosave_path = Some(path);
let mut h = harness(a);
// Arabic UI labels draw even when built without `CRAFT_FONTS_DIR` (embedded Arabic faces).
h.ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Tofu);
let mut measure = |lang: crate::i18n::Lang, on: bool| -> (egui::Rect, egui::Rect) {
h.state_mut().run("ui.language", json!({"value": lang.code()})).unwrap();
h.state_mut().run("file.autosave", json!({"value": on})).unwrap();
let want_dir = if lang.rtl() { Direction::Rtl } else { Direction::Ltr };
assert_eq!(h.state().root_env().direction, want_dir, "root_env supplies direction for {}", lang.code());
assert_eq!(h.state().autosaves(), on);
crate::test_harness::frames(&mut h, 4);
let label = crate::i18n::tr(lang, "AutoSave");
let node = h.get_by_role_and_label(Role::Switch, label);
assert_eq!(node.accesskit_node().toggled(), Some(if on { Toggled::True } else { Toggled::False }));
switch_track_and_knob(&h.output().shapes, node.rect())
};
let (ltr_on_track, ltr_on_knob) = measure(crate::i18n::Lang::EN, true);
let (ltr_off_track, ltr_off_knob) = measure(crate::i18n::Lang::EN, false);
assert!(ltr_on_knob.center().x > ltr_on_track.center().x, "left to right, on: knob sits right ({ltr_on_knob:?} in {ltr_on_track:?})");
assert!(ltr_off_knob.center().x < ltr_off_track.center().x, "left to right, off: knob sits left ({ltr_off_knob:?} in {ltr_off_track:?})");
let Some(ar) = crate::i18n::Lang::from_code("ar") else {
eprintln!("skipped RTL check: built without the craft-i18n Arabic catalog (set CRAFT_I18N_DIR to a checkout)");
return;
};
let (rtl_on_track, rtl_on_knob) = measure(ar, true);
let (rtl_off_track, rtl_off_knob) = measure(ar, false);
assert!(rtl_on_knob.center().x < rtl_on_track.center().x, "right to left, on: knob sits left ({rtl_on_knob:?} in {rtl_on_track:?})");
assert!(rtl_off_knob.center().x > rtl_off_track.center().x, "right to left, off: knob sits right ({rtl_off_knob:?} in {rtl_off_track:?})");
assert!(rtl_on_track.center().x > ltr_on_track.center().x, "right to left mirrors the AutoSave switch toward the start (right) edge");
assert!(((ltr_on_knob.center().x - ltr_on_track.min.x) - (rtl_on_track.max.x - rtl_on_knob.center().x)).abs() <= 0.5);
assert!(((ltr_off_knob.center().x - ltr_off_track.min.x) - (rtl_off_track.max.x - rtl_off_knob.center().x)).abs() <= 0.5);
}
/// #7311: the title bar's Discord community button keeps its solid accent fill and contrasting
/// `on_strong` icon/label in both wide (pill with label) and narrow (compact icon-only) windows,
/// across Light and Dark themes, and still dispatches `ui.discord` when clicked.
+5
View File
@@ -200,6 +200,11 @@ fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
app.chrome.undo_mark = if open { mark } else { UndoMark::default() };
if let Some(count) = picked {
let _ = app.run("edit.undoTo", json!({"count": count}));
// Picking a row closes the Undo History popover on its foreground layer; return keyboard
// focus to the document both now and after the pass's overlay-close focus hook (#3040).
app.canvas.focus_page(ui.ctx());
app.canvas.focus_page_after_pass();
ui.ctx().request_repaint();
}
out.response.rect
}
+143 -15
View File
@@ -66,22 +66,59 @@ pub fn credits() -> Credits {
}
/// The About tab's contents: name, blurb, version and build, and the project links in the old About's order (site,
/// Discord, source), one to a line.
/// Discord, source), one to a line. A Nightly window names its channel, its exact feed version
/// and commit, and offers a link to report a problem.
pub fn about_info() -> AboutInfo {
let build = option_env!("WORDCRAFT_BUILD_SHA").map(|s| s.get(..8).unwrap_or(s)).unwrap_or(tl!("development build"));
// The dialog's own "Version {version}" words the line, so this is the number and the build only.
let version = crate::i18n::fmt(tl!("{version} ({build})"), &[("version", env!("CARGO_PKG_VERSION")), ("build", build)]);
AboutInfo::new(
tl!("WordCraft").to_string(),
tl!("A free, open-source word processor written from scratch in Rust.\nPart of the Crafting Apps from the ArtCraft team.").to_string(),
version.to_string(),
)
.links([
AboutLink::new(tl!("getartcraft.com/apps/wordcraft").to_string(), "https://getartcraft.com/apps/wordcraft"),
AboutLink::new(tl!("Join us on Discord: discord.gg/artcraft").to_string(), "https://discord.gg/artcraft"),
AboutLink::new(tl!("Source code: github.com/storytold/wordcraft").to_string(), "https://github.com/storytold/wordcraft"),
])
.built_with(tl!("MIT OR Apache-2.0. Copyright (c) 2026 ArtCraft Team and the WordCraft contributors.").to_string())
about_info_for(crate::os_window::identity(), option_env!("WORDCRAFT_BUILD_SHA"))
}
/// The About tab's three lines for `identity`: (name, blurb, version line). A Nightly window's
/// are English only: they are not one of the stable catalogs' strings.
fn about_text(identity: crate::os_window::LaunchIdentity, commit: Option<&str>) -> (String, String, String) {
match identity {
crate::os_window::LaunchIdentity::NightlyV1 => {
let version = option_env!("WORDCRAFT_VERSION").unwrap_or(env!("CARGO_PKG_VERSION"));
let commit = commit.filter(|value| !value.is_empty()).unwrap_or("unavailable");
(
crate::os_window::name_for(identity).to_string(),
"A free, open-source word processor written from scratch in Rust.\nPart of the Crafting Apps from the ArtCraft team.".to_string(),
format!("{version}\nCommit: {commit}"),
)
}
crate::os_window::LaunchIdentity::Stable => {
let build = commit.map(|s| s.get(..8).unwrap_or(s)).unwrap_or(tl!("development build"));
// The dialog's own "Version {version}" words the line, so this is the number and the build only.
let version = crate::i18n::fmt(tl!("{version} ({build})"), &[("version", env!("CARGO_PKG_VERSION")), ("build", build)]);
(
tl!("WordCraft").to_string(),
tl!("A free, open-source word processor written from scratch in Rust.\nPart of the Crafting Apps from the ArtCraft team.")
.to_string(),
version.to_string(),
)
}
}
}
fn about_info_for(identity: crate::os_window::LaunchIdentity, commit: Option<&str>) -> AboutInfo {
let (name, blurb, version) = about_text(identity, commit);
if identity == crate::os_window::LaunchIdentity::NightlyV1 {
return AboutInfo::new(name, blurb, version)
.links([
AboutLink::new("getartcraft.com/apps/wordcraft".to_string(), "https://getartcraft.com/apps/wordcraft"),
AboutLink::new("Join us on Discord: discord.gg/artcraft".to_string(), "https://discord.gg/artcraft"),
AboutLink::new("Source code: github.com/storytold/wordcraft".to_string(), "https://github.com/storytold/wordcraft"),
// Opens only after a click; nothing is collected or sent automatically.
AboutLink::new("Report a problem".to_string(), "https://github.com/storytold/wordcraft/issues"),
])
.built_with("MIT OR Apache-2.0. Copyright (c) 2026 ArtCraft Team and the WordCraft contributors.".to_string());
}
AboutInfo::new(name, blurb, version)
.links([
AboutLink::new(tl!("getartcraft.com/apps/wordcraft").to_string(), "https://getartcraft.com/apps/wordcraft"),
AboutLink::new(tl!("Join us on Discord: discord.gg/artcraft").to_string(), "https://discord.gg/artcraft"),
AboutLink::new(tl!("Source code: github.com/storytold/wordcraft").to_string(), "https://github.com/storytold/wordcraft"),
])
.built_with(tl!("MIT OR Apache-2.0. Copyright (c) 2026 ArtCraft Team and the WordCraft contributors.").to_string())
}
/// The About dialog opened on `tab`, with the Language data tab after Models (`AboutTab::App(0)`). The name
@@ -90,3 +127,94 @@ pub(crate) fn about(tab: AboutTab) -> HostedAbout {
// PLAN: assumed `HostedAbout::layout(self, AboutLayout) -> Self` (look-dialogs-b framework fix)
HostedAbout::new(about_info(), credits()).app_tab(language_data_tab()).tab(tab).layout(AboutLayout::Listed)
}
/// A Nightly window's About names its channel, keeps the full feed version and commit, invents
/// nothing when the commit is missing, and adds the report link the stable About does not have.
#[cfg(test)]
mod nightly_about_tests {
use crate::os_window::LaunchIdentity;
const COMMIT: &str = "0123456789abcdef0123456789abcdef01234567";
#[test]
fn nightly_about_names_the_channel_and_keeps_the_full_version_and_commit() {
let (name, blurb, version) = super::about_text(LaunchIdentity::NightlyV1, Some(COMMIT));
assert_eq!(name, "WordCraft Nightly");
assert!(blurb.contains("word processor"));
let package = option_env!("WORDCRAFT_VERSION").unwrap_or(env!("CARGO_PKG_VERSION"));
assert_eq!(version, format!("{package}\nCommit: {COMMIT}"));
}
#[test]
fn nightly_about_invents_no_provenance_when_the_commit_is_missing() {
for commit in [None, Some("")] {
let (_, _, version) = super::about_text(LaunchIdentity::NightlyV1, commit);
assert!(version.ends_with("\nCommit: unavailable"), "{version}");
}
}
#[test]
fn only_the_nightly_about_offers_the_report_link_and_the_stable_name_is_unchanged() {
let nightly = super::about_info_for(LaunchIdentity::NightlyV1, Some(COMMIT));
assert!(nightly.links.iter().any(|link| link.url == "https://github.com/storytold/wordcraft/issues"));
let stable = super::about_info_for(LaunchIdentity::Stable, Some(COMMIT));
assert!(!stable.links.iter().any(|link| link.url == "https://github.com/storytold/wordcraft/issues"));
let (name, _, _) = super::about_text(LaunchIdentity::Stable, Some(COMMIT));
assert_eq!(name, "WordCraft");
}
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use std::rc::Rc;
use craft::ui::contract::Role;
use craft::ui::dialog::DialogHost;
use craft::ui::testing::Fixture;
use super::*;
fn column_header(fixture: &Fixture, label: &str) -> egui::Rect {
fixture
.by_role(Role::COLUMN_HEADER)
.into_iter()
.find(|cell| fixture.tree().name_of(cell.node) == Some(label))
.unwrap_or_else(|| panic!("missing column header {label:?}"))
.rect
}
fn table_rect(fixture: &Fixture) -> egui::Rect {
fixture.by_role(Role::TABLE).first().expect("the credits table shows").rect
}
/// Verifies that WordCraft's `about(AboutTab::Models)` (`AboutLayout::Listed` with the baked
/// `MODELS` table) fits within the dialog and refits its `Company` column when narrowed.
/// The original drag-then-content-change refit check (#5588) belongs in `craft-libs` and is
/// tracked in `storytold/craft-libs#3372`.
#[test]
fn models_table_refits_to_narrower_window() {
let wide = egui::vec2(1400.0, 800.0);
let narrow = egui::vec2(660.0, 800.0);
let host = Rc::new(RefCell::new(DialogHost::new()));
let shown_host = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| shown_host.borrow_mut().run(ui));
fixture.room(wide);
host.borrow_mut().open(about(AboutTab::Models));
fixture.settle();
let wide_table = table_rect(&fixture);
let wide_company = column_header(&fixture, "Company");
let wide_last = column_header(&fixture, "Lines +/\u{2212}");
assert!(wide_last.right() <= wide_table.right() + 1.0, "the table opens fitted to the dialog: {wide_last:?} in {wide_table:?}");
fixture.room(narrow).settle();
let slim_table = table_rect(&fixture);
let slim_company = column_header(&fixture, "Company");
let slim_last = column_header(&fixture, "Lines +/\u{2212}");
assert!(slim_table.width() < wide_table.width() - 1.0, "hosted About shrinks with window: {slim_table:?} vs {wide_table:?}");
assert!(slim_company.width() < wide_company.width() - 1.0, "hosted About refits its Company column: {slim_company:?} vs {wide_company:?}");
assert!(slim_last.right() <= slim_table.right() + 1.0, "the narrower table still fits its last column: {slim_last:?} in {slim_table:?}");
}
}
+1
View File
@@ -9,6 +9,7 @@ use serde_json::Value;
use crate::WordApp;
mod bookmarks;
pub(crate) mod chrome;
mod customize_keyboard;
mod enclose;
mod find;
+166
View File
@@ -0,0 +1,166 @@
//! Modal dialog chrome: modal nudge/shake animations and decorations (#3859, #4076, #7321).
use craft::ui::runtime::env::Env;
use craft::ui::style::rgba_color;
use egui::emath::TSTransform;
use egui::{Context, CornerRadius, Id, LayerId, Order, Stroke, StrokeKind, Ui, vec2};
use crate::WordApp;
/// How long a modal window shakes or flashes after a press beside it, in seconds.
pub(crate) const NUDGE_SECS: f64 = 0.4;
/// The `ctx.data` key for when the window `id` was last nudged, in this document window: the data
/// is shared by all of them.
pub(crate) fn nudge_id(ctx: &Context, id: Id) -> Id {
id.with(("nudge", ctx.viewport_id()))
}
/// Forgets a nudge of the window `id` as it closes, so it doesn't go on when the window reopens.
pub(crate) fn forget_nudge(ctx: &Context, id: Id) {
let key = nudge_id(ctx, id);
ctx.data_mut(|d| {
d.remove::<f64>(key);
});
}
/// The shake's sideways offset at `t` (0 to 1) through it: three swings either way of up to 6
/// points, dying away.
pub(crate) fn shake_offset(t: f32) -> f32 {
6.0 * (t * 3.0 * std::f32::consts::TAU).sin() * (1.0 - t)
}
/// Triggers a shake/nudge animation on dialog `id` if not already running.
pub(crate) fn trigger_prompt_nudge(ctx: &Context, id: Id) {
let key = nudge_id(ctx, id);
let now = ctx.input(|i| i.time);
let running = ctx.data(|d| d.get_temp::<f64>(key)).is_some_and(|s| (0.0..NUDGE_SECS).contains(&(now - s)));
if !running {
ctx.data_mut(|d| d.insert_temp(key, now));
}
ctx.request_repaint();
}
/// Applies modal shake / nudge animation (or accent border flashes under reduced motion) to the
/// active modal dialog. Also detects presses beside the dialog (on the backdrop or outside) to
/// trigger the nudge.
pub(crate) fn apply_modal_nudge(app: &mut WordApp, ui: &mut Ui) {
let ctx = ui.ctx().clone();
if craft::ui::runtime::measure::active(&ctx) {
return;
}
// Forget nudge on every dialog close, so reopening within NUDGE_SECS opens still.
// Tracking the host-provided open_serial distinguishes successive opens sharing the same ID.
let prev_open_key = Id::NULL.with("modal_dialogs_open_last_pass").with(ctx.viewport_id());
let prev_open: Vec<(Id, u64)> = ctx.data(|d| d.get_temp(prev_open_key)).unwrap_or_default();
let current_open: Vec<(Id, u64)> =
app.dialog_host.open_dialogs().into_iter().filter_map(|d| app.dialog_host.open_serial(d.id).map(|s| (d.id, s))).collect();
for (closed_id, prev_serial) in &prev_open {
if !current_open.iter().any(|(id, serial)| id == closed_id && serial == prev_serial) {
forget_nudge(&ctx, *closed_id);
}
}
ctx.data_mut(|d| d.insert_temp(prev_open_key, current_open));
let prompt_id = app.closing.as_ref().and_then(|c| c.prompt).filter(|&id| app.dialog_host.get_dyn(id).is_some());
let target_id =
prompt_id.or_else(|| app.dialog_host.shows_modal().then(|| app.dialog_host.open_dialogs().into_iter().next_back().map(|d| d.id)).flatten());
let Some(id) = target_id else {
return;
};
let hosted = app.dialog_host.get_dyn(id).is_some();
if !hosted {
return;
}
// When popups/menus are open inside a modal dialog, overlay::top points to the popup.
// Walk up .parent to locate the target modal dialog's own overlay entry so clicking
// inside the dialog (outside the popup) does not falsely trigger a shake.
let top_id = craft::ui::runtime::overlay::top(&ctx);
let mut modal_entry = top_id.and_then(|tid| craft::ui::runtime::overlay::entry(&ctx, tid));
while let Some(entry) = modal_entry.as_ref() {
if entry.rank.is_modal() {
break;
}
modal_entry = entry.parent.and_then(|pid| craft::ui::runtime::overlay::entry(&ctx, pid));
}
let modal_entry = modal_entry.filter(|e| e.rank.is_modal());
let modal_layer_id = ctx.memory(|m| m.top_modal_layer());
let (dialog_rect, area_layer_id) = if let Some(ref entry) = modal_entry {
(Some(entry.rect), Some(LayerId::new(Order::Foreground, craft::ui::runtime::memory::sub(entry.id, "area"))))
} else if let Some(layer) = modal_layer_id {
(ctx.memory(|m| m.area_rect(layer.id)), Some(layer))
} else {
(None, None)
};
let Some(rect) = dialog_rect else {
return;
};
// Include the modal dialog's rectangle and all open overlays in its family
// (such as dropdown popups or submenus) so presses on popup extensions are inside.
let mut inside_rects = vec![rect];
if let Some(ref entry) = modal_entry {
for family_id in craft::ui::runtime::overlay::family(&ctx, entry.id) {
if let Some(e) = craft::ui::runtime::overlay::entry(&ctx, family_id) {
inside_rects.push(e.rect);
if let Some(anchor) = e.anchor {
inside_rects.push(anchor);
}
}
}
}
let is_inside = |pos: egui::Pos2| inside_rects.iter().any(|r| r.contains(pos));
let beside = ctx.input(|i| {
let event_pressed = i.events.iter().any(|e| match e {
egui::Event::PointerButton { pos, pressed: true, button: egui::PointerButton::Primary, .. } => !is_inside(*pos),
_ => false,
});
let held_pressed = i.pointer.any_pressed() && i.pointer.press_origin().is_some_and(|p| !is_inside(p));
event_pressed || held_pressed
});
if beside {
trigger_prompt_nudge(&ctx, id);
}
let key = nudge_id(&ctx, id);
let now = ctx.input(|i| i.time);
let start = match ctx.data(|d| d.get_temp::<f64>(key)).filter(|s| (0.0..NUDGE_SECS).contains(&(now - s))) {
Some(s) => s,
None => return,
};
ctx.request_repaint();
let t = ((now - start) / NUDGE_SECS).clamp(0.0, 1.0) as f32;
let animate = app.animations_on() && app.system_animations();
if animate {
let offset = shake_offset(t);
let transform = TSTransform::from_translation(vec2(offset, 0.0));
if let Some(area_layer) = area_layer_id {
ctx.transform_layer_shapes(area_layer, transform);
}
if let Some(modal_layer) = modal_layer_id
&& Some(modal_layer) != area_layer_id
{
ctx.transform_layer_shapes(modal_layer, transform);
}
} else if ((t * 4.0) as u32).is_multiple_of(2) {
let env = Env::of(ui);
let radius = CornerRadius::from(env.tokens.shape.radius.window);
let stroke = Stroke::new(2.0, rgba_color(env.tokens.color.accent.solid));
if let Some(area_layer) = area_layer_id {
ctx.layer_painter(area_layer).rect_stroke(rect, radius, stroke, StrokeKind::Inside);
}
if let Some(modal_layer) = modal_layer_id
&& Some(modal_layer) != area_layer_id
{
ctx.layer_painter(modal_layer).rect_stroke(rect, radius, stroke, StrokeKind::Inside);
}
}
}
@@ -147,10 +147,14 @@ pub(crate) fn open(app: &mut WordApp, _name: &str, _params: &Value, parent: Opti
#[cfg(test)]
mod tests {
use craft::keymap::Binding;
use craft::keymap::{Binding, CommandRef};
use craft::ui::dialog::dialog_id;
use egui::accesskit::Role;
use egui_kittest::kittest::{By, NodeT, Queryable};
use serde_json::json;
use wordcraft_engine::Session;
use super::KEY;
use crate::{Services, WordApp};
fn app() -> WordApp {
@@ -181,4 +185,66 @@ mod tests {
assert_eq!(chords(&b, "format.bold"), Some(Vec::new()));
assert_eq!(chords(&b, "format.italic"), Some(italic));
}
/// #1905: a command with no shortcuts shows `None` in the Current shortcuts list, whereas a
/// command with a built-in shortcut shows its binding instead of `None`.
#[test]
fn keys_list_without_shortcuts_says_none() {
let mut a = app();
super::open(&mut a, KEY, &json!({}), None).expect("dialog opens");
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a);
h.run_steps(2);
let keymap = craft::ui::runtime::commands::keymap(&h.ctx).expect("command board installs a keymap");
let unbound_id = h
.state()
.session
.registry
.all()
.iter()
.find(|spec| {
let cmd = CommandRef::new(spec.id);
keymap.bindable(&cmd).is_some() && keymap.bindings(&cmd).is_empty()
})
.map(|spec| spec.id.to_string())
.expect("a bindable command with no built-in shortcut");
assert!(!keymap.bindings(&CommandRef::new("format.bold")).is_empty(), "format.bold has a built-in shortcut");
let dlg_id = dialog_id(KEY);
let ctx = h.ctx.clone();
let select = |h: &mut egui_kittest::Harness<'_, WordApp>, id: &str| {
h.state_mut().dialog_host.set_json_field(&ctx, dlg_id, "command", json!(id)).expect("command field accepts id");
h.run_steps(3);
let selected = h
.state()
.dialog_host
.open_dialogs()
.into_iter()
.find(|d| d.id == dlg_id)
.and_then(|d| d.fields)
.and_then(|fields| fields.get("command").and_then(|v| v.as_str()).map(str::to_owned));
assert_eq!(selected.as_deref(), Some(id), "dialog selected {id}");
};
let keys_list_labels = |h: &egui_kittest::Harness<'_, WordApp>| -> Vec<String> {
let list = h.get_by_role_and_label(Role::List, "Current shortcuts:");
let list_id = list.accesskit_node().id();
let rect = list.rect();
h.query_all(By::new())
.filter(|n| n.accesskit_node().id() != list_id && !n.accesskit_node().is_hidden() && n.accesskit_node().bounding_box().is_some())
.filter(|n| rect.contains_rect(n.rect()))
.filter_map(|n| n.accesskit_node().label())
.collect()
};
// Positive contrast: a bound command lists its shortcut and does not show the empty `None` placeholder.
select(&mut h, "format.bold");
let bound_labels = keys_list_labels(&h);
assert!(!bound_labels.is_empty(), "bound command lists its shortcut");
assert!(!bound_labels.iter().any(|t| t == "None"), "bound command keys list does not say None: {bound_labels:?}");
// Target behavior: an unbound command shows `None` inside the Current shortcuts list.
select(&mut h, &unbound_id);
let unbound_labels = keys_list_labels(&h);
assert!(unbound_labels.iter().any(|t| t == "None"), "empty keys list says None: {unbound_labels:?}");
}
}
@@ -375,3 +375,21 @@ fn date_time_dialog_keeps_open_and_displays_invalid_picture_error() {
assert!(a.dialog_host.get_dyn(id).is_some(), "the dialog stays open");
assert_eq!(a.session.doc.plain_text(wordcraft_doc::StoryRef::Body), "");
}
/// #4832: Document Information fields are offered and format instructions match the chosen
/// format.
#[test]
fn field_dialog_lists_the_document_information_fields() {
let listed: Vec<&str> = FIELDS.iter().filter(|(_, cat, _)| *cat == "Document Information").map(|(n, _, _)| *n).collect();
for name in ["COMMENTS", "KEYWORDS", "LASTSAVEDBY", "NUMCHARS", "REVNUM", "SUBJECT"] {
assert!(listed.contains(&name), "{name} in {listed:?}");
}
let a = app();
let mut f = FieldForm::new(&a);
f.select("REVNUM");
f.number_format = "ROMAN".into();
f.preserve = false;
assert_eq!(f.instruction(), r"REVNUM \* ROMAN");
f.select("SUBJECT");
assert_eq!(f.instruction(), "SUBJECT");
}
+82 -1
View File
@@ -632,7 +632,7 @@ mod tests {
use egui_kittest::kittest::Queryable;
let mut app = app("");
app.run("tools.autocorrect", json!({})).unwrap();
let mut h = crate::test_harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state(
let mut h = crate::test_harness::builder().allow_missing_glyphs().with_size(vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
@@ -665,4 +665,85 @@ mod tests {
}
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body), "Hello. world");
}
/// #3036: the Replace list says so when the filter matches nothing instead of going blank.
#[test]
fn the_autocorrect_list_says_when_the_filter_matches_nothing() {
let mut app = app("");
app.session.prefs.autocorrect.entries.push(("brb".to_string(), "be right back".to_string()));
app.run("tools.autocorrect", json!({})).unwrap();
fn texts(h: &egui_kittest::Harness<'_, WordApp>) -> Vec<String> {
fn extract(shape: &egui::Shape, out: &mut Vec<String>) {
match shape {
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
egui::Shape::Vec(v) => v.iter().for_each(|s| extract(s, out)),
_ => {}
}
}
let mut out = Vec::new();
for clipped in &h.output().shapes {
extract(&clipped.shape, &mut out);
}
out
}
let mut h = crate::test_harness::builder().allow_missing_glyphs().with_size(vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
for _ in 0..4 {
h.step();
}
assert!(!texts(&h).iter().any(|t| t.contains("(none)")), "entries show, no hint");
if let Some(host) = h.state_mut().dialog_host.get_mut::<FormHost<AutoCorrectForm>>() {
host.form_mut().from = "zzz".to_string();
} else {
panic!("the AutoCorrect form is open");
}
for _ in 0..2 {
h.step();
}
assert!(texts(&h).iter().any(|t| t.contains("(none)")), "no matches: the hint shows");
}
/// #6046: Compare › More shows "Show changes at:" and its two choices each on one line. The
/// column is not the grid's last, so it first gets the grid's minimum cell width; wrapped to
/// that, its text broke after every few letters and the column stayed that narrow.
#[test]
fn compare_more_keeps_the_show_changes_at_column_on_one_line() {
use egui_kittest::kittest::Queryable;
let mut app = app("Original text.");
app.run("review.compare", json!({})).unwrap();
let mut h = crate::test_harness::builder().allow_missing_glyphs().with_size(vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
h.run_steps(4);
h.get_by_label("More >>").click();
h.run_steps(4);
let one_line = h.get_by_label("New document").rect().height();
for label in ["Word level", "Character level"] {
let r = h.get_by_label(label).rect();
assert!(r.height() <= one_line + 1.0, "{label} wraps: {r:?}, one line is {one_line}");
}
fn find_galley<'a>(shape: &'a egui::Shape, text: &str) -> Option<&'a std::sync::Arc<egui::Galley>> {
match shape {
egui::Shape::Text(t) if t.galley.text() == text => Some(&t.galley),
egui::Shape::Vec(v) => v.iter().find_map(|s| find_galley(s, text)),
_ => None,
}
}
let galley = h.output().shapes.iter().find_map(|s| find_galley(&s.shape, "Show changes at:")).expect("Show changes at: text galley");
assert_eq!(galley.rows.len(), 1, "Show changes at: must be on one line, but has {} rows", galley.rows.len());
// The next column starts after the widest of them.
let (left, right) = (h.get_by_label("Character level").rect(), h.get_by_label("Show changes in:").rect());
assert!(right.left() >= left.right(), "the columns overlap: {left:?} {right:?}");
}
}
@@ -788,6 +788,7 @@ pub(crate) fn open(app: &mut WordApp, name: &str, _params: &Value, parent: Optio
#[cfg(test)]
mod tests {
use super::*;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use wordcraft_engine::Session;
@@ -859,4 +860,42 @@ mod tests {
crate::test_harness::frames(&mut h, 3);
assert_ne!(h.state().session.view.ruler, ruler, "the custom group's button runs its command");
}
/// #1845: typing in the command filter searches across all commands regardless of category,
/// and Add >> places the selected command on the Quick Access Toolbar.
#[test]
fn command_filter_narrows_the_picker_and_add_works() {
let mut a = app();
a.run("tools.customizeRibbon", json!({})).unwrap();
let id = craft::ui::dialog::dialog_id("customizeRibbon");
assert!(a.dialog_host.open_dialogs().iter().any(|d| d.id == id), "the dialog is open");
let (category, current) = {
let d = a.dialog_host.get_by_id::<RibbonDialog>(id).expect("dialog exists");
(d.category.clone(), d.command.clone())
};
// Empty filter keeps the category scope.
let unfiltered = matching_commands(&a, &category, "");
assert!(!unfiltered.is_empty());
// Typing searches every command, ignoring the category.
let filter = "bold";
let cmds = matching_commands(&a, &category, filter);
assert!(cmds.iter().any(|(cmd_id, _)| cmd_id == "format.bold"));
assert!(cmds.len() < a.session.registry.all().len());
let ctx = egui::Context::default();
a.dialog_host.set_json_field(&ctx, id, "filter", json!(filter)).unwrap();
prepare(&mut a, id);
let picked = select_in(&cmds, &current);
assert!(!picked.is_empty());
a.dialog_host.set_json_field(&ctx, id, "command", json!(picked)).unwrap();
// The dialog's Add >> adds the filtered pick to the Quick Access Toolbar.
a.run("tools.customizeRibbon", json!({"qatAdd": picked})).unwrap();
assert!(a.session.ribbon.qat().contains(&picked.as_str()));
assert!(a.session.ribbon.qat().contains(&"format.bold"));
}
}
+380 -70
View File
@@ -6,15 +6,18 @@
use craft::behavior::Anchor9;
use craft::color_ui::ui::ColorPickerTab;
use craft::font_manager::picker::FontPickerSettings;
use craft::ui::buttons::{Button, ToggleButton};
use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _, Trigger};
use craft::ui::buttons::{Button, ControlPlace, GroupLevel, ToggleButton};
use craft::ui::contract::{Bind, Entry, Gap, Props as _, Show as _, ShowContainer as _, Sizing, Trigger};
use craft::ui::controls::disclosure::DisclosureGlyph;
use craft::ui::dialog::DialogId;
use craft::ui::display::Picture;
use craft::ui::display::{Picture, PictureSize, Text};
use craft::ui::form::{Field, FieldGroup};
use craft::ui::list::ThumbAspect;
use craft::ui::layout_components::Row;
use craft::ui::list::{ThumbAspect, ThumbSize};
use craft::ui::menu::Menu;
use craft::ui::patterns::form_dialogs::FormCx;
use craft::ui::pickers::{ReferencePoint, ReferencePointKind, Select};
use craft::ui::pickers::{ComboBox, ReferencePoint, ReferencePointKind, Select};
use craft::ui::popover::Popover;
use craft::ui::primitives::{ContentPainterCx, Glyph, IconSpec};
use craft::ui::runtime::env::Label;
use craft::ui::sections::Section;
@@ -122,6 +125,15 @@ const ANCHORS: [Anchor9; 9] = [
Anchor9::BottomRight,
];
/// The alignment labels shown on the closed Alignment button, in [`CELL_ALIGNS`] order.
const ALIGN_LABELS: [&str; 9] = ["Top left", "Top", "Top right", "Left", "Center", "Right", "Bottom left", "Bottom", "Bottom right"];
/// The closed Alignment button's visible label for `align` (`"Auto"` when inherited).
fn align_label(align: &str) -> Label {
let text = CELL_ALIGNS.iter().position(|(n, _, _)| *n == align).and_then(|i| ALIGN_LABELS.get(i).copied()).unwrap_or("Auto");
lab(text)
}
/// The `cellAlign` name for a part's alignments, empty when it sets neither.
fn align_name(h: Option<Align>, v: Option<VAlign>) -> String {
if h.is_none() && v.is_none() {
@@ -167,7 +179,10 @@ fn region_of(st: &TableStyleProps, part: TablePart) -> TableRegion {
/// The params `table.newStyle` / `table.modifyStyle` take for the dialog's state: only what
/// changed from `basis`, part by part, so the rest stays inherited.
pub fn table_style_params(id: Option<&str>, name: &str, based_on: &str, regions: &[TableRegion; 13], basis: &[TableRegion; 13]) -> Value {
let mut v = json!({"name": name.trim(), "basedOn": based_on});
let mut v = json!({"name": name.trim()});
if !based_on.trim().is_empty() {
v["basedOn"] = json!(based_on.trim());
}
for (((part, _), r), b) in PARTS.iter().zip(regions.iter()).zip(basis.iter()) {
let ch = region_changes(r, b);
if ch.as_object().is_some_and(|o| !o.is_empty()) {
@@ -359,7 +374,9 @@ fn paint_preview(cx: &ContentPainterCx<'_>, rect: Rect, style: Option<&TableStyl
let Some(st) = style else { return };
let mut shapes: Vec<Shape> = Vec::new();
let formats: Vec<PartFormat> = TablePart::ALL.iter().map(|p| st.part(*p)).collect();
let table = rect.shrink2(vec2(14.0, 10.0));
let pad_x = (rect.width() * 0.035).clamp(6.0, 14.0);
let pad_y = (rect.height() * 0.06).clamp(4.0, 10.0);
let table = rect.shrink2(vec2(pad_x, pad_y));
let (cw, rh) = (table.width() / COLS as f32, table.height() / ROWS as f32);
let rgb = |c: Rgb| Color32::from_rgb(c.0, c.1, c.2);
let tb = st.parts.borders.unwrap_or_default();
@@ -426,16 +443,18 @@ fn paint_preview(cx: &ContentPainterCx<'_>, rect: Rect, style: Option<&TableStyl
Some(TextColor::Rgb(c)) => rgb(c),
_ => Color32::BLACK,
};
let font = egui::FontId::proportional(11.0);
let font = egui::FontId::proportional((rh * 0.65).clamp(8.5, 11.0));
let inset_x = (cw * 0.06).clamp(2.0, 4.0);
let inset_y = (rh * 0.1).clamp(1.0, 2.0);
let (ax, x) = match h {
Some(Align::Center) => (egui::Align::Center, cell.center().x),
Some(Align::Right) => (egui::Align::Max, cell.right() - 4.0),
_ => (egui::Align::Min, cell.left() + 4.0),
Some(Align::Right) => (egui::Align::Max, cell.right() - inset_x),
_ => (egui::Align::Min, cell.left() + inset_x),
};
let (ay, y) = match v {
Some(VAlign::Center) => (egui::Align::Center, cell.center().y),
Some(VAlign::Bottom) => (egui::Align::Max, cell.bottom() - 2.0),
_ => (egui::Align::Min, cell.top() + 2.0),
Some(VAlign::Bottom) => (egui::Align::Max, cell.bottom() - inset_y),
_ => (egui::Align::Min, cell.top() + inset_y),
};
let galley = cx.painter.layout_no_wrap(txt.to_string(), font, color);
let r = egui::Align2([ax, ay]).anchor_size(pos2(x, y), galley.size());
@@ -519,7 +538,7 @@ impl TableStyleForm {
FieldGroup::new(lab("Table style")).show(ui, |ui, _| {
let name_label = lab("Name:");
Field::new(name_label.clone()).show(ui, |ui, _| {
TextField::new(name_label.clone(), Bind::bound(&mut self.name)).show(ui);
TextField::new(name_label.clone(), Bind::bound(&mut self.name)).width_chars(30).show(ui);
});
let entries: Vec<Entry<usize>> = self.bases.iter().enumerate().map(|(i, b)| Entry::new(i, b.name.clone())).collect();
let current = self.bases.iter().position(|b| b.id == self.based_on).unwrap_or(usize::MAX);
@@ -545,72 +564,172 @@ impl TableStyleForm {
let Self { region, regions, pen, palette, catalog, font_settings, .. } = self;
let Some(r) = regions.get_mut(*region) else { return };
Section::fixed(lab("Formatting")).show(ui, |ui, _| {
FieldGroup::new(lab("Formatting")).show(ui, |ui, _| {
// Row 1: Font, size, and B / I / U toggles.
Row::new().gap(Gap::Inline).wrap(true).show(ui, |ui, _| {
let sizes: Vec<Entry<String>> = wordcraft_engine::cmd::format::SIZES
.iter()
.map(|s| {
let s = size_text(*s);
Entry::new(s.clone(), s)
})
.collect();
if let Some(catalog) = catalog.get() {
let font_label = lab("Font:");
Field::new(font_label.clone()).show(ui, |ui, _| {
font_picker(font_label.clone(), Bind::bound(&mut r.font), catalog, Bind::bound(&mut *font_settings), &[], None).show(ui);
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
let font_label = lab("Font:");
Text::new(font_label.clone()).show(ui);
craft::ui::runtime::env::with_env(
ui,
|overrides| {
overrides.values.set(ControlPlace::Ribbon);
},
|ui| {
font_picker(font_label, Bind::bound(&mut r.font), catalog, Bind::bound(&mut *font_settings), &[], None).show(ui);
},
);
});
}
// Text, so an empty box means the size is inherited.
let size_label = lab("Size:");
Field::new(size_label.clone()).show(ui, |ui, _| {
TextField::new(size_label.clone(), Bind::bound(&mut r.size)).show(ui);
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
let size_label = lab("Size:");
Text::new(size_label.clone()).show(ui);
craft::ui::runtime::env::with_env(
ui,
|overrides| {
overrides.values.set(ControlPlace::Ribbon);
},
|ui| {
ComboBox::new(size_label, Bind::bound(&mut r.size), &sizes).show(ui);
},
);
});
Field::new(lab("Font style:")).show(ui, |ui, _| {
ui.horizontal(|ui| {
ToggleButton::new(lab("Bold"), Bind::bound(&mut r.bold)).show(ui);
ToggleButton::new(lab("Italic"), Bind::bound(&mut r.italic)).show(ui);
ToggleButton::new(lab("Underline"), Bind::bound(&mut r.underline)).show(ui);
});
// Compact icon-only labels inside standard secondary (framed) toggle buttons so B / I / U
// keep full icon size and visible button outlines.
craft::ui::runtime::env::with_env(
ui,
|overrides| {
overrides.values.set(GroupLevel::Compact);
},
|ui| {
Row::new().gap(Gap::Tight).show(ui, |ui, _| {
ToggleButton::new(lab("Bold"), Bind::bound(&mut r.bold)).icon(crate::icons::id("bold")).tooltip(lab("Bold")).show(ui);
ToggleButton::new(lab("Italic"), Bind::bound(&mut r.italic))
.icon(crate::icons::id("italic"))
.tooltip(lab("Italic"))
.show(ui);
ToggleButton::new(lab("Underline"), Bind::bound(&mut r.underline))
.icon(crate::icons::id("underline"))
.tooltip(lab("Underline"))
.show(ui);
});
},
);
});
// Row 2: Font color and Fill color.
Row::new().gap(Gap::Section).wrap(true).show(ui, |ui, _| {
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
Text::new(lab("Font color:")).show(ui);
if color_field(ui, &lab("Font color:"), &mut r.color, &ColorFieldEmpty::NoColor, palette).more_colors {
asks.push(Asks::Color { field: "color", current: Rgb::parse(&r.color), tab: ColorPickerTab::Standard });
}
});
if color_field(ui, &lab("Font color:"), &mut r.color, &ColorFieldEmpty::NoColor, palette).more_colors {
asks.push(Asks::Color { field: "color", current: Rgb::parse(&r.color), tab: ColorPickerTab::Standard });
}
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
Text::new(lab("Fill color:")).show(ui);
if color_field(ui, &lab("Fill color:"), &mut r.fill, &ColorFieldEmpty::NoColor, palette).more_colors {
asks.push(Asks::Color { field: "fill", current: Rgb::parse(&r.fill), tab: ColorPickerTab::Standard });
}
});
});
// Row 3: Border pen style, width, and color.
Row::new().gap(Gap::Inline).wrap(true).show(ui, |ui, _| {
let styles: Vec<Entry<usize>> = LINE_STYLES.iter().enumerate().map(|(i, (_, n))| Entry::new(i, lab(n))).collect();
let current = LINE_STYLES.iter().position(|(s, _)| *s == pen.style).unwrap_or(0);
if let Some((s, _)) = pick_index(ui, "Style:", &styles, current).and_then(|i| LINE_STYLES.get(i)) {
pen.style = *s;
}
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
Text::new(lab("Style:")).show(ui);
if let Some((s, _)) = Select::new(lab("Style:"), Bind::given(current), &styles)
.sizing(Sizing::Content)
.show(ui)
.value()
.copied()
.and_then(|i| LINE_STYLES.get(i))
{
pen.style = *s;
}
});
let widths: Vec<Entry<usize>> =
WIDTHS.iter().enumerate().map(|(i, w)| Entry::new(i, crate::i18n::fmt(tl!("{n} pt"), &[("n", &w.to_string())]))).collect();
let current = WIDTHS.iter().position(|w| *w == pen.width).unwrap_or(usize::MAX);
if let Some(w) = pick_index(ui, "Width:", &widths, current).and_then(|i| WIDTHS.get(i)) {
pen.width = *w;
}
if color_field(ui, &lab("Color:"), &mut pen.color, &ColorFieldEmpty::NoColor, palette).more_colors {
asks.push(Asks::Color { field: "pen", current: Rgb::parse(&pen.color), tab: ColorPickerTab::Standard });
}
Field::new(lab("Borders:")).show(ui, |ui, _| {
let button = Button::new(lab("Borders")).show(ui);
let entries: Vec<Entry<usize>> = EDGES
.iter()
.zip(EDGE_GLYPHS.iter())
.enumerate()
.map(|(i, ((label, edges), glyph))| {
Entry::new(i, lab(label)).icon(IconSpec::glyph(glyph)).checked(edges_on(&r.borders, edges))
})
.collect();
let picked = Menu::new(lab("Borders")).opened_by(&button, Trigger::Press).pick(ui, &entries).picked;
if let Some((_, edges)) = picked.and_then(|i| EDGES.get(i)) {
pick_edges(&mut r.borders, edges, pen);
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
Text::new(lab("Width:")).show(ui);
if let Some(w) = Select::new(lab("Width:"), Bind::given(current), &widths)
.sizing(Sizing::Content)
.show(ui)
.value()
.copied()
.and_then(|i| WIDTHS.get(i))
{
pen.width = *w;
}
});
if color_field(ui, &lab("Fill color:"), &mut r.fill, &ColorFieldEmpty::NoColor, palette).more_colors {
asks.push(Asks::Color { field: "fill", current: Rgb::parse(&r.fill), tab: ColorPickerTab::Standard });
}
// The grid is row by row from the top left, as `CELL_ALIGNS` is.
let current = CELL_ALIGNS.iter().position(|(n, _, _)| *n == r.align).and_then(|i| ANCHORS.get(i)).copied();
let picked =
ReferencePoint::new(lab("Alignment:"), Bind::given(current)).kind(ReferencePointKind::Alignment).show(ui).value().copied();
if let Some(anchor) = picked {
// Picking the selected cell again clears the alignment.
r.align = anchor
.and_then(|a| ANCHORS.iter().position(|x| *x == a))
.and_then(|i| CELL_ALIGNS.get(i))
.map(|(n, _, _)| n.to_string())
.unwrap_or_default();
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
Text::new(lab("Color:")).show(ui);
if color_field(ui, &lab("Color:"), &mut pen.color, &ColorFieldEmpty::NoColor, palette).more_colors {
asks.push(Asks::Color { field: "pen", current: Rgb::parse(&pen.color), tab: ColorPickerTab::Standard });
}
});
});
// Row 4: Borders menu and compact Alignment dropdown opening the 3×3 alignment grid.
Row::new().gap(Gap::Section).wrap(true).show(ui, |ui, _| {
let button = Button::new(lab("Borders:")).painted(lab("Borders")).trailing_icon(DisclosureGlyph::menu_button()).show(ui);
let entries: Vec<Entry<usize>> = EDGES
.iter()
.zip(EDGE_GLYPHS.iter())
.enumerate()
.map(|(i, ((label, edges), glyph))| Entry::new(i, lab(label)).icon(IconSpec::glyph(glyph)).checked(edges_on(&r.borders, edges)))
.collect();
let picked = Menu::new(lab("Borders")).opened_by(&button, Trigger::Press).pick(ui, &entries).picked;
if let Some((_, edges)) = picked.and_then(|i| EDGES.get(i)) {
pick_edges(&mut r.borders, edges, pen);
}
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
Text::new(lab("Alignment:")).show(ui);
let open_id = ui.make_persistent_id("tstyle_align_open");
let mut open = ui.ctx().data(|d| d.get_temp::<bool>(open_id)).unwrap_or(false);
let align_text = align_label(&r.align);
let align_spoken = Label::from(format!("{} {}", tl!("Alignment:"), align_text.as_str()));
let button = Button::new(align_spoken)
.painted(align_text)
.icon(crate::icons::id("cellAlign"))
.trailing_icon(DisclosureGlyph::menu_button())
.show(ui);
if button.clicked() {
open = !open;
}
Popover::new(lab("Alignment"), Bind::bound(&mut open)).opened_by(&button).show(ui, |ui, cx| {
// The grid is row by row from the top left, as `CELL_ALIGNS` is.
let current = CELL_ALIGNS.iter().position(|(n, _, _)| *n == r.align).and_then(|i| ANCHORS.get(i)).copied();
let picked = ReferencePoint::new(lab("Alignment:"), Bind::given(current))
.kind(ReferencePointKind::Alignment)
.show(ui)
.value()
.copied();
if let Some(anchor) = picked {
// Picking the selected cell again clears the alignment.
r.align = anchor
.and_then(|a| ANCHORS.iter().position(|x| *x == a))
.and_then(|i| CELL_ALIGNS.get(i))
.map(|(n, _, _)| n.to_string())
.unwrap_or_default();
cx.request_close();
}
});
ui.ctx().data_mut(|d| d.insert_temp(open_id, open));
});
});
});
}
@@ -652,7 +771,9 @@ impl WordForm for TableStyleForm {
let look = look_for(self.look, self.part());
let preview = self.preview.as_ref();
Section::fixed(lab("Preview")).show(ui, |ui, _| {
Picture::painter(lab("Table style preview"), ThumbAspect::new(36, 13), |cx, rect| paint_preview(cx, rect, preview, &look)).show(ui);
Picture::painter(lab("Table style preview"), ThumbAspect::new(36, 13), |cx, rect| paint_preview(cx, rect, preview, &look))
.extent(PictureSize::Sample(ThumbSize::Large))
.show(ui);
});
true
}
@@ -777,6 +898,191 @@ mod tests {
)
}
/// Alignment choices expose their names and current selection, and can be toggled through the dialog.
#[test]
fn alignment_buttons_expose_names_selection_and_clicks() {
use crate::dialogs::host::FormHost;
use egui::accesskit::{Role, Toggled};
use egui_kittest::kittest::NodeT;
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.run("insert.table", json!({"rows": 4, "cols": 3})).unwrap();
app.run("table.newStyle", json!({"name": "AlignTest"})).unwrap();
let dialog_id = crate::dialogs::open(&mut app, "modifyTableStyle", &json!({})).expect("dialog opened");
// Keep the background ribbon's character controls out of the dialog's label queries.
app.ui.tab = "Insert".into();
let mut h = harness(app);
steps(&mut h);
// Open the Alignment popover, verify labels and unchecked state, then pick "Bottom right".
h.get_by_role_and_label(Role::Button, "Alignment: Auto").click();
steps(&mut h);
assert_eq!(h.get_by_role_and_label(Role::RadioButton, "Bottom right").accesskit_node().toggled(), Some(Toggled::False));
assert!(!h.get_by_role_and_label(Role::RadioButton, "Center").accesskit_node().is_disabled());
// Click "Bottom right", check align == "bottomRight" and button exposes the value.
h.get_by_role_and_label(Role::RadioButton, "Bottom right").click();
steps(&mut h);
{
let host = h.state().dialog_host.get_by_id::<FormHost<TableStyleForm>>(dialog_id).expect("form is hosted");
let r = &host.form().regions[host.form().region];
assert_eq!(r.align, "bottomRight");
}
// Reopen Alignment via its updated accessible name, verify "Bottom right" is checked, click again to clear it.
h.get_by_role_and_label(Role::Button, "Alignment: Bottom right").click();
steps(&mut h);
assert_eq!(h.get_by_role_and_label(Role::RadioButton, "Bottom right").accesskit_node().toggled(), Some(Toggled::True));
h.get_by_role_and_label(Role::RadioButton, "Bottom right").click();
steps(&mut h);
{
let host = h.state().dialog_host.get_by_id::<FormHost<TableStyleForm>>(dialog_id).expect("form is hosted");
let r = &host.form().regions[host.form().region];
assert_eq!(r.align, "");
}
assert!(h.query_by_role_and_label(Role::Button, "Alignment: Auto").is_some());
}
/// #7692: empty or whitespace basedOn must be omitted so build_modified does not reject unbased styles.
#[test]
fn table_style_params_omits_empty_based_on() {
let regions: [TableRegion; 13] = std::array::from_fn(|_| TableRegion::default());
let basis: [TableRegion; 13] = std::array::from_fn(|_| TableRegion::default());
let params = table_style_params(Some("tableGrid"), "Table Grid", "", &regions, &basis);
assert!(!params.as_object().unwrap().contains_key("basedOn"));
let params_whitespace = table_style_params(Some("tableGrid"), "Table Grid", " ", &regions, &basis);
assert!(!params_whitespace.as_object().unwrap().contains_key("basedOn"));
let params_with_base = table_style_params(None, "New Style", "tableGrid", &regions, &basis);
assert_eq!(params_with_base.get("basedOn").and_then(|v| v.as_str()), Some("tableGrid"));
}
/// Choosing the document default font or size on a sub-part after changing Whole Table must
/// still emit that part's explicit override instead of treating the default as unchanged.
#[test]
fn choosing_default_font_and_size_on_sub_part_overrides_whole_table() {
use crate::dialogs::host::FormHost;
use egui::accesskit::Role;
use wordcraft_doc::CharProps;
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
let default_chr = app.session.doc.styles.resolve_char(None, &CharProps::default());
let default_size = size_text(default_chr.size);
let other_size = if (default_chr.size - 9.0).abs() < 0.1 { "14".to_string() } else { "9".to_string() };
let other_font = "Georgia".to_string();
let dialog_id = crate::dialogs::open(&mut app, "modifyTableStyle", &json!({})).expect("dialog opened");
app.ui.tab = "Insert".into();
let mut h = harness(app);
steps(&mut h);
// Set Whole Table font and size to non-default values, then switch to Header Row and pick
// the document's own default font and size explicitly.
{
let host = h.state_mut().dialog_host.get_mut_by_id::<FormHost<TableStyleForm>>(dialog_id).expect("form is hosted");
host.form_mut().regions[part_index(TablePart::WholeTable)].font = other_font.clone();
host.form_mut().regions[part_index(TablePart::WholeTable)].size = other_size.clone();
}
steps(&mut h);
h.get_by_label("Apply formatting to:").click();
steps(&mut h);
h.get_by_label("Header Row").click();
steps(&mut h);
h.get_by_role_and_label(Role::ComboBox, "Size:").click();
steps(&mut h);
for _ in 0..default_size.len().max(4) {
h.key_press(egui::Key::Backspace);
}
h.event(egui::Event::Text(default_size));
h.key_press(egui::Key::Enter);
steps(&mut h);
{
let host = h.state_mut().dialog_host.get_mut_by_id::<FormHost<TableStyleForm>>(dialog_id).expect("form is hosted");
host.form_mut().regions[part_index(TablePart::FirstRow)].font = default_chr.font.clone();
}
steps(&mut h);
h.get_by_label("OK").click();
steps(&mut h);
assert!(h.state().dialog_host.open_dialogs().is_empty(), "OK closes the dialog");
let st = h.state().session.doc.styles.get("TableGrid").cloned().unwrap();
assert_eq!(st.table_part(TablePart::WholeTable).chr.font.as_deref(), Some(other_font.as_str()));
assert_eq!(st.table_part(TablePart::FirstRow).chr.font.as_deref(), Some(default_chr.font.as_str()));
assert_eq!(st.table_part(TablePart::FirstRow).chr.size, Some(default_chr.size));
}
/// #7692: modifying the default Table Grid style (which has no base style) sends no empty basedOn
/// and OK closes successfully without a blank preview or command rejection.
#[test]
fn modify_table_grid_style_omits_empty_based_on_and_does_not_fail() {
use crate::dialogs::host::FormHost;
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
let dialog_id = crate::dialogs::open(&mut app, "modifyTableStyle", &json!({})).expect("dialog opened");
app.ui.tab = "Insert".into();
let mut h = harness(app);
steps(&mut h);
{
let host = h.state().dialog_host.get_by_id::<FormHost<TableStyleForm>>(dialog_id).expect("form is hosted");
assert!(host.form().based_on.is_empty(), "Table Grid has no base style");
assert!(host.form().preview.is_some(), "Table Grid preview must build without a base style");
let r = &host.form().regions[host.form().region];
assert!(r.font.is_empty(), "unset font stays empty (inherited) until edited");
assert!(r.size.is_empty(), "unset size stays empty (inherited) until edited");
let params = host.form().params();
let obj = params.as_object().unwrap();
assert!(!obj.contains_key("basedOn"), "empty basedOn must be omitted");
assert!(!obj.contains_key("wholeTable"), "untouched style sends no region changes");
}
{
use egui::accesskit::Role;
let dialog = h.get_by_role_and_label(Role::Dialog, "Modify Table Style").rect();
assert!(h.query_by_role_and_label(Role::Heading, "Formatting").is_some(), "Formatting section heading is exposed");
assert!(h.query_by_role_and_label(Role::Label, "Font:").is_some(), "Font visible label is exposed");
assert!(h.query_by_role_and_label(Role::Label, "Size:").is_some(), "Size visible label is exposed");
let font = h.get_by_role_and_label(Role::ComboBox, "Font:").rect();
let size = h.get_by_role_and_label(Role::ComboBox, "Size:").rect();
let underline = h.get_by_role_and_label(Role::Button, "Underline").rect();
let font_color = h.query_all_by_label("Font color: No Color").next().expect("font color field").rect();
let fill = h.query_all_by_label("Fill color: No Color").next().expect("fill color field").rect();
let borders = h.get_by_role_and_label(Role::Button, "Borders:").rect();
let align = h.get_by_role_and_label(Role::Button, "Alignment: Auto").rect();
assert!(size.width() < font.width(), "Size box should be narrower than Font box: size={size:?} font={font:?}");
for (name, rect) in
[("Underline", underline), ("Font color", font_color), ("Fill color", fill), ("Borders", borders), ("Alignment", align)]
{
assert!(rect.right() <= dialog.right(), "{name} must fit inside the dialog without overflowing: rect={rect:?} dialog={dialog:?}");
}
assert!(
(borders.center().y - align.center().y).abs() < (borders.height() + align.height()) * 0.25
&& (borders.height() - align.height()).abs() < borders.height() * 0.25,
"Borders and Alignment should line up compactly on one row: borders={borders:?} align={align:?}"
);
assert!(
(font_color.center().y - fill.center().y).abs() < (font_color.height() + fill.height()) * 0.25,
"Font color and Fill color should share one row: font_color={font_color:?} fill={fill:?}"
);
let preview = h.get_by_role_and_label(Role::Image, "Table style preview").rect();
let controls_height = align.bottom() - font.top();
assert!(
preview.height() > font.height() * 2.0 && preview.height() < controls_height && preview.width() > preview.height() * 2.0,
"preview should be a landscape compact sample taller than a control row and shorter than the formatting controls: preview={preview:?} font={font:?} controls_height={controls_height}"
);
assert!(
preview.right() <= dialog.right() && preview.bottom() <= dialog.bottom(),
"preview must stay inside the dialog: preview={preview:?} dialog={dialog:?}"
);
}
h.get_by_label("OK").click();
steps(&mut h);
assert!(h.state().dialog_host.open_dialogs().is_empty(), "OK closes the dialog");
}
/// #714: picking a part under "Apply formatting to" and changing it edits that part (here the
/// even banded rows) and no other.
#[test]
@@ -797,10 +1103,14 @@ mod tests {
steps(&mut h);
for label in ["Bold", "Italic", "Underline"] {
// An off toggle button reports no toggled state; only an on one says `True`.
assert_ne!(h.get_by_label(label).accesskit_node().toggled(), Some(Toggled::True), "{label} starts off");
h.get_by_label(label).click();
assert_ne!(
h.get_by_role_and_label(egui::accesskit::Role::Button, label).accesskit_node().toggled(),
Some(Toggled::True),
"{label} starts off"
);
h.get_by_role_and_label(egui::accesskit::Role::Button, label).click();
steps(&mut h);
assert_eq!(h.get_by_label(label).accesskit_node().toggled(), Some(Toggled::True));
assert_eq!(h.get_by_role_and_label(egui::accesskit::Role::Button, label).accesskit_node().toggled(), Some(Toggled::True));
}
h.get_by_label("OK").click();
steps(&mut h);
+7
View File
@@ -108,12 +108,19 @@ pub(crate) fn settle(app: &mut WordApp, ctx: &Context) {
/// More Colors targets, so none outlives its dialog.
pub(crate) fn close_all(app: &mut WordApp, ctx: &Context) {
let ids: Vec<DialogId> = app.dialog_host.open_dialogs().into_iter().rev().map(|dialog| dialog.id).collect();
let had_dialogs = !ids.is_empty();
for id in ids {
app.dialog_host.cancel_by_id(ctx, id);
}
settle(app, ctx);
// PLAN: assumed `WordApp::more_colors` with `clear()` (ribbon-w11, rb.A4's target map)
app.more_colors.clear();
if had_dialogs && !app.file_dialog_open() && !app.ui.backstage {
app.canvas.focus_page(ctx);
app.canvas.focus_pending = true;
app.canvas.focus_page_after_pass();
ctx.request_repaint();
}
}
/// Opens the About dialog on `tab`. A second About while one is open opens nothing: the first keeps the input.
+442
View File
@@ -950,6 +950,83 @@ fn opened_paper(h: &mut egui_kittest::Harness<'_, WordApp>) -> (f32, f32) {
paper
}
/// #1433: in a right-to-left interface, typing a number wider than the field's column into a
/// margin spin button keeps the dialog the same width; clicking the visible end of the blurred
/// field enters editing again, and entering a normal value restores the field.
#[test]
fn page_setup_rtl_large_margin_can_be_edited_again_after_blur() {
use egui::accesskit::Role;
let mut app = app_with("Page");
app.run("ui.dialog", json!({"name": "pageSetup"})).unwrap();
let ar = crate::i18n::fixture_lang("ar", "\tMargins\tMargins\n");
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
move |ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
// Draw the actual dialog in a fixture language even without embedded catalogs.
crate::i18n::apply_language(ar);
ctx.global_style_mut(|s| s.right_to_left = true);
assert!(crate::i18n::current().rtl() && ctx.global_style().right_to_left);
craft::ui::runtime::env::with_env(ui, |o| o.direction = Some(craft::i18n::Direction::Rtl), |ui| app.ui(ui));
ctx.global_style_mut(|s| s.right_to_left = false);
crate::i18n::apply_language(crate::i18n::Lang::EN);
},
app,
);
h.run_steps(4);
let initial = h.get_by_role_and_label(Role::SpinButton, "Bottom").rect();
assert!(h.get_by_role_and_label(Role::SpinButton, "Top").rect().center().x > initial.center().x, "the form is mirrored");
let window = |h: &egui_kittest::Harness<'_, WordApp>| h.get_by_role_and_label(Role::Dialog, "Page Setup").rect();
let before = window(&h).width();
let id = id_of(h.state(), "pageSetup");
let initial_bottom = h.state().dialog_host.get_by_id::<PageSetupHost>(id).unwrap().setup.margins.bottom;
assert!(initial_bottom < craft::pages::setup::MAX_PAGE_SIDE, "initial margin starts below the upper bound: {initial_bottom}");
h.get_by_role_and_label(Role::SpinButton, "Bottom").click();
h.run_steps(2);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Paste(format!("1{}", "0".repeat(36))));
h.run_steps(3);
let id = id_of(h.state(), "pageSetup");
let value = h.state().dialog_host.get_by_id::<PageSetupHost>(id).unwrap().setup.margins.bottom;
assert!(
value > initial_bottom && (value - craft::pages::setup::MAX_PAGE_SIDE).abs() < 1e-3,
"oversized margin paste should be accepted and clamped to MAX_PAGE_SIDE: got {value}"
);
// While the 37-digit text is in the field, the dialog does not blow up to the typed text width.
assert!(window(&h).width() <= before + 15.0);
h.key_press(egui::Key::Tab);
h.run_steps(3);
let id = id_of(h.state(), "pageSetup");
assert_eq!(h.state().dialog_host.get_by_id::<PageSetupHost>(id).unwrap().setup.margins.bottom, value);
let field = h.get_by_role_and_label(Role::SpinButton, "Bottom");
assert!(!field.is_focused());
let wide = field.rect();
let visible = wide.intersect(initial).intersect(window(&h));
assert!(visible.is_positive());
// The inline notice "Margins do not fit" may add a few points, but the dialog does not blow up to the typed text width.
assert!(window(&h).width() <= before + 15.0);
// The AccessKit bounds include clipped text: click the visible part, not their centre.
let pos = visible.center();
h.event(egui::Event::PointerMoved(pos));
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
}
h.run_steps(3);
assert!(h.get_by_role_and_label(Role::SpinButton, "Bottom").is_focused(), "the visible field enters editing");
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Paste("2".into()));
h.run_steps(3);
h.key_press(egui::Key::Tab);
h.run_steps(3);
let id = id_of(h.state(), "pageSetup");
let bottom = h.state().dialog_host.get_by_id::<PageSetupHost>(id).unwrap().setup.margins.bottom;
let unit = crate::options::unit_kind(h.state().session.units());
let expected =
unit.to_pixels(2.0, 0.0, craft::ui::runtime::env::UnitKind::POINTS_PER_INCH, craft::ui::runtime::env::UnitKind::POINTS_PER_INCH).unwrap();
assert!((bottom - expected).abs() < 1e-3, "the field accepts a normal value again: got {bottom}, expected {expected}");
assert!(window(&h).width() <= before + 2.0);
}
/// #1433: Page Setup's Paper size shows the named size the section has, in either
/// orientation, and Custom size (None) for anything else.
#[test]
@@ -1500,6 +1577,56 @@ fn modal_dialogs_block_the_window_behind_them() {
assert!(h.state().ui.backstage, "File opens beside Find");
}
/// Dismissing a dialog opened from a non-canvas command or control returns keyboard focus to the page (#7458).
#[test]
fn dismissing_a_dialog_from_non_canvas_control_returns_keyboard_focus_to_page() {
let mut h = app_harness(WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default()));
h.run_steps(6);
// 1. Move focus to a control outside the canvas (Navigation pane search box)
h.state_mut().run("view.navigationPane", json!({"value": true})).unwrap();
h.run_steps(3);
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search document").click();
h.run_steps(2);
assert!(h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search document").is_focused());
assert!(!h.state().canvas.focused(&h.ctx), "canvas does not have focus");
// Open a dialog via command while Navigation pane has focus
h.state_mut().run("ui.dialog", json!({"name": "font"})).unwrap();
h.run_steps(3);
assert!(is_open(h.state(), "font"), "font dialog is open");
// Dismiss with Escape
h.key_press(egui::Key::Escape);
h.run_steps(3);
assert!(!is_open(h.state(), "font"), "font dialog closed");
// Canvas must have regained keyboard focus
assert!(h.state().canvas.focused(&h.ctx), "the document canvas took keyboard focus back");
h.event(egui::Event::Text("!".into()));
h.run_steps(2);
assert_eq!(body_of(h.state()), "!", "typing reached the document canvas");
// 2. Focus Navigation pane search box again, open dialog, and dismiss via Cancel button
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search document").click();
h.run_steps(2);
assert!(h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search document").is_focused());
assert!(!h.state().canvas.focused(&h.ctx), "canvas does not have focus");
h.state_mut().run("ui.dialog", json!({"name": "font"})).unwrap();
h.run_steps(3);
assert!(is_open(h.state(), "font"), "font dialog is open");
press(&mut h, "Cancel");
h.run_steps(3);
assert!(!is_open(h.state(), "font"), "font dialog closed");
assert!(h.state().canvas.focused(&h.ctx), "the document canvas took keyboard focus back after Cancel");
h.event(egui::Event::Text("?".into()));
h.run_steps(2);
assert_eq!(body_of(h.state()), "!?", "typing reached the document canvas after Cancel");
}
/// Which dialogs leave the window working (#3859, Word for Mac 16.114.1): `shows_modal` and
/// `modal_open` agree with it for each.
#[test]
@@ -1536,6 +1663,71 @@ fn find_symbol_mark_entry_cross_reference_and_merge_fields_are_modeless() {
}
}
/// #3859: Escape in the fallback file chooser over a modal dialog (`templates`) cancels only the
/// chooser; the dialog under it, drawn first on `dialog_host`, stays open and regains the top
/// of the stack.
#[test]
fn escape_in_the_browser_leaves_the_dialog_under_it_open() {
use std::sync::Arc;
use craft::browse::places::{FakeDirectories, FolderCache};
use craft::dialogs::ui::FileChooser;
use craft::host::{ManualJobs, PickRequest, Wake};
use craft::ui::dialog::DialogResult;
let mut h = app_harness(app_with(""));
h.run_steps(6);
// A new window's page takes the keyboard from the first click or command; establish focus so
// the later blocked-input check actually tests modal blocking.
let ctx = h.ctx.clone();
h.state_mut().canvas.focus_page(&ctx);
h.run_steps(2);
h.event(egui::Event::Text("a".into()));
h.run_steps(2);
assert_eq!(body_of(h.state()), "a", "the page takes typing while no modal is open");
open_named(&mut h, "templates", json!({}));
assert_eq!(open_keys(h.state()), ["templates"]);
let jobs = Arc::new(ManualJobs::new());
let folders = FolderCache::new(Arc::new(FakeDirectories::new().folder("/d/drafts").file("/d/House.dotx")), jobs.clone(), Wake::none());
let req = PickRequest::open("template").directory("/d").fallback(true);
h.state_mut().dialog_host.open(FileChooser::new(req, None, folders));
for _ in 0..4 {
jobs.run_all();
h.step();
}
assert!(h.state().dialog_host.is_open::<FileChooser>(), "browser is open");
let open = h.state().dialog_host.open_dialogs();
assert_eq!(open.len(), 2, "browser is stacked over templates");
let ids: Vec<_> = open.iter().map(|d| d.id).collect();
assert_eq!(
ids,
[craft::ui::dialog::dialog_id("templates"), craft::ui::dialog::dialog_id("fileChooser")],
"browser is stacked on top of templates"
);
let listed = open.into_iter().find_map(|d| d.fields.and_then(|f| f.get("listed").cloned()));
assert_eq!(listed, Some(json!(true)), "the chooser finished listing its folder");
h.key_press(egui::Key::Escape);
h.run_steps(3);
assert!(!h.state().dialog_host.is_open::<FileChooser>(), "Escape closes the browser");
assert_eq!(h.state_mut().dialog_host.take::<FileChooser>(), Some(DialogResult::Cancel), "Escape cancels the browser");
assert_eq!(open_keys(h.state()), ["templates"], "and leaves the dialog under it open");
h.event(egui::Event::Text("x".into()));
h.run_steps(2);
assert_eq!(body_of(h.state()), "a", "the document behind templates stays blocked");
assert!(is_open(h.state(), "templates"), "templates stays open");
h.key_press(egui::Key::Escape);
h.run_steps(3);
assert!(!is_open(h.state(), "templates"), "a second Escape closes templates once it is back on top");
assert!(h.state().dialog_host.is_empty(), "all dialogs are closed");
}
/// Every dialog name the name table knows opens its dialog under the key the host reports, or
/// nothing where its condition isn't met; scripts and every command use this table (dg.A2).
#[test]
@@ -1674,6 +1866,54 @@ fn word_count_shows_label_and_count_on_a_line_over_close_and_cancel() {
assert!(!is_open(h.state(), "wordCount"), "Cancel closes Word Count");
}
/// #1885: the close control is at the title bar's right end; a click in the close box
/// closes the dialog; one just under the title bar leaves it open; a drag that starts on the box
/// doesn't move the dialog.
#[test]
fn the_title_bar_close_box_is_the_whole_corner() {
use egui::accesskit::Role;
fn press(h: &mut egui_kittest::Harness<'_, WordApp>, from: egui::Pos2, to: egui::Pos2) {
let button =
|pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
h.event(egui::Event::PointerMoved(from));
h.step();
h.event(button(from, true));
h.step();
if to != from {
h.event(egui::Event::PointerMoved(to));
h.step();
}
h.event(button(to, false));
for _ in 0..4 {
h.step();
}
}
let mut app = app_with("Some text");
super::open(&mut app, "wordCount", &json!({})).expect("word count opens");
let mut h = app_harness(app);
h.run_steps(4);
assert!(is_open(h.state(), "wordCount"), "dialog is open");
let before = h.get_by_role_and_label(Role::Dialog, "Word Count").rect();
let closes: Vec<_> = h.query_all_by_role_and_label(Role::Button, "Close").filter(|n| !n.accesskit_node().is_hidden()).collect();
let close_box = closes.into_iter().min_by(|a, b| a.rect().min.y.total_cmp(&b.rect().min.y)).expect("title bar close");
let bx = close_box.rect();
assert!((bx.top() - before.top()).abs() <= 10.0, "box {bx:?} is in the title bar area of {before:?}");
assert!(
bx.right() <= before.right() && before.right() - bx.right() <= 10.0 && bx.left() > before.center().x,
"close button sits at the right: {bx:?} in {before:?}"
);
let under = egui::pos2(bx.center().x, bx.bottom() + 4.0);
press(&mut h, under, under);
assert!(is_open(h.state(), "wordCount"), "a click under the title bar keeps the dialog");
let at = bx.center();
press(&mut h, at, at + egui::vec2(-150.0, 90.0));
assert!(is_open(h.state(), "wordCount"), "a drag from the box isn't a click");
let after = h.get_by_role_and_label(Role::Dialog, "Word Count").rect();
assert!((after.min - before.min).length() <= 1.0, "the box isn't a drag handle: {before:?} -> {after:?}");
press(&mut h, at, at);
assert!(!is_open(h.state(), "wordCount"), "a click in the box closes the dialog");
}
// ---------------------------------------------------------------- Font layout
/// The Font dialog stands as the old one did: the Effects check boxes two to a line (Bold beside Italic, Underline
@@ -1815,3 +2055,205 @@ fn insert_chart_tiles_render_within_compact_bounds() {
let grid = h.get_by_role_and_label(Role::ListBox, "Chart types").rect();
assert!(grid.width() <= 380.0, "3-column chart types grid should not exceed comfortable dialog proportions (~360 pt), got {:?}", grid.size());
}
/// The shake starts and ends where the dialog is and swings at most 6 points either way (#3859, #4076, #7321).
#[test]
fn the_shake_comes_back_to_rest() {
assert_eq!(chrome::shake_offset(0.0), 0.0);
assert!(chrome::shake_offset(1.0).abs() < 1e-4);
assert!((0..=100).map(|i| chrome::shake_offset(i as f32 / 100.0).abs()).all(|x| x <= 6.0));
assert!((0..=100).any(|i| chrome::shake_offset(i as f32 / 100.0).abs() > 3.0), "it does move");
}
/// #7321: clicking beside the Save Changes modal dialog nudges it (or flashes its edge under reduced motion),
/// repeat clicks mid-nudge leave the animation running without restarting, and closing clears the nudge state.
#[test]
fn unsaved_changes_dialog_shakes_on_outside_click_and_clears_on_close() {
for animations in ["on", "off"] {
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.run("text.insert", json!({"text": "Unsaved"})).unwrap();
app.run("ui.animations", json!({"value": animations})).unwrap();
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(|_| app);
h.run_steps(6);
// Attempt window close while dirty. Prompt opens peacefully without shaking.
h.input_mut().viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close);
h.step();
h.step();
let prompt_id = h.state().closing.as_ref().and_then(|c| c.prompt).expect("Save Changes prompt is open");
let key = chrome::nudge_id(&h.ctx, prompt_id);
let started = |h: &egui_kittest::Harness<'_, WordApp>| h.ctx.data(|d| d.get_temp::<f64>(key));
assert_eq!(started(&h), None, "{animations:?}: prompt opens peacefully without shaking");
let look = |h: &egui_kittest::Harness<'_, WordApp>| {
let shapes = &h.output().shapes;
let mut flat = Vec::new();
fn walk<'a>(s: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
match s {
egui::Shape::Vec(children) => {
for c in children {
walk(c, out);
}
}
other => out.push(other),
}
}
for c in shapes {
walk(&c.shape, &mut flat);
}
let save_x = flat.iter().find_map(|s| match s {
egui::Shape::Text(t) if t.galley.text() == "Save" || t.galley.text() == "Don't Save" || t.galley.text() == "Cancel" => Some(t.pos.x),
_ => None,
});
let border_flashes =
flat.iter().filter(|s| matches!(s, egui::Shape::Rect(r) if r.stroke.width > 0.0 && r.fill == egui::Color32::TRANSPARENT)).count();
(save_x, border_flashes)
};
let rest_pos = look(&h).0;
let baseline_flashes = look(&h).1;
// Clicking beside the dialog triggers the nudge
let rect = craft::ui::runtime::overlay::top(&h.ctx)
.and_then(|id| craft::ui::runtime::overlay::entry(&h.ctx, id))
.map(|e| e.rect)
.or_else(|| h.ctx.memory(|m| m.top_modal_layer().and_then(|l| m.area_rect(l.id))))
.expect("dialog rect exists");
let beside = egui::pos2(rect.min.x - 20.0, rect.min.y - 20.0);
assert!(!rect.contains(beside));
h.event(egui::Event::PointerMoved(beside));
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
h.step();
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
h.step();
let first = started(&h).expect("clicking outside nudges the dialog");
let mut looks = vec![look(&h)];
// Repeat outside click while it runs does not restart it
h.event(egui::Event::PointerMoved(beside));
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
h.step();
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
h.step();
assert_eq!(started(&h), Some(first), "{animations:?}: repeat click does not reset start time mid-nudge");
for _ in 0..6 {
h.step();
looks.push(look(&h));
}
if animations == "on" {
assert!(looks.iter().any(|l| l.0 != rest_pos), "it shakes horizontally under full animations");
} else {
assert!(looks.iter().any(|l| l.1 > baseline_flashes), "it flashes accent border under reduced motion");
assert!(looks.iter().all(|l| l.0 == rest_pos), "it does not translate horizontally under reduced motion");
}
// Run until shake completes
h.run_steps(30);
let final_look = look(&h);
assert_eq!(final_look.0, rest_pos, "it comes back to rest");
assert_eq!(final_look.1, baseline_flashes, "border flash ends at rest");
// Cancel closes the dialog and forgets nudge
h.state_mut().run("ui.saveChanges", json!({"answer": "cancel"})).unwrap();
h.step();
assert_eq!(started(&h), None, "{animations:?}: closing the dialog clears nudge state");
}
}
/// #7321: ordinary click inside a dialog with a popup open does not shake it;
/// clicking outside the dialog shakes it; closing clears nudge so reopening within 0.4s opens still.
#[test]
fn modal_dialog_with_open_popup_does_not_shake_on_inside_click_but_shakes_on_outside_click() {
let app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(|_| app);
h.run_steps(6);
let id = super::open(h.state_mut(), "font", &json!({})).expect("font dialog opens");
h.run_steps(4);
// Open a dropdown popup inside the Font dialog
let buttons: Vec<_> =
h.query_all_by_role_and_label(egui::accesskit::Role::Button, "Font color: Automatic").filter(|n| !n.accesskit_node().is_hidden()).collect();
assert!(!buttons.is_empty(), "Font color button exists");
buttons.last().unwrap().click();
h.run_steps(3);
// Verify a popup is open on top of the overlay stack
let top = craft::ui::runtime::overlay::top(&h.ctx).expect("top overlay entry exists");
let top_entry = craft::ui::runtime::overlay::entry(&h.ctx, top).expect("top entry exists");
assert_eq!(top_entry.rank, craft::ui::runtime::overlay::Rank::Popup, "top entry is popup");
// Resolve the target modal dialog's own overlay entry by traversing parents
let mut cur = top_entry.clone();
while let Some(parent) = cur.parent.and_then(|p| craft::ui::runtime::overlay::entry(&h.ctx, p)) {
if cur.rank.is_modal() {
break;
}
cur = parent;
}
assert!(cur.rank.is_modal(), "found modal dialog overlay entry");
let modal_rect = cur.rect;
let popup_rect = top_entry.rect;
// A click inside the modal dialog (on body padding, outside the popup) must NOT nudge
let inside_point = egui::pos2(modal_rect.min.x + 40.0, modal_rect.min.y + 40.0);
assert!(modal_rect.contains(inside_point), "point is inside dialog");
assert!(!popup_rect.contains(inside_point), "point is outside popup");
h.event(egui::Event::PointerMoved(inside_point));
h.event(egui::Event::PointerButton { pos: inside_point, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
h.step();
h.event(egui::Event::PointerButton { pos: inside_point, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
h.step();
let key = chrome::nudge_id(&h.ctx, id);
assert!(h.ctx.data(|d| d.get_temp::<f64>(key)).is_none(), "click inside dialog with popup open does not nudge");
assert!(h.state().dialog_host.get_dyn(id).is_some(), "dialog remains open after inside click");
// A click inside the popup itself (or an extension of the popup) must also NOT nudge
let popup_point = popup_rect.center();
h.event(egui::Event::PointerMoved(popup_point));
h.event(egui::Event::PointerButton { pos: popup_point, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
h.step();
h.event(egui::Event::PointerButton { pos: popup_point, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
h.step();
assert!(h.ctx.data(|d| d.get_temp::<f64>(key)).is_none(), "click inside popup does not nudge");
// Dismiss the open dropdown popup
h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE });
h.step();
h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE });
h.step();
// A click outside the modal dialog (even completed within a single frame) MUST nudge it
let beside_point = egui::pos2(modal_rect.min.x - 20.0, modal_rect.min.y - 20.0);
assert!(!modal_rect.contains(beside_point), "point is outside dialog");
h.event(egui::Event::PointerMoved(beside_point));
h.event(egui::Event::PointerButton { pos: beside_point, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
h.event(egui::Event::PointerButton { pos: beside_point, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
h.step();
assert!(h.ctx.data(|d| d.get_temp::<f64>(key)).is_some(), "click outside dialog nudges it");
let serial1 = h.state().dialog_host.open_serial(id).expect("dialog has open serial");
// Closing the dialog clears the nudge
let ctx = h.ctx.clone();
h.state_mut().dialog_host.cancel_by_id(&ctx, id);
h.run_steps(3);
assert!(h.ctx.data(|d| d.get_temp::<f64>(key)).is_none(), "closing dialog clears nudge");
// Reopening the dialog gets a new open serial and starts still
let id2 = super::open(h.state_mut(), "font", &json!({})).expect("font dialog reopens");
let serial2 = h.state().dialog_host.open_serial(id2).expect("reopened dialog has open serial");
assert_ne!(serial1, serial2, "successive opens have distinct open serials");
h.run_steps(2);
let key2 = chrome::nudge_id(&h.ctx, id2);
assert!(h.ctx.data(|d| d.get_temp::<f64>(key2)).is_none(), "reopened dialog starts still");
}
+4
View File
@@ -0,0 +1,4 @@
//! In-app file browser trials and interaction regressions (#576, #3037, #3859).
#[cfg(test)]
pub(crate) mod tests;
+47
View File
@@ -0,0 +1,47 @@
use std::sync::Arc;
use craft::browse::places::{FakeDirectories, FolderCache};
use craft::dialogs::ui::FileChooser;
use craft::host::{ManualJobs, PickRequest, Wake};
use egui::vec2;
use serde_json::json;
use wordcraft_engine::Session;
use crate::{Services, WordApp};
/// #3859: a modal dialog that closes as it opens the browser (Save in "Save changes?" as a new
/// document closes, with no system dialog) leaves the keyboard in the browser's name box: the
/// document doesn't take it back on the next frame.
#[test]
fn a_dialog_closing_into_the_browser_leaves_it_the_keyboard() {
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Unsaved"})).unwrap();
let _ = a.run("file.close", json!({}));
assert!(a.dialog_host.shows_modal(), "Save Changes prompt opens");
let mut h = crate::test_harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
crate::test_harness::logic(&ctx, app);
app.ui(ui);
},
a,
);
crate::test_harness::frames(&mut h, 4);
let _ = h.state_mut().run("ui.saveChanges", json!({"answer": "save"}));
let folders = FolderCache::new(Arc::new(FakeDirectories::new().folder("/d/drafts")), Arc::new(ManualJobs::new()), Wake::none());
let req = PickRequest::save("document").file_name("Unsaved.docx").fallback(true);
h.state_mut().dialog_host.open(FileChooser::new(req, None, folders));
crate::test_harness::frames(&mut h, 4);
assert!(h.state().dialog_host.is_open::<FileChooser>(), "Save As goes on in the browser");
assert!(!h.state().canvas.focused(&h.ctx), "document does not take the keyboard back");
let before_doc = h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body);
h.event(egui::Event::Text("x".into()));
crate::test_harness::frames(&mut h, 2);
let after_doc = h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body);
assert_eq!(after_doc, before_doc, "typing does not leak into the document behind the browser");
}
+70
View File
@@ -923,3 +923,73 @@ fn many_failed_fonts_end_with_a_count() {
a.add_fonts(fonts).unwrap();
assert_eq!(status_text(&a), "Added 0 fonts; 5 couldn't be read: f0.ttf, f1.ttf, f2.ttf and 2 more");
}
/// Drawn entries have names and selection state, and choosing one still picks its path (#576, #6790).
#[test]
fn entries_expose_names_selection_and_picking() {
use craft::browse::places::{FakeDirectories, FolderCache};
use craft::dialogs::Answer;
use craft::dialogs::ui::FileChooser;
use craft::host::{ManualJobs, Wake};
use craft::ui::dialog::DialogResult;
use egui::accesskit::Role;
use egui::vec2;
use egui_kittest::kittest::{NodeT, Queryable};
let fake = Arc::new(FakeDirectories::new().folder("/d/Drafts").file("/d/chapter.docx"));
let jobs = Arc::new(ManualJobs::new());
let folders = FolderCache::new(fake, jobs.clone(), Wake::none());
let a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
let mut h = crate::test_harness::builder().with_size(vec2(760.0, 520.0)).build_eframe(|_| a);
let req = PickRequest::open("document").directory("/d").fallback(true);
h.state_mut().dialog_host.open(FileChooser::new(req, None, folders));
let step = |h: &mut egui_kittest::Harness<'_, WordApp>, count: usize| {
for _ in 0..count {
jobs.run_all();
h.step();
}
};
let chooser_fields = |h: &egui_kittest::Harness<'_, WordApp>| {
h.state()
.dialog_host
.open_dialogs()
.into_iter()
.find_map(|d| d.fields.filter(|f| f.get("listed").is_some()))
.expect("FileChooser fields are exposed")
};
step(&mut h, 6);
assert_eq!(chooser_fields(&h)["listed"], json!(true), "folder finished listing");
// Both entries are exposed with ListItem role and start unselected.
for name in ["Drafts", "chapter.docx"] {
assert_eq!(h.get_by_role_and_label(Role::ListItem, name).accesskit_node().is_selected(), Some(false), "{name} starts unselected");
}
// Selecting the folder marks Drafts selected, leaves chapter.docx unselected, and leaves the name box empty.
h.get_by_role_and_label(Role::ListItem, "Drafts").click();
step(&mut h, 3);
assert_eq!(h.get_by_role_and_label(Role::ListItem, "Drafts").accesskit_node().is_selected(), Some(true));
assert_eq!(h.get_by_role_and_label(Role::ListItem, "chapter.docx").accesskit_node().is_selected(), Some(false));
assert_eq!(chooser_fields(&h)["selection"], json!(["Drafts"]));
assert_eq!(chooser_fields(&h)["name"], json!(""));
// Selecting chapter.docx moves selection from Drafts to chapter.docx and fills the File name box.
h.get_by_role_and_label(Role::ListItem, "chapter.docx").click();
step(&mut h, 3);
assert_eq!(h.get_by_role_and_label(Role::ListItem, "Drafts").accesskit_node().is_selected(), Some(false));
assert_eq!(h.get_by_role_and_label(Role::ListItem, "chapter.docx").accesskit_node().is_selected(), Some(true));
assert_eq!(chooser_fields(&h)["selection"], json!(["chapter.docx"]));
assert_eq!(chooser_fields(&h)["name"], json!("chapter.docx"));
assert_eq!(h.get_by_role_and_label(Role::TextInput, "File name").accesskit_node().value().as_deref(), Some("chapter.docx"));
// Open button confirms the pick.
h.get_by_role_and_label(Role::Button, "Open").click();
step(&mut h, 3);
let answer = h.state_mut().dialog_host.take::<FileChooser>();
assert_eq!(answer, Some(DialogResult::Ok(Answer::Paths(vec![PathBuf::from("/d/chapter.docx")]))));
}
+31
View File
@@ -207,6 +207,37 @@ fn fonts_of_one_download_are_listed_together() {
assert_eq!((g[1].fonts.as_slice(), g[1].url), (["Cascadia Code"].as_slice(), "https://c"));
}
/// As many downloads as the box lists, in a short window and a very short one: what is above
/// the row with Close scrolls, so the opt-out and Close stay on screen and the box in the window.
#[test]
fn many_downloads_in_a_short_window_leave_the_opt_out_and_close_on_screen() {
for height in [600.0, 400.0] {
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Lanterns")), crate::Services::default());
let fonts: Vec<Row> = (0..LISTED)
.map(|i| Row {
font: format!("Harbour Face {i}"),
shown_as: vec!["Carlito".into()],
download: format!("Harbour Face {i}"),
publisher: "Lantern Works".into(),
url: format!("https://example.org/{i}"),
restricted: false,
})
.collect();
open_with(&mut a, None, FontBox::new(fonts, false), DialogHooks { prepare: None, settle });
let h = harness_sized(a, egui::vec2(1000.0, height));
// The steps are still there, to scroll to.
assert!(h.query_by_label("Add Font…").is_some());
for label in ["Don't show this again", "Close"] {
// Close is also the window's close box: every match is on screen.
let rects: Vec<egui::Rect> = h.query_all_by_label(label).map(|n| n.rect()).collect();
assert!(!rects.is_empty(), "no {label}");
for r in rects {
assert!(r.min.y >= 0.0 && r.max.y <= height, "{label} is at {r:?}, outside the {height} pt window");
}
}
}
}
/// A font whose publisher limits its use says so on its card, and has a card of its own.
#[test]
fn a_font_with_a_limited_licence_says_so() {
+23
View File
@@ -512,4 +512,27 @@ mod tests {
assert!((x - ex).abs() < 0.05 && (y - ey).abs() < 0.05, "({x}, {y}) vs ({ex}, {ey})");
}
}
/// #7317: the `fitOnePage` app icon is a document the registry resolves and the rasteriser draws.
/// A document the engine fails to parse or draw gives no texture, and so no shape: the tile would
/// be blank. The pre-#7101 test painted the hand-written vector path; this checks the same icon
/// through the SVG set that replaced it.
#[test]
fn fit_one_page_icon_paints_without_panic() {
const KEY: &str = "fitOnePage";
use craft::theme::{Contrast, Mode};
use craft::ui::primitives::{Draw, DrawEnv, PaintRecord};
use craft::ui::testing::{Frames, style};
register();
let tokens = style::tokens(Mode::Light, Contrast::Standard);
let record = std::cell::RefCell::new(PaintRecord::default());
let mut frames = Frames::new();
let shapes = frames.frame_shapes(|ui| {
let env = DrawEnv { tokens: &tokens, direction: craft::i18n::Direction::Ltr, ink: craft::ui::style::Ink::OnPanel };
let icon = IconSpec::svg(IconId::new(KEY));
Draw::new(ui.painter(), &record, env).icon(Rect::from_min_size(Pos2::ZERO, egui::vec2(20.0, 20.0)), &icon);
});
assert!(!shapes.is_empty(), "{KEY} icon must paint");
}
}
+25
View File
@@ -284,6 +284,31 @@ fn copied_bold_app() -> WordApp {
a
}
/// #5616: after Mod+Shift+V (Paste Formatting) and a paired browser paste event, a later
/// menu-bar paste (`Event::Paste`) with no key or pointer press in between still keeps source
/// formatting instead of reading the earlier Mod+Shift as Keep Text Only.
#[test]
fn the_ignored_paste_uses_up_its_paste_modifiers() {
let mut h = app_harness(copied_bold_app());
let chord = Modifiers { shift: true, ..mod_held() };
batch_frame(&mut h, vec![egui::Event::ModifiersChanged(chord), key_event(Key::V, true, chord), egui::Event::Paste("x".into())]);
crate::test_harness::frame(&mut h);
assert_eq!(body(h.state()), "source target");
assert!(is_bold(&mut h));
run(&mut h, "select.text", json!({"text": "target"}));
offer(&h, vec![ClipItem::Html("<p><i>menu</i></p>".into()), ClipItem::Text("menu".into())]);
batch_frame(&mut h, vec![egui::Event::Paste("menu".into())]);
crate::test_harness::frame(&mut h);
assert_eq!(body(h.state()), "source menu");
let state = run(&mut h, "format.state", json!({}));
assert_ne!(
state.get("bold").and_then(serde_json::Value::as_bool),
Some(true),
"a later menu-bar paste does not inherit target's bold via Keep Text Only: {state}"
);
assert_eq!(state.get("italic").and_then(serde_json::Value::as_bool), Some(true), "a later menu-bar paste keeps clipboard formatting: {state}");
}
/// Paste Formatting on a chord the user bound pastes the copied formatting once.
#[test]
fn paste_formatting_on_another_key_pastes_the_copied_formatting() {
+167 -71
View File
@@ -3,8 +3,10 @@
//! machine, badges, claimed keys) is the framework's `Keytips`; this module gives it WordCraft's
//! tabs, controls, legacy sequences and regions.
use std::sync::Arc;
use std::collections::HashMap;
use std::sync::{Arc, OnceLock};
use craft::behavior::overlay::MinWidth;
use craft::keymap::CommandRef;
use craft::menu::{KeytipControl, Keytips, RibbonOutput};
use craft::ui::contract::Bind;
@@ -33,10 +35,58 @@ pub(crate) fn backstage_region() -> egui::Id {
egui::Id::unique("wc_keytips_backstage_region")
}
/// The key of the inspected region the screen bar (Focus, Full Screen View) records; the legacy hint hangs from
/// its first element when no ribbon shows.
pub(crate) fn screen_bar_region() -> egui::Id {
egui::Id::unique("wc_keytips_screen_bar_region")
/// Per-context map of ribbon `menu_button` widget ids to the command id each opens a menu for,
/// so [`Keytips`] places badges on menu buttons without binding them to fire on pointer click.
fn menu_buttons_id() -> egui::Id {
egui::Id::unique("wc_keytips_menu_buttons")
}
/// Records (or clears) the command id associated with a ribbon `menu_button` widget id so
/// [`show`] can attach `CommandRef` to its inspected element for language-independent badge placement.
pub(crate) fn note_menu_button(ctx: &egui::Context, widget_id: egui::Id, command_id: Option<&str>) {
let existing = ctx.data(|d| d.get_temp::<Arc<HashMap<egui::Id, CommandRef>>>(menu_buttons_id()));
let unchanged = match (&existing, command_id) {
(Some(map), Some(id)) => map.get(&widget_id).is_some_and(|cmd| cmd.id == id && cmd.params.is_null()),
(Some(map), None) => !map.contains_key(&widget_id),
(None, None) => true,
(None, Some(_)) => false,
};
if unchanged {
return;
}
ctx.data_mut(|d| {
let mut map = d.get_temp::<Arc<HashMap<egui::Id, CommandRef>>>(menu_buttons_id()).map(|a| (*a).clone()).unwrap_or_default();
match command_id {
Some(id) => {
map.insert(widget_id, CommandRef::new(id));
}
None => {
map.remove(&widget_id);
}
}
d.insert_temp(menu_buttons_id(), Arc::new(map));
});
}
/// Attaches noted `menu_button` commands to uncommanded root elements of a ribbon `Recorded`
/// snapshot so `craft::menu::Keytips` places badges on menu buttons regardless of translation.
fn with_menu_commands(ctx: &egui::Context, recorded: Arc<Recorded>) -> Arc<Recorded> {
let Some(commands) = ctx.data(|d| d.get_temp::<Arc<HashMap<egui::Id, CommandRef>>>(menu_buttons_id())) else {
return recorded;
};
if commands.is_empty() || !recorded.elements.iter().any(|e| e.part.is_none() && e.command.is_none() && commands.contains_key(&e.id)) {
return recorded;
}
let mut patched = (*recorded).clone();
for element in &mut patched.elements {
if element.part.is_none()
&& element.command.is_none()
&& let Some(cmd) = commands.get(&element.id)
{
element.command = Some(cmd.clone());
}
}
Arc::new(patched)
}
/// Word's tab letters, as Word for Windows shows them after Alt (File F, Design G, References S,
@@ -64,29 +114,32 @@ pub const SEARCH_LETTER: &str = "Q";
/// Legacy menu keys (#1697): Word 2003 menu sequences Word for Windows still takes after Alt,
/// observed there. Hidden, as in Word: no badges, not in Customize Keyboard. They start only on
/// letters no tab keytip or Search uses (see the test).
fn legacy() -> Vec<(&'static str, CommandRef)> {
let cmd = CommandRef::new;
let dialog = |name: &str| CommandRef::with_params("ui.dialog", serde_json::json!({ "name": name }));
vec![
("VU", cmd("view.fullScreenView")),
("VP", cmd("view.printLayout")),
("VW", cmd("view.webLayout")),
("VO", cmd("view.outline")),
("VN", cmd("view.draft")),
("VD", cmd("view.navigationPane")),
("VL", cmd("view.ruler")),
("VZ", dialog("zoom")),
("EL", cmd("select.all")),
("EF", dialog("find")),
("EE", dialog("replace")),
("EG", dialog("goto")),
("IS", dialog("symbol")),
("IPF", cmd("insert.picture")),
("OF", dialog("font")),
("OP", dialog("paragraph")),
("TW", cmd("review.wordCount")),
("AIT", dialog("insertTable")),
]
fn legacy() -> &'static [(&'static str, CommandRef)] {
static LEGACY: OnceLock<Vec<(&'static str, CommandRef)>> = OnceLock::new();
LEGACY.get_or_init(|| {
let cmd = CommandRef::new;
let dialog = |name: &str| CommandRef::with_params("ui.dialog", serde_json::json!({ "name": name }));
vec![
("VU", cmd("view.fullScreenView")),
("VP", cmd("view.printLayout")),
("VW", cmd("view.webLayout")),
("VO", cmd("view.outline")),
("VN", cmd("view.draft")),
("VD", cmd("view.navigationPane")),
("VL", cmd("view.ruler")),
("VZ", dialog("zoom")),
("EL", cmd("select.all")),
("EF", dialog("find")),
("EE", dialog("replace")),
("EG", dialog("goto")),
("IS", dialog("symbol")),
("IPF", cmd("insert.picture")),
("OF", dialog("font")),
("OP", dialog("paragraph")),
("TW", cmd("review.wordCount")),
("AIT", dialog("insertTable")),
]
})
}
/// The letter badge for a tab (empty when it has none).
@@ -384,41 +437,75 @@ fn controls(tab: &str) -> Vec<Control> {
}
}
/// A control with the letters it asks for.
struct Row {
control: Control,
letters: Option<String>,
/// Maps an ASCII alphanumeric keytip letter to a static single-character `&'static str`, avoiding
/// per-control `String` allocations when caching [`KeytipControl`].
fn ascii_upper_str(c: char) -> Option<&'static str> {
const CHARS: &str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let idx = CHARS.find(c.to_ascii_uppercase())?;
CHARS.get(idx..idx + 1)
}
/// A tab's controls with the shortcut letter each keeps, when its command has an Alt+letter shortcut.
fn rows(app: &WordApp, tab: &str) -> Vec<Row> {
controls(tab)
.into_iter()
.map(|control| {
let letters = shortcut_letter(app, &control.command.id).map(String::from);
Row { control, letters }
})
.collect()
/// Cached keytip controls and reserved shortcut letters per engine registry and active ribbon tab,
/// avoiding per-frame `registry.all()` scans and `KeytipControl` / `CommandRef` allocations while
/// idle.
pub(crate) struct KeytipCache {
registry: Arc<wordcraft_engine::Registry>,
reserved: Vec<char>,
tab: String,
tab_controls: Vec<KeytipControl<'static>>,
}
/// The Search box: its badge is Alt, Q on every tab.
fn search_row() -> Row {
Row { control: Control { tip: "Search", command: CommandRef::new("tools.search") }, letters: Some(SEARCH_LETTER.to_string()) }
impl KeytipCache {
fn build_tab_controls(app: &WordApp, tab: &str) -> Vec<KeytipControl<'static>> {
let mut out: Vec<KeytipControl<'static>> = controls(tab)
.into_iter()
.map(|control| {
let letters = shortcut_letter(app, &control.command.id).and_then(ascii_upper_str);
KeytipControl::new(control.command, control.tip, letters)
})
.collect();
out.push(KeytipControl::new(CommandRef::new("tools.search"), "Search", Some(SEARCH_LETTER)));
out
}
fn new(app: &WordApp, tab: &str) -> Self {
KeytipCache {
registry: app.session.registry.clone(),
reserved: reserved_letters(app),
tab: tab.to_owned(),
tab_controls: Self::build_tab_controls(app, tab),
}
}
fn sync(&mut self, app: &WordApp, tab: &str) {
let reg_changed = !Arc::ptr_eq(&self.registry, &app.session.registry);
if reg_changed {
self.registry = app.session.registry.clone();
self.reserved = reserved_letters(app);
}
if reg_changed || self.tab != tab {
self.tab.clear();
self.tab.push_str(tab);
self.tab_controls = Self::build_tab_controls(app, tab);
}
}
}
/// The Backstage's pages, one badge each: the first letter its page has in `KEYTIPS`.
fn backstage_rows() -> Vec<Row> {
crate::backstage::KEYTIPS
.iter()
.map(|(page, letter)| Row {
control: Control { tip: page, command: CommandRef::with_params("ui.backstage", serde_json::json!({ "page": page })) },
letters: Some(letter.to_string()),
})
.collect()
/// The Backstage's pages as cached static keytip controls.
fn backstage_controls() -> &'static [KeytipControl<'static>] {
static CONTROLS: OnceLock<Vec<KeytipControl<'static>>> = OnceLock::new();
CONTROLS.get_or_init(|| {
crate::backstage::KEYTIPS
.iter()
.map(|(page, letter)| {
KeytipControl::new(CommandRef::with_params("ui.backstage", serde_json::json!({ "page": page })), page, Some(letter))
})
.collect()
})
}
/// Shows the keytips after the ribbon and the regions they place badges on, and acts on what the keys chose.
pub(crate) fn show(ui: &mut Ui, app: &mut WordApp, ribbon: &RibbonOutput<String>) {
/// Shows the keytips after the shell and the regions they place badges on, and acts on what the keys chose.
pub(crate) fn show(ui: &mut Ui, app: &mut WordApp, ribbon: &RibbonOutput<String>, screen_bar: Option<Rect>) {
let ctx = ui.ctx().clone();
// Alt during an object drag is part of the drag (Alt moves an object freely), not a keytip tap.
// PLAN: `CanvasState::object_gesture` is canvas-w9's (cv.A10).
@@ -431,14 +518,15 @@ pub(crate) fn show(ui: &mut Ui, app: &mut WordApp, ribbon: &RibbonOutput<String>
.filter_map(|t| ribbon.tab_ids.iter().find(|(name, _)| name == t).map(|(_, id)| (Label::from(t), tab_letter(t), *id)))
.collect();
let mut rows = if app.ui.backstage { backstage_rows() } else { rows(app, &app.ui.tab) };
if !app.ui.backstage {
rows.push(search_row());
}
let controls: Vec<KeytipControl<'_>> =
rows.iter().map(|r| KeytipControl::new(r.control.command.clone(), r.control.tip, r.letters.as_deref())).collect();
let sequences = if cfg!(target_os = "macos") { Vec::new() } else { legacy() };
let cache = match app.keytip_cache.take() {
Some(mut cache) => {
cache.sync(app, &app.ui.tab);
cache
}
None => KeytipCache::new(app, &app.ui.tab),
};
let controls: &[KeytipControl<'_>] = if app.ui.backstage { backstage_controls() } else { &cache.tab_controls };
let sequences: &[(&str, CommandRef)] = if cfg!(target_os = "macos") { &[] } else { legacy() };
// A hidden toolbar has no badges, and a disabled command's button has none to press.
let digits: Vec<CommandRef> = if app.ui.quick_access_toolbar {
app.session
@@ -452,18 +540,25 @@ pub(crate) fn show(ui: &mut Ui, app: &mut WordApp, ribbon: &RibbonOutput<String>
} else {
Vec::new()
};
let reserved = reserved_letters(app);
let mut places: Vec<Arc<Recorded>> = Vec::new();
places.extend(ribbon.controls.clone());
let patch_menu_places = enabled && (app.keytips_active || !ctx.input(|i| i.events.is_empty()));
places.extend(ribbon.controls.clone().map(|recorded| if patch_menu_places { with_menu_commands(&ctx, recorded) } else { recorded }));
places.extend(inspect::recorded(&ctx, qat_region()));
places.extend(inspect::recorded(&ctx, search_region()));
if app.ui.backstage {
places.extend(inspect::recorded(&ctx, backstage_region()));
}
let out =
Keytips::new(enabled).tabs(&tabs).controls(&controls).sequences(&sequences).digits(&digits).reserved(&reserved).places(&places).show_over(ui);
let out = Keytips::new(enabled)
.tabs(&tabs)
.controls(controls)
.sequences(sequences)
.digits(&digits)
.reserved(&cache.reserved)
.places(&places)
.show_over(ui);
app.keytip_cache = Some(cache);
// PLAN: `WordApp::keytips_active` is app-hub's (rb.A11).
app.keytips_active = out.active;
if let Some(tab) = out.tab.as_deref().and_then(tab_of_badge) {
@@ -471,7 +566,6 @@ pub(crate) fn show(ui: &mut Ui, app: &mut WordApp, ribbon: &RibbonOutput<String>
}
if let Some(pending) = &out.pending {
// With no ribbon showing (Focus, Full Screen View) the hint hangs under the screen bar.
let screen_bar = inspect::recorded(&ctx, screen_bar_region()).and_then(|r| r.rect_in(&ctx, 0, ui.layer_id()));
if let Some(anchor) = ribbon.tabs.or(screen_bar) {
legacy_hint(ui, pending, anchor);
}
@@ -483,9 +577,11 @@ fn legacy_hint(ui: &mut Ui, pending: &str, anchor: Rect) {
let keys: Vec<String> = pending.chars().map(String::from).collect();
let text = crate::i18n::fmt(tl!("Old menu keys: Alt, {keys}. Keep typing, or press Esc to cancel."), &[("keys", &keys.join(", "))]);
let mut open = true;
Popover::new(tl!("Old menu keys"), Bind::bound(&mut open)).overlay(|overlay| overlay.anchor(Anchor::Rect(anchor))).show(ui, |ui, _| {
Text::new(text.clone()).show(ui);
});
Popover::new(tl!("Old menu keys"), Bind::bound(&mut open))
.overlay(|overlay| overlay.anchor(Anchor::Rect(anchor)).min_width(MinWidth::None))
.show(ui, |ui, _| {
Text::new(text.clone()).show(ui);
});
}
#[cfg(test)]
+365 -7
View File
@@ -30,6 +30,25 @@ fn bold(h: &mut egui_kittest::Harness<'static, WordApp>) -> bool {
h.state_mut().session.run("format.state", &serde_json::json!({})).unwrap()["bold"] == true
}
fn painted_text_rects(shapes: &[egui::epaint::ClippedShape]) -> Vec<(String, egui::Rect)> {
fn walk(shape: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
match shape {
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
egui::Shape::Vec(children) => {
for child in children {
walk(child, out);
}
}
_ => {}
}
}
let mut out = Vec::new();
for clipped in shapes {
walk(&clipped.shape, &mut out);
}
out
}
#[test]
fn every_keytip_command_is_registered() {
// The keytip tables name commands by id; a renamed or removed command must fail here,
@@ -56,13 +75,14 @@ fn keytips_never_reuse_another_commands_shortcut_letter() {
let reserved = reserved_letters(&a);
let folder = craft::i18n::Folder::new("en");
for (tab, _) in TAB_LETTERS.iter().chain(&TABLE_TAB_LETTERS) {
let rows = rows(&a, tab);
let labels: Vec<(&str, Option<&str>)> = rows.iter().map(|r| (r.control.tip, r.letters.as_deref())).collect();
let tab_controls = KeytipCache::build_tab_controls(&a, tab);
let labels: Vec<(&str, Option<&str>)> = tab_controls.iter().map(|c| (c.label, c.letters)).collect();
let badges = craft::keymap::mnemonic::assign_keytips(&labels, &reserved, &folder);
assert_eq!(badges.len(), rows.len(), "{tab}: one badge per control");
for (row, badge) in rows.iter().zip(&badges) {
let id = &row.control.command.id;
if let Some(own) = &row.letters {
assert_eq!(badges.len(), tab_controls.len(), "{tab}: one badge per control");
for (control, badge) in tab_controls.iter().zip(&badges) {
let id = &control.command.id;
assert!(!badge.is_empty(), "{tab}: {id} must receive a non-empty keytip badge");
if let Some(own) = control.letters {
assert_eq!(badge, own, "{tab}: {id} should keep its shortcut letter {own}");
} else {
let first = badge.chars().next().unwrap_or('?');
@@ -72,6 +92,61 @@ fn keytips_never_reuse_another_commands_shortcut_letter() {
}
}
/// Home's Paste, a menu button, shows its keytip whatever the interface language. The keytips
/// table holds the English tips, and `menu_button` previously matched it with its translated one,
/// which no other language's "Paste" equals or begins with. Pseudo-localization stands in for one.
#[test]
fn a_menu_buttons_keytip_does_not_depend_on_the_language() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable as _;
let a = app();
let reserved = reserved_letters(&a);
let cache = KeytipCache::new(&a, "Home");
let paste_idx = cache.tab_controls.iter().position(|c| c.command.id == "edit.paste").expect("Home tab has Paste");
let labels: Vec<(&str, Option<&str>)> = cache.tab_controls.iter().map(|c| (c.label, c.letters)).collect();
let english_folder = craft::i18n::Folder::new("en");
let english_badges = craft::keymap::mnemonic::assign_keytips(&labels, &reserved, &english_folder);
let paste_badge = &english_badges[paste_idx];
assert!(!paste_badge.is_empty(), "Paste receives a keytip badge");
for lang in ["de", "fr", "es", "tr", "pseudo", "ja", "zh", "pt-BR"] {
let folder = craft::i18n::Folder::new(lang);
let badges = craft::keymap::mnemonic::assign_keytips(&labels, &reserved, &folder);
assert_eq!(&badges[paste_idx], paste_badge, "language={lang}: Paste badge must stay {paste_badge} regardless of language");
}
let mut h = harness(app());
h.ctx.add_glyph_rasterizer(egui::GlyphRasterizer::new("wordcraft::keytips::pseudo_markers", |request| {
matches!(request.cluster, "⟦" | "⟧").then(|| egui::RasterizedGlyph {
bitmap: egui::GlyphBitmap {
image: egui::ColorImage::new([1, 1], vec![egui::Color32::WHITE]),
offset_px: egui::Vec2::ZERO,
is_color: false,
},
advance_px: request.font_size_px.max(1.0),
})
}));
h.state_mut().ui.language = "pseudo".into();
crate::test_harness::frames(&mut h, 2);
let paste_rect = h.get_by_role_and_label(Role::Button, "⟦Paste⟧").rect();
h.input_mut().events.push(key_event(egui::Key::F10, true, egui::Modifiers::NONE));
crate::test_harness::frame(&mut h);
h.input_mut().events.extend([key_event(egui::Key::H, true, egui::Modifiers::NONE), egui::Event::Text("h".into())]);
crate::test_harness::frames(&mut h, 3);
let painted = painted_text_rects(&h.output().shapes);
crate::i18n::apply_language(crate::i18n::Lang::EN);
assert_eq!(h.state().ui.tab.as_str(), "Home");
assert!(h.state().keytips_active, "F10, H activates Home command keytips");
assert!(
painted.iter().any(|(text, rect)| text == paste_badge && paste_rect.expand(8.0).contains(rect.center())),
"Paste's {paste_badge:?} badge is drawn over Paste {paste_rect:?} under pseudo-localization: {painted:?}"
);
}
/// #1697: legacy sequences never start on a tab keytip (table tabs included) or Search, and
/// every one reaches a command or dialog that exists.
#[test]
@@ -83,7 +158,7 @@ fn legacy_menu_keys_stay_off_the_ribbon_letters_and_all_resolve() {
for (keys, command) in legacy() {
let first = &keys[..1];
assert!(!taken.iter().any(|l| l.starts_with(first)), "{keys} starts on a ribbon letter");
assert!(!legacy().iter().any(|(k, _)| *k != keys && k.starts_with(keys)), "{keys} hides a longer sequence");
assert!(!legacy().iter().any(|(k, _)| *k != *keys && k.starts_with(*keys)), "{keys} hides a longer sequence");
let mut b = app();
// The hosted parameter dialogs open nothing before the window's context is known.
b.ctx = Some(egui::Context::default());
@@ -96,6 +171,232 @@ fn legacy_menu_keys_stay_off_the_ribbon_letters_and_all_resolve() {
}
}
/// #1697 review: with no ribbon showing (Focus, Full Screen View) no tab rects are recorded,
/// so the legacy hint hangs under the slim screen bar at the top of the window instead of not
/// showing; with the ribbon showing (normal window or dropped ribbon in Focus) it hangs under
/// the tab row.
#[test]
fn the_legacy_hint_hangs_under_the_slim_bar_without_a_ribbon() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable as _;
if cfg!(target_os = "macos") {
return;
}
let trigger_legacy_v = |h: &mut egui_kittest::Harness<'static, WordApp>| {
h.input_mut().events.push(key_event(egui::Key::F10, true, egui::Modifiers::NONE));
crate::test_harness::frame(h);
h.input_mut().events.extend([key_event(egui::Key::V, true, egui::Modifiers::NONE), egui::Event::Text("v".into())]);
crate::test_harness::frames(h, 2);
};
let cancel = |h: &mut egui_kittest::Harness<'static, WordApp>| {
h.input_mut().events.push(key_event(egui::Key::Escape, true, egui::Modifiers::NONE));
crate::test_harness::frames(h, 2);
};
let mut h = harness(app());
let home_tab = h.get_by_label("Home").rect();
trigger_legacy_v(&mut h);
assert!(h.state().keytips_active, "F10, V enters legacy keytip wait with the ribbon showing");
assert!(h.query_by_label("Old menu keys: Alt, V. Keep typing, or press Esc to cancel.").is_some(), "hint displays pending Alt, V sequence");
let ribbon_hint = h.get_by_role_and_label(Role::Dialog, "Old menu keys").rect();
assert!(ribbon_hint.top() >= home_tab.bottom() - 1.0, "legacy hint {ribbon_hint:?} hangs under the ribbon tab row {home_tab:?}");
cancel(&mut h);
assert!(!h.state().keytips_active, "Escape ends legacy keytips");
assert!(h.query_by_role_and_label(Role::Dialog, "Old menu keys").is_none(), "hint closes on Escape");
// Focus hides the ribbon and shows the slim screen bar at the top.
h.state_mut().run("view.focus", serde_json::json!({})).unwrap();
crate::test_harness::frames(&mut h, 3);
assert!(h.query_by_label("Insert").is_none(), "Focus hides the ribbon");
let focus_bar = h.get_by_label("Show the ribbon").rect();
trigger_legacy_v(&mut h);
assert!(h.state().keytips_active, "F10, V activates legacy keytips in Focus mode");
let focus_hint = h.get_by_role_and_label(Role::Dialog, "Old menu keys").rect();
assert!(
focus_hint.top() >= focus_bar.bottom() - 1.0 && focus_hint.top() < ribbon_hint.top(),
"Focus legacy hint {focus_hint:?} hangs under the slim screen bar {focus_bar:?} (above ribbon hint {ribbon_hint:?})"
);
assert!(focus_hint.width() < 720.0, "Focus hint {focus_hint:?} sizes to its content rather than stretching across the screen bar");
cancel(&mut h);
assert!(!h.state().keytips_active, "Escape ends legacy keytips in Focus");
assert!(h.state().session.view.focus_mode, "Escape cancelling legacy keytips keeps Focus active");
// When Focus drops the ribbon down, the tab row wins over the screen bar.
h.state_mut().run("ui.focusRibbon", serde_json::json!({"value": true})).unwrap();
crate::test_harness::frames(&mut h, 3);
let dropped_tab = h.get_by_label("Home").rect();
trigger_legacy_v(&mut h);
let dropped_hint = h.get_by_role_and_label(Role::Dialog, "Old menu keys").rect();
assert!(
dropped_hint.top() >= dropped_tab.bottom() - 1.0 && dropped_hint.top() > focus_hint.top(),
"dropped-ribbon hint {dropped_hint:?} hangs under the dropped tab row {dropped_tab:?}"
);
cancel(&mut h);
// Full Screen View hides the ribbon and shows the slim screen bar with Search.
h.state_mut().run("view.focus", serde_json::json!({})).unwrap();
h.state_mut().run("view.fullScreenView", serde_json::json!({})).unwrap();
crate::test_harness::frames(&mut h, 3);
assert!(h.query_by_label("Insert").is_none(), "Full Screen View hides the ribbon");
let search_bar = h.get_by_label("Search commands and help").rect();
trigger_legacy_v(&mut h);
assert!(h.state().keytips_active, "F10, V activates legacy keytips in Full Screen View");
let fs_hint = h.get_by_role_and_label(Role::Dialog, "Old menu keys").rect();
assert!(
fs_hint.top() >= search_bar.bottom() - 1.0 && fs_hint.top() < ribbon_hint.top(),
"Full Screen View legacy hint {fs_hint:?} hangs under the slim screen bar {search_bar:?} (above ribbon hint {ribbon_hint:?})"
);
assert!(fs_hint.width() < 720.0, "Full Screen View hint {fs_hint:?} sizes to its content rather than stretching across the screen bar");
h.input_mut().events.extend([key_event(egui::Key::U, true, egui::Modifiers::NONE), egui::Event::Text("u".into())]);
crate::test_harness::frames(&mut h, 3);
assert!(!h.state().session.view.full_screen_view, "Alt/F10, V, U leaves Full Screen View");
assert!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body).is_empty(), "no letter typed into the document");
}
fn painted_texts(shapes: &[egui::epaint::ClippedShape]) -> Vec<String> {
fn walk(shape: &egui::Shape, out: &mut Vec<String>) {
match shape {
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
egui::Shape::Vec(children) => {
for child in children {
walk(child, out);
}
}
_ => {}
}
}
let mut out = Vec::new();
for clipped in shapes {
walk(&clipped.shape, &mut out);
}
out
}
#[test]
fn long_qat_badges_wait_for_the_complete_number_and_escape_cancels() {
// Collect genuinely enabled commands from a live harness context (where `frame_input` has
// published command states) so all 20 QAT buttons remain active during the test.
let mut h = harness(app());
let commands: Vec<String> = {
let ctx = h.ctx.clone();
let a = h.state();
let mut ids: Vec<String> = a
.session
.registry
.all()
.iter()
.filter(|s| s.id != "format.bold" && s.id != "format.italic" && crate::chrome::qat_enabled(&ctx, a, s.id))
.take(18)
.map(|s| s.id.to_string())
.collect();
ids.insert(0, "format.italic".into());
ids.insert(9, "format.bold".into());
ids
};
assert_eq!(commands.len(), 20, "expected 20 enabled QAT commands");
h.state_mut().session.ribbon.qat = Some(commands);
crate::test_harness::frames(&mut h, 2);
{
let ctx = h.ctx.clone();
let a = h.state();
let enabled_count = a.session.ribbon.qat().iter().filter(|id| crate::chrome::qat_enabled(&ctx, a, id)).count();
assert_eq!(enabled_count, 20, "all 20 QAT commands stay enabled");
}
let digit = |key, ch: &str| [key_event(key, true, egui::Modifiers::NONE), egui::Event::Text(ch.into())];
h.input_mut().events.push(key_event(egui::Key::F10, true, egui::Modifiers::NONE));
crate::test_harness::frame(&mut h);
assert!(h.state().keytips_active);
let shown = painted_texts(&h.output().shapes);
assert!(shown.iter().any(|t| t == "001"), "20-button QAT paints 001 for the 10th button: {shown:?}");
h.input_mut().events.extend(digit(egui::Key::Num0, "0"));
crate::test_harness::frame(&mut h);
assert!(h.state().keytips_active, "first 0 waits for the rest of the multi-digit badge");
h.input_mut().events.extend(digit(egui::Key::Num0, "0"));
crate::test_harness::frame(&mut h);
assert!(h.state().keytips_active, "second 0 still waits for the final digit of 001");
assert!(!bold(&mut h), "incomplete prefix 00 must not fire Bold");
let narrowed = painted_texts(&h.output().shapes);
assert!(narrowed.iter().any(|t| t == "001"), "001 remains painted while waiting on prefix 00");
assert!(!narrowed.iter().any(|t| t == "010"), "non-matching multi-digit badges are hidden under prefix 00");
h.input_mut().events.extend(digit(egui::Key::Num1, "1")); // 001: first button after the first nine.
crate::test_harness::frames(&mut h, 3);
assert!(bold(&mut h), "001 runs Bold");
assert!(!h.state().keytips_active, "completing 001 ends keytips");
assert!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body).is_empty(), "QAT digits never type into the document");
h.input_mut().events.push(key_event(egui::Key::F10, true, egui::Modifiers::NONE));
crate::test_harness::frame(&mut h);
assert!(h.state().keytips_active);
h.input_mut().events.extend(digit(egui::Key::Num0, "0"));
crate::test_harness::frame(&mut h);
assert!(h.state().keytips_active);
h.input_mut().events.push(key_event(egui::Key::Escape, true, egui::Modifiers::NONE));
crate::test_harness::frame(&mut h);
assert!(!h.state().keytips_active, "Escape cancels a partial multi-digit prefix");
// Reopening keytips and pressing 1 fires button 1 (Italic), proving the cancelled "0" prefix was cleared.
h.input_mut().events.push(key_event(egui::Key::F10, true, egui::Modifiers::NONE));
crate::test_harness::frame(&mut h);
assert!(h.state().keytips_active);
h.input_mut().events.extend(digit(egui::Key::Num1, "1"));
crate::test_harness::frames(&mut h, 3);
assert!(!h.state().keytips_active);
assert_eq!(
h.state_mut().session.run("format.state", &serde_json::json!({})).unwrap()["italic"],
true,
"after Escape, F10 then 1 runs the first button"
);
assert!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body).is_empty(), "no keytip digit typed into the document");
// Verify production `craft::menu::Keytips` assigns distinct, prefix-free digit badges across
// single- and multi-digit QAT lengths without any test-only label helper.
for count in [9, 10, 18, 19, 100, 200] {
let digits: Vec<CommandRef> = (0..count).map(|i| CommandRef::new(format!("test.qat.{i}"))).collect();
let region_id = egui::Id::unique(("test_qat_digit_badges", count));
let ctx = crate::test_harness::context();
let run_pass = |events: Vec<egui::Event>| {
craft::ui::shell::embed::before_input(&ctx, |_| craft::ui::runtime::frame::FrameInput::new(craft::ui::runtime::env::RootEnv::default()));
ctx.run_ui(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(2000.0, 2000.0))),
focused: true,
events,
..Default::default()
},
|ui| {
let (_, recorded) = inspect::record(ui, region_id, |ui| {
for row in digits.chunks(20) {
ui.horizontal(|ui| {
for cmd in row {
craft::ui::buttons::IconButton::command(craft::behavior::IconId::new("bold"), cmd.clone()).show(ui);
}
});
}
});
let places: Vec<Arc<Recorded>> = recorded.into_iter().collect();
let _ = Keytips::new(true).digits(&digits).places(&places).show_over(ui);
},
)
};
run_pass(Vec::new()).drop_without_applying_deltas();
let shown = run_pass(vec![key_event(egui::Key::F10, true, egui::Modifiers::NONE)]);
let labels = painted_texts(&shown.shapes);
shown.drop_without_applying_deltas();
assert_eq!(labels.len(), count, "expected one painted digit badge per QAT command for count={count}: {labels:?}");
for (i, label) in labels.iter().enumerate() {
assert!(!label.is_empty() && label.chars().all(|c| c.is_ascii_digit()), "non-digit badge {label:?} at {i} for count={count}");
assert!(
!labels.iter().enumerate().any(|(j, other)| i != j && other.starts_with(label.as_str())),
"ambiguous label {label} in {count} buttons"
);
}
}
}
#[test]
fn qat_keytips_follow_custom_order_and_skip_disabled_commands() {
let mut a = app();
@@ -171,3 +472,60 @@ fn keytips_option_persists() {
b.apply_prefs(serde_json::from_str("{}").unwrap());
assert!(b.ui.keytips_enabled, "older preferences retain enabled KeyTips");
}
/// After idle frames populate the keytip cache on Home, switching tabs updates the active tab's
/// keytips so Insert badges run Insert commands and switching back to Home runs Home commands.
#[test]
fn keytips_update_controls_when_switching_tabs() {
let badge_for = |a: &WordApp, tab: &str, command_id: &str| -> String {
let reserved = reserved_letters(a);
let folder = craft::i18n::Folder::new("en");
let tab_controls = KeytipCache::build_tab_controls(a, tab);
let labels: Vec<(&str, Option<&str>)> = tab_controls.iter().map(|c| (c.label, c.letters)).collect();
let badges = craft::keymap::mnemonic::assign_keytips(&labels, &reserved, &folder);
tab_controls
.iter()
.zip(badges)
.find(|(c, _)| c.command.id == command_id)
.map(|(_, badge)| badge)
.expect("command has a keytip badge on its tab")
};
let press_keytip_seq = |h: &mut egui_kittest::Harness<'static, WordApp>, seq: &str| {
for ch in seq.chars() {
let name = ch.to_ascii_uppercase().to_string();
let key = egui::Key::from_name(&name).unwrap();
let text = ch.to_ascii_lowercase().to_string();
h.input_mut().events.extend([key_event(key, true, egui::Modifiers::NONE), egui::Event::Text(text)]);
crate::test_harness::frame(h);
}
};
let mut h = harness(app());
// Let idle frames populate the keytip cache on the initial Home tab.
crate::test_harness::frames(&mut h, 4);
assert_eq!(h.state().ui.tab, "Home");
// Switch to Insert via keytips (F10, N) and fire Page Break through its Insert keytip badge.
let page_break_badge = badge_for(h.state(), "Insert", "insert.pageBreak");
h.input_mut().events.push(key_event(egui::Key::F10, true, egui::Modifiers::NONE));
crate::test_harness::frame(&mut h);
press_keytip_seq(&mut h, tab_letter("Insert"));
assert_eq!(h.state().ui.tab, "Insert", "F10 and the Insert tab badge switch to Insert");
press_keytip_seq(&mut h, &page_break_badge);
crate::test_harness::frames(&mut h, 3);
assert!(
h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body).contains('\u{000C}'),
"Insert keytip badge {page_break_badge} runs insert.pageBreak after switching from Home"
);
assert!(!bold(&mut h), "switching to Insert does not fire Home's Bold command");
// Switch back to Home via keytips (F10, H) and fire Bold through its Home keytip badge.
let bold_badge = badge_for(h.state(), "Home", "format.bold");
h.input_mut().events.push(key_event(egui::Key::F10, true, egui::Modifiers::NONE));
crate::test_harness::frame(&mut h);
press_keytip_seq(&mut h, tab_letter("Home"));
assert_eq!(h.state().ui.tab, "Home", "F10 and the Home tab badge switch back to Home");
press_keytip_seq(&mut h, &bold_badge);
crate::test_harness::frames(&mut h, 3);
assert!(bold(&mut h), "Home keytip badge {bold_badge} runs format.bold after switching back from Insert");
}
+9
View File
@@ -55,6 +55,8 @@ pub mod md_source;
pub mod mini_toolbar;
pub mod objects;
pub mod options;
/// The window identity of the channel this build runs as (stable or Nightly).
pub mod os_window;
pub mod panes;
pub mod paste_picture;
pub mod prefs;
@@ -400,6 +402,11 @@ pub struct WordApp {
/// The app-scope command states handed to the runtime, edited only when they change: the runtime resolves
/// commands again only when their revision moves ([`WordApp::command_input`]).
pub(crate) command_states: craft::ui::contract::Tracked<craft::ui::runtime::commands::CommandStates>,
/// Precomputed command metadata, translated hints, and last gate results for [`WordApp::command_input`],
/// avoiding per-frame allocations and catalog reparsing while idle.
pub(crate) command_states_cache: Option<app::command_board::CommandStatesCache>,
/// Cached keytip control lists and reserved shortcut letters per registry and active ribbon tab.
pub(crate) keytip_cache: Option<keytips::KeytipCache>,
/// Frames drawn so far, counted to 2: the control channel's queued requests wait until the
/// fonts are warm.
pub(crate) fonts_frames: u8,
@@ -571,6 +578,8 @@ pub(crate) fn rust_sources(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
files
}
#[cfg(test)]
mod file_browser;
#[cfg(test)]
mod test_harness;
#[cfg(test)]
+52 -15
View File
@@ -643,21 +643,28 @@ impl ObjectGesture {
/// it's over. `lock` (`Some(horizontal)`) keeps an aligned copy on its axis.
fn snap_move(&mut self, body: &PageBody, cx: &mut ToolContext, object: &ObjectHit, lock: Option<bool>) {
let Some(pp) = placed(body, self.to_page) else { return };
let b = object.spin.bounds(self.rect);
let Some(b) = finite_spin_bounds(self.rect, object.spin) else { return };
let a = pp.to_doc(&body.view, pt(b.x, b.y));
let c = pp.to_doc(&body.view, pt(b.right(), b.bottom()));
if !a.x.is_finite() || !a.y.is_finite() || !c.x.is_finite() || !c.y.is_finite() {
return;
}
let off = cx.snap_rect(DocRect::from_points(a, c));
let off = match lock {
Some(true) => Vec2::new(off.x, 0.0),
Some(false) => Vec2::new(0.0, off.y),
None => off,
};
if off == Vec2::ZERO {
if !off.x.is_finite() || !off.y.is_finite() || off == Vec2::ZERO {
return;
}
let at = pp.from_doc(&body.view, a + off);
self.rect.x += (at.x - f64::from(b.x)) as f32;
self.rect.y += (at.y - f64::from(b.y)) as f32;
let dx = (at.x - f64::from(b.x)) as f32;
let dy = (at.y - f64::from(b.y)) as f32;
if dx.is_finite() && dy.is_finite() {
self.rect.x += dx;
self.rect.y += dy;
}
}
/// The button went up. Commits a move as one command; false for a press on a Behind Text
@@ -789,15 +796,32 @@ pub(crate) fn snap(app: &WordApp, layout: &DocLayout) -> Option<PageSnap> {
Some(pages.into_iter().enumerate().fold(PageSnap::new(options), |snap, (page, targets)| snap.page(page, targets)))
}
/// Axis-aligned bounds of `rect` turned by `spin`, or `None` when any input or bound is non-finite.
fn finite_spin_bounds(rect: wordcraft_geom::Rect, spin: wordcraft_geom::Spin) -> Option<wordcraft_geom::Rect> {
if !rect.x.is_finite() || !rect.y.is_finite() || !rect.w.is_finite() || !rect.h.is_finite() || !spin.deg.is_finite() {
return None;
}
let (bw, bh) = spin.extent(rect.w, rect.h);
let x = rect.x + (rect.w - bw) / 2.0;
let y = rect.y + (rect.h - bh) / 2.0;
(x.is_finite() && y.is_finite() && bw.is_finite() && bh.is_finite()).then(|| wordcraft_geom::Rect::new(x, y, bw, bh))
}
/// The snap targets of `pg` in its own page points, each spanning the page's own range:
/// its edges and centre, its margins, and the floating objects on it that `me` can snap to (all but
/// itself and, for a text box, the objects in its text: they move with it). The page's own width
/// leaves out the comment balloons' markup area.
fn snap_targets(pg: &wordcraft_layout::Page, me: Option<&ObjectHit>) -> Vec<SnapTarget> {
let w = f64::from((pg.w - pg.markup).max(0.0));
let h = f64::from(pg.h);
if !pg.w.is_finite() || !pg.h.is_finite() || !pg.markup.is_finite() {
return Vec::new();
}
let w = (f64::from(pg.w) - f64::from(pg.markup)).max(0.0);
let h = f64::from(pg.h).max(0.0);
let mut targets = Vec::new();
let vertical = |targets: &mut Vec<SnapTarget>, x: f64, kind: SnapKind| {
if !x.is_finite() {
return;
}
let mut t = SnapTarget::new(Axis::Y, x, kind);
t.span = Some((0.0, h));
targets.push(t);
@@ -805,9 +829,14 @@ fn snap_targets(pg: &wordcraft_layout::Page, me: Option<&ObjectHit>) -> Vec<Snap
for (x, kind) in [(0.0, SnapKind::Bounds), (w / 2.0, SnapKind::Center), (w, SnapKind::Bounds)] {
vertical(&mut targets, x, kind);
}
vertical(&mut targets, f64::from(pg.body.x), SnapKind::Guide);
vertical(&mut targets, f64::from(pg.body.right()), SnapKind::Guide);
if pg.body.x.is_finite() && pg.body.w.is_finite() {
vertical(&mut targets, f64::from(pg.body.x), SnapKind::Guide);
vertical(&mut targets, f64::from(pg.body.x) + f64::from(pg.body.w), SnapKind::Guide);
}
let horizontal = |targets: &mut Vec<SnapTarget>, y: f64, kind: SnapKind| {
if !y.is_finite() {
return;
}
let mut t = SnapTarget::new(Axis::X, y, kind);
t.span = Some((0.0, w));
targets.push(t);
@@ -815,8 +844,10 @@ fn snap_targets(pg: &wordcraft_layout::Page, me: Option<&ObjectHit>) -> Vec<Snap
for (y, kind) in [(0.0, SnapKind::Bounds), (h / 2.0, SnapKind::Center), (h, SnapKind::Bounds)] {
horizontal(&mut targets, y, kind);
}
horizontal(&mut targets, f64::from(pg.body.y), SnapKind::Guide);
horizontal(&mut targets, f64::from(pg.body.bottom()), SnapKind::Guide);
if pg.body.y.is_finite() && pg.body.h.is_finite() {
horizontal(&mut targets, f64::from(pg.body.y), SnapKind::Guide);
horizontal(&mut targets, f64::from(pg.body.y) + f64::from(pg.body.h), SnapKind::Guide);
}
let pos = me.map(ObjectHit::pos);
let own = me.and_then(|m| m.text_box).map(StoryRef::Part);
for it in pg.items.iter().chain(&pg.header).chain(&pg.footer) {
@@ -825,12 +856,18 @@ fn snap_targets(pg: &wordcraft_layout::Page, me: Option<&ObjectHit>) -> Vec<Snap
if *wrap == Wrap::Inline || is_me || Some(*story) == own {
continue;
}
let b = spin.bounds(*rect);
for (x, kind) in [(b.x, SnapKind::LayerEdge), (b.x + b.w / 2.0, SnapKind::LayerCenter), (b.right(), SnapKind::LayerEdge)] {
vertical(&mut targets, f64::from(x), kind);
let Some(b) = finite_spin_bounds(*rect, *spin) else {
continue;
};
let x0 = f64::from(b.x);
let x1 = x0 + f64::from(b.w);
for (x, kind) in [(x0, SnapKind::LayerEdge), ((x0 + x1) / 2.0, SnapKind::LayerCenter), (x1, SnapKind::LayerEdge)] {
vertical(&mut targets, x, kind);
}
for (y, kind) in [(b.y, SnapKind::LayerEdge), (b.y + b.h / 2.0, SnapKind::LayerCenter), (b.bottom(), SnapKind::LayerEdge)] {
horizontal(&mut targets, f64::from(y), kind);
let y0 = f64::from(b.y);
let y1 = y0 + f64::from(b.h);
for (y, kind) in [(y0, SnapKind::LayerEdge), ((y0 + y1) / 2.0, SnapKind::LayerCenter), (y1, SnapKind::LayerEdge)] {
horizontal(&mut targets, y, kind);
}
}
targets
+281
View File
@@ -1053,6 +1053,287 @@ fn a_dragged_objects_snap_lines_include_the_page_margins_and_a_neighbouring_obje
assert!(!has_target(&targets, Axis::Y, SnapKind::LayerEdge, me.rect.x), "the dragged object is no target of its own drag: {targets:?}");
}
/// #7749: empty targets, negative tolerance, disabled alignment guides, and hostile non-finite
/// page/margin/object/moving geometry never produce non-finite snap targets, emit snap lines, or
/// move a dragged object.
#[test]
fn nothing_to_snap_to() {
use craft::behavior::geometry::SnapTargets;
use egui::{Event, PointerButton};
use wordcraft_geom::{Point as GeomPoint, Rect as GeomRect, Spin};
use wordcraft_layout::{Page, Placed};
let moving = DocRect::new(100.0, 200.0, 150.0, 220.0);
// Empty target set and negative tolerance never move anything.
assert_eq!(SnapTargets::new().snap_rect(moving, 6.0), (Vec2::ZERO, Vec::new()));
let mut single = SnapTargets::new();
single.add(SnapTarget::new(Axis::Y, 99.0, SnapKind::Guide));
assert_eq!(single.snap_rect(moving, -1.0), (Vec2::ZERO, Vec::new()));
// Non-finite page dimensions or markup yield no targets.
for (w, h, markup) in [
(f32::NAN, 792.0, 0.0),
(f32::INFINITY, 792.0, 0.0),
(612.0, f32::NAN, 0.0),
(612.0, f32::INFINITY, 0.0),
(612.0, 792.0, f32::NAN),
(612.0, 792.0, f32::NEG_INFINITY),
] {
let pg = Page { w, h, markup, body: GeomRect::new(72.0, 72.0, 468.0, 648.0), ..Page::default() };
assert!(snap_targets(&pg, None).is_empty(), "non-finite page ({w}, {h}, {markup}) must yield no targets");
}
// Non-finite margins or floating objects on an otherwise valid page are dropped so they cannot
// poison snapping onto valid targets on the same page.
let placed_obj = |rect: GeomRect, spin: Spin, off: usize| Placed::Object {
rect,
spin,
story: StoryRef::Body,
path: wordcraft_doc::Path::top(0),
off,
text_box: None,
wrap: Wrap::InFrontOfText,
origin: GeomPoint::default(),
group_boxes: Vec::new(),
};
let mut pg = Page { w: 612.0, h: 792.0, markup: 0.0, body: GeomRect { x: f32::NAN, y: 72.0, w: 468.0, h: f32::INFINITY }, ..Page::default() };
pg.items.push(placed_obj(GeomRect { x: f32::NAN, y: 200.0, w: 50.0, h: 20.0 }, Spin::default(), 0));
pg.items.push(placed_obj(GeomRect { x: 100.0, y: f32::INFINITY, w: 50.0, h: 20.0 }, Spin::default(), 1));
pg.header.push(placed_obj(GeomRect::new(100.0, 200.0, 50.0, 20.0), Spin { deg: f32::NAN, ..Spin::default() }, 2));
pg.footer.push(placed_obj(GeomRect::new(10.0, 20.0, 3e38, 3e38), Spin::new(45.0, false, false), 3));
// Valid neighbouring floating object at x = 300..380, y = 400..440.
pg.items.push(placed_obj(GeomRect::new(300.0, 400.0, 80.0, 40.0), Spin::default(), 4));
let targets = snap_targets(&pg, None);
assert!(!targets.is_empty(), "valid page and neighbour targets remain");
assert!(!has_target(&targets, Axis::X, SnapKind::Guide, 72.0), "non-finite body margin dropped: {targets:?}");
assert!(!has_target(&targets, Axis::Y, SnapKind::LayerEdge, 100.0), "non-finite objects dropped: {targets:?}");
assert!(!has_target(&targets, Axis::X, SnapKind::LayerEdge, 200.0), "non-finite objects dropped: {targets:?}");
assert!(!has_target(&targets, Axis::Y, SnapKind::LayerEdge, 0.0), "rotated-bounds overflow dropped: {targets:?}");
assert!(!has_target(&targets, Axis::X, SnapKind::LayerEdge, 0.0), "rotated-bounds overflow dropped: {targets:?}");
assert!(
targets.iter().all(|t| t.position.is_finite() && t.span.is_none_or(|(a, b)| a.is_finite() && b.is_finite() && a <= b)),
"all emitted snap targets and spans must be finite: {targets:?}"
);
let mut snap_set = SnapTargets::new();
for t in targets {
snap_set.add(t);
}
let (delta, lines) = snap_set.snap_rect(DocRect::new(297.0, 402.0, 347.0, 422.0), 6.0);
assert!(delta.x.is_finite() && delta.y.is_finite(), "snap delta must stay finite: {delta:?}");
assert!((delta.x - 3.0).abs() < 1e-6 && (delta.y + 2.0).abs() < 1e-6, "valid neighbour still snaps: {delta:?}");
assert!(lines.iter().all(|l| l.position.is_finite()), "snap lines must be finite: {lines:?}");
// Turning alignment guides off via `ui.alignmentGuides` disables snapping on a live drag.
let mut app = WordApp::new(wordcraft_engine::Session::new(Document::new()), crate::Services::default());
app.run("view.commentsPane", json!({"value": false})).unwrap();
app.run("ui.alignmentGuides", json!({"value": false})).unwrap();
app.run("insert.shape", json!({"kind": "rectangle", "width": 100, "height": 50})).unwrap();
app.run("arrange.bounds", json!({"page": 0, "x": 100, "y": 250})).unwrap();
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
h.run_steps(6);
let page = h.state_mut().session.layout().pages.first().map(|p| p.w - p.markup).unwrap();
let centre = page / 2.0;
let r = h.state_mut().session.layout().object(&Pos::body(0, 0), 0).unwrap().rect;
let (cx, cy) = (r.x + r.w / 2.0, r.y + r.h / 2.0);
let from = crate::canvas::page_to_screen(h.state_mut(), 0, cx, cy).unwrap();
let to = crate::canvas::page_to_screen(h.state_mut(), 0, centre + 1.5, cy).unwrap();
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
h.event(Event::PointerMoved(from));
h.event(button(from, true));
h.run_steps(1);
for at in [from + egui::vec2(0.0, 40.0), to + egui::vec2(0.0, 40.0), to] {
h.event(Event::PointerMoved(at));
h.run_steps(1);
}
assert!(h.state().canvas.object_gesture().is_some(), "dragging");
h.event(button(to, false));
h.run_steps(3);
let landed = h.state_mut().session.layout().object(&Pos::body(0, 0), 0).unwrap().rect;
assert!((landed.x + landed.w / 2.0 - (centre + 1.5)).abs() < 0.01, "disabled guides leave drop unsnapped: {landed:?}");
assert_snap_move_guards_non_finite_moving_bounds();
}
/// #7749: `ObjectGesture::snap_move` leaves `self.rect` unchanged and emits no snap lines when the
/// moving object's bounds or mapped corners are non-finite, while snapping finite bounds onto the
/// same page targets.
fn assert_snap_move_guards_non_finite_moving_bounds() {
use std::collections::VecDeque;
use craft::behavior::geometry::SnapLine;
use craft::behavior::kurbo::Size;
use craft::behavior::value::CancelReason;
use craft::pages::ui::{PageSnap, PageSource, PageView, PageViewState};
use craft::ui::canvas::{CanvasTool, ToolAction, ToolHost, ToolPath};
use craft::ui::primitives::textures::{Revision, ThumbRender, ThumbRequest, ThumbSource};
use craft::ui::style::DataColor;
use egui::{Color32, Event, PointerButton};
use wordcraft_geom::{Point as GeomPoint, Rect as GeomRect, Spin};
struct BlankPage;
impl ThumbSource<usize> for BlankPage {
fn revision(&self, _: &usize, _: &ThumbRequest) -> Revision {
Revision::new(0)
}
fn render(&self, _: &usize, _: &ThumbRequest) -> ThumbRender {
ThumbRender::Blank
}
}
impl PageSource for BlankPage {
fn page_count(&self) -> usize {
1
}
fn page_size(&self, _: usize) -> Size {
Size::new(612.0, 792.0)
}
}
struct Case {
label: &'static str,
rect: GeomRect,
spin: Spin,
should_snap: bool,
}
struct Outcome {
label: &'static str,
before: GeomRect,
after: GeomRect,
snapped: Vec<SnapLine>,
should_snap: bool,
}
struct ProbeState {
view: PageViewState,
page_center: Option<Pos2>,
pending: VecDeque<Case>,
outcomes: Vec<Outcome>,
}
struct SnapMoveProbe<'a, 'b> {
body: &'b PageBody<'b>,
pending: &'a mut VecDeque<Case>,
ran: Option<(&'static str, GeomRect, GeomRect, bool)>,
}
impl CanvasTool for SnapMoveProbe<'_, '_> {
fn press(&mut self, _: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction {
if let Some(case) = self.pending.pop_front() {
let mut gesture = ObjectGesture { to_page: 0, rect: case.rect, ..ObjectGesture::inert() };
let hit = ObjectHit {
page: 0,
rect: case.rect,
spin: case.spin,
story: StoryRef::Body,
path: wordcraft_doc::Path::top(0),
off: 0,
text_box: None,
wrap: Wrap::InFrontOfText,
origin: GeomPoint::default(),
member: None,
};
gesture.snap_move(self.body, cx, &hit, None);
self.ran = Some((case.label, case.rect, gesture.rect, case.should_snap));
}
ToolAction::Done
}
fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {}
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
fn command_form(&self) -> ToolPath {
ToolPath::Command("snap_move probe")
}
}
let cases = VecDeque::from([
Case { label: "finite control snaps", rect: GeomRect::new(297.0, 402.0, 50.0, 20.0), spin: Spin::default(), should_snap: true },
Case {
label: "nan spin",
rect: GeomRect::new(297.0, 402.0, 50.0, 20.0),
spin: Spin { deg: f32::NAN, ..Spin::default() },
should_snap: false,
},
Case { label: "nan x", rect: GeomRect { x: f32::NAN, y: 402.0, w: 50.0, h: 20.0 }, spin: Spin::default(), should_snap: false },
Case { label: "inf y", rect: GeomRect { x: 297.0, y: f32::INFINITY, w: 50.0, h: 20.0 }, spin: Spin::default(), should_snap: false },
Case { label: "nan w", rect: GeomRect { x: 297.0, y: 402.0, w: f32::NAN, h: 20.0 }, spin: Spin::default(), should_snap: false },
Case { label: "neg inf h", rect: GeomRect { x: 297.0, y: 402.0, w: 50.0, h: f32::NEG_INFINITY }, spin: Spin::default(), should_snap: false },
Case { label: "overflow right", rect: GeomRect::new(2e38, 402.0, 2e38, 20.0), spin: Spin::default(), should_snap: false },
Case {
label: "rotated extent overflow",
rect: GeomRect::new(10.0, 20.0, 3e38, 3e38),
spin: Spin::new(45.0, false, false),
should_snap: false,
},
Case {
label: "rotated origin overflow",
rect: GeomRect::new(-3e38, 0.0, 0.0, 3e38),
spin: Spin::new(90.0, false, false),
should_snap: false,
},
]);
let case_count = cases.len();
let state = ProbeState { view: PageViewState::default(), page_center: None, pending: cases, outcomes: Vec::new() };
let mut h = crate::test_harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state(
|ui, state: &mut ProbeState| {
let snap = PageSnap::new(SnapOptions::default()).page(
0,
vec![
SnapTarget::new(Axis::Y, 0.0, SnapKind::Bounds),
SnapTarget::new(Axis::X, 0.0, SnapKind::Bounds),
SnapTarget::new(Axis::Y, 300.0, SnapKind::LayerEdge),
SnapTarget::new(Axis::X, 400.0, SnapKind::LayerEdge),
],
);
PageView::new("SnapProbe", &BlankPage, &mut state.view, DataColor::new(Color32::WHITE)).snap(Some(snap)).show(ui, |ui, body| {
if state.page_center.is_none() {
state.page_center = body.pages.first().map(|p| p.rect.center());
}
if let Some(pass) = body.pass {
let mut probe = SnapMoveProbe { body, pending: &mut state.pending, ran: None };
let reply = ToolHost::new().run(ui, pass, &mut probe);
if let Some((label, before, after, should_snap)) = probe.ran {
state.outcomes.push(Outcome { label, before, after, snapped: reply.snapped, should_snap });
}
}
});
},
state,
);
h.run_steps(3);
let at = h.state().page_center.expect("probe page placed");
let button = |pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
h.event(Event::PointerMoved(at));
for _ in 0..case_count {
h.event(button(true));
h.run_steps(1);
h.event(button(false));
h.run_steps(1);
}
assert_eq!(h.state().outcomes.len(), case_count, "all snap_move probe cases ran");
for o in &h.state().outcomes {
if o.should_snap {
assert!(!o.snapped.is_empty(), "{}: expected snap lines on finite control", o.label);
assert!((o.after.x - 300.0).abs() < 1e-4 && (o.after.y - 400.0).abs() < 1e-4, "{}: snapped to target, got {:?}", o.label, o.after);
} else {
assert!(o.snapped.is_empty(), "{}: expected no snap lines, got {:?}", o.label, o.snapped);
assert_eq!(
[o.after.x.to_bits(), o.after.y.to_bits(), o.after.w.to_bits(), o.after.h.to_bits()],
[o.before.x.to_bits(), o.before.y.to_bits(), o.before.w.to_bits(), o.before.h.to_bits()],
"{}: moving rect must stay unchanged ({:?} -> {:?})",
o.label,
o.before,
o.after,
);
}
}
}
/// #2277: the actual picture pixels follow the rotation handle before release, including
/// pictures whose cached preview already contains a rotation and either reflection.
#[test]
+75
View File
@@ -0,0 +1,75 @@
//! The app id every WordCraft OS window carries and the channel its title shows: the root window
//! (`main.rs`), the runtime's windows (`InstallSpec::app_id`) and the document windows
//! (`craft::window`), so docks show the WordCraft icon on them and Wayland compositors' window
//! rules can match them. Without one the app id is empty.
/// Matches the `.desktop` file and hicolor icon name, so Wayland docks pick up the icon.
pub const APP_ID: &str = "ai.storyteller.wordcraft";
/// Immutable startup identity. The desktop selects it before any UI/runtime service is created.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LaunchIdentity {
Stable,
NightlyV1,
}
static IDENTITY: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
pub fn select_identity(identity: LaunchIdentity) -> Result<(), String> {
let value = match identity {
LaunchIdentity::Stable => 1,
LaunchIdentity::NightlyV1 => 2,
};
IDENTITY
.compare_exchange(0, value, std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire)
.map(|_| ())
.map_err(|_| "the window launch identity was already selected".into())
}
pub fn identity() -> LaunchIdentity {
if IDENTITY.load(std::sync::atomic::Ordering::Acquire) == 2 { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable }
}
pub const fn id_for(identity: LaunchIdentity) -> &'static str {
match identity {
LaunchIdentity::Stable => APP_ID,
LaunchIdentity::NightlyV1 => "ai.storyteller.wordcraft.nightly-v1",
}
}
pub fn app_id() -> &'static str {
id_for(identity())
}
pub const fn name_for(identity: LaunchIdentity) -> &'static str {
match identity {
LaunchIdentity::Stable => "WordCraft",
LaunchIdentity::NightlyV1 => "WordCraft Nightly",
}
}
pub const fn stable_services_for(identity: LaunchIdentity) -> bool {
matches!(identity, LaunchIdentity::Stable)
}
pub fn stable_services_allowed() -> bool {
stable_services_for(identity())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nightly_identity_is_distinct_and_never_enables_stable_services() {
assert_eq!(id_for(LaunchIdentity::Stable), APP_ID);
assert_ne!(id_for(LaunchIdentity::NightlyV1), APP_ID);
assert!(stable_services_for(LaunchIdentity::Stable));
assert!(!stable_services_for(LaunchIdentity::NightlyV1));
}
#[test]
fn the_channel_names_are_distinct_and_keep_the_stable_name() {
assert_eq!(name_for(LaunchIdentity::Stable), "WordCraft");
assert_eq!(name_for(LaunchIdentity::NightlyV1), "WordCraft Nightly");
}
}
+24 -1
View File
@@ -137,7 +137,7 @@ pub(crate) fn paste_named_files(app: &mut WordApp, text: &str) -> bool {
mod tests {
use super::*;
use crate::system_clipboard::testing::{app_holding, rgba8};
use craft::platform::clipboard::{Flavor, URI_LIST};
use craft::platform::clipboard::{Flavor, RGBA8, URI_LIST};
fn pictures(a: &mut WordApp) -> usize {
a.session.run("arrange.selectionPane", &json!({})).unwrap().as_array().map(|x| x.len()).unwrap_or(0)
@@ -148,6 +148,29 @@ mod tests {
Flavor::new(URI_LIST, lines.concat().into_bytes())
}
/// Hostile or damaged clipboard pictures and non-picture files are refused without panicking.
#[test]
fn hostile_clipboard_pictures_are_refused() {
assert!(png_from_rgba(usize::MAX, 2, Vec::new()).is_err());
assert!(png_from_rgba(10_000, 10_000, Vec::new()).is_err());
assert!(png_from_rgba(4, 4, vec![0; 63]).is_err());
assert!(png_from_rgba(0, 4, Vec::new()).is_err());
// Damaged RGBA8 pixels buffer on the clipboard.
let mut damaged = Vec::new();
damaged.extend_from_slice(&(4u32).to_le_bytes());
damaged.extend_from_slice(&(4u32).to_le_bytes());
damaged.extend_from_slice(&[0u8; 10]);
let mut a = app_holding(&[Flavor::new(RGBA8, damaged)]);
assert!(a.run("edit.paste", json!({})).is_err());
assert_eq!(pictures(&mut a), 0);
// Copied files that aren't pictures leave Paste to the usual clipboard.
let mut a = app_holding(&[uri_list(&[PathBuf::from("/tmp/notes.txt")])]);
assert_eq!(a.run("edit.paste", json!({})).unwrap_err(), system_clipboard::nothing_to_paste(&a));
assert_eq!(pictures(&mut a), 0);
}
/// Paste with only a picture on the clipboard inserts it at its natural size, one undo step.
#[test]
fn paste_inserts_clipboard_pixels() {
+32
View File
@@ -177,3 +177,35 @@ pub(crate) fn show(app: &mut WordApp, ui: &mut Ui) {
ui.ctx().request_repaint();
}
}
#[cfg(test)]
mod tests {
use super::*;
use egui::accesskit::Role;
use egui_kittest::kittest::{By, Queryable};
fn harness(app: WordApp) -> egui_kittest::Harness<'static, WordApp> {
crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
)
}
/// #1885: The Read Aloud player opens as a modeless dialog and closes from its title bar close action.
#[test]
fn read_aloud_player_closes_from_title_bar() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.session.read_aloud.open = true;
let mut h = harness(app);
h.run_steps(4);
assert!(h.state().session.read_aloud.open, "the player is open");
let close = h.query_all(By::new().role(Role::Button).label("Close")).next().expect("close button on player");
close.click();
h.run_steps(3);
assert!(!h.state().session.read_aloud.open, "the player stops and closes");
}
}
+1 -1
View File
@@ -68,7 +68,7 @@ pub use tabs::{
use view::{outlining, view};
/// What a pass with no ribbon reports.
fn no_ribbon() -> RibbonOutput<String> {
pub(crate) fn no_ribbon() -> RibbonOutput<String> {
// PLAN: assumed `RibbonOutput::tab_ids` (S-L361) has a `Default` value; the field replaces `menu`.
RibbonOutput { shown: None, picked: None, controls: None, tabs: None, tab_ids: Default::default() }
}
+3
View File
@@ -36,6 +36,9 @@ pub(crate) fn menu_button(
face = face.tooltip(TooltipSpec::new(hint.clone()).disabled_text(hint));
}
let opener = face.trailing_icon(IconSpec::glyph(&MENU_ARROW)).enabled(enabled).show(ui);
if !ui.is_sizing_pass() {
crate::keytips::note_menu_button(ui.ctx(), opener.response.id, about.filter(|id| !id.is_empty()));
}
Menu::new(name).opened_by(&opener.response, Trigger::Click).show(ui, body).output
}
+24 -15
View File
@@ -1,10 +1,11 @@
use craft::behavior::IconId;
use craft::behavior::{ColumnWidth, IconId};
use craft::keymap::CommandRef;
use craft::menu::ribbon::{RibbonGroup, RibbonRow};
use craft::ui::buttons::{Arrangement, Button, IconButton, ToggleButton};
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _};
use craft::ui::layout_components::{Row, Stack};
use craft::ui::layout::{GridFit, empty_cell};
use craft::ui::layout_components::{Grid, Row, Stack};
use craft::ui::menu::MenuItem;
use craft::ui::text::NumberField;
@@ -17,25 +18,33 @@ use crate::undo_marks::apply_edits;
/// The row height and column width a Cell Size field accepts, in points (0.02 to 22 inches).
const CELL_SIZE_RANGE: std::ops::RangeInclusive<f64> = 1.44..=1584.0;
/// Two checkbox columns separated by two empty gutter cells: `Grid::gap` sets both axes, so the
/// empty gutter widens the column gap to `3 * Gap::Tight` (at least `Gap::Stack`) while keeping
/// rows `Gap::Tight` apart inside the ribbon group.
const TABLE_STYLE_OPTION_COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content; 4];
pub(super) fn table_design(row: &mut RibbonRow<'_>, app: &mut WordApp) {
let look = app.session.sel.focus.path.cell().and_then(|(tp, _, _)| app.session.doc.table(app.session.sel.focus.story, &tp).map(|t| t.props.look));
if let Some(l) = look {
// Three rows of two, so Tab runs Header Row, First Column, Total Row, Last Column, Banded Rows, Banded Columns.
// Row-major pairs, so Tab runs Header Row, First Column, Total Row, Last Column, Banded Rows, Banded Columns.
let options = [
[("Header Row", "headerRow", l.header_row), ("First Column", "firstColumn", l.first_column)],
[("Total Row", "totalRow", l.total_row), ("Last Column", "lastColumn", l.last_column)],
[("Banded Rows", "bandedRows", l.banded_rows), ("Banded Columns", "bandedColumns", l.banded_columns)],
("Header Row", "headerRow", l.header_row),
("First Column", "firstColumn", l.first_column),
("Total Row", "totalRow", l.total_row),
("Last Column", "lastColumn", l.last_column),
("Banded Rows", "bandedRows", l.banded_rows),
("Banded Columns", "bandedColumns", l.banded_columns),
];
row.group(RibbonGroup::new("tableStyleOptions", tl!("Table Style Options").to_string(), IconId::new("tableStyleOptions").into()), |ui| {
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
for line in options {
Row::new().show(ui, |ui, _| {
for (label, key, value) in line {
let out = Checkbox::new(Bind::given(value)).label(tl!(label).to_string()).show(ui);
apply_edits(app, out.events, |app, v| {
let _ = app.run("table.look", json!({ key: v }));
});
}
Grid::new(&TABLE_STYLE_OPTION_COLUMNS).fit(GridFit::Fixed).gap(Gap::Tight).show(ui, |ui, _| {
for (index, (label, key, value)) in options.into_iter().enumerate() {
if index % 2 == 1 {
empty_cell(ui);
empty_cell(ui);
}
let out = Checkbox::new(Bind::given(value)).label(tl!(label).to_string()).show(ui);
apply_edits(app, out.events, |app, v| {
let _ = app.run("table.look", json!({ key: v }));
});
}
});
+237
View File
@@ -342,6 +342,20 @@ fn language_names_resolve_aliases_and_tags() {
assert!(c.extra.is_some() && !c.listed.contains(&true));
}
/// #1110: the strip's drawn buttons have names for screen readers: Share, and the "»" that
/// holds the tabs that don't fit ("More tabs", not a glyph).
#[test]
fn the_tab_strip_buttons_have_names() {
let app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Text")), crate::Services::default());
let mut h = app_harness(app, vec2(760.0, 700.0));
h.get_by_role_and_label(egui::accesskit::Role::Button, tl!("Share"));
let more = h.get_by_role_and_label(egui::accesskit::Role::Button, tl!("More tabs"));
more.click();
crate::test_harness::frames(&mut h, 2);
// The menu lists a tab that didn't fit (View is among the last on a narrow strip).
assert!(h.query(By::new().role(egui::accesskit::Role::MenuItem).label(tl!("View"))).is_some(), "the » menu lists the tabs left out");
}
/// Each contextual tab shows on the tab strip while its object is selected and leaves with the
/// selection.
#[test]
@@ -994,3 +1008,226 @@ fn decorative_text_dropdown_renders_compact_wordart_tiles() {
rect.height()
);
}
/// #7691: Table Design › Table Style Options aligns its six checkboxes in two columns with a gap
/// between them and keeps all three rows above the group caption.
#[test]
fn table_style_options_align_in_two_columns() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
let h = tab_harness(app, "Table Design");
let rect = |label: &str| h.get_by_role_and_label(Role::CheckBox, label).rect();
let header = rect("Header Row");
let first_col = rect("First Column");
let total = rect("Total Row");
let last_col = rect("Last Column");
let banded = rect("Banded Rows");
let banded_col = rect("Banded Columns");
// Left column checkboxes share one left edge, and right column checkboxes share another.
assert!(
(header.left() - total.left()).abs() < 0.5 && (header.left() - banded.left()).abs() < 0.5,
"left column misaligned: {header:?}, {total:?}, {banded:?}"
);
assert!(
(first_col.left() - last_col.left()).abs() < 0.5 && (first_col.left() - banded_col.left()).abs() < 0.5,
"right column misaligned: {first_col:?}, {last_col:?}, {banded_col:?}"
);
// Each row's pair shares the same top edge and stacks vertically with tight spacing.
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
let tight_gap = env.tokens.space.gap.tight;
let min_col_gap = env.tokens.space.gap.stack;
assert!((header.top() - first_col.top()).abs() < 0.5, "row 1 misaligned: {header:?}, {first_col:?}");
assert!((total.top() - last_col.top()).abs() < 0.5, "row 2 misaligned: {total:?}, {last_col:?}");
assert!((banded.top() - banded_col.top()).abs() < 0.5, "row 3 misaligned: {banded:?}, {banded_col:?}");
assert!(header.bottom() <= total.top() && total.bottom() <= banded.top(), "rows overlap: {header:?}, {total:?}, {banded:?}");
let row_gap_1 = total.top() - header.bottom();
let row_gap_2 = banded.top() - total.bottom();
assert!(
(row_gap_1 - tight_gap).abs() <= 0.5 && (row_gap_2 - tight_gap).abs() <= 0.5,
"rows should remain Gap::Tight ({tight_gap} pt) apart, got {row_gap_1} and {row_gap_2}"
);
// A horizontal gap at least `space.gap.stack` separates the widest left-column label from the second column.
let text_rect = |label: &str| {
h.output()
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::Shape::Text(t) if t.galley.text() == label => Some(egui::Rect::from_min_size(t.pos, t.galley.size())),
_ => None,
})
.unwrap_or_else(|| panic!("painted text for {label:?}"))
};
let left_label_max_right =
["Header Row", "Total Row", "Banded Rows"].into_iter().map(|label| text_rect(label).right()).fold(f32::NEG_INFINITY, f32::max);
let col_gap = first_col.left() - left_label_max_right;
assert!(
col_gap >= min_col_gap,
"column gap between widest left label and right column too narrow: got {col_gap:.2} pt, expected >= {min_col_gap:.2} pt (left_label_max_right={left_label_max_right}, first_col={first_col:?})"
);
// All three rows stay above the group's caption.
let caption = text_rect("Table Style Options");
assert!(banded.bottom() <= caption.top(), "checkboxes collide with group caption: {banded:?} vs {caption:?}");
}
struct StylesGalleryLayout {
gallery: egui::Rect,
tiles: Vec<(String, egui::Rect, Option<egui::accesskit::Toggled>)>,
up: egui::Rect,
down: egui::Rect,
more: egui::Rect,
}
/// Lay out the Home tab in LTR (`rtl == false`) or Arabic RTL (`rtl == true`) using `fixture_lang`
/// so the test never skips when `CRAFT_I18N_DIR` is unset, and collect the Styles gallery's
/// container, visible tiles, and stepper/More buttons.
fn styles_gallery_layout(rtl: bool) -> StylesGalleryLayout {
use egui::accesskit::Role;
struct ResetLang;
impl Drop for ResetLang {
fn drop(&mut self) {
crate::i18n::apply_language(crate::i18n::Lang::EN);
}
}
let _reset = ResetLang;
let lang = if rtl {
crate::i18n::fixture_lang("ar", "\tHome\tالرئيسية\n\tStyles\tالأنماط\n\tNormal\tعادي\n")
} else {
crate::i18n::Lang::EN
};
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.ui.language = "en".into();
app.run("ui.tab", json!({"tab": "Home"})).unwrap();
let mut h = crate::test_harness::builder().with_size(vec2(2560.0, 900.0)).build_ui_state(
move |ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
if rtl {
ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Tofu);
crate::i18n::apply_language(lang);
ctx.global_style_mut(|s| s.right_to_left = true);
craft::ui::runtime::env::with_env(ui, |o| o.direction = Some(craft::i18n::Direction::Rtl), |ui| app.ui(ui));
ctx.global_style_mut(|s| s.right_to_left = false);
crate::i18n::apply_language(crate::i18n::Lang::EN);
} else {
app.ui(ui);
}
},
app,
);
crate::test_harness::frames(&mut h, 4);
crate::i18n::apply_language(lang);
let gallery_label = crate::i18n::t("Styles").to_string();
let names: Vec<String> = h.state().session.doc.styles.gallery().iter().take(6).map(|s| crate::i18n::style_name(s)).collect();
crate::i18n::apply_language(crate::i18n::Lang::EN);
let gallery = h
.query_all(By::new().role(Role::RadioGroup).label(gallery_label.as_str()))
.next()
.unwrap_or_else(|| panic!("Styles radio group '{gallery_label}' not found"))
.rect();
assert!(gallery.is_positive(), "Styles gallery rect must be positive: {gallery:?}");
let in_gallery = |rect: egui::Rect| gallery.contains_rect(rect);
let tiles: Vec<_> = names
.iter()
.filter_map(|name| {
h.query_all(By::new().role(Role::RadioButton).label(name.as_str()))
.find(|node| in_gallery(node.rect()))
.map(|node| (name.clone(), node.rect(), node.accesskit_node().toggled()))
})
.collect();
assert_eq!(tiles.len(), names.len(), "expected all {} visible Styles tiles inside {gallery:?}: {tiles:?} vs {names:?}", names.len());
let button = |label: &str| {
h.query_all(By::new().role(Role::Button).label(label))
.find(|node| in_gallery(node.rect()))
.unwrap_or_else(|| panic!("gallery button '{label}' not found inside {gallery:?}"))
.rect()
};
StylesGalleryLayout { gallery, tiles, up: button("Previous row"), down: button("Next row"), more: button("More") }
}
/// #5566, #7753: in a right-to-left interface the Styles gallery starts at the right, as the rest
/// of the ribbon does: the first style (Normal) is the rightmost tile, and the scroll arrows and
/// More button sit in a column at the gallery's left end. Left to right is unchanged.
#[test]
fn the_styles_gallery_reads_from_the_right_in_a_right_to_left_interface() {
use egui::accesskit::Toggled;
let assert_common = |layout: &StylesGalleryLayout, expected_first: &str, dir: &str| {
assert_eq!(layout.tiles.len(), 6, "{dir}: expected 6 visible gallery tiles: {:?}", layout.tiles);
let (first_name, first_rect, first_toggled) = &layout.tiles[0];
assert_eq!(first_name, expected_first, "{dir}: first tile should be localized Normal");
assert_eq!(*first_toggled, Some(Toggled::True), "{dir}: active Normal style should be checked");
assert!(
layout
.tiles
.iter()
.all(|(_, r, _)| r.is_positive() && layout.gallery.contains_rect(*r) && (r.center().y - first_rect.center().y).abs() <= 1.0),
"{dir}: gallery tiles must sit on one horizontal row inside {:?}: {:?}",
layout.gallery,
layout.tiles
);
let controls = [("Previous row", layout.up), ("Next row", layout.down), ("More", layout.more)];
for (name, rect) in controls {
assert!(rect.is_positive(), "{dir}: {name} rect must be positive: {rect:?}");
assert!(layout.gallery.contains_rect(rect), "{dir}: {name} {rect:?} must sit inside gallery {:?}", layout.gallery);
}
assert!(
(layout.up.center().x - layout.down.center().x).abs() <= 1.0 && (layout.down.center().x - layout.more.center().x).abs() <= 1.0,
"{dir}: up, down, and More buttons must align in one column: up={:?}, down={:?}, more={:?}",
layout.up,
layout.down,
layout.more
);
assert!(
layout.up.max.y <= layout.down.min.y + 1.0 && layout.down.max.y <= layout.more.min.y + 1.0,
"{dir}: buttons must stack top-to-bottom (up -> down -> More): up={:?}, down={:?}, more={:?}",
layout.up,
layout.down,
layout.more
);
};
// 1. Left-to-right (English)
let ltr = styles_gallery_layout(false);
assert_common(&ltr, "Normal", "LTR");
assert!(
ltr.tiles.windows(2).all(|w| w[0].1.center().x < w[1].1.center().x && w[0].1.max.x <= w[1].1.min.x + 1.0),
"LTR: tiles must run left to right: {:?}",
ltr.tiles
);
for (name, ctrl) in [("Previous row", ltr.up), ("Next row", ltr.down), ("More", ltr.more)] {
assert!(
ltr.tiles.iter().all(|(_, tile, _)| ctrl.min.x >= tile.max.x),
"LTR: {name} ({ctrl:?}) must sit to the right of every tile: {:?}",
ltr.tiles
);
}
// 2. Right-to-left (Arabic)
let rtl = styles_gallery_layout(true);
assert_common(&rtl, "عادي", "RTL");
assert!(
rtl.tiles.windows(2).all(|w| w[0].1.center().x > w[1].1.center().x && w[0].1.min.x + 1.0 >= w[1].1.max.x),
"RTL: tiles must run right to left from the rightmost Normal tile: {:?}",
rtl.tiles
);
for (name, ctrl) in [("Previous row", rtl.up), ("Next row", rtl.down), ("More", rtl.more)] {
assert!(
rtl.tiles.iter().all(|(_, tile, _)| ctrl.max.x <= tile.min.x),
"RTL: {name} ({ctrl:?}) must sit to the left of every tile: {:?}",
rtl.tiles
);
}
}
+28
View File
@@ -459,4 +459,32 @@ mod tests {
a.run("edit.paste", params).unwrap();
assert!(!a.session.doc.media.is_empty());
}
#[test]
fn empty_copy_does_not_publish_or_overwrite_clipboard_state() {
let mut a = app_with_copied_picture();
assert!(a.clipboard_published);
let clip = handle(&a).unwrap();
let image = clip.read_image().unwrap().unwrap();
assert_eq!((image.width, image.height), (2, 2));
a.run("caret.docEnd", json!({})).unwrap();
assert!(a.session.sel.is_collapsed());
let ctx = a.ctx.clone().unwrap();
let empty_r = a.run("edit.copy", json!({})).unwrap();
put_result(&mut a, &ctx, &empty_r);
assert!(a.clipboard_published, "empty copy must not change published-copy state");
let clip = handle(&a).unwrap();
let image2 = clip.read_image().unwrap().unwrap();
assert_eq!((image2.width, image2.height), (2, 2), "empty copy must not overwrite clipboard image");
let mut a2 = app_holding(&[]);
assert!(!a2.clipboard_published);
let ctx2 = a2.ctx.clone().unwrap();
let empty_r2 = a2.run("edit.copy", json!({})).unwrap();
put_result(&mut a2, &ctx2, &empty_r2);
assert!(!a2.clipboard_published, "empty copy must not change published-copy state when false");
}
}
+18
View File
@@ -231,6 +231,24 @@ fn dragging_across_cells_selects_their_rectangle() {
assert!(!crate::mini_toolbar::visible(h.state()));
}
/// The "+" left of a row border adds a row there and selects it, in one undo step; over it
/// the pointer is the plain arrow.
#[test]
fn the_plus_button_adds_a_row() {
let mut h = table_window();
let a = cell(&mut h, 0, 0);
let depth = h.state().session.undo_depth();
let at = screen(&mut h, a.x - 10.0, a.bottom());
h.event(egui::Event::PointerMoved(at));
steps(&mut h, 2);
assert_eq!(arrow_toward(&h), None, "over the insert button the pointer is the plain arrow");
click(&mut h, at);
let rows = h.state().session.doc.body.iter().find_map(|b| b.as_table()).map(|t| t.rows.len());
assert_eq!(rows, Some(3));
assert_eq!(h.state().session.cell_range().map(|r| (r.rows, r.cols)), Some(((1, 1), (0, 2))), "the new row is selected");
assert_eq!(h.state().session.undo_depth(), depth + 1);
}
/// A double-click along a cell's left edge selects its row, as in Word.
#[test]
fn a_double_click_by_a_cells_edge_selects_its_row() {
+140 -5
View File
@@ -55,6 +55,24 @@ fn save_as_suggests_the_first_words_of_a_new_document() {
assert_eq!(app.default_save_name(), "kept.docm", "a saved file keeps its name and format");
}
/// #3634: every source of the title (path, file name, document title) drops NUL.
#[test]
fn title_stem_omits_nul_from_each_title_source() {
let mut app = app();
let fallback = app.title_stem();
for title in ["Résumé\u{0} notes", "\u{0}"] {
let expected = if title == "\u{0}" { fallback.as_str() } else { "Résumé notes" };
app.session.doc.core.title = title.into();
assert_eq!(app.title_stem(), expected);
app.session.file_name = Some(title.into());
assert_eq!(app.title_stem(), expected);
app.session.path = Some(std::path::PathBuf::from(format!("{title}.docx")));
assert_eq!(app.title_stem(), expected);
app.session.path = None;
app.session.file_name = None;
}
}
/// A harness on a document with text whose page has the keyboard.
fn canvas_harness() -> egui_kittest::Harness<'static, WordApp> {
let mut a = app();
@@ -850,11 +868,13 @@ fn web_layout_fills_the_window_width() {
frame(&mut a, 1400.0, tick);
assert_eq!(a.session.view.web_width, wide, "no change without a resize");
let page = first_page(&a).unwrap();
// The page view keeps a side gutter clear (the rail width, S-L: the framework's page spacing); the page fills the
// rest of the window, so it neither overflows to the right nor leaves more than the gutter on the left.
let gutter = 40.0; // the `size.rail.width` token the page view keeps clear
assert!(page.left() <= gutter + 4.0, "page starts at the left gutter: {page:?}");
assert!(page.right() <= 1400.0 - gutter + 4.0, "page ends before the right gutter: {page:?}");
// The page view keeps its `PageSpacing::side` gutter clear on both sides; the page fills the rest of the window,
// so it uses the full room up to the PageView gutter rather than the wider rail width, without overflowing.
let gutter = a.canvas.page_side.expect("page view records its side gutter");
let rail = craft::ui::runtime::env::Env::of_root(&ctx).tokens.size.rail.width;
assert!(gutter < rail, "Productivity PageView gutter ({gutter}) is narrower than the rail width ({rail})");
assert!((page.left() - gutter).abs() <= 4.0, "page starts at the left gutter ({gutter}): {page:?}");
assert!(page.right() >= 1400.0 - gutter - 4.0 && page.right() <= 1400.0 - gutter + 4.0, "page fills to the right gutter ({gutter}): {page:?}");
// A window drag: the width holds while the size keeps changing, then follows once it settles.
for w in [1300.0, 1100.0, 900.0, 700.0, 500.0] {
frame(&mut a, w, tick);
@@ -887,6 +907,23 @@ fn web_layout_fills_the_window_width() {
frame(&mut a, 1400.0, tick);
}
assert_eq!(lines(&mut a), print_lines, "Print Layout is unchanged");
// Entering Web Layout before any prior PageView pass still settles to PageView's side gutter.
let fresh_ctx = crate::test_harness::context();
let mut fresh = app();
fresh.run("view.webLayout", json!({})).unwrap();
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 740.0));
for step in 1..=2 {
let input = egui::RawInput { events: vec![], time: Some(step as f64 * tick), screen_rect: Some(screen), ..Default::default() };
crate::test_harness::pass(&fresh_ctx, &mut fresh, input);
}
let fresh_gutter = fresh.canvas.page_side.expect("page view records its side gutter on first Web Layout pass");
let fresh_page = first_page(&fresh).unwrap();
assert!((fresh_page.left() - fresh_gutter).abs() <= 4.0, "fresh Web Layout starts at the left gutter ({fresh_gutter}): {fresh_page:?}");
assert!(
fresh_page.right() >= 1400.0 - fresh_gutter - 4.0 && fresh_page.right() <= 1400.0 - fresh_gutter + 4.0,
"fresh Web Layout fills to the right gutter ({fresh_gutter}): {fresh_page:?}"
);
}
/// #688: dragging a selection past the viewport's edge scrolls the view toward the pointer, and the
@@ -1913,6 +1950,21 @@ fn save_prompt_shows_why_the_save_failed() {
let _ = std::fs::remove_dir_all(&dir);
}
/// #3172: the ribbon's combo boxes name themselves: a screen reader reads their label (Font,
/// Font Size), and the drop-down arrows say what they drop down.
#[test]
fn the_ribbon_boxes_name_themselves_for_a_screen_reader() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
let mut a = app();
a.run("file.new", json!({"template": "sample"})).unwrap();
let mut h = harness(a);
h.run_steps(6);
for (role, name) in [(Role::ComboBox, "Font"), (Role::ComboBox, "Font Size"), (Role::Button, "Font Color")] {
assert!(h.query_by_role_and_label(role, name).is_some(), "nothing on the ribbon is called {name:?} with {role:?}");
}
}
/// #3172: the Paste button is named "Paste": its tooltip adds the key as the platform writes it,
/// so its name no longer carries macOS's "⌘V", which screen readers read on Windows as "Paste (⌘V)".
#[test]
@@ -3364,6 +3416,62 @@ fn f11_and_escape_toggle_full_screen() {
assert!(h.state().session.view.full_screen, "and only that");
}
/// The Full Screen button tells assistive technology what the command can do: it is enabled
/// exactly when the command is, so the browser build (which keeps full screen to itself)
/// does not announce a control that cannot be activated.
#[test]
fn the_full_screen_button_reports_the_commands_own_enabled_state() {
use egui_kittest::kittest::{NodeT, Queryable};
use wordcraft_engine::{CommandSpec, Registry};
// The browser build's reason for refusing full screen, forced here so the test says
/// something on every platform.
fn unavailable(_: &wordcraft_engine::Session) -> Option<&'static str> {
Some("Use the browser's full screen (F11)")
}
let mut a = app();
let specs: Vec<CommandSpec> = a
.session
.registry
.all()
.iter()
.map(|s| {
if s.id == "view.fullScreen" {
CommandSpec {
id: s.id,
label: s.label,
location: s.location,
shortcut: s.shortcut,
params: s.params,
mutates: s.mutates,
enabled: unavailable,
run: s.run,
}
} else {
s.clone()
}
})
.collect();
a.session.registry = std::sync::Arc::new(Registry::new(specs));
let mut h = crate::test_harness::builder().with_size(egui::vec2(1920.0, 900.0)).build_eframe(|_| a);
for _ in 0..6 {
h.step();
}
h.state_mut().run("ui.tab", json!({ "tab": "View" })).unwrap();
for _ in 0..3 {
h.step();
}
let node = h
.query_all(egui_kittest::kittest::By::new().role(egui::accesskit::Role::Button))
.into_iter()
.find(|n| n.accesskit_node().label().as_deref().is_some_and(|l| l.replace('\n', " ").contains("Full Screen")))
.expect("the Full Screen button is on the View tab");
assert!(!crate::app::command_board::command_enabled(h.state(), "view.fullScreen"), "the command is unavailable, as the test arranged it",);
assert!(node.accesskit_node().is_disabled(), "a control the command refuses is announced as disabled",);
}
/// #980: in full screen, Escape with text selected collapses the selection (as in a normal
/// window) and leaves full screen alone; the next Escape, with nothing selected, leaves it.
#[test]
@@ -3416,6 +3524,33 @@ fn full_screen_follows_the_window() {
assert!(!a.session.view.full_screen);
}
/// #1678: Focus and Full Screen View put the window in full screen, asked of the system once
/// per change (switching between the two keeps it), and the usual window comes back after.
#[test]
fn focus_and_full_screen_view_ask_for_full_screen_once_per_change() {
use egui::ViewportCommand::Fullscreen;
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| app());
for _ in 0..6 {
h.step();
}
let sent = |h: &mut egui_kittest::Harness<WordApp>| {
let mut out = Vec::new();
for _ in 0..2 {
h.step();
out.extend(h.output().viewport_output.values().flat_map(|v| v.commands.iter()).filter(|c| matches!(c, Fullscreen(_))).cloned());
}
out
};
assert_eq!(sent(&mut h), vec![], "a normal window to start with");
h.state_mut().run("view.focus", json!({})).unwrap();
assert_eq!(sent(&mut h), vec![Fullscreen(true)]);
assert_eq!(sent(&mut h), vec![]);
h.state_mut().run("view.fullScreenView", json!({})).unwrap();
assert_eq!(sent(&mut h), vec![], "Focus to Full Screen View stays full screen");
h.state_mut().run("view.fullScreenView", json!({})).unwrap();
assert_eq!(sent(&mut h), vec![Fullscreen(false)]);
}
/// #312: Dark page darkens only the pages; the interface keeps following its own setting.
#[test]
fn dark_page_leaves_the_interface_theme_alone() {
+59
View File
@@ -34,6 +34,7 @@ struct Recorder {
held: Arc<Mutex<Vec<mpsc::Sender<()>>>>,
never_sent: bool,
names: Vec<&'static str>,
chooses: bool,
}
impl Recorder {
@@ -45,6 +46,7 @@ impl Recorder {
held: Arc::default(),
never_sent: true,
names: vec!["Test queue"],
chooses: true,
}
}
@@ -54,6 +56,12 @@ impl Recorder {
self
}
/// A spooler where the user does not choose a printer (e.g. system print dialog).
fn without_choosing(mut self) -> Self {
self.chooses = false;
self
}
/// A recorder whose cancel answers `never_sent`.
fn cancelling(reply: Reply, never_sent: bool) -> Self {
Recorder { never_sent, ..Recorder::new(reply) }
@@ -76,7 +84,14 @@ impl Recorder {
}
impl SpoolBackend for Recorder {
fn chooses_printer(&self) -> bool {
self.chooses
}
fn printers(&self) -> Option<Vec<craft::print::Printer>> {
if !self.chooses {
return None;
}
Some(
self.names
.iter()
@@ -630,6 +645,50 @@ fn return_on_the_print_page_prints() {
assert_eq!(rec.sent_count(), 2, "Return in the chooser prints nothing");
}
/// #2958: the Print button leads the settings, above the printer and the settings it prints
/// with (as in Word), and it wears the accent the app gives a dialog's primary button, so the
/// page's one action is found first and reads as one rather than as another setting.
#[test]
fn the_print_button_leads_the_settings_and_is_the_primary_action() {
use egui::accesskit::Role;
use egui_kittest::kittest::{By, Queryable};
fn collect_shapes<'a>(shapes: &'a [egui::epaint::ClippedShape], out: &mut Vec<&'a egui::Shape>) {
for clipped in shapes {
fn walk<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
match shape {
egui::Shape::Vec(children) => {
for child in children {
walk(child, out);
}
}
other => out.push(other),
}
}
walk(&clipped.shape, out);
}
}
const BLURB: &str = "Send the document straight to the system print dialog, or save a copy in another format below.";
let mut a = app();
a.services.print = Some(Recorder::new(Reply::Sent).without_choosing().spool());
a.run("file.print", json!({})).unwrap();
let mut h = harness(a);
h.run_steps(4);
// The page's own Print button (the backstage list has a Print entry too): the last.
let print = h.query_all(By::new().role(Role::Button).label("Print")).last().expect("a Print button").rect();
let blurb = h.get_by_label(BLURB).rect();
assert!(print.min.y < blurb.min.y, "the Print button leads the settings: {print:?} above {blurb:?}");
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
let accent = egui::Color32::from(craft::theme::Srgba::from(env.tokens.color.accent.strong));
let mut shapes = Vec::new();
collect_shapes(&h.output().shapes, &mut shapes);
assert!(
shapes.iter().any(|s| matches!(s, egui::Shape::Rect(r) if (r.rect.min.distance(print.min) < 1.0) && r.fill == accent)),
"the Print button is the primary (accent) button"
);
}
/// #3210: a successful native print submission returns to the document, the same as Word —
/// previously the Print page stayed up until the user clicked Back, even though the job had
/// already gone to the spooler. A failed submission stays up instead, so the error (and the
+28
View File
@@ -58,6 +58,16 @@ impl WordApp {
rt.updater = Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).with_translator(translate).with_source(refused_check());
}
/// The Nightly channel's rule: ArtCraft Launcher installs and replaces the nightly build, so
/// this window never checks for, offers or starts one. Nightly-only text is English: it is not
/// one of the stable catalogs' strings.
#[cfg(not(target_arch = "wasm32"))]
pub fn use_launcher_updates(&mut self) {
let rt = &mut self.updates_rt;
rt.startup_check = false;
rt.updater = Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).with_translator(translate).with_source(launcher_check());
}
/// Answers every update check with "up to date" instead of asking GitHub, so a test's result
/// doesn't depend on the network or its rate limit (#7463).
#[cfg(all(test, not(target_arch = "wasm32")))]
@@ -90,6 +100,13 @@ fn refused_check() -> craft::update::updater::CheckSource {
std::sync::Arc::new(move || Err(why.clone().into()))
}
/// A check whose only answer is that the Launcher owns this build's updates.
#[cfg(not(target_arch = "wasm32"))]
fn launcher_check() -> craft::update::updater::CheckSource {
let why = "Updates for WordCraft Nightly are managed by ArtCraft Launcher. Open ArtCraft Launcher to update it.".to_string();
std::sync::Arc::new(move || Err(why.clone().into()))
}
/// Help ▸ Check for Updates. The result dialog opens from [`run`] while the updater has a status.
pub(crate) fn check(app: &mut WordApp) {
#[cfg(not(target_arch = "wasm32"))]
@@ -270,3 +287,14 @@ mod tests {
}
}
}
/// The Nightly channel's rule: the Launcher owns its updates, so a check never reaches the network
/// and says why.
#[cfg(all(test, not(target_arch = "wasm32")))]
mod launcher_updates {
#[test]
fn a_nightly_check_never_reaches_the_network_and_names_the_launcher() {
let error = super::launcher_check()().unwrap_err();
assert!(error.to_string().contains("ArtCraft Launcher"), "{error}");
}
}
+23
View File
@@ -76,4 +76,27 @@ mod tests {
// Scales above 150% (e.g. 175% where half width is ~548.5 pt) clamp up to the 600 pt minimum width.
assert_eq!(requested_size(egui::vec2(548.0, 480.0), 8192.0), Some(egui::vec2(600.0, 480.0)));
}
/// #7317: insane values in requested window geometry are clamped or dropped.
#[test]
fn insane_values_are_clamped_or_dropped() {
// Zero or non-positive width/height are dropped.
assert_eq!(requested_size(egui::vec2(0.0, 800.0), 16384.0), None);
assert_eq!(requested_size(egui::vec2(800.0, 0.0), 16384.0), None);
assert_eq!(requested_size(egui::vec2(-5.0, 800.0), 16384.0), None);
// NaN and infinite values are dropped.
assert_eq!(requested_size(egui::vec2(f32::NAN, 800.0), 16384.0), None);
assert_eq!(requested_size(egui::vec2(800.0, f32::NAN), 16384.0), None);
assert_eq!(requested_size(egui::vec2(f32::INFINITY, 800.0), 16384.0), None);
assert_eq!(requested_size(egui::vec2(800.0, f32::NEG_INFINITY), 16384.0), None);
// Tiny side clamps up to MIN_SIZE, huge side clamps down to MAX_SIZE (16384.0).
let tiny_and_huge = requested_size(egui::vec2(10.0, 1.0e9), 16384.0);
assert_eq!(tiny_and_huge, Some(egui::vec2(MIN_SIZE.x, 16384.0)));
// Sane values within bounds are preserved as-is.
let sane = egui::vec2(1200.0, 800.0);
assert_eq!(requested_size(sane, 16384.0), Some(sane));
}
}
+2
View File
@@ -146,6 +146,8 @@ impl WordApp {
command_catalog_lang: _,
key_overrides: _,
command_states: _,
command_states_cache: _,
keytip_cache: _,
fonts_frames: _,
printing: _,
print_feedback_seen: _,
+22 -4
View File
@@ -43,9 +43,27 @@ use crate::{WordApp, documents, window_geometry::MIN_SIZE, window_ui::WindowUi};
pub(crate) mod arrange;
/// The window title for a document called `name`.
/// The window title for a document called `name`, in the channel this window runs as: a Nightly
/// keeps its name in every document window's title, so the two channels never look alike.
pub(crate) fn title(name: &str, dirty: bool) -> String {
format!("{name}{} - WordCraft", if dirty { " •" } else { "" })
channel_title(name, dirty, crate::os_window::name_for(crate::os_window::identity()))
}
/// [`title`] for an explicit channel name: the stable spelling is unchanged, and a Nightly's keeps
/// its channel after the document and the unsaved dot.
fn channel_title(name: &str, dirty: bool, app: &str) -> String {
format!("{name}{} - {app}", if dirty { " •" } else { "" })
}
#[cfg(test)]
mod channel_title_tests {
#[test]
fn the_channel_name_stays_in_every_document_title() {
assert_eq!(super::channel_title("Document1", false, "WordCraft"), "Document1 - WordCraft");
assert_eq!(super::channel_title("Document1", true, "WordCraft"), "Document1 • - WordCraft");
assert_eq!(super::channel_title("Letter", false, "WordCraft Nightly"), "Letter - WordCraft Nightly");
assert_eq!(super::channel_title("Letter", true, "WordCraft Nightly"), "Letter • - WordCraft Nightly");
}
}
/// The id of the container that shows window `id`; the window host names its viewport by it.
@@ -469,7 +487,7 @@ impl WordApp {
/// The drawn window's title: its document's name as View › Window › Switch Windows gives it.
pub(crate) fn window_title(&self) -> String {
if !self.has_document() {
return "WordCraft".to_string();
return crate::os_window::name_for(crate::os_window::identity()).to_string();
}
let name = self.window_menu().title(self.windows.shown).map(str::to_string).unwrap_or_else(|| self.title_stem());
title(&name, self.session.dirty)
@@ -479,7 +497,7 @@ impl WordApp {
fn title_in(menu: &WindowMenu, id: WindowId) -> String {
match menu.get(id).filter(|e| !e.title.is_empty()) {
Some(e) => title(&e.title, e.dirty),
None => "WordCraft".to_string(),
None => crate::os_window::name_for(crate::os_window::identity()).to_string(),
}
}
+67
View File
@@ -544,3 +544,70 @@ fn nul_in_the_document_title_never_reaches_an_os_window_title() {
}
}
}
/// Issue #117: a viewport command schedules a repaint, so resending an unchanged window title every
/// frame would keep the app redrawing at the monitor's refresh rate while idle. WordCraft supplies
/// a stable `window_title()` to `AppShell` every frame so `craft-libs` (`ui-contract` windows
/// `native.rs`) deduplicates `SetTitle` per viewport and idle frames emit no
/// `ViewportCommand::Title`.
#[test]
fn window_title_is_sent_only_when_it_changes() {
let mut rig = Rig::new();
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
let titles = |rig: &mut Rig, a: &mut WordApp| -> Vec<(ViewportId, String)> {
rig.frame(a);
rig.commands
.iter()
.filter_map(|(v, c)| match c {
ViewportCommand::Title(t) => Some((*v, t.clone())),
_ => None,
})
.collect()
};
let initial_title = a.window_title();
// The title goes out on the first frame that sets it.
assert_eq!(titles(&mut rig, &mut a), vec![(ViewportId::ROOT, initial_title.clone())], "first frame sends the window title");
assert!(titles(&mut rig, &mut a).is_empty(), "subsequent idle frame sends no title");
assert!(titles(&mut rig, &mut a).is_empty(), "steady idle sends no title");
a.run("text.insert", json!({"text": "edit"})).unwrap();
let dirty_title = a.window_title();
assert_ne!(dirty_title, initial_title, "editing the document changes the window title");
assert_eq!(titles(&mut rig, &mut a), vec![(ViewportId::ROOT, dirty_title)], "dirty document changes the title stem, sending it once");
assert!(titles(&mut rig, &mut a).is_empty(), "steady state after edit sends no title");
}
/// When the root window closes and WordCraft promotes another open window into the root viewport,
/// `WordApp::paint_window` supplies the promoted window's `window_title()` every frame so
/// `ViewportId::ROOT` receives the new title once and emits no further `ViewportCommand::Title`
/// while idle (per-viewport deduplication lives in `craft-libs` `ui-contract` windows `native.rs`).
#[test]
fn root_viewport_receives_promoted_windows_title_after_root_closes() {
let mut rig = Rig::new();
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
rig.frames(&mut a, 2);
assert_eq!(a.window_title(), super::title("Document1", false));
a.run("file.new", json!({})).unwrap();
let promoted = a.windows.shown();
let promoted_title = a.window_title();
assert_eq!(promoted_title, super::title("Document2", false));
rig.frames(&mut a, 2);
assert_eq!(a.window_count(), 2);
rig.close(ViewportId::ROOT);
rig.frame(&mut a);
assert_eq!((a.window_count(), a.windows.root.get()), (1, promoted), "the remaining window moves into the root viewport");
let root_titles: Vec<&str> = rig
.commands
.iter()
.filter_map(|(v, c)| match c {
ViewportCommand::Title(t) if *v == ViewportId::ROOT => Some(t.as_str()),
_ => None,
})
.collect();
assert_eq!(root_titles, [promoted_title.as_str()], "root viewport receives the promoted window's title");
rig.frame(&mut a);
let idle_titles = rig.commands.iter().filter(|(v, c)| *v == ViewportId::ROOT && matches!(c, ViewportCommand::Title(_))).count();
assert_eq!(idle_titles, 0, "idle frame after promotion sends no duplicate title");
}
+14
View File
@@ -0,0 +1,14 @@
# The root window hides instead of taking over another document
The first window an app opens is the framework's root window, and the app ends when it closes. WordCraft
used to keep it open when the user closed it with other document windows open: it switched to another
window's document and that window disappeared, so the window the user closed stayed and a different one
vanished (#7752). We decided instead that the root window hides (storytold/craft-libs#584) and adopts
nothing, so the window the user closes is always the one that goes, and the app ends only when the last
document window closes or the user quits.
## Considered options
- **Root takes over another document** (the old behaviour): no framework change, but it is the reported bug,
and the moved window loses its position and size.
- **Root shows no document and stays visible**: leaves an empty window the user did not ask for.
+141
View File
@@ -0,0 +1,141 @@
# Windows, Linux and macOS release-ref nightly: supervised manual go-live
**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and
the signer (`nightly-sign.yml`, on the dedicated `nightly-signer` branch) keep only their exact
context guards and run when one of the reviewed manual actors dispatches them.
`nightly-dispatch.yml` stays literally off: it only forwards scheduled producers. There is no
schedule. The installed policy
[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 policy.
Its `producer_workflow_id` is the registration of `nightly.yml` on main, read with:
```bash
gh api repos/storytold/wordcraft/actions/workflows/nightly.yml --jq .id
```
The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation
permissions are for its isolated attester; its compiler narrows to contents and Actions read
only, with no OIDC, attestation write, release environment or platform signing secrets.
Shared tooling is pinned to `be00e5ccd18b68e950c8a08532f2230e7c3d0cba`, the craft-common-actions
main commit that merged [#371](https://github.com/storytold/craft-common-actions/pull/371) (the
candidate is admitted on the built commit's own Sonar analysis, not main's latest) after
[#370](https://github.com/storytold/craft-common-actions/pull/370) (the Windows and macOS nightly
registry rows for the 14 apps) and
[#369](https://github.com/storytold/craft-common-actions/pull/369) (shared helper checkouts kept out
of the app's clean-source check, and macOS on `macos-15`), following
[#364](https://github.com/storytold/craft-common-actions/pull/364) (the signer may run on the
policy's signer branch) and [#363](https://github.com/storytold/craft-common-actions/pull/363) (the
multi-app pipeline, which makes the signer's `app-name` input required and admits any reviewed
registry app), with #342 (`a4f6fd51`, policy v3 and the `platforms` input) and #339 (`605d5876`)
earlier. Both callers name it in `uses` and `tooling-revision`. A pin is reviewed source
availability, not provider, queue, native signing or crypto qualification.
**Registry admission.** Craft-common-actions #363 ("run the shared nightly pipeline for any reviewed
registry app") is in the pin, and `nightly-apps.json` admits `storytold/wordcraft`. Both callers'
`uses`, `tooling-revision` and the policy pins move together to the same reviewed revision. The
signer also requires the policy's `platforms` map to equal the app's admitted targets, so
WordCraft's `windows-x86_64` and `macos-aarch64` rows need the targets and entrypoints that a
craft-common-actions follow-up adds; until it merges, the first signer run stops at admission.
**First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a
listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `nightly-signer`
with that producer run ID and attempt, by a listed manual actor. `nightly-dispatch.yml` only matters
once a schedule is approved.
**Signer branch.** The signer runs on `refs/heads/nightly-signer`, not on the stable `release`
branch, so nightly signer files never need a stable release sync. The policy's `release_branch`
names it, the signer's guard requires it and the dispatcher targets it. The branch only
fast-forwards to reviewed main commits, through the settings script's `advance` (no queued signer
run, a trust-closure scan, then the full diff of `.github/` and `packaging/`), and the existing
`release` environment trusts it alongside `release`. Its trust closure is all of `.github/` and
`packaging/`, including `packaging/env.sh`, which `packaging/macos/import-cert.sh` sources with
the Apple keys. On that branch only the pinned `nightly-sign.yml` caller may reach an environment:
no app workflow binds one, nothing else calls `nightly-release.yml`, and the only caller of the
shared stable `release.yml` is `release.yml`, whose callee must carry the stable-only environment
guard. The contract tests check the in-repo part on every main PR; the settings scan also resolves
the callee. Stable releases still come only from `refs/heads/release`. History does not carry over
a switch between `release` and `nightly-signer`, so the switch happens before the first
publication.
**Registry admission.** The signer requires the protected policy's `platforms` map to equal the
run app's admitted targets in craft-common-actions' `nightly-apps.json`, and it refuses rather
than sign a subset. WordCraft's row admits `linux-x86_64`; the matching `windows-x86_64` and
`macos-aarch64` targets and entrypoints are a craft-common-actions follow-up, and the first
signer run stops at admission until they merge.
**Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the
producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers
team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team
changes.
**Admission timing.** The candidate check reads the newest CI run on the candidate commit and
main's latest finished Sonar analysis, so pick a quiet main, wait for its CI and SonarCloud analysis
to finish green, then dispatch the producer and, once it succeeds, the signer, before another main
push lands a newer analysis.
**Platform rows.** The producer caller lists
`platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single job: one producer
run builds every listed platform for one all-or-nothing release (one failed or skipped platform stops
that night's release), and the signer admits platforms only from the protected policy, so
there is no separate Linux or macOS caller job and the signer caller has no platform input.
## Installed policy values and their sources
Read on 2026-11-24; re-read anything that may have moved (and fill in `producer_workflow_id` after
`nightly.yml` lands on `main`) before `nightly-signer` is advanced to it.
| Field | Value | Source |
|---|---|---|
| `repository_id` | `1408489772` | `gh api repos/storytold/wordcraft --jq .id` |
| `producer_workflow_id` | `429734489` | `gh api repos/storytold/wordcraft/actions/workflows/nightly.yml --jq .id` |
| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `be00e5cc…` (craft-common-actions #371 after #370, #369 and #364) | The callers' pin |
| `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members; equals the producer caller's `manual-actors` |
| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist |
| `platforms` | three rows | Storytold stable signing identities (Windows Authenticode subject, Linux OpenPGP fingerprint, macOS Apple Team ID `DJ6XS33FX8`) |
| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135788`), `gate / gate (ubuntu-24.04)` | Workflow list API; always-run main push gate job |
| `candidate_policy.sonar` | `storytold` / `storytold_wordcraft`, app `12526` | `sonar-project.properties` |
| Sonar conditions | `new_security_rating` accepted (max 5); the other five required | Standard Storytold SonarCloud quality gate |
| Sonar `issue_types` / `debt` | `VULNERABILITY`; `[]` | Refresh from SonarCloud before `nightly-signer` is advanced to it |
The candidate check refuses whenever main's unresolved vulnerability set differs from `debt`, whether
an issue is new or fixed, and whenever a required condition fails or a listed CI job is renamed. Refresh
those values in the same reviewed change that `nightly-signer` is then advanced to.
## Ownership and interface
- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named
`WordCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets
may be passed or inherited.
- `.github/workflows/nightly-sign.yml`: top-level registration on `nightly-signer`, enabled for manual dispatch,
and only ever fast-forwards to reviewed main commits. It rejects wrong repository/event/actual
branch, including same-name tags. Its constant whole-run concurrency (`wordcraft-nightly-release`,
`queue: max`, `cancel-in-progress: false`) is distinct from stable. The caller itself passes no
credentials; only the shared callee's sign jobs bind the `release` environment, which trusts `release` and
`nightly-signer`.
- `.github/workflows/nightly-dispatch.yml`: transport only, never authorization. It is literally
off (`false &&`) and forwards only a first-attempt scheduled producer to `nightly-sign.yml` on
`nightly-signer`. No schedule is registered until activation is reviewed.
- Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in
`storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable commit**;
the defining workflow SHA and tooling input must match.
- `packaging/windows/sign.ps1 -Required` is the app-owned Windows adapter, invoked only from the
immutable release execution SHA checkout.
## Local regression checks
`python3 packaging/nightly-release-tests.py` verifies:
- Both callers share one full 40-char commit pin in `uses` and `tooling-revision`.
- Both callers keep their exact context guards (reading all continuation lines), have no cache
actions/options or secrets, and register no schedule.
- `nightly-sign.yml` keeps its literal `wordcraft-nightly-release` concurrency group, `queue: max`,
and `cancel-in-progress: false`.
- `manual-actors` in `nightly.yml` and `manual_actors` in `.github/nightly-signing-policy.json` are
identical and equal to the reviewed release managers list, with `automatic_signer_actors` empty.
- `.github/nightly-signing-policy.json` matches the `craft-nightly-release-policy/v3` schema,
repository identity, platform trust anchors, CI workflow trigger, and `sonar-project.properties`.
- The signer guards `refs/heads/nightly-signer`, passes `app-name: wordcraft`, and the policy's
`release_branch` names it.
- A trust-closure scan reads every workflow: nothing binds an `environment`, only `nightly-sign.yml`
calls `nightly-release.yml` (at a full SHA), and the only caller of the shared stable `release.yml`
is `release.yml`.
- `nightly-dispatch.yml` keeps a literal-off guard, a `workflow_run`-only trigger and a
`refs/heads/nightly-signer` request.
+38
View File
@@ -0,0 +1,38 @@
# Implementation plan: closing document windows
For [the specification](../specs/multi-window-close.md) (#7822, part of #7671). Steps run in order; each is
its own PR.
## 1. craft-libs prerequisites (base `next`)
- **Hidden root window** (storytold/craft-libs#584, [ADR 0001](../adr/0001-hidden-root-window.md)): the root
OS window can close or hide while document windows stay open, and adopts nothing.
- **Test kit with any number of windows** (C5-8): `craft_ui_test_kit::windows::Windows` keeps focus and close
events per child, so three-window tests can target one child.
- Not in scope: the cursor on non-root windows (C5-5, `cursor::image_target`) gets its own issue.
## 2. Repin craft-libs in WordCraft
Brings storytold/craft-libs#3290 (one modal stack across windows) and the two changes above. Stage 3 of
#7671 does this repin.
## 3. WordCraft PR (Fixes #7822)
Code is in `crates/ui-egui/src/` unless noted.
| Spec rule | Change |
|---|---|
| 1 | Drop the root taking over another document (`settle_windows` in `windows.rs`); closing the root window closes it through step 1's hidden root. Rewrite `closing_a_window_asks_first_and_the_root_adopts_another`. |
| 2 | `other_window_on_document` filters windows by document (C5-6). |
| 3, 9 | `app::Closing` records the window that owns the prompt. Pumping, cancelling and closing the prompt use that window's dialog host, not the active one. |
| 4, 9 | `run` and `close_decision` check `closing` first: a close while one is running raises the prompt and returns, never calls `begin_closing` again. |
| 9 | Clearing `closing.prompt` in `sync_document` and `apply_close_answer` either continues the close or ends it, so no `Hold` is left with no prompt. `apply_close_answer` matches the guard's document, not the active one. |
| 5 | Cancelling Save As during a close cancels the close or quit (`continue_after_save`). |
| 7 | On one-document-at-a-time hosts, the root close acts on the active entry, not `root_key()`; the fallback layer keeps its close button (C5-1..3). |
| 8 | `file.close` takes `save`; `close_refused` names both options. `ui.closeWindow` takes `window` and defaults to `active_viewport()` (`control/handler.rs`). Update `docs/control-protocol.md` and `docs/mcp.md`. |
| — | `queue_for_window` repaints the target window (C5-7). |
Tests: the table in the specification, in `windows/tests.rs` and `documents.rs`.
Checks: `cargo fmt --all --check`, `cargo clippy -p wordcraft-ui-egui --all-targets -- -D warnings`,
`cargo test -p wordcraft-ui-egui`, `cargo xtask layers`, `cargo xtask wasm`.
+51
View File
@@ -22,9 +22,60 @@ synced from the release manager's machine. On the release branch, the shared wor
macOS and Windows jobs if their signing credentials are missing. Local packaging can still
produce unsigned builds with a warning.
The supervised nightly signer does not sign from `release`: it runs on `refs/heads/nightly-signer`,
which only ever fast-forwards to reviewed main commits, and the `release` environment trusts both
branches. Everything that can reach it is the trust closure: all of `.github/` and `packaging/`,
including `packaging/env.sh`, which `packaging/macos/import-cert.sh` sources with the Apple keys.
Stable releases still come only from `refs/heads/release`.
Local packaging: `packaging/macos/package.sh --arch universal`, `packaging/windows/package.ps1`,
`packaging/linux/package.sh` (then `packaging/linux/flatpak-bundle.sh` for the Flatpak), `packaging/web/package.sh`.
A scheduled dry run runs on `main` nightly at 03:00 UTC. It builds every release target except
macOS, without signing, entering the `release` environment, pushing Flatpak images or making a
draft release. Manual dispatch uses the normal release path (`dry-run` is false).
## The Nightly channel
A separate **Nightly** channel exists beside the release above. Its producer and signer are
**enabled for supervised manual runs only** (no schedule, no automatic dispatch) and its signing
policy is installed; it is not the release dry run above.
What the channel is:
- A build channel: `WORDCRAFT_BUILD_CHANNEL=nightly-v1` (with `WORDCRAFT_VERSION`, `WORDCRAFT_BUILD_SHA`
and `WORDCRAFT_BUILD_DATE`) compiles a `WordCraft Nightly` build with its own version line,
Windows identity and icon. Unset or `stable` stays the ordinary build.
- The Launcher protocol: `--launch-profile nightly-v1 --profile-root <abs> -- files`, with
`--version` answered in both plain and profile form before any state is read. A Nightly build
without a profile is refused (it never falls back to the stable data).
- Its own data: preferences, window place, logs, recovery, fonts, templates, the dictionary, the
suite font store and any control tokens live under that profile, which may not overlap stable
data, the shared font store or an installation.
- Packaging: `packaging/linux/nightly.sh --arch x86_64` (plus the Arch handoff in
`packaging/linux/nightly-arch-tar.sh`), `packaging/windows/package.ps1 -Arch x64 -Nightly
-BuildOnly`, `packaging/macos/nightly.sh --arch aarch64` with `nightly-sign.sh` and
`nightly-verify.sh` for the trusted step, and `packaging/nightly-icons.py` for its icons.
- Qualification: `.github/workflows/nightly-build.yml` builds and checks all three unsigned
archives on the `full-ci` label or on dispatch, with no secrets;
`packaging/nightly-tests.py` runs the synthetic suites in Packaging lint.
Every packaged Linux format ships one launcher (`packaging/linux/nightly-launcher.sh`) that starts
the binary the channel's way, because a Nightly build refuses to run without a profile:
`wordcraft --launch-profile nightly-v1 --profile-root "${XDG_DATA_HOME:-$HOME/.local/share}/wordcraft-nightly" -- "$@"`.
That launcher is the deb/rpm `/usr/bin/wordcraft-nightly` wrapper (real binary in
`/usr/lib/wordcraft-nightly/`), the AppImage `AppRun` (a script, not a symlink, calling
`usr/bin/wordcraft`), the Arch `bin/wordcraft-nightly` launcher (real binary in
`bin/.wordcraft-nightly/`), the plain tar's `bin/wordcraft` (real binary in `lib/wordcraft-nightly/`), which the Flatpak
bundle also installs. The app-owned Nightly tar's `wordcraft` is craft-common-actions' shared
template instead (`packaging/linux/nightly-tar-launch.sh`, #363 rendered for this app), starting
`wordcraft-bin` beside it with
`--profile-root ${XDG_DATA_HOME:-$HOME/.local/share}/ai.storyteller.wordcraft.nightly`, and asking a
bare `--version`/`-V` in the Launcher's form. `XDG_DATA_HOME` keeps the profile on the app's own data directory inside the
Flatpak sandbox (`~/.var/app/ai.storyteller.wordcraft.nightly/data/wordcraft-nightly`), which
persists; the sandbox's home is discarded. Redirecting `XDG_*` alone is refused: the build's root
validator derives the stable boundary from it, so the profile would sit inside it. The launcher
passes an already-supplied Launcher form (`--launch-profile`, and `--version`/`-V`) straight
through, so the ArtCraft Launcher's own root is used and its version check opens no window. The
remaining activation steps are described in
[nightly-release-preparation.md](nightly-release-preparation.md).
+62
View File
@@ -0,0 +1,62 @@
# Closing document windows
Specification for #7822 (part of #7671). Terms are defined in [GLOSSARY.md](../../GLOSSARY.md): **Document
window**, **Save prompt**. The decision on the root window is [ADR 0001](../adr/0001-hidden-root-window.md).
## Rules
1. **A close acts on what its window shows.** Closing a document window (its ✕, the OS close, Ctrl+W or
Ctrl+F4, File › Close) acts only on the document that window shows. No other window changes what it
shows, and no other window disappears. This holds for the first window opened too.
2. **Another window on the same document.** When another document window still shows the document, the
window closes without a Save prompt. The Save prompt is asked only when the last window showing a
document with unsaved changes closes.
3. **The Save prompt belongs to its window.** It appears in the window being closed. While it is up, the
other windows wait; clicking one of them brings the prompt to the front. Its answer is taken from it
whichever window is active.
4. **One close at a time.** A second close request made while a Save prompt is up brings that prompt to the
front and is otherwise ignored, not queued.
5. **Answers.**
- Save: the document is saved, then the window closes.
- Don't Save: the window closes without saving.
- Cancel: nothing closes.
- Save on a never-saved document opens Save As; cancelling Save As cancels the whole close (or quit).
6. **Quit.** Quit asks about each document with unsaved changes in turn, in a window showing it. Save and
Don't Save move to the next; Cancel stops the quit and leaves every remaining window as it was.
7. **One document at a time.** On a host that draws one document at a time (the web app, a full-screen
window, a maximized window on Wayland), ✕, Ctrl+W and File › Close act on the document on screen, and
the most recently used other document is shown next.
8. **Automation follows the same rules.** Over the control channel and MCP:
- `file.close` on a document with unsaved changes needs `save: true` (save, then close) or `force: true`
(close without saving). With neither it closes nothing and returns "unsaved changes: pass save or force".
A close that rule 2 lets through needs neither.
- `ui.closeWindow` takes an optional `window` id and otherwise closes the active window, never the root.
- Automation never leaves a Save prompt waiting for an answer nobody will give.
9. **Nothing gets stuck.** After any answer, cancel, or the prompt's window closing, the app accepts the
next close or quit. In particular:
- a second close cannot replace the first and leave its prompt on screen unanswered;
- clearing the prompt always ends or continues the close, never leaves it half-done;
- cancelling the prompt works whichever window is active;
- an answer given while another window is active is still read;
- an answer over the control channel from another window does not cancel the close.
## Tests
One test per rule and per stuck path; unit tests under 100 ms, app-harness tests under 1 s (#7671).
| Test | Rule |
|---|---|
| Closing the first window of three leaves the other two showing their own documents | 1 |
| Closing a middle window of three closes only its document | 1 |
| ✕ on one of two windows on a modified document asks nothing | 2 |
| ✕ on the last window of a modified document asks, in that window | 2, 3 |
| Clicking another window while the prompt is up raises the prompt | 3 |
| Answering the prompt while another window is active is read | 3, 9 |
| Ctrl+W and ✕ while a prompt is up leave one prompt, and its answer is read | 4, 9 |
| Save, Don't Save and Cancel each do what rule 5 says | 5 |
| Cancelling Save As cancels the close and the quit | 5, 6 |
| Quit with three modified documents asks three times; Cancel on the second keeps two | 6 |
| One-at-a-time host: ✕ closes the document on screen and shows the last used other one | 7 |
| `file.close` without `save`/`force` refuses; with each, saves or discards | 8 |
| `ui.closeWindow` closes the active window, or the one named by `window` | 8 |
| After each of the five stuck paths, a following close and quit both succeed | 9 |
+53 -8
View File
@@ -17,6 +17,12 @@ set -euo pipefail
. "$(dirname "${BASH_SOURCE[0]}")/../env.sh"
HERE="$ROOT/packaging/linux"
APP_ID=ai.storyteller.wordcraft
FLATPAK_ID="$APP_ID"
# The remote indexes both app IDs on the stable ref branch; IDs isolate installations.
FLATPAK_BRANCH=stable
if [[ "${WORDCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
FLATPAK_ID="$APP_ID.nightly"
fi
FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo
TEST=1
@@ -38,7 +44,11 @@ case "$ARCH" in
aarch64 | arm64) ARCH=aarch64 ;;
*) echo "unsupported architecture $ARCH" >&2; exit 2 ;;
esac
BASENAME="wordcraft-$VERSION-linux-$ARCH"
BASENAME_VERSION="$VERSION"
if [[ "$FLATPAK_ID" != "$APP_ID" && "$BASENAME_VERSION" != *-nightly* ]]; then
BASENAME_VERSION="$BASENAME_VERSION-nightly"
fi
BASENAME="wordcraft-$BASENAME_VERSION-linux-$ARCH"
TARBALL="${TARBALL:-$DIST/$BASENAME.tar.gz}"
[[ -f "$TARBALL" ]] || { echo "error: $TARBALL not found (run packaging/linux/package.sh --formats tar first)" >&2; exit 1; }
for tool in flatpak flatpak-builder; do
@@ -52,29 +62,64 @@ rm -rf "$WORK"
mkdir -p "$WORK/stage"
tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1
[[ -x "$WORK/stage/bin/wordcraft" ]] || { echo "error: $TARBALL has no bin/wordcraft" >&2; exit 1; }
cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml"
if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then
sed -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \
-e "s|^Name=WordCraft$|Name=WordCraft Nightly|" \
-e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.wordcraft.nightly-v1|' \
-e '/^MimeType=/d' \
"$WORK/stage/share/applications/$APP_ID.desktop" >"$WORK/stage/share/applications/$FLATPAK_ID.desktop"
rm -f "$WORK/stage/share/applications/$APP_ID.desktop"
sed -e "s|<id>$APP_ID</id>|<id>$FLATPAK_ID</id>|g" \
-e "s|<name>WordCraft</name>|<name>WordCraft Nightly</name>|g" \
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$FLATPAK_ID.desktop</launchable>|g" \
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$FLATPAK_ID</icon>|g" \
-e '/<mediatype>/d' \
"$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" >"$WORK/stage/share/metainfo/$FLATPAK_ID.metainfo.xml"
rm -f "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml"
mv "$WORK/stage/share/mime/packages/$APP_ID.xml" "$WORK/stage/share/mime/packages/$FLATPAK_ID.xml"
rm -rf "$WORK/stage/share/icons/hicolor"
NIGHTLY_ICON="$ROOT/assets/app-icon/wordcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
install -Dm644 "$NIGHTLY_ICON" \
"$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png"
# The nightly tar carries the launcher in bin/wordcraft and the GUI in lib/wordcraft-nightly/;
# the bundle must install both. The launcher keeps the profile under XDG_DATA_HOME, which inside
# the sandbox is this app's own persistent data directory
# (~/.var/app/ai.storyteller.wordcraft.nightly/data), not the throwaway sandbox home.
sed -e "s|ai\.storyteller\.wordcraft|$FLATPAK_ID|g" \
-e 's|^\( - install -Dm755 bin/wordcraft /app/bin/wordcraft\)$|\1\n - install -Dm755 lib/wordcraft-nightly/wordcraft /app/lib/wordcraft-nightly/wordcraft|' \
"$HERE/flatpak/$APP_ID.bundle.yml" >"$WORK/$FLATPAK_ID.yml"
grep -qx ' - install -Dm755 lib/wordcraft-nightly/wordcraft /app/lib/wordcraft-nightly/wordcraft' \
"$WORK/$FLATPAK_ID.yml" || { echo "error: the nightly manifest did not take the launcher's binary" >&2; exit 1; }
else
cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$FLATPAK_ID.yml"
fi
flatpak remote-add --user --if-not-exists flathub "$FLATHUB"
# --disable-rofiles-fuse: no FUSE in containers and CI runners.
flatpak-builder --user --install-deps-from=flathub --disable-rofiles-fuse --force-clean \
--default-branch=stable --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$APP_ID.yml"
--default-branch="$FLATPAK_BRANCH" --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$FLATPAK_ID.yml"
OUT="$DIST/$BASENAME.flatpak"
# --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing.
flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable
flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$FLATPAK_ID" "$FLATPAK_BRANCH"
echo "wrote $OUT"
if [[ "$OCI" = 1 ]]; then
OUT_OCI="$DIST/$BASENAME-oci"
rm -rf "$OUT_OCI"
flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable
flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$FLATPAK_ID" "$FLATPAK_BRANCH"
echo "wrote OCI layout to $OUT_OCI"
fi
if [[ "$TEST" = 1 ]]; then
flatpak install --user -y --noninteractive --reinstall "$OUT"
flatpak info --user "$APP_ID"
flatpak run --command=wordcraft-cli "$APP_ID" --version
flatpak run --command=sh "$APP_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/scalable/apps'
flatpak info --user "$FLATPAK_ID"
flatpak run --command=wordcraft-cli "$FLATPAK_ID" --version
if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then
# The launcher and the GUI it starts are both installed, and the version query answers.
flatpak run --command=wordcraft "$FLATPAK_ID" --version
fi
flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/*/apps'
fi
echo "==> done"
ls -lh "$OUT"
+16 -13
View File
@@ -3,7 +3,7 @@
# exports VERSION and NFPM_ARCH.
#
# nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/
name: wordcraft
name: ${NFPM_NAME}
arch: ${NFPM_ARCH}
platform: linux
version: ${VERSION}
@@ -67,26 +67,29 @@ overrides:
- espeak-ng
contents:
- src: ${STAGE}/usr/bin/wordcraft
dst: /usr/bin/wordcraft
- src: ${STAGE}/usr/bin/${NFPM_BIN}
dst: /usr/bin/${NFPM_BIN}
file_info: { mode: 0755 }
- src: ${STAGE}/usr/bin/wordcraft-cli
dst: /usr/bin/wordcraft-cli
- src: ${STAGE}/usr/bin/${NFPM_CLI}
dst: /usr/bin/${NFPM_CLI}
file_info: { mode: 0755 }
- src: ${STAGE}/usr/lib/
dst: /usr/lib/
type: tree
# Named one by one rather than as a tree of /usr/share: a tree would also own shared directories
# such as /usr/share/mime, which openSUSE's filesystem package owns with other modes, and RPM
# refuses to install a package that conflicts with it.
- src: ${STAGE}/usr/share/applications/ai.storyteller.wordcraft.desktop
dst: /usr/share/applications/ai.storyteller.wordcraft.desktop
- src: ${STAGE}/usr/share/mime/packages/ai.storyteller.wordcraft.xml
dst: /usr/share/mime/packages/ai.storyteller.wordcraft.xml
- src: ${STAGE}/usr/share/metainfo/ai.storyteller.wordcraft.metainfo.xml
dst: /usr/share/metainfo/ai.storyteller.wordcraft.metainfo.xml
- src: ${STAGE}/usr/share/applications/${NFPM_APP_ID}.desktop
dst: /usr/share/applications/${NFPM_APP_ID}.desktop
- src: ${STAGE}/usr/share/mime/packages/${NFPM_APP_ID}.xml
dst: /usr/share/mime/packages/${NFPM_APP_ID}.xml
- src: ${STAGE}/usr/share/metainfo/${NFPM_APP_ID}.metainfo.xml
dst: /usr/share/metainfo/${NFPM_APP_ID}.metainfo.xml
- src: ${STAGE}/usr/share/icons/hicolor/
dst: /usr/share/icons/hicolor/
type: tree
- src: ${STAGE}/usr/share/doc/wordcraft/
dst: /usr/share/doc/wordcraft/
- src: ${STAGE}/usr/share/doc/${NFPM_NAME}/
dst: /usr/share/doc/${NFPM_NAME}/
type: tree
scripts:
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env bash
# Validate the staged Arch launcher without building or opening WordCraft.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
stage="$work/source"
dst="$work/dist"
base=wordcraft-0.0.1-nightly.1-linux-x86_64
mkdir -p "$stage/bin" "$dst" "$work/extract"
# A local argv/env recorder stands in for the compiled binaries. It never opens a UI.
cat >"$stage/bin/wordcraft" <<'RECORDER'
#!/bin/sh
printf 'XDG_CONFIG_HOME=%s\n' "${XDG_CONFIG_HOME:-}"
printf 'XDG_DATA_HOME=%s\n' "${XDG_DATA_HOME:-}"
printf '<%s>\n' "$@"
RECORDER
chmod 755 "$stage/bin/wordcraft"
cp "$stage/bin/wordcraft" "$stage/bin/wordcraft-cli"
bash "$HERE/nightly-arch-tar.sh" "$stage" "$work/stage" "$dst" "$base"
tar -xzf "$dst/$base.tar.gz" -C "$work/extract"
bin="$work/extract/$base/bin"
# Simulate the existing Arch bin-tree copy and public launcher rename.
mkdir -p "$work/installed"
cp -R "$bin" "$work/installed/bin"
bin="$work/installed/bin"
mv "$bin/wordcraft" "$bin/wordcraft-nightly"
mv "$bin/wordcraft-cli" "$bin/wordcraft-nightly-cli"
test ! -e "$stage/bin/.wordcraft-nightly"
cmp "$stage/bin/wordcraft" "$bin/.wordcraft-nightly/wordcraft"
cmp "$stage/bin/wordcraft-cli" "$bin/wordcraft-nightly-cli"
export HOME="$work/home with space"
# The launcher must not redirect XDG_* (the profile holds the state); the recorder prints them so
# a regression to the environment model is visible.
export XDG_CONFIG_HOME="$work/xdg config with space"
export XDG_DATA_HOME="$work/xdg data with space"
expect() {
expected="$1"
shift
actual=$(PATH="$bin:$PATH" wordcraft-nightly "$@")
if [[ "$actual" != "$expected" ]]; then
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
exit 1
fi
}
profile="$XDG_DATA_HOME/wordcraft-nightly"
prefix="$(printf 'XDG_CONFIG_HOME=%s\nXDG_DATA_HOME=%s' "$XDG_CONFIG_HOME" "$XDG_DATA_HOME")"
# Run from a directory that holds no .wordcraft-nightly: a launcher found through PATH must
# resolve its own folder, and must never follow XDG_* to the profile.
cd "$work"
expect "$(printf '%s\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' "$prefix" \
--launch-profile nightly-v1 --profile-root "$profile" --)"
expect "$(printf '%s\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' "$prefix" \
--launch-profile nightly-v1 --profile-root "$profile" -- 'doc with spaces.docx' '--other-name.docx')" \
'doc with spaces.docx' '--other-name.docx'
expect "$(printf '%s\n<%s>' "$prefix" --version)" --version
expect "$(printf '%s\n<%s>' "$prefix" -V)" -V
# The ArtCraft Launcher's form passes through untouched: wrapping it again would make its tokens
# file names and ignore the root it chose.
root="$work/launcher profile with space"
expect "$(printf '%s\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' "$prefix" \
--launch-profile nightly-v1 --profile-root "$root" -- 'a.docx')" \
--launch-profile nightly-v1 --profile-root "$root" -- 'a.docx'
expect "$(printf '%s\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' "$prefix" \
--launch-profile nightly-v1 --profile-root "$root" --version)" \
--launch-profile nightly-v1 --profile-root "$root" --version
echo "PASS: Arch Nightly handoff isolates the profile and preserves launch arguments"
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
# Stage the WordCraft Nightly-only handoff for the Arch packager.
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
source_tree="$1"
work="$2"
destination="$3"
basename="$4"
stage="$work/$basename"
mkdir -p "$work"
cp -R "$source_tree" "$stage"
mkdir "$stage/bin/.wordcraft-nightly"
mv "$stage/bin/wordcraft" "$stage/bin/.wordcraft-nightly/wordcraft"
cp "$here/nightly-launcher.sh" "$stage/bin/wordcraft"
chmod 755 "$stage/bin/wordcraft"
tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename"
echo "wrote $destination/$basename.tar.gz"
+53
View File
@@ -0,0 +1,53 @@
#!/bin/sh
# The Nightly channel's launcher, installed by every Linux format in place of the GUI binary.
#
# A Nightly keeps all of its user state in its own launch profile, so the launcher adds
# `--launch-profile nightly-v1 --profile-root ...` and passes the user's arguments after `--`.
# Redirecting XDG_* instead is refused by the build's profile validator, which derives the stable
# boundary from the environment, so the chosen profile would sit inside that boundary.
#
# The GUI sits beside the launcher in one of these layouts:
# wordcraft-bin an unpacked app-owned nightly tar (nightly.sh)
# .wordcraft-nightly/wordcraft the Arch handoff (nightly-arch-tar.sh)
# ../lib/wordcraft-nightly/wordcraft deb/rpm and the plain FHS tar (package.sh)
# usr/bin/wordcraft an AppImage, whose AppRun is this launcher
# The path is resolved from this script, never from the working directory, and only a regular
# executable is used.
#
# The ArtCraft Launcher starts the tar's `wordcraft` with the profile form already supplied
# (`--launch-profile nightly-v1 --profile-root <abs> -- files`, or `--version` for its check).
# That form passes straight through: wrapping it again would turn its tokens into file names and
# ignore the root the Launcher chose. `--version`/`-V` do too, so a version check opens no window
# and creates no profile.
set -eu
case $0 in
*/*) self=$0 ;;
*) self=$(command -v -- "$0") || { echo "wordcraft: cannot locate this launcher" >&2; exit 2; } ;;
esac
here=$(CDPATH='' cd -- "$(dirname -- "$self")" && pwd -P) \
|| { echo "wordcraft: cannot resolve this launcher's folder" >&2; exit 2; }
real_bin=
for candidate in \
"$here/wordcraft-bin" \
"$here/.wordcraft-nightly/wordcraft" \
"$here/../lib/wordcraft-nightly/wordcraft" \
"$here/usr/bin/wordcraft"
do
if [ -f "$candidate" ] && [ -x "$candidate" ]; then
real_bin=$candidate
break
fi
done
[ -n "$real_bin" ] || { echo "wordcraft: cannot find the Nightly GUI next to $here" >&2; exit 2; }
case ${1:-} in
--launch-profile | --version | -V) exec "$real_bin" "$@" ;;
esac
data_home=${XDG_DATA_HOME:-}
if [ -z "$data_home" ]; then
data_home=${HOME:?HOME is required}/.local/share
fi
exec "$real_bin" --launch-profile nightly-v1 --profile-root "$data_home/wordcraft-nightly" -- "$@"
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env bash
# Render the Nightly Linux tar exactly as package.sh does, without building or opening WordCraft,
# and run the launcher it installs. Guards the tar step's paths and the launcher's argument rules.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$HERE/../.." && pwd)"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
export CARGO_TARGET_DIR="$work/target"
export DIST="$work/dist"
export WORDCRAFT_BUILD_CHANNEL=nightly-v1
export WORDCRAFT_VERSION="0.0.0-nightly.20260101.1.1.g0123456789ab"
export WORDCRAFT_BUILD_DATE="2026-01-01"
mkdir -p "$CARGO_TARGET_DIR/release" "$DIST"
# A local argv recorder stands in for the compiled binaries. It never opens a UI.
cat >"$CARGO_TARGET_DIR/release/wordcraft" <<'RECORDER'
#!/bin/sh
printf '<%s>\n' "$@"
RECORDER
cp "$CARGO_TARGET_DIR/release/wordcraft" "$CARGO_TARGET_DIR/release/wordcraft-cli"
chmod 755 "$CARGO_TARGET_DIR/release/wordcraft" "$CARGO_TARGET_DIR/release/wordcraft-cli"
# The tar format is first in package.sh's default set; a broken nightly tar aborted every run here.
(cd "$ROOT" && bash packaging/linux/package.sh --skip-build --formats tar)
base="wordcraft-$WORDCRAFT_VERSION-linux-$(uname -m)"
archive="$DIST/$base.tar.gz"
[ -f "$archive" ] || { echo "error: package.sh wrote no $archive" >&2; exit 1; }
tar -xzf "$archive" -C "$work"
tree="$work/$base"
# The FHS tree the desktop file and the Flatpak bundle expect: the launcher in bin/, the GUI in
# lib/wordcraft-nightly/.
[ -x "$tree/bin/wordcraft" ] && [ ! -L "$tree/bin/wordcraft" ] || { echo 'error: bin/wordcraft is not the launcher' >&2; exit 1; }
[ -x "$tree/lib/wordcraft-nightly/wordcraft" ] || { echo 'error: no GUI in lib/wordcraft-nightly' >&2; exit 1; }
cmp "$tree/lib/wordcraft-nightly/wordcraft" "$CARGO_TARGET_DIR/release/wordcraft"
cmp "$tree/bin/wordcraft" "$HERE/nightly-launcher.sh"
home="$work/home with space"
mkdir -p "$home"
expect() {
expected="$1"
shift
actual=$(env -i HOME="$home" PATH="/usr/bin:/bin" "$tree/bin/wordcraft" "$@")
if [ "$actual" != "$expected" ]; then
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
exit 1
fi
}
profile="$home/.local/share/wordcraft-nightly"
expect "$(printf '<%s>\n<%s>\n<%s>\n<%s>\n<%s>' \
--launch-profile nightly-v1 --profile-root "$profile" --)"
expect "$(printf '<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' \
--launch-profile nightly-v1 --profile-root "$profile" -- 'doc with spaces.docx' '--other-name.docx')" \
'doc with spaces.docx' '--other-name.docx'
expect "$(printf '<%s>' --version)" --version
expect "$(printf '<%s>' -V)" -V
# The ArtCraft Launcher's own form passes through untouched, including the root it chose.
root="$work/launcher profile with space"
expect "$(printf '<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' \
--launch-profile nightly-v1 --profile-root "$root" -- 'a.docx')" \
--launch-profile nightly-v1 --profile-root "$root" -- 'a.docx'
expect "$(printf '<%s>\n<%s>\n<%s>\n<%s>\n<%s>' \
--launch-profile nightly-v1 --profile-root "$root" --version)" \
--launch-profile nightly-v1 --profile-root "$root" --version
# A data directory the person set themselves (and the Flatpak sandbox's own) keeps the profile
# beside the stable folder rather than on the throwaway home.
data="$work/xdg data with space"
mkdir -p "$data"
actual=$(env -i HOME="$home" XDG_DATA_HOME="$data" PATH="/usr/bin:/bin" "$tree/bin/wordcraft" --version)
[ "$actual" = '<--version>' ]
actual=$(env -i HOME="$home" XDG_DATA_HOME="$data" PATH="/usr/bin:/bin" "$tree/bin/wordcraft" 'x.docx')
[ "$actual" = "$(printf '<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' --launch-profile nightly-v1 --profile-root "$data/wordcraft-nightly" -- x.docx)" ]
# A launcher found through PATH still resolves its own folder, never the working directory.
mkdir -p "$work/elsewhere"
actual=$(cd "$work/elsewhere" && env -i HOME="$home" PATH="$tree/bin:/usr/bin:/bin" wordcraft --version)
[ "$actual" = '<--version>' ]
# The other two layouts the same file is installed in: the AppImage (AppRun beside usr/bin) and
# the app-owned nightly tar (wordcraft-bin beside the launcher).
mkdir -p "$work/AppDir/usr/bin" "$work/flat"
install -m 755 "$HERE/nightly-launcher.sh" "$work/AppDir/AppRun"
cp "$CARGO_TARGET_DIR/release/wordcraft" "$work/AppDir/usr/bin/wordcraft"
install -m 755 "$HERE/nightly-launcher.sh" "$work/flat/wordcraft"
cp "$CARGO_TARGET_DIR/release/wordcraft" "$work/flat/wordcraft-bin"
for layout in "$work/AppDir/AppRun" "$work/flat/wordcraft"; do
actual=$(env -i HOME="$home" PATH="/usr/bin:/bin" "$layout" 'x.docx')
[ "$actual" = "$(printf '<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' --launch-profile nightly-v1 --profile-root "$home/.local/share/wordcraft-nightly" -- x.docx)" ] \
|| { echo "error: $layout did not wrap: $actual" >&2; exit 1; }
actual=$(env -i HOME="$home" PATH="/usr/bin:/bin" "$layout" --version)
[ "$actual" = '<--version>' ] || { echo "error: $layout did not pass --version: $actual" >&2; exit 1; }
done
echo "PASS: the Nightly tar starts the GUI through its launcher and keeps the profile it is given"
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env bash
# The launcher inside the plain Nightly tar (packaging/linux/nightly-tar-launch.sh): craft-common-actions'
# template rendered for WordCraft. Every argument follows the profile tokens, the profile root is the
# package identity under the XDG data home (or HOME), and a version query is asked in the Launcher's
# own form so the GUI answers before any profile is read.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
mkdir -p "$work/tar"
cat >"$work/tar/wordcraft-bin" <<'RECORDER'
#!/bin/sh
printf '<%s>\n' "$@"
RECORDER
chmod 755 "$work/tar/wordcraft-bin"
install -m 755 "$HERE/nightly-tar-launch.sh" "$work/tar/wordcraft"
# The bytes are the shared template rendered for this app, not a local script.
sha256sum "$HERE/nightly-tar-launch.sh" | cut -d' ' -f1 | grep -qx \
982164049ab06cd805fd41aa9b9f66624628e6ac34d63848043f3fd780fef6c5 || {
echo "FAIL: nightly-tar-launch.sh is not the shared template rendered for wordcraft" >&2
exit 1
}
home="$work/home with space"
mkdir -p "$home"
identity="ai.storyteller.wordcraft.nightly"
expect() {
local root="$1" actual
shift
actual=$(env -i HOME="$home" PATH="/usr/bin:/bin" "$work/tar/wordcraft" "$@")
[ "$actual" = "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$root" -- "$@")" ] || {
printf 'expected:\n%s\nactual:\n%s\n' \
"$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$root" -- "$@")" "$actual" >&2
exit 1
}
}
expect_query() {
local root="$1" actual
for flag in --version -V; do
actual=$(env -i HOME="$home" PATH="/usr/bin:/bin" "$work/tar/wordcraft" "$flag")
[ "$actual" = "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$root" --version)" ] || {
printf 'expected:\n%s\nactual:\n%s\n' \
"$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$root" --version)" "$actual" >&2
exit 1
}
done
}
expect "$home/.local/share/$identity"
expect "$home/.local/share/$identity" 'doc with spaces.docx' '--other-name.docx'
expect_query "$home/.local/share/$identity"
data="$work/xdg data with space"
actual=$(env -i HOME="$home" XDG_DATA_HOME="$data" PATH="/usr/bin:/bin" "$work/tar/wordcraft" 'x.docx')
[ "$actual" = "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$data/$identity" -- x.docx)" ]
[ ! -e "$data" ] || { echo "FAIL: the launcher created the profile folder" >&2; exit 1; }
# The ArtCraft Launcher names its own profile and per-install root: the argv goes to the GUI unchanged.
actual=$(env -i HOME="$home" PATH="/usr/bin:/bin" "$work/tar/wordcraft" \
--launch-profile nightly-v1 --profile-root "$work/launcher profile with space" -- 'a.docx')
[ "$actual" = "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$work/launcher profile with space" -- a.docx)" ]
# The launcher found through PATH still resolves the GUI beside itself.
mkdir -p "$work/elsewhere"
actual=$(cd "$work/elsewhere" && env -i HOME="$home" PATH="$work/tar:/usr/bin:/bin" wordcraft 'x.docx')
[ "$actual" = "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$home/.local/share/$identity" -- x.docx)" ]
# The flat tar nightly.sh stages: `wordcraft` beside `wordcraft-bin`, nothing else.
source="$HERE/nightly.sh"
# The pattern is the literal source text, not an expansion in this script.
# shellcheck disable=SC2016
grep -q 'nightly-tar-launch.sh" "$STAGE/wordcraft"' "$source" || {
echo "FAIL: nightly.sh does not stage the template as wordcraft" >&2
exit 1
}
echo "PASS: the flat tar launcher is the shared template and starts the GUI through the channel's profile"
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
# Nightly launcher generated by craft-common-actions scripts/nightly-launcher.sh.in. Do not edit:
# the shared nightly producer accepts this file only byte for byte as rendered for the app.
set -eu
dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd -P)
readonly dir
target="$dir/wordcraft-bin"
readonly target
profile_root="${XDG_DATA_HOME:-$HOME/.local/share}/ai.storyteller.wordcraft.nightly"
readonly profile_root
case "${1-}" in
# The ArtCraft Launcher passes its own profile and per-install root; the app validates the pair.
--launch-profile) exec "$target" "$@" ;;
--version | -V) exec "$target" --launch-profile nightly-v1 --profile-root "$profile_root" --version ;;
esac
exec "$target" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@"
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks.
set -euo pipefail
ARCH=
while [[ $# -gt 0 ]]; do
case "$1" in
--arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;;
-h|--help) echo 'Usage: nightly.sh --arch x86_64'; exit 0 ;;
*) echo "unsupported nightly argument: $1" >&2; exit 2 ;;
esac
done
[[ "$ARCH" == x86_64 && "$(uname -s)" == Linux ]] || { echo 'only native Linux x86_64 nightly packaging is supported' >&2; exit 2; }
# shellcheck source=../nightly-common.sh
. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh"
nightly_init linux "$ARCH" x86_64-unknown-linux-gnu
OUTPUT="$DIST/wordcraft-$VERSION-linux-x86_64-nightly.tar.gz"
[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive'
nightly_build_gui
STAGE="$NIGHTLY_WORK/stage"
mkdir -p "$STAGE"
# An unpacked GUI tar is isolated too: `wordcraft` is the channel's launcher and `wordcraft-bin`
# is the GUI it starts beside it. Redirecting XDG_* instead is refused by the build's root
# validator. This launcher is craft-common-actions' canonical template rendered for this app
# (scripts/nightly_app.py launcher); every packaged format keeps packaging/linux/nightly-launcher.sh.
cp "$NIGHTLY_GUI" "$STAGE/wordcraft-bin"
chmod 755 "$STAGE/wordcraft-bin"
install -m 755 "$ROOT/packaging/linux/nightly-tar-launch.sh" "$STAGE/wordcraft"
NIGHTLY_ICON="$ROOT/assets/app-icon/wordcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/wordcraft-1024.png"
cp "$NIGHTLY_ICON" "$STAGE/wordcraft-nightly.png"
nightly_copy_notices "$STAGE"
# The private mktemp cwd is the helper authority root, not a CLI path parent.
(cd "$NIGHTLY_WORK" && python3 "$ROOT/packaging/nightly-archive.py" linux stage archive.tar.gz)
nightly_publish_archive "$NIGHTLY_WORK/archive.tar.gz" "$OUTPUT"
+143 -10
View File
@@ -7,7 +7,7 @@
# $DIST/wordcraft-<version>-linux-<arch>.rpm Fedora, openSUSE, RHEL, ...
# $DIST/wordcraft-<version>-linux-<arch>.tar.gz plain FHS-style tree (bin/, share/)
#
# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"]
# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] [--arch-tar-dir DIRECTORY]
#
# Needs: cargo; nfpm for deb/rpm (https://nfpm.goreleaser.com); appimagetool for the AppImage
# (downloaded into $CARGO_TARGET_DIR if missing). Build on an old distro (CI: Ubuntu 22.04,
@@ -21,10 +21,16 @@ APP_ID=ai.storyteller.wordcraft
SKIP_BUILD=0
FORMATS="appimage deb rpm tar"
ARCH_TAR_DIR=
while [[ $# -gt 0 ]]; do
case "$1" in
--skip-build) SKIP_BUILD=1; shift ;;
--formats) FORMATS="$2"; shift 2 ;;
--arch-tar-dir)
[[ -n "${2:-}" ]] || { echo "error: --arch-tar-dir needs a directory" >&2; exit 2; }
ARCH_TAR_DIR="$2"
shift 2
;;
-h | --help) sed -n '2,17p' "$0"; exit 0 ;;
*) echo "unknown argument: $1" >&2; exit 2 ;;
esac
@@ -38,9 +44,23 @@ case "$ARCH" in
*) echo "unsupported architecture $ARCH" >&2; exit 2 ;;
esac
export WORDCRAFT_MAINTAINER="${WORDCRAFT_MAINTAINER:-WordCraft maintainers <wordcraft@storyteller.ai>}"
BASENAME="wordcraft-$VERSION-linux-$ARCH"
IS_NIGHTLY=0
if [[ "${WORDCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
IS_NIGHTLY=1
export WORDCRAFT_BUILD_CHANNEL=nightly-v1
fi
BASENAME_VERSION="$VERSION"
if [[ "$IS_NIGHTLY" = 1 && "$BASENAME_VERSION" != *-nightly* ]]; then
BASENAME_VERSION="$BASENAME_VERSION-nightly"
fi
BASENAME="wordcraft-$BASENAME_VERSION-linux-$ARCH"
echo "==> WordCraft $VERSION for Linux $ARCH ($FORMATS)"
if [[ -n "$ARCH_TAR_DIR" && "$IS_NIGHTLY" != 1 ]]; then
echo "error: --arch-tar-dir is only for Nightly builds" >&2
exit 2
fi
echo "==> WordCraft $VERSION for Linux $ARCH ($FORMATS, channel=${WORDCRAFT_BUILD_CHANNEL:-stable})"
if [[ "$SKIP_BUILD" = 0 ]]; then
if [[ -n "${CROSS_TARGET:-}" ]]; then
@@ -59,6 +79,11 @@ install -Dm755 "$BIN/wordcraft" "$STAGE/usr/bin/wordcraft"
install -Dm755 "$BIN/wordcraft-cli" "$STAGE/usr/bin/wordcraft-cli"
"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/wordcraft" "$STAGE/usr/bin/wordcraft-cli" 2>/dev/null || true
install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop"
if [[ "$IS_NIGHTLY" = 1 ]]; then
sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.wordcraft.nightly-v1|' \
"$STAGE/usr/share/applications/$APP_ID.desktop" >"$STAGE/usr/share/applications/$APP_ID.desktop.tmp"
mv "$STAGE/usr/share/applications/$APP_ID.desktop.tmp" "$STAGE/usr/share/applications/$APP_ID.desktop"
fi
install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml"
mkdir -p "$STAGE/usr/share/metainfo"
sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$WORDCRAFT_BUILD_DATE/g" \
@@ -77,21 +102,99 @@ fi
has() { local item="$1"; case " $FORMATS " in *" $item "*) return 0 ;; *) return 1 ;; esac; }
# The Nightly channel starts only through its own launch profile, which holds every piece of user
# state (preferences, window place, logs, recovery, fonts, templates, the dictionary and the suite
# font store). Redirecting XDG_* instead is refused: the build's root validator derives the stable
# boundary from it, so the chosen profile would sit inside it. One launcher serves every format
# (packaging/linux/nightly-launcher.sh); it finds the GUI in ../lib/wordcraft-nightly/wordcraft,
# the layout the packages, the plain tar and the Flatpak bundle built from that tar install.
nightly_launcher() {
install -Dm755 "$HERE/nightly-launcher.sh" "$1"
}
# ---- .tar.gz ------------------------------------------------------------------------------------
if has tar; then
mkdir -p "$WORK/tar"
cp -R "$STAGE/usr" "$WORK/tar/$BASENAME"
if [[ "$IS_NIGHTLY" = 1 ]]; then
# An unpacked nightly tar is isolated too: the launcher keeps the desktop file's Exec
# (bin/wordcraft) and the real binary moves to lib/wordcraft-nightly/, the layout the
# deb/rpm wrapper and the Flatpak bundle built from this tar use as well. The tar holds the
# contents of usr/, so these paths have no usr/ component.
install -d "$WORK/tar/$BASENAME/lib/wordcraft-nightly"
mv "$WORK/tar/$BASENAME/bin/wordcraft" "$WORK/tar/$BASENAME/lib/wordcraft-nightly/wordcraft"
nightly_launcher "$WORK/tar/$BASENAME/bin/wordcraft"
fi
tar -C "$WORK/tar" -czf "$DIST/$BASENAME.tar.gz" "$BASENAME"
echo "wrote $DIST/$BASENAME.tar.gz"
fi
# The Arch handoff keeps the same basename as the plain tarball in a separate directory. It
# stages the plain usr/ tree (GUI in bin/, no launcher), then installs its own launcher there.
if [[ -n "$ARCH_TAR_DIR" ]]; then
mkdir -p "$ARCH_TAR_DIR"
if [[ "$(cd "$ARCH_TAR_DIR" && pwd -P)" == "$(cd "$DIST" && pwd -P)" ]]; then
echo "error: the Arch tar directory must differ from the release directory" >&2
exit 2
fi
bash "$HERE/nightly-arch-tar.sh" "$STAGE/usr" "$WORK/arch-tar" "$ARCH_TAR_DIR" "$BASENAME"
fi
# ---- .deb / .rpm --------------------------------------------------------------------------------
if has deb || has rpm; then
command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; }
export VERSION
export NFPM_ARCH="$DEB_ARCH"
NFPM_STAGE="$STAGE"
export NFPM_NAME="wordcraft"
export NFPM_BIN="wordcraft"
export NFPM_CLI="wordcraft-cli"
export NFPM_APP_ID="$APP_ID"
if [[ "$IS_NIGHTLY" = 1 ]]; then
NIGHTLY_DESK_ID="$APP_ID.nightly-v1"
export NFPM_NAME="wordcraft-nightly"
export NFPM_BIN="wordcraft-nightly"
export NFPM_CLI="wordcraft-nightly-cli"
export NFPM_APP_ID="$NIGHTLY_DESK_ID"
NFPM_STAGE="$WORK/nfpm-root"
rm -rf "$NFPM_STAGE"
cp -R "$STAGE" "$NFPM_STAGE"
install -Dm755 "$NFPM_STAGE/usr/bin/wordcraft" "$NFPM_STAGE/usr/lib/wordcraft-nightly/wordcraft"
nightly_launcher "$NFPM_STAGE/usr/bin/$NFPM_BIN"
rm -f "$NFPM_STAGE/usr/bin/wordcraft"
mv "$NFPM_STAGE/usr/bin/wordcraft-cli" "$NFPM_STAGE/usr/bin/$NFPM_CLI"
mv "$NFPM_STAGE/usr/share/doc/wordcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME"
sed -e "s#^Exec=wordcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \
-e "s|^TryExec=wordcraft$|TryExec=$NFPM_BIN|" \
-e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \
-e "s|^Name=WordCraft$|Name=WordCraft Nightly|" \
-e '/^MimeType=/d' \
"$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" >"$NFPM_STAGE/usr/share/applications/$NIGHTLY_DESK_ID.desktop"
rm -f "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop"
sed -e "s|<id>$APP_ID</id>|<id>$NIGHTLY_DESK_ID</id>|g" \
-e "s|<name>WordCraft</name>|<name>WordCraft Nightly</name>|g" \
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$NIGHTLY_DESK_ID.desktop</launchable>|g" \
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$NIGHTLY_DESK_ID</icon>|g" \
-e "s|<binary>wordcraft</binary>|<binary>$NFPM_BIN</binary>|g" \
-e '/<mediatype>/d' \
"$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" >"$NFPM_STAGE/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml"
rm -f "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml"
rm -rf "$NFPM_STAGE/usr/share/mime"
rm -rf "$NFPM_STAGE/usr/share/icons/hicolor"
NIGHTLY_ICON="$ROOT/assets/app-icon/wordcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
install -Dm644 "$NIGHTLY_ICON" \
"$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png"
fi
# nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`.
sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
DROP_LIB_TREE=
# shellcheck disable=SC2016
[[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;'
DROP_MIME=
# shellcheck disable=SC2016
[[ -f "$NFPM_STAGE/usr/share/mime/packages/$NFPM_APP_ID.xml" ]] || DROP_MIME='\|^ - src: \${STAGE}/usr/share/mime/packages/|,+1d;'
# shellcheck disable=SC2016
sed "${DROP_LIB_TREE}${DROP_MIME}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g;s|\${NFPM_APP_ID}|$NFPM_APP_ID|g;s|\${NFPM_NAME}|$NFPM_NAME|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
for fmt in deb rpm; do
if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi
done
@@ -131,10 +234,31 @@ if has appimage; then
}
APPDIR="$WORK/WordCraft.AppDir"
cp -R "$STAGE" "$APPDIR"
ln -s usr/bin/wordcraft "$APPDIR/AppRun"
cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop"
cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png"
ln -s "$APP_ID.png" "$APPDIR/.DirIcon"
if [[ "$IS_NIGHTLY" = 1 ]]; then
APPIMAGE_ID="$APP_ID.nightly-v1"
# A real file, not a symlink to the binary: the Nightly build starts only through its own
# launch profile, which holds every piece of user state. The launcher finds the GUI in
# usr/bin/wordcraft inside this AppDir.
nightly_launcher "$APPDIR/AppRun"
sed -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \
-e "s|^Name=WordCraft$|Name=WordCraft Nightly|" \
-e '/^MimeType=/d' \
"$APPDIR/usr/share/applications/$APP_ID.desktop" >"$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop"
rm -f "$APPDIR/usr/share/applications/$APP_ID.desktop"
cp "$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" "$APPDIR/$APPIMAGE_ID.desktop"
rm -rf "$APPDIR/usr/share/icons/hicolor"
NIGHTLY_ICON="$ROOT/assets/app-icon/wordcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
install -Dm644 "$NIGHTLY_ICON" \
"$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png"
cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png"
ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon"
else
ln -s usr/bin/wordcraft "$APPDIR/AppRun"
cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop"
cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png"
ln -s "$APP_ID.png" "$APPDIR/.DirIcon"
fi
TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}"
if [[ -z "$TOOL" ]]; then
@@ -162,12 +286,21 @@ if has appimage; then
# each AppImage on GitHub Releases. `latest` is the newest published release that is not a
# pre-release. A fork's builds point at its own releases through GITHUB_REPOSITORY.
REPO="${GITHUB_REPOSITORY:-storytold/wordcraft}"
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|wordcraft-*-linux-$ARCH.AppImage.zsync"
UPDATE_ARGS=()
if [[ "$IS_NIGHTLY" = 0 ]]; then
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|wordcraft-*-linux-$ARCH.AppImage.zsync"
UPDATE_ARGS=(-u "$UPDATE_INFO")
else
# Nightly releases are GitHub pre-releases (`latest` only selects stable releases), so point
# zsync update metadata at pre-release tags matching `-nightly` rather than stable `latest`.
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|wordcraft-*-nightly*-linux-$ARCH.AppImage.zsync"
UPDATE_ARGS=(-u "$UPDATE_INFO")
fi
# Extract-and-run: works without FUSE (containers, CI). The output embeds the pinned static
# runtime, so users don't need libfuse2 either. With zsyncmake on the host (CI installs the zsync
# package) appimagetool also writes the .zsync, into its working directory, hence the cd.
(cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream \
--runtime-file "$RUNTIME" -u "$UPDATE_INFO" "$APPDIR" "$OUT")
--runtime-file "$RUNTIME" "${UPDATE_ARGS[@]}" "$APPDIR" "$OUT")
echo "wrote $OUT"
if [[ -s "$OUT.zsync" ]]; then
echo "wrote $OUT.zsync"

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