Compare commits

..
141 changed files with 656 additions and 9327 deletions
-16
View File
@@ -1,16 +0,0 @@
-----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
@@ -1,107 +0,0 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/gridcraft",
"repository_id": 1408285582,
"producer_workflow_id": 429713469,
"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": "gridcraft-nightly-20261124",
"repository": "storytold/gridcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 380135773,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_gridcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_gridcraft&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"
}
}
}
}
-2
View File
@@ -9,8 +9,6 @@ workflows:
'.github/workflows/lockfile.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/nightly-sign.yml': []
'.github/workflows/nightly.yml': []
'.github/workflows/nix.yml': []
'.github/workflows/packaging-lint.yml':
- 'actions/checkout@v7.0.1'
-45
View File
@@ -1,45 +0,0 @@
name: GridCraft 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: gridcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
if: >-
github.repository == 'storytold/gridcraft' &&
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: gridcraft
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 release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
-34
View File
@@ -1,34 +0,0 @@
name: GridCraft 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/gridcraft' &&
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: gridcraft
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"]'
+2 -21
View File
@@ -5,9 +5,9 @@ name: Packaging lint
on:
push:
branches: [main, release]
paths: [".github/workflows/**", ".github/nightly-linux-signing-key.asc", "packaging/**", "assets/app-icon/**", "sonar-project.properties"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
pull_request:
paths: [".github/workflows/**", ".github/nightly-linux-signing-key.asc", "packaging/**", "assets/app-icon/**", "sonar-project.properties"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
workflow_dispatch:
permissions:
@@ -22,25 +22,6 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main
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@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Run the synthetic nightly packaging suites
run: python3 packaging/nightly-tests.py
- name: Check the committed nightly icons still match their provenance
run: python3 packaging/nightly-icons.py --check
windows-install-policy:
timeout-minutes: 10
name: Windows installation policy (no app build)
-6
View File
@@ -8,9 +8,3 @@ plan/
/.claude/
/target-*/
/craft-fonts/
# Checked out inside the workspace by the shared nightly workflows (craft-common-actions).
/.nightly-tools
/.nightly-input
/craft-i18n
__pycache__/
+69
View File
@@ -0,0 +1,69 @@
# 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
**GridCraft** (`storytold/gridcraft`) is an open-source spreadsheet application written in pure Rust.
- **Published application builds:** macOS, Windows, Linux, FreeBSD, and Web (WebAssembly)
- **Command-line and automation interface:** `gridcraft-cli` provides headless terminal and automation access for scripted workflows without the graphical interface
- **Report an accessibility barrier:** [Open an issue in `storytold/gridcraft`](https://github.com/storytold/gridcraft/issues/new)
- **Tracked accessibility issues:** [Open issues labelled `accessibility` in `storytold/gridcraft`](https://github.com/storytold/gridcraft/issues?q=is%3Aissue+state%3Aopen+label%3Aaccessibility)
- **Pull requests awaiting assistive-technology verification:** [Pull requests labelled `needs screen reader test` in `storytold/gridcraft`](https://github.com/storytold/gridcraft/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
@@ -38,12 +38,6 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra
| `assets/app-icon/hicolor/256x256/apps/ai.storyteller.gridcraft.png` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, Linux hicolor render |
| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.gridcraft.png` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, Linux hicolor render |
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.gridcraft.svg` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, copy of gridcraft.svg |
| `assets/app-icon/gridcraft-nightly.svg` | GridCraft contributors | original (the stable placeholder artwork with only its field colour deepened; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly (nightly-v1) icon master |
| `assets/app-icon/gridcraft-nightly.png` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg`; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly icon, 256 px (Linux tar and runtime window icon) |
| `assets/app-icon/gridcraft-nightly-1024.png` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg` on the 824/1024 Mac grid; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly icon, padded Mac master |
| `assets/app-icon/gridcraft-nightly.icns` | GridCraft contributors | original (PNG slots packed from `gridcraft-nightly.svg` renders; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly macOS bundle icon |
| `assets/app-icon/gridcraft-nightly.ico` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg`; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly Windows exe icon |
| `assets/app-icon/nightly-provenance.json` | GridCraft contributors | original (written by `packaging/nightly-icons.py`) | MIT OR Apache-2.0 | Hashes and method of the nightly icon derivatives |
| `assets/app-icon/README.md` | GridCraft contributors | original | MIT OR Apache-2.0 | Icon documentation |
| `assets/app-icon/LICENSE.txt` | (licence text) | original | — | Licence of the app icon files |
| `docs/images/hero-sales.png` | GridCraft contributors | screenshot of GridCraft rendered offscreen (`crates/ui-egui/examples/snapshot.rs`) showing an original sample workbook | MIT OR Apache-2.0 | README screenshot; no third-party content |
Generated
+150 -1402
View File
File diff suppressed because it is too large Load Diff
+30 -38
View File
@@ -30,29 +30,29 @@ gridcraft-math = { path = "crates/math" }
# ui-egui, craft-print in the app, craft-web-api and craft-web-host in the web app) comes from one
# craft-libs revision.
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", features = ["ui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "=0.1.0", features = ["egui"] }
# PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers.
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0", default-features = false }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ff142b3ad58aa7306676749428f4f2f9b277b5dd", version = "0.1.0", default-features = false }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f7e0d7fd5577e102b4634bcbe062e649eb68165f", version = "0.1.0" }
# Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]).
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
# OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`.
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
# Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs`
# turn them into workbooks.
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
# The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back.
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9a6d894200221fcfedc274870c30394d404f859d", version = "0.1.0" }
# Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model.
# SpreadsheetML worksheet/drawing/string/package XML; workbook model mapping stays in gridcraft-xlsx.
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e", version = "0.1.0" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c", version = "=0.1.0" }
# foundation
thiserror = "2"
@@ -92,15 +92,7 @@ skrifa = { version = "0.44", default-features = false, features = ["std"] }
epaint_default_fonts = "0.37"
# One native window per workbook: the window list, Window menu titles and the immediate-viewport
# driver. Same craft-libs revision as craft-update above.
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false, features = ["ui"] }
# The UI runtime GridCraft's egui UI is hosted by (`crates/ui-egui/src/framework.rs`): who the app is
# to the framework's dialogs, the runtime's key bindings, the theme mode, window placement and the
# printer controls. Same craft-libs revision as above.
craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", default-features = false, features = ["egui"] }
[workspace.lints.rust]
unsafe_code = "forbid"
@@ -128,18 +120,18 @@ debug = 0
# Keep the complete egui family and native event bridge on reviewed fork commits.
[patch.crates-io]
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
-4
View File
@@ -165,10 +165,6 @@ directives, e.g. `RUST_LOG=debug` or `RUST_LOG=warn,gridcraft_engine=debug` (a t
matches a prefix: `gridcraft*=debug`). Runs with `GRIDCRAFT_NO_PREFS` set (no saved settings)
log to standard error only.
The `nightly-v1` channel keeps all of that in its own profile instead, which the Launcher names
(`--launch-profile nightly-v1 --profile-root <dir>`); a nightly build refuses to start without one,
so a Nightly run never touches the stable app's settings, prefs or logs.
## For agents: MCP, CLI and the control channel
```sh
-39
View File
@@ -65,35 +65,12 @@ fn stdout_failed(e: std::io::Error) -> ! {
std::process::exit(1);
}
/// The first Launcher-profile argument in `args`, in either its separate or `=` form. Only the
/// tokens a shell would see before `--` count: after it they are file names.
fn launch_profile_argument(args: &[std::ffi::OsString]) -> Option<String> {
for arg in args {
if arg == "--" {
return None;
}
let text = arg.to_string_lossy();
for flag in ["--launch-profile", "--profile-root"] {
if text == flag || text.starts_with(&format!("{flag}=")) {
return Some(flag.to_string());
}
}
}
None
}
fn main() -> ExitCode {
// A confined launcher run (and its probes) comes first, before anything else starts.
let raw: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
if let Some(code) = gridcraft_sandbox::handle_args(&raw) {
return ExitCode::from(u8::try_from(code).unwrap_or(1));
}
// The nightly profile protocol belongs to the desktop app: the Launcher's selector is not a
// CLI option, and a CLI that silently ignored it would act on the wrong files.
if let Some(flag) = launch_profile_argument(&raw) {
eprintln!("gridcraft-cli: {flag} belongs to the GridCraft desktop app, not this CLI");
return ExitCode::from(2);
}
let args: Vec<String> = std::env::args().skip(1).collect();
let rest = args.get(1..).unwrap_or_default();
let r = match args.first().map(String::as_str) {
@@ -613,22 +590,6 @@ mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
/// The Launcher's nightly selector belongs to the desktop app; the CLI says so and exits 2
/// rather than acting on whatever it thinks the file list is.
#[test]
fn launcher_profile_arguments_are_refused_in_both_forms_and_only_before_the_delimiter() {
let args = |values: &[&str]| values.iter().map(std::ffi::OsString::from).collect::<Vec<_>>();
assert_eq!(launch_profile_argument(&args(&["--launch-profile", "nightly-v1"])).as_deref(), Some("--launch-profile"));
assert_eq!(launch_profile_argument(&args(&["--profile-root", "/tmp/p", "info", "a.xlsx"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["--profile-root=/tmp/p"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["info", "--launch-profile=nightly-v1"])).as_deref(), Some("--launch-profile"));
// After `--` they are file names, exactly as the desktop app parses them.
assert_eq!(launch_profile_argument(&args(&["--", "--launch-profile", "nightly-v1"])), None);
assert_eq!(launch_profile_argument(&args(&["--", "--profile-root=/tmp/p"])), None);
assert_eq!(launch_profile_argument(&args(&["info", "a.xlsx", "--json"])), None);
assert_eq!(launch_profile_argument(&[]), None);
}
#[test]
fn parses_commands() {
assert_eq!(parse_command("home.bold={\"range\":\"A1\"}").unwrap(), Some(("home.bold".into(), json!({"range": "A1"}))));
+2 -2
View File
@@ -18,8 +18,8 @@ gridcraft-engine = { workspace = true }
gridcraft-ui-egui = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
# The page command API (storytold/craft-libs#413): window.gridcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9", version = "0.1.0" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
-3
View File
@@ -49,7 +49,6 @@ pub fn start() {
canvas,
options,
Box::new(move |cc| {
gridcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
let inbox: Inbox = Inbox::default();
let mut session = Session::new();
// In host mode the host sends the workbook to edit; no sample meanwhile.
@@ -159,7 +158,6 @@ impl eframe::App for WebShell {
});
}
self.app.logic(ctx);
self.app.close_path(ctx);
// Store changed preferences straight away: a reload or closed tab runs no exit code (#1562).
let changed = self.prefs.changed(&self.app);
if !changed.is_empty() {
@@ -179,7 +177,6 @@ impl eframe::App for WebShell {
/// Forwards a browser frame's raw input to the shared app before eframe handles it.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.app.raw_input_hook(ctx, raw);
self.app.before_input(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
+1 -3
View File
@@ -32,7 +32,7 @@ winit = { version = "0.30", default-features = false, features = ["x11", "waylan
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Same craft-libs revision as the workspace's craft-update and craft-window (see the root
# Cargo.toml).
craft-print = { workspace = true }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9" }
craft-update = { workspace = true }
rfd = { workspace = true }
arboard = { workspace = true, features = ["image-data"] }
@@ -46,8 +46,6 @@ arboard = { workspace = true, features = ["image-data", "wayland-data-control"]
[target.'cfg(target_os = "windows")'.dependencies]
# Blocks on the start-up DirectX 12 adapter probe (`graphics.rs`); already in the tree via eframe.
pollster = "1"
# The explicit AppUserModelID the nightly channel sets before its first window (`process_identity.rs`).
winsafe = { version = "0.0.29", features = ["user", "shell"] }
[target.'cfg(target_os = "macos")'.dependencies]
muda = { version = "0.21", default-features = false }
+6 -48
View File
@@ -1,67 +1,25 @@
//! Windows only: embed the app icon and version info (VERSIONINFO) into `gridcraft.exe`, so it
//! shows in Explorer, the taskbar, the Start menu and Alt-Tab.
//!
//! On every other target this does nothing but the channel work. A missing resource compiler is a
//! warning, so a cross-compile from macOS or Linux still links, unless `GRIDCRAFT_REQUIRE_WINRES=1`
//! turns it into an error (for release builds).
//!
//! The nightly channel is a build-time decision: `GRIDCRAFT_BUILD_CHANNEL=nightly-v1` sets
//! `cfg(gridcraft_nightly_v1)` and requires the prepared `GRIDCRAFT_VERSION` feed identity, which
//! becomes the executable's `ProductVersion` (the Launcher checks that, not `FileVersion`) and the
//! version the app answers `--version` with. Anything else than `stable`, empty or `nightly-v1`
//! is a build error, so a typo cannot silently ship the wrong channel.
#[path = "src/build_channel.rs"]
mod build_channel;
//! 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 `GRIDCRAFT_REQUIRE_WINRES=1` turns it
//! into an error (for release builds).
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=GRIDCRAFT_BUILD_CHANNEL");
println!("cargo:rustc-check-cfg=cfg(gridcraft_nightly_v1)");
let nightly = match std::env::var("GRIDCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=gridcraft_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 GRIDCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
println!("cargo:rerun-if-changed=../../assets/app-icon/gridcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/gridcraft-nightly.ico");
println!("cargo:rerun-if-env-changed=GRIDCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=GRIDCRAFT_VERSION");
let built_version = if nightly {
match std::env::var("GRIDCRAFT_VERSION") {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit GRIDCRAFT_VERSION feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=GRIDCRAFT_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(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "GridCraft Nightly" } else { "GridCraft" })
.set("FileDescription", if nightly { "GridCraft Nightly spreadsheet" } else { "GridCraft spreadsheet" })
res.set_icon("../../assets/app-icon/gridcraft.ico")
.set("ProductName", "GridCraft")
.set("FileDescription", "GridCraft spreadsheet")
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) the GridCraft authors. MIT OR Apache-2.0.")
.set("OriginalFilename", "gridcraft.exe")
.set("InternalName", "gridcraft");
if nightly {
// The Launcher compares the PE ProductVersion with the exact feed identity.
res.set("ProductVersion", &built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("GRIDCRAFT_REQUIRE_WINRES").is_some() {
eprintln!("embedding Windows resources failed: {e}");
-92
View File
@@ -1,92 +0,0 @@
//! The one place a GridCraft data root is resolved, so the nightly profile and the platform
//! default can never disagree.
//!
//! Everything the desktop writes about the user lives under [`config_dir`]: `ui.json`,
//! `prefs.json` and `logs/` (see `logging`). The control channel's token folder is resolved by
//! `gridcraft_mcp` from the same root at start-up. Nothing else in the app persists user state.
//! A nightly takes its root from the Launcher's validated profile and nothing else, so stable has
//! no environment override of its own: the platform's published folder is the whole story.
use std::ffi::OsString;
use std::path::PathBuf;
fn default_config_dir(platform: &str, env: &impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
match platform {
"macos" => env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/GridCraft")),
"windows" => env("APPDATA").map(|a| PathBuf::from(a).join("GridCraft")),
_ => env("XDG_CONFIG_HOME")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config")))
.map(|c| c.join("gridcraft")),
}
}
/// The folder the settings and the log files live in.
pub fn config_dir_for(platform: &str, env: &impl Fn(&str) -> Option<OsString>, nightly_root: Option<&std::path::Path>) -> Option<PathBuf> {
match nightly_root {
// The profile was already validated (absolute, fenced, writable) before this runs.
Some(root) => Some(root.to_path_buf()),
None => default_config_dir(platform, env),
}
}
pub fn config_dir() -> Option<PathBuf> {
config_dir_for(std::env::consts::OS, &|key| std::env::var_os(key), crate::launch_profile::current().root())
}
/// Where the log files live: `logs` in the settings folder, next to `ui.json`.
pub fn log_dir() -> Option<PathBuf> {
Some(config_dir()?.join("logs"))
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<OsString> {
let map: BTreeMap<String, OsString> = pairs.iter().map(|(k, v)| ((*k).to_string(), OsString::from(v))).collect();
move |key| map.get(key).cloned()
}
#[test]
fn each_platform_keeps_its_published_folder() {
// The base is joined with the host's own separator, so these hold on any machine the gate
// runs on: what each platform publishes is the folder name, not how the host spells a slash.
let appdata = PathBuf::from(r"C:\Users\u\AppData\Roaming");
assert_eq!(config_dir_for("windows", &env(&[("APPDATA", &appdata.to_string_lossy())]), None), Some(appdata.join("GridCraft")));
let home = PathBuf::from("/home/u");
assert_eq!(
config_dir_for("macos", &env(&[("HOME", &home.to_string_lossy())]), None),
Some(home.join("Library/Application Support/GridCraft"))
);
assert_eq!(config_dir_for("linux", &env(&[("HOME", &home.to_string_lossy())]), None), Some(home.join(".config").join("gridcraft")));
assert_eq!(
config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", &home.to_string_lossy())]), None),
Some(PathBuf::from("/xdg").join("gridcraft"))
);
assert_eq!(config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "")]), None), None);
}
#[test]
fn an_empty_xdg_config_home_falls_back_to_the_home_folder() {
let home = PathBuf::from("/home/u");
let home_str = home.to_string_lossy().into_owned();
assert_eq!(
config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", ""), ("HOME", &home_str)]), None),
Some(home.join(".config").join("gridcraft"))
);
assert_eq!(
config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", &home_str)]), None),
Some(PathBuf::from("/xdg").join("gridcraft"))
);
}
#[test]
fn the_nightly_profile_is_the_whole_answer() {
let profile = std::path::Path::new("/var/lib/gridcraft-nightly/profile");
assert_eq!(config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", "/home/u")]), Some(profile)), Some(profile.to_path_buf()));
assert_eq!(config_dir_for("linux", &env(&[("HOME", "/home/u")]), Some(profile)).unwrap().join("logs"), profile.join("logs"));
}
}
-55
View File
@@ -1,55 +0,0 @@
//! 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/gridcraft-nightly.ico" } else { "../../assets/app-icon/gridcraft.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/gridcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/gridcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.19.1-nightly.20261124.7.1.gabcdef012345"));
for invalid in [
"",
"0.19.1",
"0.19.1-nightly",
"0.19.1-nightly.20261124",
"0.19.1-nightly.20261124.7.1.gABCDEF012345",
"0.19.1-nightly.20261124.7.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.19.1-nightly.20261124.1.1.gabcdef012345",
"0.19.1-nightly.20261124.1.1.gabcdef012345/other",
"0.19.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
-73
View File
@@ -1,73 +0,0 @@
//! Build-time channel is distinct from a launch selector: a runtime environment cannot promote a
//! stable build, and a nightly build cannot be talked out of its profile.
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!(gridcraft_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 GridCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable GridCraft 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
}
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
}
}
#[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.19.1"), "0.19.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.19.1"), "0.19.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
-223
View File
@@ -1,223 +0,0 @@
//! Launcher-owned nightly-v1 bootstrap, selected before logging, updates, fonts or saved state.
//! Stable launches keep their original arguments and directory policy. No environment mutation.
//!
//! The protocol is the Launcher's, as PhotoCraft's is: `--launch-profile nightly-v1` with
//! `--profile-root <absolute>` as separate tokens, then `--` and the files. Everything after `--`
//! is a file, even when it looks like a profile flag. `--version` (and the Launcher's
//! `--launch-profile nightly-v1 --profile-root <abs> --version`) is answered by `main` before any
//! of this can create a directory, open a log or start a window.
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".to_string())
}
/// Recognize only the agreed literal selector/root pair before `--`. 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 config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_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\gridcraft" } else { "/nightly-data/profiles/gridcraft" }
}
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(&["sales.xlsx"]), args(&["--control", "7979"]), args(&["--", "--launch-profile", "book.xlsx"])] {
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_selector_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "a file with spaces.xlsx", "--version"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "a file with spaces.xlsx", "--version"]));
}
#[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", "/one/../two", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "sales.xlsx", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse(argv.clone()).is_err(), "{argv:?}");
}
assert!(parse(args(&["--launch-profile", "--profile-root", absolute(), "--"])).is_err(), "a flag is not a value");
}
#[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(), "--control", "7979", "--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());
}
}
+49 -208
View File
@@ -9,25 +9,16 @@
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod app_dirs;
#[cfg(target_os = "macos")]
mod apple_events;
// The build channel's own parser and icon-path tests (build.rs compiles the same file by path).
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod control_server;
#[cfg(any(target_os = "windows", target_os = "macos", test))]
mod graphics;
mod launch_profile;
mod logging;
#[cfg(target_os = "macos")]
mod native_menu;
mod nightly_session;
mod opener;
mod print;
mod process_identity;
mod profile_root;
use std::cell::RefCell;
use std::rc::Rc;
@@ -38,63 +29,45 @@ use gridcraft_ui_egui::{Services, SheetApp};
use serde_json::json;
/// The app, its native window per workbook window, and (macOS) the menu bar and Finder events.
/// The session record and its notice flag are only meaningful in the nightly channel.
struct App {
app: SheetApp,
windows: DocWindows,
#[cfg(target_os = "macos")]
menu: Option<native_menu::NativeMenu>,
#[cfg(target_os = "macos")]
apple_events: fmv_macos_events::Inbox,
/// The Nightly session record, shared with the exit hook and the return path.
nightly: nightly_session::Shared,
/// Whether this window already told the user the previous session did not finish.
nightly_notice_shown: bool,
}
struct App(SheetApp, DocWindows, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>, #[cfg(target_os = "macos")] fmv_macos_events::Inbox);
impl eframe::App for App {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
{
if self.menu.is_none() && std::env::var_os("GRIDCRAFT_NO_NATIVE_MENU").is_none() {
self.menu = Some(native_menu::NativeMenu::install(ctx));
if self.2.is_none() && std::env::var_os("GRIDCRAFT_NO_NATIVE_MENU").is_none() {
self.2 = Some(native_menu::NativeMenu::install(ctx));
}
if let Some(m) = &mut self.menu {
m.poll(&mut self.app, ctx, self.windows.focused_viewport());
if let Some(m) = &mut self.2 {
m.poll(&mut self.0, ctx, self.1.focused_viewport());
}
apple_events::poll(&self.apple_events, &mut self.app, ctx);
apple_events::poll(&self.3, &mut self.0, ctx);
}
self.0.logic(ctx);
self.1.logic(&mut self.0, ctx);
if ctx.input(|input| input.viewport().close_requested()) && self.0.printing.busy() {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
}
self.app.logic(ctx);
self.windows.logic(&mut self.app, ctx);
self.app.close_path(ctx);
}
/// Forwards raw input to the shared app, then opens every non-empty dropped file path as a workbook.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.app.raw_input_hook(ctx, raw);
self.app.before_input(ctx);
self.0.raw_input_hook(ctx, raw);
// Files dropped on the window open as workbooks.
for f in std::mem::take(&mut raw.dropped_files) {
if let Some(p) = f.path().to_str().map(str::to_string).filter(|p| !p.is_empty()) {
self.app.open_path(&p);
self.0.open_path(&p);
}
}
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
gridcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
self.windows.show(&mut self.app, ui);
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.1.show(&mut self.0, ui);
}
fn on_exit(&mut self) {
print::finish_pending_jobs();
save_prefs(&self.app);
save_prefs(&self.0);
// A ready update installs once the process has exited. The macOS exit below skips
// dropping the app, so the helper is started here. A nightly has no updater at all.
if gridcraft_ui_egui::channel::stable_services_allowed() {
self.app.start_pending_update();
}
// The Nightly session record is finished here: every way of quitting reaches `on_exit`,
// and on macOS AppKit's terminate ends the process right after it, so nothing after
// `eframe::run_native` can run there. `finish_once` makes the later call a no-op.
nightly_session::finish_once(&self.nightly, self.nightly_notice_shown);
// dropping the app, so the helper is started here.
self.0.start_pending_update();
// macOS (#117): end the process here, before eframe tears the window down. AccessKit's
// macOS adapter subclasses the window's content view and restores its class on teardown;
// AppKit's Touch Bar support observes that view (KVO), so in the next display cycle
@@ -108,10 +81,17 @@ impl eframe::App for App {
}
}
/// The settings folder: the validated nightly profile, else the platform's own folder
/// (`app_dirs`). Every writer of user state goes through it.
fn config_dir() -> Option<std::path::PathBuf> {
app_dirs::config_dir()
if cfg!(target_os = "macos") {
std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join("Library/Application Support/GridCraft"))
} else if cfg!(windows) {
std::env::var_os("APPDATA").map(|a| std::path::PathBuf::from(a).join("GridCraft"))
} else {
std::env::var_os("XDG_CONFIG_HOME")
.map(std::path::PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config")))
.map(|c| c.join("gridcraft"))
}
}
/// Runs without preferences (`GRIDCRAFT_NO_PREFS`, agents' test runs) neither read nor write
@@ -122,7 +102,7 @@ fn prefs_enabled() -> bool {
/// Where the log files live: `logs` in the settings folder, next to `ui.json` (see `logging`).
fn log_dir() -> Option<std::path::PathBuf> {
app_dirs::log_dir()
Some(config_dir()?.join("logs"))
}
fn load_prefs(app: &mut SheetApp) {
@@ -261,97 +241,13 @@ fn icon() -> Option<egui::IconData> {
Some(egui::IconData { width: img.width(), height: img.height(), rgba: img.into_raw() })
}
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
process_identity::initialize(
build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1,
gridcraft_ui_egui::channel::id_for(gridcraft_ui_egui::channel::Channel::NightlyV1),
)
}
/// Tell a desktop user why a nightly launch was refused. A headless form (`--version` on a runner)
/// never gets here: the version query is answered before this and before any profile work.
fn report_launch_profile_error(error: &str) {
eprintln!("GridCraft 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(error) = initialize_nightly_process_identity() {
eprintln!("GridCraft launch profile: {error}");
return;
}
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
let _ = rfd::MessageDialog::new()
.set_title("GridCraft Nightly")
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Select the immutable launch channel and profile before any startup service or side effect.
/// `None` means the answer was printed (`--version`) and the process is done.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
let argv: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
let nightly_build = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1;
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, IPC or any window (a dialog
// here would hang a headless runner and fail a Linux build).
if nightly_build && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) {
use std::io::Write as _;
let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION"));
let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable));
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, |root| {
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
})
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let channel =
if early.profile.is_nightly() { gridcraft_ui_egui::channel::Channel::NightlyV1 } else { gridcraft_ui_egui::channel::Channel::Stable };
if let Err(error) =
launch_profile::install(early.profile).and_then(|()| gridcraft_ui_egui::channel::select(channel, env!("GRIDCRAFT_BUILT_VERSION")))
{
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
}
fn main() -> eframe::Result<()> {
// A confined launcher run (`gridcraft_sandbox::launch_command`, which a Python cell starts from
// this same executable) comes before everything else: it opens no window, writes no log, and
// becomes the program it confines. It must stay ahead of the launch profile, or a nightly build
// would refuse its own sandbox helper.
// A confined launcher run (`gridcraft_sandbox::launch_command`) comes before everything else:
// it opens no window, writes no log, and becomes the program it confines.
let raw: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
if let Some(code) = gridcraft_sandbox::handle_args(&raw) {
std::process::exit(code);
}
// Then the Launcher protocol and the version query (see `prepare_launch`).
let Some(arguments) = prepare_launch() else { return Ok(()) };
// A nightly profile owns its control tokens as well, so even a nightly build that is asked
// for a control server can never write the stable app's token file.
if let Some(root) = launch_profile::current().root() {
match profile_root::control_directory(root).and_then(gridcraft_mcp::control_auth::set_token_root) {
Ok(()) => {}
Err(error) => {
report_launch_profile_error(&error);
std::process::exit(2);
}
}
}
// First, so the panic hook and every start-up warning are recorded (`logging`).
let logger = logging::install();
// Commands catch their panics (`Session::execute`), but the default hook only prints to
@@ -372,32 +268,21 @@ fn main() -> eframe::Result<()> {
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("gridcraft: {report}\n"));
}
}));
let args: Vec<String> = arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect();
let nightly = gridcraft_ui_egui::channel::current() == gridcraft_ui_egui::channel::Channel::NightlyV1;
let args: Vec<String> = std::env::args().skip(1).collect();
// The restart helper a self-update spawns: it finishes the swap and relaunches, then exits.
// A nightly has no updater, so it never runs this and never inherits a stable swap.
if !nightly
&& let Some(done) = craft_update::self_update::finish(&gridcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
{
if let Some(done) = craft_update::self_update::finish(&gridcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
if let Err(e) = done {
eprintln!("GridCraft update helper failed: {e}");
std::process::exit(1);
}
return Ok(());
}
// Before `--` only: everything after it is a file, even one named `--version`.
if arguments.iter().take_while(|a| *a != "--").any(|a| a == "--version" || a == "-V") {
println!("GridCraft {}", gridcraft_ui_egui::channel::version());
if args.iter().any(|a| a == "--version" || a == "-V") {
println!("GridCraft {}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
// The control channel is a stable-only service: a nightly window owns no port, writes no
// token and never inherits the stable app's `GRIDCRAFT_CONTROL_PORT`/`GRIDCRAFT_CONTROL_TOKEN`.
if nightly && args.iter().any(|a| a == "--control" || a == "--control-token") {
eprintln!("GridCraft Nightly: the control channel is not part of the nightly channel");
std::process::exit(2);
}
let mut control_port: Option<u16> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten();
let mut control_token: Option<String> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten();
let mut control_port: Option<u16> = std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
let mut control_token: Option<String> = std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok();
let mut sample: Option<String> = None;
let mut files: Vec<String> = Vec::new();
let mut i = 0;
@@ -427,9 +312,7 @@ fn main() -> eframe::Result<()> {
if let Some(logger) = logger {
match log_dir().filter(|_| prefs_enabled()) {
Some(dir) => match logger.attach_dir(&dir) {
Ok(path) => {
log::info!("{} {}, log file {}", gridcraft_ui_egui::channel::name(), gridcraft_ui_egui::channel::version(), path.display())
}
Ok(path) => log::info!("GridCraft {}, log file {}", env!("CARGO_PKG_VERSION"), path.display()),
// Standard error only by now (`attach_dir` gave up on the file); unlike `eprintln!`, never panics.
Err(e) => log::warn!("no log file: {e}"),
},
@@ -444,11 +327,7 @@ fn main() -> eframe::Result<()> {
}
let mut app = SheetApp::new(session, services());
app.watch_desktop_theme();
// The updater is a stable-only service: a nightly is installed, replaced and updated by the
// Launcher, so it never checks for one, never prompts and never writes craft-update's state.
if !nightly {
app.start_update_check();
}
app.start_update_check();
let control_port = control_port;
load_prefs(&mut app);
// Stamp the startup workbook's author from the persisted user name.
@@ -456,30 +335,6 @@ fn main() -> eframe::Result<()> {
app.session.new_workbook();
}
app.after_engine(); // Show warnings from the sample.
// Nightly session health: the record is written before the window exists and finished by
// `on_exit`. A record left by an interrupted run is reported once, then cleared on the next
// clean quit.
let session_watch = std::sync::Arc::new(std::sync::Mutex::new(None));
let mut nightly_notice_shown = false;
match nightly_session::Session::begin_with_health(launch_profile::current().root(), env!("GRIDCRAFT_BUILT_VERSION")) {
Ok((watch, unavailable)) => {
if let Some(watch) = &watch
&& watch.previous_unclean()
{
app.notice = Some(gridcraft_ui_egui::Notice {
text: "The last GridCraft Nightly session did not finish cleanly. Your saved workbooks are as you left them; only unsaved changes are affected.".into(),
kind: gridcraft_ui_egui::NoticeKind::Warning,
action: None,
});
nightly_notice_shown = true;
}
if unavailable {
log::warn!("this window shares a GridCraft Nightly profile another window owns; its exit is not recorded");
}
*session_watch.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = watch;
}
Err(error) => log::warn!("Nightly session state was not written: {error}"),
}
// Files named on the command line (a double-click on Windows and Linux) open as File › Open
// opens them: a password-protected one asks for its password, and errors are shown, not
// only logged. Each replaces the untouched blank Book1, as a file opened from Finder does.
@@ -489,16 +344,11 @@ fn main() -> eframe::Result<()> {
// Linux/BSD: Excel's layout — no window-manager title bar above ours; our title bar carries the
// window controls. `GRIDCRAFT_SYSTEM_TITLEBAR=1` keeps the system frame.
app.window_controls = cfg!(not(any(target_os = "macos", target_os = "windows"))) && std::env::var_os("GRIDCRAFT_SYSTEM_TITLEBAR").is_none();
// The window carries its channel's name and OS app id: a nightly window is never mistaken for
// the stable one by a dock, a window manager rule or the taskbar (Windows AUMID above). A
// Flatpak package carries its own id instead, which is what its .desktop file and portal name.
let window_app_id =
std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| gridcraft_ui_egui::channel::app_id().to_string());
let mut viewport = egui::ViewportBuilder::default()
.with_title(gridcraft_ui_egui::channel::default_title())
.with_title("GridCraft")
.with_inner_size([1440.0, 900.0])
.with_min_inner_size([640.0, 420.0])
.with_app_id(window_app_id)
.with_app_id("ai.storyteller.gridcraft")
.with_drag_and_drop(true)
.with_decorations(!app.window_controls);
if cfg!(target_os = "macos") {
@@ -537,13 +387,12 @@ fn main() -> eframe::Result<()> {
let pending = std::cell::Cell::new(Some(app));
let run = |options: eframe::NativeOptions| {
eframe::run_native(
gridcraft_ui_egui::channel::name(),
"GridCraft",
options,
Box::new(|cc| {
let Some(mut app) = pending.take() else {
return Err("the app was already created".into());
};
gridcraft_ui_egui::framework::install(&cc.egui_ctx)?;
SheetApp::setup_context_for_language(&cc.egui_ctx, app.ui.dark, app.ui.language);
if let Some(port) = control_port {
match control_server::start(port, control_token.clone(), cc.egui_ctx.clone()) {
@@ -552,16 +401,14 @@ fn main() -> eframe::Result<()> {
}
}
let windows = DocWindows::new(&mut app, window_builder.clone(), DocWindows::platform_quits_with_last_window());
Ok(Box::new(App {
Ok(Box::new(App(
app,
windows,
#[cfg(target_os = "macos")]
menu: None,
None,
#[cfg(target_os = "macos")]
apple_events: apple_events.connect(&cc.egui_ctx),
nightly: session_watch.clone(),
nightly_notice_shown,
}))
apple_events.connect(&cc.egui_ctx),
)))
}),
)
};
@@ -569,7 +416,7 @@ fn main() -> eframe::Result<()> {
// A graphics error before the app existed: start once more with the other backend (eframe
// reuses its event loop for the second run). Errors after that, or from winit, are returned.
#[cfg(target_os = "windows")]
let result = if let Err(eframe::Error::Wgpu(e)) = &result
if let Err(eframe::Error::Wgpu(e)) = &result
&& let Some(app) = pending.take()
&& let Some(backends) = graphics::fallback_backends(backend_override, first_backends)
{
@@ -577,14 +424,8 @@ fn main() -> eframe::Result<()> {
pending.set(Some(app));
let mut options = retry_options;
graphics::configure_backends(&mut options, backends);
run(options)
} else {
result
};
// A start that failed before the app existed never reached `on_exit`, and on the platforms
// where the event loop returns this is also the end of a clean exit. `finish_once` makes the
// second of the two calls a no-op, so a successor's record is never touched.
nightly_session::finish_once(&session_watch, nightly_notice_shown);
return run(options);
}
result
}
-310
View File
@@ -1,310 +0,0 @@
//! App-private Nightly session health, not telemetry and not 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, and
//! on macOS that path is `on_exit` (a ⌘Q ends the process inside AppKit's terminate, after
//! `on_exit`, so nothing after `eframe::run_native` runs there).
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Write};
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),
}
}
/// Replace `path` with `bytes` without following a link at the destination: the temporary file is
/// created exclusively beside it and renamed over it, so a planted link is replaced, not written
/// through. `gridcraft_engine::io::write_file` does the same for workbooks; the session record is
/// the app's own file and must not depend on the engine's script sandbox policy.
fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
let name = path.file_name().ok_or_else(|| io::Error::other("the session record has no file name"))?;
let mut tmp_name = std::ffi::OsString::from(".");
tmp_name.push(name);
tmp_name.push(".new");
let tmp = path.with_file_name(tmp_name);
match std::fs::remove_file(&tmp) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
let write = (|| -> io::Result<()> {
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt as _;
options.mode(0o600);
}
let mut file = options.open(&tmp)?;
file.write_all(bytes)?;
file.sync_all()?;
drop(file);
std::fs::rename(&tmp, path)
})();
if write.is_err() {
let _ = std::fs::remove_file(&tmp);
}
write
}
/// The owner's session, shared by the app's exit hook and the return path.
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) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version)?;
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) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.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)?;
// The commit is read back from the version (`…g<sha12>`), never invented here.
let commit = gridcraft_ui_egui::channel::commit_for(version);
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit,
}))?;
atomic_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 (a failed start before the app existed), the record is left for the next owner.
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Clear the record this owner wrote, and only that one. An unwind, abort, forced exit or killed
/// process never calls this.
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!("gridcraft-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();
}
}
fn version() -> &'static str {
"0.19.1-nightly.20261124.7.1.gabcdef012345"
}
#[test]
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable").unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), version()).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), version()).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), version()).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), version()).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 unfinished = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(!unfinished.previous_unclean());
drop(unfinished); // Abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), version()).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), version()).unwrap().unwrap());
// The renderer failed before the app existed: no notice was shown.
let failed = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
// The retry (or the next start) still sees the interruption and shows it.
let retry = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(retry.previous_unclean());
retry.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), version()).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), version()).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");
let successor = Session::begin(Some(&fixture.0), version()).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), version()).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)).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "").unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), version()).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, ["channel", "commit", "schema_version", "version"].into_iter().collect());
assert_eq!(data["commit"], "abcdef012345", "the commit comes from the version, not the environment");
watch.complete().unwrap();
}
#[test]
fn a_version_without_a_commit_does_not_invent_one() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "0.19.1").unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
assert!(data["commit"].is_null());
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), version()).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
#[test]
#[cfg(unix)]
fn replacing_a_planted_record_link_writes_our_own_file_only() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
std::os::unix::fs::symlink(&external, fixture.0.join(RECORD)).unwrap();
// regular_or_missing refuses an alias outright; the temporary writer is what a first write
// uses, and it never follows one either.
assert!(Session::begin(Some(&fixture.0), version()).is_err());
// The link is at RECORD itself: writing there must replace the alias, not follow it.
atomic_write_no_follow(&fixture.0.join(RECORD), b"ours").unwrap();
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"ours");
assert!(!fixture.0.join(RECORD).is_symlink(), "the alias must be replaced, not written through");
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
assert!(!fixture.0.join(".nightly-session.json.new").exists());
}
}
+10 -12
View File
@@ -1,12 +1,15 @@
//! Desktop spooler adapter. Discovery and submission never run on the UI thread.
use gridcraft_ui_egui::printing::{Destination, Discover, Duplex, Printer, Settings, Submit};
use gridcraft_ui_egui::printing::{Discover, Duplex, Printer, Settings, Submit};
/// Returns a printer-discovery closure that enumerates `craft_print::printers()` on a named background thread and sends the mapped list through a channel.
pub fn discover() -> Discover {
Box::new(|| {
let (sender, receiver) = std::sync::mpsc::channel();
let _ = std::thread::Builder::new().name("print-discovery".into()).spawn(move || {
let printers = craft_print::printers().into_iter().map(Printer::from).collect();
let printers = craft_print::printers()
.into_iter()
.map(|printer| Printer { name: printer.name, label: printer.description, default: printer.default })
.collect();
let _ = sender.send(printers);
});
receiver
@@ -31,17 +34,12 @@ pub fn submit() -> Submit {
let (sender, receiver) = std::sync::mpsc::channel();
let worker = std::thread::Builder::new().name("print-submit".into()).spawn(move || {
let job = craft_print::Job {
printer: match settings.destination {
Destination::Printer(name) => Some(name),
_ => None,
},
printer: Some(settings.printer),
copies: settings.copies.clamp(1, 999),
collate: settings.collate,
duplex: settings.duplex.and_then(|value| match value {
Duplex::LongEdge => Some(craft_print::Duplex::LongEdge),
Duplex::ShortEdge => Some(craft_print::Duplex::ShortEdge),
Duplex::Off => Some(craft_print::Duplex::Off),
_ => None,
duplex: settings.duplex.map(|value| match value {
Duplex::LongEdge => craft_print::Duplex::LongEdge,
Duplex::ShortEdge => craft_print::Duplex::ShortEdge,
Duplex::Off => craft_print::Duplex::Off,
}),
grayscale: settings.grayscale,
scaling: craft_print::Scaling::ShrinkToFit,
-81
View File
@@ -1,81 +0,0 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged, so the MSI's
//! advertised shortcuts keep matching it.
use std::sync::OnceLock;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IdentityError(String);
impl std::fmt::Display for IdentityError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for IdentityError {}
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)
}
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());
}
#[test]
fn a_non_nightly_build_never_reaches_the_windows_api() {
assert!(initialize(false, "nightly-id").is_ok());
}
}
-528
View File
@@ -1,528 +0,0 @@
//! GridCraft's nightly profile fences: no stable fallback, no migration and no change to the
//! process environment. Every stable place a GridCraft build keeps user state is refused as a
//! nightly root, in both directions, so the two channels can never share a file.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
/// The folder the Windows build writes its control-channel token to (`gridcraft_mcp`).
const WINDOWS_TOKEN_DIR: &str = ".gridcraft";
/// The subfolder of the profile the nightly control-channel token goes to, when one runs.
pub const CONTROL_DIR: &str = "Control";
#[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),
// FreeBSD, the BSDs and anything else have no nightly channel.
_ => 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 an 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 => {
// `apps/gridcraft/src/main.rs` (ui.json, prefs.json and logs) and `gridcraft_mcp`'s
// token folder, plus both MSI install folders (`install-policy.wxi`).
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("GridCraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("GridCraft"));
roots.push(required_base(env, "USERPROFILE")?.join(WINDOWS_TOKEN_DIR));
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("GridCraft"));
}
}
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("gridcraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/gridcraft", "/usr/local/bin/gridcraft", "/opt/gridcraft"].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.gridcraft"));
// `gridcraft_mcp`'s token folder when no XDG runtime directory is set.
roots.push(required_base(env, "HOME")?.join(".cache").join("gridcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/GridCraft"),
library.join("Caches/GridCraft"),
library.join("Caches/ai.storyteller.gridcraft"),
library.join("Preferences/GridCraft"),
library.join("Preferences/ai.storyteller.gridcraft.plist"),
library.join("Saved Application State/ai.storyteller.gridcraft.savedState"),
home.join("Applications/GridCraft.app"),
PathBuf::from("/Applications/GridCraft.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 (settings, logs and so on) must resolve inside it,
/// so a link there cannot point Nightly's writes at the stable 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(())
}
/// Where a nightly control-channel token goes: `<profile>/Control`, created lazily by
/// `gridcraft_mcp` if a control server is ever started. Resolving it never creates anything.
pub fn control_directory(root: &Path) -> Result<PathBuf, String> {
private_subdirectory(root, CONTROL_DIR, "control folder")
}
/// The app's own exclusive writable probe: create a file inside the profile, then remove it.
pub fn ensure_writable(root: &Path) -> std::io::Result<()> {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
// A crashed launch can leave a probe with this name behind: take the next one instead of
// failing, and remove only the file this call created, never someone else's.
loop {
let probe =
root.join(format!(".gridcraft-nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
Ok(_) => return std::fs::remove_file(&probe),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
}
/// The writable hook is injected so filesystem boundary tests exercise the real policy without
/// starting the app or changing global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty())
&& id.to_string_lossy().as_ref() != gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID
{
// `packaging/linux/flatpak-bundle.sh` builds GridCraft Nightly as its own Flatpak
// (`ai.storyteller.gridcraft.nightly`), whose sandbox is already a private home, so that one
// instance may carry a profile. Any other, the stable app's included, could point it at
// another installation's tree; these rows are otherwise native tar/app-bundle launches.
return Err(format!(
"nightly-v1 can only run inside its own Flatpak instance ({}), not {}",
gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID,
id.to_string_lossy()
));
}
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 a subfolder elsewhere.
control_directory(&chosen)?;
entries_stay_inside(&chosen)?;
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());
}
control_directory(&confirmed)?;
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!("gridcraft-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/gridcraft");
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.clone()), ("USERPROFILE", 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> {
self.check_with(platform, root, |_| Ok(()))
}
fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result<PathBuf, String> {
validate_for(platform, root, |key| self.get(key), Some(&self.exe), writable)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
fn every_stable_data_root_is_refused_on_its_own_platform() {
let mut fixture = Fixture::new();
// Windows: APPDATA\GridCraft (settings and logs), LOCALAPPDATA\GridCraft, the per-user
// and per-machine install folders and the control-token folder.
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("GridCraft");
for candidate in [stable.clone(), stable.join("nightly")] {
assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{key}");
}
assert!(!stable.exists());
}
assert!(
fixture
.check(Platform::Windows, &PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/GridCraft/nightly"))
.is_err()
);
assert!(fixture.check(Platform::Windows, &fixture.home().join(".gridcraft/nightly")).is_err());
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());
assert!(fixture.check(Platform::Windows, &base.join("ArtCraft/GridCraft/nightly")).is_err(), "{key}");
assert!(!base.join("ArtCraft/GridCraft").exists());
}
// Linux: the four XDG folders, then the stable Flatpak row and the token folder.
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("gridcraft");
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"), "{key}");
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.gridcraft/data")).is_err());
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
assert!(fixture.check(Platform::Linux, Path::new("/usr/bin/gridcraft/../gridcraft-nightly")).is_err(), "parent traversal is refused");
// macOS: the four Library rows and the bundle itself.
for suffix in [
"Application Support/GridCraft",
"Caches/GridCraft",
"Preferences/GridCraft",
"Saved Application State/ai.storyteller.gridcraft.savedState",
] {
assert!(fixture.check(Platform::Mac, &fixture.home().join("Library").join(suffix).join("nightly")).is_err(), "{suffix}");
}
}
#[test]
fn the_launcher_profile_row_is_accepted_on_every_platform() {
let fixture = Fixture::new();
let data = fixture.root.join("Launcher/nightly/profiles/gridcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert_eq!(fixture.check(platform, &data).unwrap(), data);
}
assert!(
fixture
.check(
Platform::Linux,
&PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/ArtCraftLauncher/nightly/gridcraft")
)
.is_ok(),
"the Launcher's own folder is not GridCraft's install"
);
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/gridcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("Control"), platform));
assert!(overlaps(&root.join("Control"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("gridcraft-other"), platform));
}
}
#[test]
fn the_install_folder_of_the_running_build_is_refused() {
let fixture = Fixture::new();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(fixture.check(platform, &fixture.exe.parent().unwrap().join("profile")).is_err());
}
}
#[test]
fn mac_fences_the_whole_bundle_not_just_its_macos_folder() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/GridCraft Nightly.app/Contents/MacOS/GridCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
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());
assert!(fixture.check(Platform::Mac, &fixture.home().join("Library/Application Support/ArtCraft/nightly/profiles/gridcraft")).is_ok());
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/gridcraft");
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("FLATPAK_ID".into(), "ai.storyteller.gridcraft".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
assert!(!candidate.exists());
}
#[test]
fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() {
let mut fixture = Fixture::new();
let root = fixture.root.join("flatpak profile");
for (id, accepted) in [
(gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID, true),
// The stable Flatpak, and a lookalike that only shares the prefix, stay refused.
("ai.storyteller.gridcraft", false),
("ai.storyteller.gridcraft.nightly-v1", false),
("io.github.other.Gridcraft", false),
] {
fixture.env.insert("FLATPAK_ID".into(), id.into());
let result = fixture.check(Platform::Linux, &root);
assert_eq!(result.is_ok(), accepted, "{id}");
let _ = std::fs::remove_dir_all(&root);
}
}
#[test]
fn failed_write_probe_never_falls_back_to_stable() {
let fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/gridcraft");
let result = fixture.check_with(Platform::Linux, &candidate, |_| Err(std::io::Error::other("read-only mount")));
assert!(result.unwrap_err().contains("not writable"));
assert!(candidate.is_dir(), "a created profile is not rolled back onto stable data");
assert!(!fixture.home().join(".config/gridcraft").exists());
}
#[test]
fn a_file_in_place_of_the_profile_is_refused() {
let fixture = Fixture::new();
let candidate = fixture.root.join("not-a-directory");
std::fs::write(&candidate, b"a file, not a profile").unwrap();
assert!(fixture.check(Platform::Linux, &candidate).is_err());
assert_eq!(std::fs::read(&candidate).unwrap(), b"a file, not a profile");
}
#[cfg(unix)]
#[test]
fn profile_entry_aliases_must_stay_inside_the_profile() {
let fixture = Fixture::new();
let stable = fixture.home().join(".config/gridcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("ui.json"), b"stable settings").unwrap();
for name in ["ui.json", "logs", "Control", "profile"] {
let private = fixture.root.join(format!("nightly-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
let probed = std::cell::Cell::new(false);
let result = fixture.check_with(Platform::Linux, &private, |_| {
probed.set(true);
Ok(())
});
assert!(result.is_err(), "{name} must not lead outside the profile");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-inside");
std::fs::create_dir_all(private.join("real-logs")).unwrap();
std::fs::write(private.join("ui.json"), b"{}").unwrap();
std::os::unix::fs::symlink(private.join("real-logs"), private.join("logs")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok(), "links that stay inside are fine");
assert_eq!(std::fs::read(stable.join("ui.json")).unwrap(), b"stable settings");
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn a_control_folder_alias_cannot_redirect_the_token_outside_the_profile() {
let fixture = Fixture::new();
let outside = fixture.home().join("shared-tokens");
std::fs::create_dir_all(&outside).unwrap();
let private = fixture.root.join("nightly-control");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&outside, private.join(CONTROL_DIR)).unwrap();
assert!(control_directory(&private).is_err());
assert!(fixture.check(Platform::Linux, &private).is_err());
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
}
#[test]
fn the_control_folder_is_a_private_lazy_subfolder() {
let fixture = Fixture::new();
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap();
let control = control_directory(&private).unwrap();
assert!(control.starts_with(&private) && control != private);
assert!(!control.exists(), "resolving it must not create it");
assert_eq!(control.file_name().unwrap(), CONTROL_DIR);
}
#[test]
fn the_writable_probe_leaves_nothing_behind() {
let fixture = Fixture::new();
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap();
ensure_writable(&private).unwrap();
assert_eq!(std::fs::read_dir(&private).unwrap().count(), 0);
}
}
-13
View File
@@ -50,16 +50,3 @@ ID and `packaging/linux/ai.storyteller.gridcraft.desktop`.
Edit `gridcraft.svg`, then run `packaging/icons.sh`. It needs `resvg`, and `iconutil` for the
`.icns` (macOS only). It packs the `.ico` with `cargo xtask ico`.
## Nightly channel
The nightly (`nightly-v1`) derivatives keep the artwork, geometry and the Mac padding unchanged and
change only the field colour: `#1f9d55` in the stable icon, `#14532d` in
`gridcraft-nightly.svg`. There is no letter, badge or crescent; the app and the Launcher name the
channel in text (`GridCraft Nightly`, the `ai.storyteller.gridcraft.nightly-v1` window id).
`gridcraft-nightly.svg` is the vector master. `packaging/nightly-icons.py` renders every frame from
it at its own size (never an upscale) and packs the nine-frame ICO and the eleven-slot ICNS; it
uses `resvg` when present, else a headless Chrome. Each output's SHA-256, the palette and the
method are recorded in [`nightly-provenance.json`](nightly-provenance.json), and
`python3 packaging/nightly-icons.py --check` verifies the committed files still match it.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

-30
View File
@@ -1,30 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
<!-- GridCraft Nightly (nightly-v1) icon: the stable artwork with only its background contribution
deepened. Foreground, geometry and alpha are unchanged; no badge, letter or crescent, so the
channel reads from the app and the Launcher in text.
Palette: ink #0b0b0c, paper #efe9dc, stable field #1f9d55
(proposed), nightly field #14532d. -->
<defs>
<clipPath id="tile"><rect width="512" height="512" rx="112"/></clipPath>
</defs>
<g clip-path="url(#tile)">
<rect width="512" height="512" fill="#14532d"/>
<g transform="rotate(-6 256 268)" stroke="#0b0b0c" stroke-linejoin="round" stroke-linecap="round">
<!-- page with a folded top-right corner -->
<path d="M112 76 H336 L404 144 V440 H112 Z" fill="#efe9dc" stroke-width="14"/>
<path d="M336 76 V144 H404" fill="none" stroke-width="12"/>
<!-- title lines -->
<path d="M146 106 H272 M146 130 H232" stroke-width="12"/>
<!-- header row and row-number column, in the app colour -->
<path d="M112 164 H404 V204 H164 V440 H112 Z" fill="#14532d" stroke="none"/>
<!-- grid -->
<path d="M112 164 H404 M112 204 H404 M112 250 H404 M112 296 H404 M112 342 H404 M112 388 H404
M164 164 V440 M244 164 V440 M324 164 V440" fill="none" stroke-width="8"/>
<!-- the selected cell and its fill handle -->
<rect x="244" y="250" width="80" height="46" fill="none" stroke-width="16"/>
<rect x="312" y="284" width="24" height="24" fill="#0b0b0c" stroke="#efe9dc" stroke-width="5"/>
<!-- double rule under the total -->
<path d="M252 410 H316 M252 424 H316" stroke-width="7"/>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.7 KiB

-56
View File
@@ -1,56 +0,0 @@
{
"title": "GridCraft nightly deep-background icons",
"author": "@skylartaylor",
"license": "MIT OR Apache-2.0",
"inputs": [
{
"path": "assets/app-icon/gridcraft-nightly.svg",
"sha256": "671748d45b785a840cf6ad062024c008e4704edc8925bed986dac2558438516b",
"purpose": "vector master for every frame"
},
{
"path": "assets/app-icon/gridcraft.svg",
"sha256": "a4c55f2f52893b319862b610c006af83da9f097a4112b5a982b8ba95f43d2850",
"purpose": "stable artwork this is derived from"
}
],
"method": {
"kind": "vector render of the project-owned artwork with only its field colour deepened",
"stable_field": "#1f9d55",
"nightly_field": "#14532d",
"unchanged": "ink #0b0b0c, paper #efe9dc, every path, stroke width and the 824/1024 Mac padding",
"sizes": "each frame rendered at its own size, never upscaled",
"renderer": "chrome",
"generator": "packaging/nightly-icons.py"
},
"outputs": {
"gridcraft-nightly.png": "f06a2507dbd07c307d3b3e46eb2b7d849c29cc51f56114d61091d68d9d59e0d0",
"gridcraft-nightly-1024.png": "914314b91dd214132bc017503d88197ca1537fab0de144a59cc65e03a03be400",
"gridcraft-nightly.ico": "20cdb98a65c157f1db67800d439730b2c5dd564722d615d2b9483dc948f6e751",
"gridcraft-nightly.icns": "e8fb90269660151b8ab1370bbd7194f5bae29888aa44959cf4c48110dcdebe9a"
},
"ico_frame_sizes": [
16,
20,
24,
32,
40,
48,
64,
128,
256
],
"icns_png_slots": {
"icp4": 16,
"icp5": 32,
"ic11": 32,
"icp6": 64,
"ic12": 64,
"ic07": 128,
"ic08": 256,
"ic13": 256,
"ic09": 512,
"ic14": 512,
"ic10": 1024
}
}
+3
View File
@@ -11,4 +11,7 @@ disallowed-methods = [
{ path = "std::time::SystemTime::now", reason = "traps on wasm; read the clock only off wasm" },
]
disallowed-types = [
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
]
cognitive-complexity-threshold = 30
+5 -28
View File
@@ -68,26 +68,10 @@ pub fn check_first_line(line: &str, token: &str) -> Result<Value, Value> {
}
}
/// An app-selected folder for the tokens, set once before any window exists. The nightly channel
/// points it at its own private profile, so a nightly control server can never write the stable
/// app's token (and two channels can never authenticate each other).
static TOKEN_ROOT: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
/// Choose the token folder for this process. Only a desktop app that owns its data root calls
/// this; a client (`gridcraft-cli`, the MCP bridge) keeps reading the app's own folder.
pub fn set_token_root(dir: PathBuf) -> Result<(), String> {
if !dir.is_absolute() {
return Err("the control token folder must be absolute".into());
}
TOKEN_ROOT.set(dir).map_err(|_| "the control token folder was already selected".to_string())
}
/// The folder tokens go in: [`set_token_root`]'s when an app chose one, else the user's own.
pub fn token_root() -> Option<PathBuf> {
TOKEN_ROOT.get().cloned().or_else(default_token_root)
}
fn default_token_root() -> Option<PathBuf> {
/// Where the app writes the token it made for `port`, and where clients look for it: a folder
/// only the user can open (`$XDG_RUNTIME_DIR/gridcraft`, else `~/.cache/gridcraft`; on Windows
/// `%USERPROFILE%\.gridcraft`), file `control-<port>.token`. `None` when no such folder is known.
pub fn token_path(port: u16) -> Option<PathBuf> {
let dir = if cfg!(windows) {
PathBuf::from(std::env::var_os("USERPROFILE").filter(|v| !v.is_empty())?).join(".gridcraft")
} else if let Some(run) = std::env::var_os("XDG_RUNTIME_DIR").filter(|v| !v.is_empty()) {
@@ -95,14 +79,7 @@ fn default_token_root() -> Option<PathBuf> {
} else {
PathBuf::from(std::env::var_os("HOME").filter(|v| !v.is_empty())?).join(".cache").join("gridcraft")
};
Some(dir)
}
/// Where the app writes the token it made for `port`, and where clients look for it: a folder
/// only the user can open (`$XDG_RUNTIME_DIR/gridcraft`, else `~/.cache/gridcraft`; on Windows
/// `%USERPROFILE%\.gridcraft`), file `control-<port>.token`. `None` when no such folder is known.
pub fn token_path(port: u16) -> Option<PathBuf> {
Some(token_root()?.join(format!("control-{port}.token")))
Some(dir.join(format!("control-{port}.token")))
}
/// The port of a control address (`127.0.0.1:7979` → 7979).
-9
View File
@@ -512,15 +512,6 @@ fn control_auth_handshake_and_compare() {
assert_eq!(hex(&[0x00, 0xab, 0xff]), "00abff");
}
#[test]
fn a_relative_token_root_is_refused_before_it_is_selected() {
// The app may point the tokens at its own private profile, but only at an absolute folder: a
// relative one would resolve against whatever directory the process was started in. (A
// successful selection is process-wide, so this test only exercises the refusal.)
assert!(crate::control_auth::set_token_root(std::path::PathBuf::from("relative/tokens")).is_err());
assert!(crate::control_auth::set_token_root(std::path::PathBuf::from("")).is_err());
}
#[cfg(unix)]
#[test]
fn control_token_file_is_private() {
+4 -9
View File
@@ -9,15 +9,9 @@ description = "GridCraft egui frontend (Excel-style UI); swappable — nothing b
workspace = true
[dependencies]
# The UI runtime that hosts this egui UI (`src/framework.rs`) and the framework dialogs, from the
# one craft-libs revision every craft-libs dependency uses (see the root Cargo.toml).
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-behavior = { workspace = true }
craft-host = { workspace = true }
craft-keymap = { workspace = true }
craft-print = { workspace = true }
craft-theme = { workspace = true }
craft-window = { workspace = true }
# The shared capture slot (`craft_ui::capture`) comes from the one craft-libs revision every
# craft-libs dependency uses (see the root Cargo.toml).
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9" }
gridcraft-engine = { workspace = true }
gridcraft-chart = { workspace = true }
# `monochrome_emoji_fonts` restores the Noto Emoji and emoji-icon faces that 0.37 moved behind
@@ -48,6 +42,7 @@ gridcraft-xlsx = { workspace = true, features = ["test-support"] }
craft-update = { workspace = true }
# The desktop's preferred language for the first-run interface language.
sys-locale = { workspace = true }
craft-window = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# Read the browser's preferred language for the first-run web interface language.
+6 -12
View File
@@ -88,8 +88,6 @@ impl SheetApp {
arrange_windows: None,
#[cfg(not(target_arch = "wasm32"))]
updates_rt: Default::default(),
framework_dialogs: Default::default(),
framework_host: crate::framework::host(),
}
}
@@ -104,7 +102,7 @@ impl SheetApp {
/// Sets up fonts and visuals for a specific persisted interface language.
pub fn setup_context_for_language(ctx: &egui::Context, dark: bool, language: i18n::Language) {
craft_ui::fonts::load(ctx, theme::font_definitions_for_language(language));
ctx.set_fonts(theme::font_definitions_for_language(language));
theme::apply(ctx, dark);
}
@@ -125,6 +123,7 @@ impl SheetApp {
self.desktop_dark = Some(answer);
}
self.sync_theme_preference(ctx);
self.sync_input_options(ctx);
// The geometry captures are bound to. Native frames recorded it from their fresh
// `RawInput` in `raw_input_hook` (including hidden logic-only ticks); the epoch is
// monotonic, so a resize back to the original values is still a new epoch and old pixels
@@ -140,6 +139,7 @@ impl SheetApp {
// Printing feedback is polled once per frame, here, so hidden windows and logic-only
// frames still see worker completion. `ui` and the desktop app no longer poll it.
self.poll_printing(ctx);
self.guard_window_close(ctx);
#[cfg(not(target_arch = "wasm32"))]
updates_ui::tick(self, ctx);
// Files read asynchronously (web file picker, dropped files).
@@ -164,7 +164,6 @@ impl SheetApp {
}
let Some(d) = self.session.active() else { return };
let title = format!("{}{}", d.display_title(), if d.is_dirty() { " — Edited" } else { "" });
let title = crate::channel::window_title(&title);
if self.grid.last_title.as_deref() != Some(title.as_str()) {
ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone()));
self.grid.last_title = Some(title);
@@ -213,6 +212,8 @@ impl SheetApp {
}
// The language the widgets translate with this frame (see `i18n::current`).
i18n::set_current(&ctx, self.ui.language);
#[cfg(not(target_arch = "wasm32"))]
updates_ui::show(self, &ctx);
let t = theme::Tokens::get(&ctx);
// A host can turn the File tab off while Backstage is already open: close it.
if !self.chrome.file_tab {
@@ -255,12 +256,6 @@ impl SheetApp {
widgets::toast(self, &ctx);
// Last, so its resize cursors win over the widgets under the window edges.
ribbon::window_frame(self, &ctx);
// The update flow and the framework dialogs run once per frame, in the root window.
if ctx.viewport_id() == egui::ViewportId::ROOT {
#[cfg(not(target_arch = "wasm32"))]
updates_ui::show(self, &ctx);
self.run_framework_dialogs(ui);
}
self.flush_viewport_commands(&ctx);
// Requests are admitted in `logic`, for the root viewport, so only its pass issues them.
if ctx.viewport_id() == egui::ViewportId::ROOT {
@@ -377,7 +372,6 @@ mod lifecycle_tests {
/// A font-gated early-returning pass does not lose the queued step; the hook offers it again and a later real pass applies it.
fn a_font_gated_pass_offers_the_synthetic_step_again() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
ctx.set_fonts(theme::font_definitions());
let mut app = app();
app.fonts_ready = true;
@@ -530,7 +524,7 @@ mod lifecycle_tests {
fn a_logic_only_tick_polls_printing_feedback() {
let ctx = egui::Context::default();
let mut app = app();
app.printing.printers.push(crate::printing::Printer::new("Queue").is_default(true));
app.printing.printers.push(crate::printing::Printer { name: "Queue".into(), label: String::new(), default: true });
app.run("ui.printSettings", serde_json::json!({"printer": "Queue"})).unwrap();
app.services.print_native = Some(Box::new(|_, _| {
let (sender, receiver) = std::sync::mpsc::channel();
+2 -2
View File
@@ -81,7 +81,7 @@ impl SheetApp {
return;
}
if self.prepared_fonts {
craft_ui::fonts::load(ctx, theme::pinned_font_definitions());
ctx.set_fonts(theme::pinned_font_definitions());
theme::apply(ctx, self.ui.dark);
} else {
SheetApp::setup_context_for_language(ctx, self.ui.dark, self.ui.language);
@@ -107,7 +107,7 @@ impl SheetApp {
if used == self.fonts_bound {
return;
}
craft_ui::fonts::load(ctx, theme::font_definitions_with(self.ui.language, &used));
ctx.set_fonts(theme::font_definitions_with(self.ui.language, &used));
self.fonts_bound = used;
self.fonts_rebind = true;
ctx.request_repaint();
+22 -10
View File
@@ -27,24 +27,36 @@ impl SheetApp {
self.effective_dark = ctx.theme() == egui::Theme::Dark;
}
/// Keeps egui's own keyboard zoom and quit shortcuts off and applies GridCraft's zoom factor.
pub(super) fn sync_input_options(&mut self, ctx: &egui::Context) {
// Interface size: the preference owns the zoom factor, so egui's own Ctrl/Cmd +/-/0 zoom
// keys stay off (they would also swallow GridCraft's shortcuts).
if ctx.options(|o| o.zoom_with_keyboard) {
ctx.options_mut(|o| o.zoom_with_keyboard = false);
}
// egui closes the window on Ctrl+Q (and with Shift or Alt held too) without asking to save
// (#1443). Excel for Windows has no such key (Ctrl+Q is Quick Analysis). With a native
// window per workbook egui's Cmd+Q would close only the window it was typed in: the menu
// bar's Quit item has the key instead (it asks about unsaved workbooks first).
if (ctx.os() != egui::os::OperatingSystem::Mac || self.native_windows) && ctx.options(|o| !o.quit_shortcuts.is_empty()) {
ctx.options_mut(|o| o.quit_shortcuts.clear());
}
let zoom = self.ui.zoom_factor();
if (ctx.zoom_factor() - zoom).abs() > 0.001 {
ctx.set_zoom_factor(zoom);
ctx.request_repaint();
}
}
/// Look for a newer release once, in the background, as the desktop app starts (a no-op on the
/// web). A found release opens the update prompt; nothing is shown when GridCraft is current.
/// A nightly channel has no update feed of its own: the Launcher installs and replaces it.
pub fn start_update_check(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
if crate::channel::stable_services_allowed() {
updates_ui::start(self, false);
}
updates_ui::start(self, false);
}
/// Help ▸ Check for Updates…: look now, and say so when GridCraft is up to date or the check fails.
pub fn check_for_updates(&mut self) {
// Never from the nightly channel: a check would download into, and record in, the stable
// app's folders, and an install would replace a Launcher-managed copy.
if !crate::channel::stable_services_allowed() {
self.message = Some((crate::channel::name().into(), "GridCraft Nightly is updated by ArtCraft Launcher.".into()));
return;
}
#[cfg(not(target_arch = "wasm32"))]
updates_ui::start(self, true);
#[cfg(target_arch = "wasm32")]
+11 -19
View File
@@ -1,35 +1,28 @@
use craft_ui::shell::embed::CloseDecision;
use super::{SaveAnswer, SheetApp, json};
impl SheetApp {
/// The root window was asked to close (the close button, Alt+F4, the OS quitting the app): whether it closes
/// now. A running print job holds it. With a native window per workbook the close is that window's
/// ([`crate::doc_windows`]) unless the app is quitting. Otherwise unsaved changes hold it while they are asked
/// about.
pub fn close_decision(&mut self, ctx: &egui::Context) -> CloseDecision {
if self.printing.busy() {
return CloseDecision::Hold;
}
if self.allow_close {
return CloseDecision::Close;
}
if self.native_windows {
return CloseDecision::Hold;
/// Holds back a window close (the close button, Alt+F4, the OS quitting the app) while a
/// workbook has unsaved changes, and asks about them first.
pub(super) fn guard_window_close(&mut self, ctx: &egui::Context) {
if self.native_windows || self.allow_close || !ctx.input(|i| i.viewport().close_requested()) {
return;
}
// A cell still being edited is part of the workbook, as for File › Close.
if !self.commit_edit(0, 0, false, false) {
return CloseDecision::Hold;
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
return;
}
// The macro step editor asks about its own unsaved steps and debug run first; once it has
// closed, the window close goes on.
if self.dialog.as_ref().is_some_and(|d| d.name == "macroEditor") {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
crate::macro_editor::request_close(self, true);
return CloseDecision::Hold;
return;
}
if !self.session.documents().iter().any(|d| d.is_dirty()) {
return CloseDecision::Close;
return;
}
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
match self.dialog.as_mut() {
// Already asking about a workbook (File › Close): answering it now goes on to quit.
Some(d) if d.name() == "saveChanges" => {
@@ -37,7 +30,6 @@ impl SheetApp {
}
_ => self.continue_quit(ctx),
}
CloseDecision::Hold
}
/// Asks about the next unsaved workbook before quitting, in its window, or closes the app
+9 -4
View File
@@ -233,7 +233,12 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) {
});
});
bs.text_edit_focused = ctx.text_edit_focused();
if !typing && app.dialog.is_none() && app.message.is_none() && !egui::Popup::is_any_open(&ctx) && crate::framework::consume_escape(&ctx) {
if !typing
&& app.dialog.is_none()
&& app.message.is_none()
&& !egui::Popup::is_any_open(&ctx)
&& ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape))
{
out.close = true;
}
if let Some(page) = out.page {
@@ -676,7 +681,7 @@ fn save_as(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcom
let current = SAVE_TYPES.iter().find(|(ext, _)| *ext == fmt).map_or("Excel Workbook (*.xlsx)", |(_, label)| *label);
ui.horizontal(|ui| {
let label = ui.label(lang.tr("Save as type"));
egui::ComboBox::from_id_salt("backstage_save_type")
craft_ui::ComboBox::from_id_salt("backstage_save_type")
.width(280.0)
.selected_text(lang.tr(current))
.show_ui(ui, |ui| {
@@ -793,11 +798,11 @@ fn account(app: &mut SheetApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
let lang = app.ui.language;
section(ui, lang, "Product Information");
ui.label(RichText::new(crate::channel::name()).font(theme::ui_bold(16.0)).color(t.text));
ui.label(RichText::new("GridCraft").font(theme::ui_bold(16.0)).color(t.text));
ui.add_space(8.0);
egui::Grid::new("backstage_account").num_columns(2).spacing(vec2(18.0, 8.0)).show(ui, |ui| {
for (label, value) in
[("Version", crate::channel::version().to_string()), ("Platform", platform()), ("Licence", env!("CARGO_PKG_LICENSE").to_string())]
[("Version", env!("CARGO_PKG_VERSION").to_string()), ("Platform", platform()), ("Licence", env!("CARGO_PKG_LICENSE").to_string())]
{
ui.label(RichText::new(lang.tr(label)).color(t.text_dim));
ui.label(value);
+2 -2
View File
@@ -63,7 +63,7 @@ fn general_options(app: &mut SheetApp, ui: &mut Ui, lang: Language) {
"dark" => "Dark",
_ => "Light",
};
egui::ComboBox::from_id_salt("backstage_theme")
craft_ui::ComboBox::from_id_salt("backstage_theme")
.width(160.0)
.selected_text(lang.tr(current))
.show_ui(ui, |ui| {
@@ -77,7 +77,7 @@ fn general_options(app: &mut SheetApp, ui: &mut Ui, lang: Language) {
.labelled_by(label.id);
ui.end_row();
let label = ui.label(lang.tr("Interface language"));
egui::ComboBox::from_id_salt("backstage_language")
craft_ui::ComboBox::from_id_salt("backstage_language")
.width(160.0)
.selected_text(lang.name())
.show_ui(ui, |ui| {
+2 -2
View File
@@ -22,7 +22,7 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
let pages: Vec<Json> = bs.preview.as_ref().and_then(|(_, p)| p.get("pageList")).and_then(Json::as_array).cloned().unwrap_or_default();
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(340.0);
ui.set_width(250.0);
if let Some(discover) = &app.services.printers {
crate::printing::show(&mut app.printing, ui, discover, |label| lang.tr(label).to_owned());
}
@@ -35,7 +35,7 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
}
ui.add_space(16.0);
let scope = if bs.print_all { "Print Entire Workbook" } else { "Print Active Sheets" };
egui::ComboBox::from_id_salt("backstage_print_scope")
craft_ui::ComboBox::from_id_salt("backstage_print_scope")
.width(230.0)
.selected_text(lang.tr(scope))
.show_ui(ui, |ui| {
-251
View File
@@ -1,251 +0,0 @@
//! One-shot completion slots for screenshot requests.
//!
//! Applications retain request IDs, output paths, deadlines, settling policy, geometry epochs and
//! aggregate admission budgets. This module only correlates one capture with one slot, checks the
//! retained image against a per-image byte bound, and wakes the owning viewport.
//!
//! [`CaptureSlot::new`] does not issue a screenshot command. Send the returned [`egui::ScreenshotCallback`]
//! with [`egui::ViewportCommand::Screenshot`] when the application decides the capture is due, or
//! complete it directly from a headless renderer. The callback holds only a weak reference to the
//! slot, so dropping or cancelling the request releases its image and makes late results inert.
//!
//! Every retry needs a fresh slot and a fresh callback from [`CaptureSlot::new`]; a callback is
//! one-shot, and a slot ignores completions after its result was taken, cancelled or dropped. The
//! slot does not track whether a request is still open: keep that pending/closed distinction in the
//! application's request record.
//!
//! A completion that publishes its result just before a concurrent [`CaptureSlot::cancel`] or drop
//! can still deliver its single wakeup afterwards. That extra repaint is harmless: if the
//! cancellation won, the image is released and a later [`CaptureSlot::take`] returns `None`; if
//! `take` won first, the caller already owns the result and nothing else changes. A completion that
//! observes a cancelled or taken slot stores no image and does not wake. Cancellation and completion
//! are therefore not atomic with respect to the wakeup, and this module never waits for another
//! thread while holding the slot lock.
//!
//! [`CaptureSlot`] holds a strong [`egui::Context`]. Keep it in the application's request record;
//! storing it in `Context`-owned data (`egui::Memory::data` or a registered plugin) forms a
//! `Context` → slot → `Context` cycle that keeps both alive.
use std::mem::size_of;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use egui::{Color32, ColorImage, Context, ScreenshotCallback, ViewportId};
/// Why a completed screenshot was rejected and released.
///
/// The enum is `#[non_exhaustive]`: consumers should match the known variants and use a wildcard
/// arm for a future rejection reason.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CaptureError {
/// The checked `width * height` pixel count, or its `width * height * size_of::<Color32>()`
/// byte count, overflowed `usize`.
DimensionsOverflow { width: usize, height: usize },
/// The pixel buffer does not match the reported image dimensions, or the image has zero width
/// or height.
MalformedImage { width: usize, height: usize, pixels: usize },
/// The checked image size exceeds the slot's per-image byte bound.
ImageTooLarge { bytes: usize, max_bytes: usize },
}
impl core::fmt::Display for CaptureError {
/// Format a human-readable rejection reason. The wording is informative only and is not an
/// API contract; the variants keep checked-overflow, malformed-image and size-cap cases
/// distinguishable.
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::DimensionsOverflow { width, height } => {
write!(f, "screenshot dimensions {width}×{height} overflow the checked pixel or byte count")
}
Self::MalformedImage { width, height, pixels } => write!(f, "screenshot has {pixels} pixels for its {width}×{height} dimensions"),
Self::ImageTooLarge { bytes, max_bytes } => write!(f, "screenshot uses {bytes} bytes, over the {max_bytes}-byte per-image limit"),
}
}
}
impl std::error::Error for CaptureError {}
enum SlotState {
Pending,
Ready(Result<Arc<ColorImage>, CaptureError>),
Taken,
Cancelled,
}
struct Shared {
state: Mutex<SlotState>,
/// The live request owns the strong context; the callback only upgrades it briefly to wake.
context: Context,
viewport: ViewportId,
max_image_bytes: usize,
}
/// The live request side of a capture. Keep it alive until the result is taken or the request is
/// cancelled; dropping it cancels the completion and releases any retained image.
///
/// This type is `Send + Sync`; the application may hold it in its request record and poll
/// [`Self::take`] from its logic pass. Do not store it in `Context`-owned storage: the slot holds a
/// strong [`egui::Context`], so `egui::Memory::data` or a registered plugin would create a cycle.
#[must_use = "the slot must be kept alive to receive and take the screenshot"]
pub struct CaptureSlot {
shared: Arc<Shared>,
}
impl CaptureSlot {
/// Create a completion slot and its one-shot callback.
///
/// `max_image_bytes` bounds the single retained image only. The application must separately
/// reserve its aggregate in-flight/completed budget before issuing the request.
///
/// This function does not send a viewport command. If the request is issued in a UI pass, send
/// the callback with [`egui::ViewportCommand::Screenshot`]; a pending screenshot command itself
/// requests the paint needed while the window is hidden. Issue that command at most once per
/// slot, after the application has settled the frame it wants; every retry needs a fresh slot
/// and callback.
pub fn new(context: &Context, viewport: ViewportId, max_image_bytes: usize) -> (Self, ScreenshotCallback) {
let shared = Arc::new(Shared { state: Mutex::new(SlotState::Pending), context: context.clone(), viewport, max_image_bytes });
let weak = Arc::downgrade(&shared);
let callback = ScreenshotCallback::new(move |image| complete(&weak, image));
(Self { shared }, callback)
}
/// Take the completed result, at most once.
///
/// Returns `None` while the capture is pending, after it was cancelled or dropped, and after a
/// previous call already took the image or error. The slot cannot distinguish those states;
/// the application's request record owns the pending/closed distinction. Invalid images are
/// returned as an error so the application can report completion failure with its own request
/// identity.
pub fn take(&self) -> Option<Result<Arc<ColorImage>, CaptureError>> {
let mut state = lock(&self.shared.state);
if !matches!(&*state, SlotState::Ready(_)) {
return None;
}
match core::mem::replace(&mut *state, SlotState::Taken) {
SlotState::Ready(result) => Some(result),
_ => None,
}
}
/// Cancel the request and release any completed image.
///
/// A completion that published its result before this call may still deliver one harmless
/// repaint afterwards; the slot retains no image and a later [`Self::take`] returns `None`. A
/// completion that observes the cancellation stores no image and does not wake. Calling `cancel`
/// after [`Self::take`] is harmless. Any retained image is dropped after the slot mutex is
/// unlocked.
pub fn cancel(&self) {
close(&self.shared);
}
#[cfg(test)]
/// Nonblocking probe used by the wakeup test to prove that the slot mutex is free while the
/// repaint observer runs.
fn lock_is_free(&self) -> bool {
self.shared.state.try_lock().is_ok()
}
#[cfg(test)]
/// Count strong references to the shared slot state, proving callbacks retain none.
fn state_strong_count(&self) -> usize {
Arc::strong_count(&self.shared)
}
#[cfg(test)]
/// A weak handle to the shared state, used to inject a second completion directly when egui has
/// already consumed the public callback.
fn state_weak(&self) -> Weak<Shared> {
Arc::downgrade(&self.shared)
}
}
impl Drop for CaptureSlot {
/// Cancel the request as the slot goes away. A later completion upgrades no live state and
/// releases its image, a retained ready image is dropped, and no repaint is requested. Results
/// already taken by the caller are unaffected.
fn drop(&mut self) {
close(&self.shared);
}
}
impl core::fmt::Debug for CaptureSlot {
/// Format only the viewport and omit the remaining fields. The retained image and error payload
/// are deliberately hidden so logging cannot hold or dump screenshot contents.
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("CaptureSlot").field("viewport", &self.shared.viewport).finish_non_exhaustive()
}
}
/// Lock the slot state, recovering from poisoning instead of panicking. The guard must be
/// released before entering the egui context or a repaint observer; completion and close do so
/// before waking the viewport.
fn lock(state: &Mutex<SlotState>) -> MutexGuard<'_, SlotState> {
state.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Mark the slot closed and drop any retained image after releasing the mutex.
fn close(shared: &Shared) {
let previous = {
let mut state = lock(&shared.state);
core::mem::replace(&mut *state, SlotState::Cancelled)
};
drop(previous);
}
/// Validate a completed image, store it, and wake the owning viewport.
///
/// The slot lock is released before calling into the context, so a repaint observer may call
/// [`CaptureSlot::take`] or [`CaptureSlot::cancel`] re-entrantly. Inside an observer, only consume or
/// release that value; any further `Context` access must happen outside the observer.
/// [`egui::Context::request_repaint_of`] takes egui's context lock. Ordinary `Ui` closures and egui
/// 0.37 plugin hooks run outside that lock, as do renderer/worker callbacks. Repaint observers and
/// request-repaint callbacks run under it: completing from either would deadlock when requesting
/// the repaint. This function never waits under the slot lock.
fn complete(weak: &Weak<Shared>, image: Arc<ColorImage>) {
let Some(shared) = weak.upgrade() else {
// The request was dropped; the image is released here without a reply.
return;
};
let result = checked_image(image, shared.max_image_bytes);
let should_wake = {
let mut state = lock(&shared.state);
if matches!(&*state, SlotState::Pending) {
*state = SlotState::Ready(result);
true
} else {
// Cancelled, already taken, or (defensively) completed twice: drop the image.
false
}
};
// The slot lock is released before calling into the context, so a repaint observer may take
// the result or cancel the request re-entrantly without deadlocking.
if should_wake {
shared.context.request_repaint_of(shared.viewport);
}
}
/// Validate `image` against the slot's per-image byte bound before publishing it.
///
/// Zero width or height is malformed before any arithmetic; the pixel count and its byte size use
/// checked multiplication; the buffer length must equal `width * height`; and only then is the
/// byte count compared with `max_image_bytes`, rejecting a count greater than it (equality is
/// accepted). `max_image_bytes` bounds this one image, not an aggregate request budget. Returns the
/// same `Arc` without waking the viewport or requesting a repaint.
fn checked_image(image: Arc<ColorImage>, max_image_bytes: usize) -> Result<Arc<ColorImage>, CaptureError> {
let [width, height] = image.size;
if width == 0 || height == 0 {
return Err(CaptureError::MalformedImage { width, height, pixels: image.pixels.len() });
}
let pixels = width.checked_mul(height).ok_or(CaptureError::DimensionsOverflow { width, height })?;
let bytes = pixels.checked_mul(size_of::<Color32>()).ok_or(CaptureError::DimensionsOverflow { width, height })?;
if image.pixels.len() != pixels {
return Err(CaptureError::MalformedImage { width, height, pixels: image.pixels.len() });
}
if bytes > max_image_bytes {
return Err(CaptureError::ImageTooLarge { bytes, max_bytes: max_image_bytes });
}
Ok(image)
}
#[cfg(test)]
mod tests;
-491
View File
@@ -1,491 +0,0 @@
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Barrier};
use super::*;
/// Allocate a filled `Arc<ColorImage>` fixture of `size` with every pixel set to `color`.
fn image(size: [usize; 2], color: egui::Color32) -> Arc<ColorImage> {
Arc::new(ColorImage::filled(size, color))
}
/// Install a repaint observer and return the viewport requests it records.
fn observe_repaints(ctx: &Context) -> Arc<Mutex<Vec<ViewportId>>> {
let requests = Arc::new(Mutex::new(Vec::new()));
let observed = requests.clone();
ctx.set_repaint_observer(move |info| observed.lock().unwrap().push(info.viewport_id));
requests
}
#[test]
/// Compile-time assertion that `CaptureSlot` and `ScreenshotCallback` are `Send + Sync`.
fn slot_is_send_and_sync() {
/// Compile-time helper requiring `T: Send + Sync`; the enclosing test uses it to
/// assert the public capture types are thread-safe.
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<CaptureSlot>();
assert_send_sync::<ScreenshotCallback>();
}
#[test]
/// Two independent slots for different viewports may complete in reverse order; each `take`
/// returns exactly its own image and dimensions.
fn distinct_requests_complete_in_reverse_order() {
let ctx = Context::default();
let first_viewport = ViewportId::from_hash_of("first-window");
let second_viewport = ViewportId::from_hash_of("second-window");
let (first, first_callback) = CaptureSlot::new(&ctx, first_viewport, 1024);
let (second, second_callback) = CaptureSlot::new(&ctx, second_viewport, 1024);
let first_image = image([2, 1], egui::Color32::RED);
let second_image = image([1, 3], egui::Color32::BLUE);
// The renderer may answer the later request first.
second_callback.complete(second_image.clone());
first_callback.complete(first_image.clone());
let taken_first = first.take().unwrap().unwrap();
let taken_second = second.take().unwrap().unwrap();
assert!(Arc::ptr_eq(&taken_first, &first_image));
assert!(Arc::ptr_eq(&taken_second, &second_image));
assert_eq!(taken_first.size, [2, 1]);
assert_eq!(taken_second.size, [1, 3]);
}
#[test]
/// Slots keep separate results and byte caps: a 2×2 image over the first slot's 4-byte cap is
/// rejected as too large while the second stays pending, then the second accepts its own image and
/// a taken slot remains empty.
fn slots_do_not_share_results_or_byte_bounds() {
let ctx = Context::default();
let first_viewport = ViewportId::from_hash_of("first-slot");
let second_viewport = ViewportId::from_hash_of("second-slot");
let (first, first_callback) = CaptureSlot::new(&ctx, first_viewport, 4);
let (second, second_callback) = CaptureSlot::new(&ctx, second_viewport, 16);
let rejected_for_first = image([2, 2], egui::Color32::RED);
first_callback.complete(rejected_for_first);
assert!(second.take().is_none(), "completing one slot leaves the other pending");
assert!(matches!(first.take(), Some(Err(CaptureError::ImageTooLarge { bytes: 16, max_bytes: 4 }))));
let accepted_for_second = image([2, 2], egui::Color32::BLUE);
second_callback.complete(accepted_for_second.clone());
assert!(Arc::ptr_eq(&second.take().unwrap().unwrap(), &accepted_for_second));
assert!(first.take().is_none(), "a taken slot stays empty");
}
#[test]
/// Cloned callbacks share one completion: the first result wins, the losing image is released, and
/// `take` yields the result only once.
fn callback_clones_share_one_completion_and_take_is_single_use() {
let ctx = Context::default();
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
let duplicate = callback.clone();
let first_image = image([1, 1], egui::Color32::RED);
let second_image = image([1, 1], egui::Color32::BLUE);
let weak_loser = Arc::downgrade(&second_image);
callback.complete(first_image.clone());
duplicate.complete(second_image);
assert!(weak_loser.upgrade().is_none(), "the losing completion releases its image");
let taken = slot.take().unwrap().unwrap();
assert!(Arc::ptr_eq(&taken, &first_image), "the first completion wins");
assert!(slot.take().is_none(), "the result is taken once");
}
#[test]
/// After `take`, both a duplicate callback and a direct completion release their images without
/// storing a result or requesting a repaint.
fn duplicate_completion_after_take_neither_stores_nor_wakes() {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
let duplicate_callback = callback.clone();
let first_image = image([1, 1], egui::Color32::RED);
callback.complete(first_image.clone());
assert!(Arc::ptr_eq(&slot.take().unwrap().unwrap(), &first_image));
assert_eq!(requests.lock().unwrap().len(), 1, "the first completion wakes");
let duplicate_image = image([1, 1], egui::Color32::BLUE);
let weak_duplicate = Arc::downgrade(&duplicate_image);
duplicate_callback.complete(duplicate_image);
assert!(weak_duplicate.upgrade().is_none(), "a duplicate after take is released");
assert!(slot.take().is_none());
assert_eq!(requests.lock().unwrap().len(), 1, "a duplicate after take does not wake");
// Deliver a second completion straight to the slot; egui already consumed its callback.
let direct_image = image([1, 1], egui::Color32::GREEN);
let weak_direct = Arc::downgrade(&direct_image);
complete(&slot.state_weak(), direct_image);
assert!(weak_direct.upgrade().is_none(), "a direct second completion after take is released");
assert!(slot.take().is_none());
assert_eq!(requests.lock().unwrap().len(), 1, "a direct second completion after take does not wake");
}
#[test]
/// An early `take` returns `None` without closing the request; a later completion still delivers.
fn take_before_completion_is_empty_and_keeps_the_request_open() {
let ctx = Context::default();
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
assert!(slot.take().is_none());
let expected = image([1, 1], egui::Color32::RED);
callback.complete(expected.clone());
assert!(Arc::ptr_eq(&slot.take().unwrap().unwrap(), &expected));
}
#[test]
/// Cancelling before completion releases a late image, leaves `take` empty, and suppresses the
/// repaint wakeup.
fn cancel_releases_late_images_without_waking() {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let viewport = ViewportId::from_hash_of("cancelled-window");
let (slot, callback) = CaptureSlot::new(&ctx, viewport, 1024);
slot.cancel();
let late_image = image([2, 2], egui::Color32::RED);
let weak_image = Arc::downgrade(&late_image);
callback.complete(late_image.clone());
drop(late_image);
assert!(weak_image.upgrade().is_none(), "a cancelled slot releases the late image");
assert!(slot.take().is_none());
assert!(requests.lock().unwrap().is_empty(), "cancellation suppresses the wakeup");
}
#[test]
/// A ready slot retains its image and has woken once; `cancel` releases the image and does not wake
/// again.
fn cancel_after_ready_releases_the_image() {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
let completed = image([2, 2], egui::Color32::RED);
let weak_image = Arc::downgrade(&completed);
callback.complete(completed.clone());
drop(completed);
assert!(weak_image.upgrade().is_some(), "the ready slot retains the image");
assert_eq!(requests.lock().unwrap().len(), 1, "the completion woke the viewport");
slot.cancel();
assert!(weak_image.upgrade().is_none(), "cancel releases a ready image");
assert!(slot.take().is_none());
assert_eq!(requests.lock().unwrap().len(), 1, "cancellation itself does not wake");
}
#[test]
/// Dropping the slot releases an image that is only retained by the completed slot.
fn dropping_the_slot_releases_a_completed_image() {
let ctx = Context::default();
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
let completed = image([2, 2], egui::Color32::RED);
callback.complete(completed.clone());
let weak_image = Arc::downgrade(&completed);
drop(completed);
assert!(weak_image.upgrade().is_some(), "the slot retains the completed image");
drop(slot);
assert!(weak_image.upgrade().is_none(), "dropping the slot releases its image");
}
#[test]
/// A completion after the slot is dropped releases the image and does not wake the viewport.
fn late_completion_after_drop_is_inert() {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let viewport = ViewportId::ROOT;
let (slot, callback) = CaptureSlot::new(&ctx, viewport, 1024);
drop(slot);
let late_image = image([1, 1], egui::Color32::RED);
let weak_image = Arc::downgrade(&late_image);
callback.complete(late_image.clone());
drop(late_image);
assert!(weak_image.upgrade().is_none());
assert!(requests.lock().unwrap().is_empty(), "a late result does not wake the viewport");
}
#[test]
/// Callbacks hold only a weak reference: the slot state has one strong owner, dropping the slot
/// releases the context and state, and a later completion is inert.
fn callback_retains_only_a_weak_reference_to_live_state() {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
let callback_clone = callback.clone();
assert_eq!(slot.state_strong_count(), 1, "the callback must not own the slot state");
let weak_state = slot.state_weak();
drop(slot);
assert!(weak_state.upgrade().is_none(), "dropping the slot releases its context and state");
let late_image = image([1, 1], egui::Color32::RED);
let weak_image = Arc::downgrade(&late_image);
callback_clone.complete(late_image.clone());
drop(late_image);
assert!(weak_image.upgrade().is_none());
assert!(requests.lock().unwrap().is_empty());
}
#[test]
/// A completion distinguishes the per-image size cap, a malformed pixel buffer, and overflow of
/// the pixel or byte count; a returned error is taken at most once.
fn rejects_oversized_malformed_and_overflowing_images() {
let ctx = Context::default();
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 16);
callback.complete(image([3, 3], egui::Color32::RED));
assert!(matches!(slot.take(), Some(Err(CaptureError::ImageTooLarge { bytes: 36, max_bytes: 16 }))));
assert!(slot.take().is_none(), "a completion error is reported once");
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
callback.complete(Arc::new(ColorImage { size: [2, 2], source_size: egui::Vec2::ZERO, pixels: vec![egui::Color32::RED; 3] }));
assert!(matches!(slot.take(), Some(Err(CaptureError::MalformedImage { width: 2, height: 2, pixels: 3 }))));
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
callback.complete(Arc::new(ColorImage { size: [usize::MAX, 2], source_size: egui::Vec2::ZERO, pixels: Vec::new() }));
assert!(matches!(slot.take(), Some(Err(CaptureError::DimensionsOverflow { width, height })) if width == usize::MAX && height == 2));
// The pixel count fits but the byte count does not.
let wide = usize::MAX / 2;
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
callback.complete(Arc::new(ColorImage { size: [wide, 1], source_size: egui::Vec2::ZERO, pixels: Vec::new() }));
assert!(matches!(slot.take(), Some(Err(CaptureError::DimensionsOverflow { width, height })) if width == wide && height == 1));
}
#[test]
/// Oversized and malformed images are dropped immediately and each rejection still wakes the error
/// consumer exactly once before `take` reports it.
fn rejected_oversized_and_malformed_images_are_released_before_take() {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 16);
let oversized = image([3, 3], egui::Color32::RED);
let weak_oversized = Arc::downgrade(&oversized);
callback.complete(oversized);
assert!(weak_oversized.upgrade().is_none(), "an oversized image is released");
assert_eq!(*requests.lock().unwrap(), [ViewportId::ROOT], "rejection wakes the error consumer");
assert!(matches!(slot.take(), Some(Err(CaptureError::ImageTooLarge { bytes: 36, max_bytes: 16 }))));
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
let malformed = Arc::new(ColorImage { size: [2, 2], source_size: egui::Vec2::ZERO, pixels: vec![egui::Color32::RED; 3] });
let weak_malformed = Arc::downgrade(&malformed);
callback.complete(malformed);
assert!(weak_malformed.upgrade().is_none(), "a malformed image is released");
assert_eq!(*requests.lock().unwrap(), [ViewportId::ROOT, ViewportId::ROOT]);
assert!(matches!(slot.take(), Some(Err(CaptureError::MalformedImage { width: 2, height: 2, pixels: 3 }))));
}
#[test]
/// Any zero width or height is rejected as malformed before overflow or size-cap decisions, even
/// for extreme extents such as `usize::MAX × 0`.
fn zero_area_images_are_rejected_even_with_extreme_extents() {
let ctx = Context::default();
for size in [[0, 4], [4, 0], [0, 0], [usize::MAX, 0], [0, usize::MAX]] {
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
callback.complete(Arc::new(ColorImage { size, source_size: egui::Vec2::ZERO, pixels: Vec::new() }));
let rejected = slot.take();
assert!(
matches!(rejected, Some(Err(CaptureError::MalformedImage { width, height, pixels }))
if width == size[0] && height == size[1] && pixels == 0),
"zero-area image {size:?} must be rejected"
);
}
}
#[test]
/// A 2×2 image at exactly the 16-byte cap is accepted: the bound is inclusive.
fn accepts_an_image_exactly_at_the_byte_bound() {
let ctx = Context::default();
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 16);
let exact = image([2, 2], egui::Color32::GREEN);
callback.complete(exact.clone());
assert!(Arc::ptr_eq(&slot.take().unwrap().unwrap(), &exact));
}
#[test]
/// A worker thread completes a child-window slot; every recorded wake belongs to that slot's
/// viewport and the expected image is delivered.
fn another_thread_completes_and_wakes_only_the_owning_viewport() {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let viewport = ViewportId::from_hash_of("child-window");
let (slot, callback) = CaptureSlot::new(&ctx, viewport, 1024);
let expected = image([1, 1], egui::Color32::RED);
let sent = expected.clone();
let handle = std::thread::spawn(move || callback.complete(sent));
handle.join().unwrap();
let requested = requests.lock().unwrap();
assert!(!requested.is_empty(), "completion wakes the owning viewport");
assert!(requested.iter().all(|requested_viewport| *requested_viewport == viewport), "completion wakes only the owning viewport: {requested:?}");
drop(requested);
assert!(Arc::ptr_eq(&slot.take().unwrap().unwrap(), &expected));
}
#[test]
/// The repaint observer can `take` the image re-entrantly: `try_lock` succeeds during the wakeup,
/// proving the slot lock is released before `request_repaint_of`.
fn wakeup_runs_after_the_slot_lock_is_released() {
let ctx = Context::default();
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
let slot = Arc::new(slot);
let weak_slot = Arc::downgrade(&slot);
let observed = Arc::new(AtomicBool::new(false));
let lock_free = Arc::new(AtomicBool::new(true));
let taken = Arc::new(AtomicBool::new(false));
let observer_observed = observed.clone();
let observer_lock_free = lock_free.clone();
let observer_taken = taken.clone();
ctx.set_repaint_observer(move |info| {
if info.viewport_id == ViewportId::ROOT {
observer_observed.store(true, Ordering::SeqCst);
if let Some(slot) = weak_slot.upgrade() {
if slot.lock_is_free() {
observer_taken.store(slot.take().is_some(), Ordering::SeqCst);
} else {
observer_lock_free.store(false, Ordering::SeqCst);
}
}
}
});
callback.complete(image([1, 1], egui::Color32::RED));
assert!(observed.load(Ordering::SeqCst), "completion wakes the owning viewport");
assert!(lock_free.load(Ordering::SeqCst), "the slot lock is released before the wakeup");
assert!(taken.load(Ordering::SeqCst), "the observer can consume the image reentrantly");
assert!(slot.take().is_none());
}
/// Complete, cancel and take all racing on one slot. Every interleaving must leave at most one
/// wake and at most one taken result, and every image must be released once the slot and result
/// are dropped.
#[test]
fn complete_cancel_and_take_race_without_retaining_or_double_waking() {
const RACE_TRIALS: usize = 100;
for trial in 0..RACE_TRIALS {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let viewport = ViewportId::from_hash_of("race-window");
let (slot, callback) = CaptureSlot::new(&ctx, viewport, 4096);
let slot = Arc::new(slot);
let completed = image([1, 1], egui::Color32::RED);
let weak_image = Arc::downgrade(&completed);
let barrier = Arc::new(Barrier::new(3));
let taken = std::thread::scope(|scope| {
let completion_barrier = barrier.clone();
let completion_image = completed.clone();
scope.spawn(move || {
completion_barrier.wait();
callback.complete(completion_image);
});
let cancel_barrier = barrier.clone();
let cancel_slot = slot.clone();
scope.spawn(move || {
cancel_barrier.wait();
cancel_slot.cancel();
});
barrier.wait();
slot.take()
});
let wake_count = requests.lock().unwrap().len();
assert!(wake_count <= 1, "trial {trial}: one completion wakes at most once, got {wake_count}");
if taken.is_some() {
assert_eq!(wake_count, 1, "trial {trial}: a published result wakes exactly once");
}
if let Some(result) = &taken {
match result {
Ok(taken_image) => assert!(Arc::ptr_eq(taken_image, &completed), "trial {trial}: only the completed image is returned"),
Err(error) => panic!("trial {trial}: a valid image was rejected: {error:?}"),
}
}
drop(taken);
drop(slot);
drop(completed);
assert!(weak_image.upgrade().is_none(), "trial {trial}: the slot and any taken result release the image");
}
}
#[test]
/// A zero byte budget rejects any nonempty image as too large and wakes once.
fn zero_budget_rejects_a_nonempty_image_and_wakes() {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 0);
callback.complete(image([1, 1], egui::Color32::GREEN));
assert!(matches!(slot.take(), Some(Err(CaptureError::ImageTooLarge { bytes: 4, max_bytes: 0 }))));
assert_eq!(*requests.lock().unwrap(), [ViewportId::ROOT]);
}
#[test]
/// Two threads racing on `take` produce exactly one result, and a subsequent take is empty.
fn concurrent_takers_receive_the_result_exactly_once() {
let ctx = Context::default();
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 4);
let expected = image([1, 1], egui::Color32::GREEN);
callback.complete(expected.clone());
let barrier = Barrier::new(3);
let results = std::thread::scope(|scope| {
let first = scope.spawn(|| {
barrier.wait();
slot.take()
});
let second = scope.spawn(|| {
barrier.wait();
slot.take()
});
barrier.wait();
[first.join().unwrap(), second.join().unwrap()]
});
assert_eq!(results.iter().filter(|result| result.is_some()).count(), 1);
for result in results.into_iter().flatten() {
assert!(Arc::ptr_eq(&result.unwrap(), &expected));
}
assert!(slot.take().is_none());
}
#[test]
/// A renderer thread can complete a capture while a UI closure is blocked; the image is delivered
/// and the owning child viewport is woken exactly once.
fn renderer_completion_during_a_live_ui_pass_can_wake_and_deliver() {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let viewport = ViewportId::from_hash_of("render-readback");
let (slot, callback) = CaptureSlot::new(&ctx, viewport, 4);
let expected = image([1, 1], egui::Color32::GREEN);
let sent = expected.clone();
let (start_tx, start_rx) = std::sync::mpsc::channel();
let (done_tx, done_rx) = std::sync::mpsc::channel();
std::thread::scope(|scope| {
scope.spawn(move || {
start_rx.recv().unwrap();
callback.complete(sent);
done_tx.send(()).unwrap();
});
let mut start_tx = Some(start_tx);
let mut output = ctx.run_ui(Default::default(), |ui| {
ui.label("A live frame while readback completes");
if let Some(tx) = start_tx.take() {
tx.send(()).unwrap();
done_rx.recv_timeout(std::time::Duration::from_secs(3)).expect("readback must complete while the UI closure is active");
}
});
// This synchronization test has no renderer to apply the atlas upload.
output.textures_delta.clear();
});
assert!(Arc::ptr_eq(&slot.take().unwrap().unwrap(), &expected));
assert_eq!(requests.lock().unwrap().iter().filter(|id| **id == viewport).count(), 1);
}
-167
View File
@@ -1,167 +0,0 @@
//! The compiled channel this process belongs to: its OS identity, its window titles and the
//! version the Help ▸ About and File ▸ Account views show.
//!
//! The desktop selects it once, before any window exists (`prepare_launch`), so a launch cannot
//! change it later and nothing here is a user preference. A stable build keeps its old identity
//! and titles byte for byte; the nightly build carries its own app id so docks, window managers
//! and the taskbar keep the two channels apart.
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU8, Ordering};
/// The stable window/Wayland app id, matching the `.desktop` file and the hicolor icon name.
pub const APP_ID: &str = "ai.storyteller.gridcraft";
/// The nightly window id and Windows AUMID.
pub const NIGHTLY_APP_ID: &str = "ai.storyteller.gridcraft.nightly-v1";
/// The nightly Flatpak package (and macOS bundle) identity, `packaging/linux/flatpak-bundle.sh`.
/// A different string from [`NIGHTLY_APP_ID`] on purpose: inside its sandbox the Flatpak names the
/// window after the package id, which is what its `.desktop` file and portal entry carry.
pub const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.gridcraft.nightly";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Channel {
Stable,
NightlyV1,
}
static SELECTED: AtomicU8 = AtomicU8::new(0);
static VERSION: OnceLock<&'static str> = OnceLock::new();
/// Fix the channel and its version for this process, once. `version` is the build's own identity
/// (`GRIDCRAFT_BUILT_VERSION` from `build.rs`), not a value read from the environment at runtime.
pub fn select(channel: Channel, version: &'static str) -> Result<(), String> {
let value = match channel {
Channel::Stable => 1,
Channel::NightlyV1 => 2,
};
SELECTED.compare_exchange(0, value, Ordering::AcqRel, Ordering::Acquire).map_err(|_| "the channel was already selected".to_string())?;
VERSION.set(version).map_err(|_| "the channel version was already selected".to_string())
}
pub fn current() -> Channel {
if SELECTED.load(Ordering::Acquire) == 2 { Channel::NightlyV1 } else { Channel::Stable }
}
pub const fn id_for(channel: Channel) -> &'static str {
match channel {
Channel::Stable => APP_ID,
Channel::NightlyV1 => NIGHTLY_APP_ID,
}
}
pub fn app_id() -> &'static str {
id_for(current())
}
pub const fn name_for(channel: Channel) -> &'static str {
match channel {
Channel::Stable => "GridCraft",
Channel::NightlyV1 => "GridCraft Nightly",
}
}
pub fn name() -> &'static str {
name_for(current())
}
/// The title of a window that shows no document yet: the channel's own name.
pub fn default_title() -> &'static str {
name()
}
/// Only a stable build runs the stable-only services (the updater, the shared suite state).
pub const fn stable_services_for(channel: Channel) -> bool {
matches!(channel, Channel::Stable)
}
pub fn stable_services_allowed() -> bool {
stable_services_for(current())
}
/// The version to show: the selected build's own identity, else the crate version (a web build,
/// or a shell that never selected a channel).
pub fn version_for(channel: Channel, configured: Option<&'static str>) -> &'static str {
match (channel, configured) {
(Channel::NightlyV1, Some(version)) => version,
_ => env!("CARGO_PKG_VERSION"),
}
}
pub fn version() -> &'static str {
version_for(current(), VERSION.get().copied())
}
/// The commit a nightly was built from, read back from its version (`…g<sha12>`), if any.
///
/// The producer writes the sha in lower case (the version pattern every nightly job enforces), so an
/// upper-case one is a malformed version rather than a commit: nothing is read back for it.
pub fn commit_for(version: &str) -> Option<&str> {
let (_, suffix) = version.split_once("-nightly.")?;
let (_, sha) = suffix.rsplit_once(".g")?;
(sha.len() == 12 && sha.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))).then_some(sha)
}
pub fn commit() -> Option<&'static str> {
(current() == Channel::NightlyV1).then_some(version()).and_then(commit_for)
}
/// A window title that names the channel whenever a document is shown in it. A stable window keeps
/// exactly the title it always had; a nightly one appends its channel, so two windows on the same
/// workbook are never mistaken for each other in the taskbar or the window menu.
pub fn window_title_for(channel: Channel, base: &str) -> String {
match channel {
Channel::Stable => base.to_string(),
Channel::NightlyV1 => format!("{base} \u{2014} {}", name_for(channel)),
}
}
pub fn window_title(base: &str) -> String {
window_title_for(current(), base)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_two_channels_have_distinct_ids_and_names() {
assert_eq!(id_for(Channel::Stable), "ai.storyteller.gridcraft");
assert_eq!(id_for(Channel::NightlyV1), "ai.storyteller.gridcraft.nightly-v1");
assert_ne!(id_for(Channel::Stable), id_for(Channel::NightlyV1));
// Three strings, not two: the Flatpak package id is not the window id, and neither is stable's.
assert_eq!(NIGHTLY_PACKAGE_ID, "ai.storyteller.gridcraft.nightly");
assert_ne!(NIGHTLY_PACKAGE_ID, id_for(Channel::NightlyV1));
assert_ne!(NIGHTLY_PACKAGE_ID, id_for(Channel::Stable));
assert_eq!(name_for(Channel::Stable), "GridCraft");
assert_eq!(name_for(Channel::NightlyV1), "GridCraft Nightly");
assert!(stable_services_for(Channel::Stable));
assert!(!stable_services_for(Channel::NightlyV1));
}
#[test]
fn stable_titles_and_version_are_unchanged() {
for base in ["Book1", "Book1 — Edited", "", "sales.xlsx"] {
assert_eq!(window_title_for(Channel::Stable, base), base);
}
assert_eq!(version_for(Channel::Stable, Some("0.19.1-nightly.20261124.7.1.gabcdef012345")), env!("CARGO_PKG_VERSION"));
assert_eq!(version_for(Channel::Stable, None), env!("CARGO_PKG_VERSION"));
}
#[test]
fn nightly_titles_name_the_channel_and_keep_the_document() {
assert_eq!(window_title_for(Channel::NightlyV1, "Book1"), "Book1 \u{2014} GridCraft Nightly");
assert_eq!(window_title_for(Channel::NightlyV1, ""), " \u{2014} GridCraft Nightly");
let nightly = "0.19.1-nightly.20261124.7.1.gabcdef012345";
assert_eq!(version_for(Channel::NightlyV1, Some(nightly)), nightly);
assert_eq!(version_for(Channel::NightlyV1, None), env!("CARGO_PKG_VERSION"), "a nightly build without its own version is not invented");
}
#[test]
fn the_commit_is_read_back_only_from_a_nightly_version() {
assert_eq!(commit_for("0.19.1-nightly.20261124.7.1.gabcdef012345"), Some("abcdef012345"));
assert_eq!(commit_for("0.19.1"), None);
assert_eq!(commit_for("0.19.1-nightly.20261124.7.1"), None);
assert_eq!(commit_for("0.19.1-nightly.20261124.7.1.gABCDEF012345"), None, "versions are lower-case");
assert_eq!(commit_for("0.19.1-nightly.20261124.7.1.gabcdef01234"), None);
}
}
+8 -9
View File
@@ -326,15 +326,14 @@ mod tests {
// --- frames ---
fn harness(s: Session) -> Harness {
let mut h =
egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).with_context_setup(crate::framework::install_headless).build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
SheetApp::new(s, Default::default()),
);
let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
SheetApp::new(s, Default::default()),
);
h.run_steps(8);
h
}
-67
View File
@@ -1,67 +0,0 @@
//! The drop-down menu of the ribbon's combo fields (font name and size): a menu under a field that
//! scrolls its rows and can keep a header (the filter field) in place above them.
use egui::{Frame, Popup, PopupCloseBehavior, RectAlign, Response, ScrollArea, TextWrapMode, Ui};
/// A menu under a field that opens and closes on the field's clicks, closes on a click, and opens
/// below the field or above it, never beside it.
pub(crate) struct Menu<'a> {
popup: Popup<'a>,
field: egui::Rect,
height: f32,
}
impl<'a> Menu<'a> {
/// The menu under `field`, a widget in `ui`.
pub(crate) fn new(ui: &Ui, field: &Response) -> Self {
let flipped: &'static [RectAlign] = if ui.ctx().global_style().right_to_left { &[RectAlign::TOP_END] } else { &[RectAlign::TOP_START] };
Self { popup: Popup::menu(field).align_alternatives(flipped), field: field.rect, height: ui.spacing().combo_height }
}
/// The most height of the menu's contents, inside its frame; the room on the field's roomier
/// side caps it.
pub(crate) fn height(mut self, height: f32) -> Self {
self.height = height;
self
}
/// Shows `add` in the menu while it is open, scrolling when it is taller than the menu.
/// Returns what `add` returned, or `None` while the menu is closed.
pub(crate) fn show_ui<R>(self, add: impl FnOnce(&mut Ui) -> R) -> Option<R> {
self.show(|_| (), |ui, ()| add(ui))
}
/// Shows `header` at the top of the menu and `list` under it while the menu is open, and
/// returns what `list` returned. `list` gets what `header` returned. Only `list` scrolls; the
/// header stays in place.
pub(crate) fn show_ui_with_header<H, R>(self, header: impl FnOnce(&mut Ui) -> H, list: impl FnOnce(&mut Ui, H) -> R) -> Option<R> {
self.show(header, list)
}
fn show<H, R>(self, header: impl FnOnce(&mut Ui) -> H, list: impl FnOnce(&mut Ui, H) -> R) -> Option<R> {
let Self { popup, field, height } = self;
let ctx = popup.ctx().clone();
let screen = ctx.content_rect();
let room = (screen.bottom() - field.bottom()).max(field.top() - screen.top());
let style = egui::style::StyleModifier::from(egui::containers::menu::menu_style);
let mut popup_style = (*ctx.global_style()).clone();
style.apply(&mut popup_style);
let frame = Frame::popup(&popup_style).total_margin().sum().y;
let height = height.min(room - frame).max(0.0);
popup
.width(field.width())
.style(style)
.close_behavior(PopupCloseBehavior::CloseOnClick)
.show(|ui| {
ui.set_min_width(ui.available_width());
// egui offers the popup last pass's height; offer the full height so a list that
// shrank (a filter with no matches) grows back.
ui.set_max_height(height);
let header = header(ui);
// Labels widen a narrow menu rather than wrap early, as in egui's combo box.
ui.style_mut().wrap_mode = Some(TextWrapMode::Extend);
ScrollArea::vertical().max_height(ui.available_height().max(0.0)).show(ui, |ui| list(ui, header)).inner
})
.map(|shown| shown.inner)
}
}
+1 -1
View File
@@ -19,7 +19,7 @@
use std::sync::mpsc::Sender;
use crate::capture::CaptureSlot;
use craft_ui::capture::CaptureSlot;
use gridcraft_engine::core::CellRef;
use serde_json::{Value as Json, json};
-1
View File
@@ -284,7 +284,6 @@ fn one_admitted_capture_issues_one_callback_and_replies_once() {
let mut h = egui_kittest::Harness::builder()
.with_size(egui::vec2(900.0, 700.0))
.with_context_setup(|ctx| {
crate::framework::install_headless(ctx);
ctx.set_fonts(crate::theme::pinned_font_definitions());
crate::theme::apply(ctx, false);
})
+1 -1
View File
@@ -50,7 +50,7 @@ pub fn place(app: &mut SheetApp, ui: &Ui, resp: &egui::Response, geo: &Geo, sh:
return false;
};
let ctx = ui.ctx().clone();
if crate::framework::escape_pressed(&ctx) {
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
app.grid.placing = None;
app.grid.place_start = None;
return true;
+1 -1
View File
@@ -222,7 +222,7 @@ pub fn contributors_ui(ui: &mut egui::Ui) {
}
ui.separator();
ui.label("Sort");
egui::ComboBox::from_id_salt("credits_sort").selected_text(v.key.label().0).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt("credits_sort").selected_text(v.key.label().0).show_ui(ui, |ui| {
for k in SortKey::ALL {
if ui.selectable_label(v.key == k, k.label().0).clicked() {
v.key = k;
+2 -5
View File
@@ -15,11 +15,8 @@ pub(super) fn about(ui: &mut egui::Ui, d: &mut Dialog) {
"Contributors" => crate::credits::contributors_ui(ui),
"Models" => crate::credits::models_ui(ui),
_ => {
ui.heading(crate::channel::name());
ui.label(format!("Version {}", crate::channel::version()));
if let Some(commit) = crate::channel::commit() {
ui.label(egui::RichText::new(format!("Built from {commit}")).small());
}
ui.heading("GridCraft");
ui.label(format!("Version {}", env!("CARGO_PKG_VERSION")));
ui.add_space(4.0);
ui.label("A clean-room, open-source, Rust-native spreadsheet. Part of ArtCraft.");
ui.hyperlink_to("getartcraft.com/apps/gridcraft", "https://getartcraft.com/apps/gridcraft");
+2 -2
View File
@@ -493,7 +493,7 @@ pub(super) fn solver(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, conf
ui.horizontal(|ui| {
ref_edit(app, ui, d, "newLhs", RefLabel::Named("Constraint Cell Reference"), 130.0);
let op = text(d, "newOp");
egui::ComboBox::from_id_salt("solverOp")
craft_ui::ComboBox::from_id_salt("solverOp")
.selected_text(op.clone())
.width(60.0)
.show_ui(ui, |ui| {
@@ -539,7 +539,7 @@ pub(super) fn solver(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, conf
"evolutionary" => "Evolutionary",
_ => "GRG Nonlinear",
};
egui::ComboBox::from_id_salt("solverMethod")
craft_ui::ComboBox::from_id_salt("solverMethod")
.selected_text(label(&method))
.show_ui(ui, |ui| {
for m in ["grg", "simplex", "evolutionary"] {
+1 -1
View File
@@ -118,7 +118,7 @@ pub(super) fn format_cells(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog
ui.checkbox(&mut st.align.shrink, lang.tr("Shrink to fit"));
}
"Font" => {
egui::ComboBox::from_label(lang.tr("Font")).selected_text(st.font.name.clone()).show_ui(ui, |ui| {
craft_ui::ComboBox::from_label(lang.tr("Font")).selected_text(st.font.name.clone()).show_ui(ui, |ui| {
for f in crate::fonts::families() {
ui.selectable_value(&mut st.font.name, f.clone(), f.clone());
}
@@ -34,7 +34,7 @@ pub(super) fn insert_function(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dia
let menu_was_open = egui::Popup::is_any_open(ui.ctx());
let picker = ui.horizontal(|ui| {
let label = ui.label(language.tr("Or select a category:"));
egui::ComboBox::from_id_salt("insertFunctionCategory")
craft_ui::ComboBox::from_id_salt("insertFunctionCategory")
.width(220.0)
.selected_text(language.tr(&category))
.show_ui(ui, |ui| {
@@ -48,7 +48,7 @@ pub(super) fn insert_function(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dia
// Enter on the category list or in its menu opens it or picks a category, as Space does
// (egui clicks a focused control on either key); it does not also confirm the dialog.
let picker = picker.inner;
if menu_was_open || picker.has_focus() || egui::ComboBox::is_open(ui.ctx(), picker.id) {
if menu_was_open || picker.has_focus() || craft_ui::ComboBox::is_open(ui.ctx(), picker.id) {
ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
}
if category != saved {
+1 -1
View File
@@ -186,7 +186,7 @@ pub(super) fn place_window<'a>(
// Escape and Enter are used up either way: left in the frame's input, the dialog would
// read them as its own and close or confirm. When another field owned them, that field
// (drawn before the dialogs) has read them already, and nothing more happens here.
if crate::framework::consume_escape(ctx) | ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {
if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape) | i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {
if !other_field {
d.refs.collapsed = None;
}
+2 -2
View File
@@ -400,7 +400,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
open_url(&u);
}
}
if crate::framework::escape_pressed(ctx) || !win_open {
if ctx.input(|i| i.key_pressed(Key::Escape)) || !win_open {
// In Solver Options, Escape (or closing the window) cancels the options only.
if in_solver_options(&d) {
cancel_solver_options(&mut d);
@@ -655,7 +655,7 @@ pub(super) fn form_fields(app: &SheetApp, ui: &mut egui::Ui, d: &mut Dialog) {
let cur = d.values.get(key).and_then(Json::as_str).unwrap_or("").to_string();
if d.name == "dataValidation" {
let selected = options.iter().find(|(val, _)| *val == cur).map(|(_, text)| lang.tr(text)).unwrap_or("");
egui::ComboBox::from_id_salt(("dataValidation", key))
craft_ui::ComboBox::from_id_salt(("dataValidation", key))
.selected_text(selected)
.width(300.0)
.show_ui(ui, |ui| {
+3 -3
View File
@@ -337,7 +337,7 @@ fn levels_table(ui: &mut egui::Ui, levels: &mut [Json], selected: &mut usize, ch
.iter()
.find(|(l, _, _)| l.eq_ignore_ascii_case(&col))
.map_or_else(|| column_label(lang, &col.to_ascii_uppercase()), |(_, t, _)| t.clone());
let r = egui::ComboBox::from_id_salt(("col", i)).selected_text(shown).width(w).show_ui(ui, |ui| {
let r = craft_ui::ComboBox::from_id_salt(("col", i)).selected_text(shown).width(w).show_ui(ui, |ui| {
for (letters, label, _) in choices {
ui.selectable_value(&mut col, letters.clone(), label);
}
@@ -353,7 +353,7 @@ fn levels_table(ui: &mut egui::Ui, levels: &mut [Json], selected: &mut usize, ch
"fontColor" => "Font Color",
_ => "Cell Values",
});
let r = egui::ComboBox::from_id_salt(("by", i)).selected_text(by_label).width(w).show_ui(ui, |ui| {
let r = craft_ui::ComboBox::from_id_salt(("by", i)).selected_text(by_label).width(w).show_ui(ui, |ui| {
ui.selectable_value(&mut by, "values".into(), lang.tr("Cell Values"));
ui.selectable_value(&mut by, "cellColor".into(), lang.tr("Cell Color"));
ui.selectable_value(&mut by, "fontColor".into(), lang.tr("Font Color"));
@@ -368,7 +368,7 @@ fn levels_table(ui: &mut egui::Ui, levels: &mut [Json], selected: &mut usize, ch
let (asc_label, desc_label) = (lang.tr(asc_label), lang.tr(desc_label));
let mut desc = lv["order"].as_str() == Some("desc");
let order_label = if desc { desc_label } else { asc_label };
let r = egui::ComboBox::from_id_salt(("order", i)).selected_text(order_label).width(w).show_ui(ui, |ui| {
let r = craft_ui::ComboBox::from_id_salt(("order", i)).selected_text(order_label).width(w).show_ui(ui, |ui| {
ui.selectable_value(&mut desc, false, asc_label);
ui.selectable_value(&mut desc, true, desc_label);
});
+30 -24
View File
@@ -18,12 +18,10 @@
//!
//! [`Session::windows`]: gridcraft_engine::Session::windows
use craft_window::{WindowId, WindowList};
use egui::Rect;
use craft_window::{CASCADE_STEP, Frame, Rect, Viewports, WindowEvent, WindowId, WindowList, cascade};
use serde_json::json;
use crate::SheetApp;
use crate::viewports::{CASCADE_STEP, Viewports, WindowEvent};
/// The native windows (see the module docs).
pub struct DocWindows {
@@ -42,7 +40,8 @@ impl DocWindows {
/// Takes over `app`'s windows. `base` is the root window's builder, used for new windows.
pub fn new(app: &mut SheetApp, base: egui::ViewportBuilder, quit_with_last_window: bool) -> DocWindows {
app.native_windows = true;
DocWindows { list: WindowList::new(), viewports: Viewports::default(), base, quit_with_last_window, root_hidden: false }
// The root window keeps the desktop's frame, so every window does.
DocWindows { list: WindowList::new(), viewports: Viewports::new(Frame::Desktop), base, quit_with_last_window, root_hidden: false }
}
/// The platform default for the last window closing: macOS keeps running, others quit.
@@ -92,7 +91,7 @@ impl DocWindows {
let (monitor, infos) = ctx.input(|i| (i.viewport().monitor_size, i.raw.viewports.clone()));
// Platforms that don't report the monitor (Wayland, tests) get a common laptop screen.
let size = monitor.filter(|m| m.x > 0.0 && m.y > 0.0).unwrap_or(egui::vec2(1280.0, 800.0));
let mut rects = arrange_rects(arrange, ids.len(), Rect::from_min_size(egui::Pos2::ZERO, size));
let mut rects = arrange_rects(arrange, ids.len(), Rect::new(0.0, 0.0, size.x, size.y));
if arrange == "cascade" {
// The active window goes in front: the last step of the cascade.
rects.reverse();
@@ -101,8 +100,8 @@ impl DocWindows {
let vp = self.viewports.viewport_id(*id);
// Inner size is what can be set: take off the frame the window has now.
let frame = infos.get(&vp).and_then(|v| Some(v.outer_rect?.size() - v.inner_rect?.size())).unwrap_or(egui::Vec2::ZERO);
ctx.send_viewport_cmd_to(vp, egui::ViewportCommand::OuterPosition(r.min));
ctx.send_viewport_cmd_to(vp, egui::ViewportCommand::InnerSize((r.size() - frame).max(egui::vec2(240.0, 160.0))));
ctx.send_viewport_cmd_to(vp, egui::ViewportCommand::OuterPosition(egui::pos2(r.x, r.y)));
ctx.send_viewport_cmd_to(vp, egui::ViewportCommand::InnerSize((egui::vec2(r.width, r.height) - frame).max(egui::vec2(240.0, 160.0))));
}
if let Some(first) = ids.first() {
self.viewports.focus(ctx, *first);
@@ -124,7 +123,7 @@ impl DocWindows {
// The window the engine brought forward, else the most recently focused.
let next = app.session.active_window().and_then(|w| self.find(w)).or_else(|| self.list.active());
match next {
Some(id) => self.viewports.adopt(ctx, id),
Some(id) => self.viewports.adopt(ctx, &self.list, id),
None => self.viewports.set_root(None),
}
}
@@ -206,7 +205,7 @@ impl DocWindows {
match event {
WindowEvent::Focused(_) => {}
WindowEvent::CloseRequested(id) => {
if let Some(w) = self.close_requested(app, id) {
if let Some(w) = self.close_requested(app, &ctx, id) {
requested = Some(w);
}
}
@@ -229,13 +228,16 @@ impl DocWindows {
/// A window's close button. Returns the window to bring forward when the close needs an
/// answer (or moved focus); `None` when nothing changed.
/// The root window's close request is held by the app's close path ([`SheetApp::close_decision`]),
/// so closing it closes only its workbook window, as for any other window.
fn close_requested(&mut self, app: &mut SheetApp, id: WindowId) -> Option<u64> {
fn close_requested(&mut self, app: &mut SheetApp, ctx: &egui::Context, id: WindowId) -> Option<u64> {
let is_root = self.viewports.root() == Some(id);
if app.allow_close {
// Quitting: every workbook has been answered for; the root's close ends the app.
return None;
}
if is_root {
// eframe would end the app with the root window; closing it is the app's decision.
ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::CancelClose);
}
let window = *self.list.get(id)?;
app.enter_window(window);
app.run_or_alert("window.close", json!({"window": window}));
@@ -255,9 +257,7 @@ fn visible_windows(app: &SheetApp) -> Vec<u64> {
fn window_title(app: &SheetApp, window: u64) -> String {
let title = app.session.window_title(window).unwrap_or_default();
let dirty = app.session.window(window).and_then(|w| app.session.documents().iter().find(|d| d.uid == w.doc_uid)).is_some_and(|d| d.is_dirty());
let title = if dirty { format!("{title} — Edited") } else { title };
// Nightly says which channel the window belongs to; stable titles are unchanged.
crate::channel::window_title(&title)
if dirty { format!("{title} — Edited") } else { title }
}
/// Outer rectangles for `n` windows arranged within `bounds` as View › Arrange All's `arrange`
@@ -271,28 +271,34 @@ pub fn arrange_rects(arrange: &str, n: usize, bounds: Rect) -> Vec<Rect> {
let count = n as f32;
match arrange {
"horizontal" => {
let h = bounds.height() / count;
(0..n).map(|i| Rect::from_min_size(bounds.min + egui::vec2(0.0, h * i as f32), egui::vec2(bounds.width(), h))).collect()
let h = bounds.height / count;
(0..n).map(|i| Rect::new(bounds.x, bounds.y + h * i as f32, bounds.width, h)).collect()
}
"vertical" => {
let w = bounds.width() / count;
(0..n).map(|i| Rect::from_min_size(bounds.min + egui::vec2(w * i as f32, 0.0), egui::vec2(w, bounds.height()))).collect()
let w = bounds.width / count;
(0..n).map(|i| Rect::new(bounds.x + w * i as f32, bounds.y, w, bounds.height)).collect()
}
"cascade" => {
let shift = CASCADE_STEP * (count - 1.0);
let size = egui::vec2((bounds.width() - shift).max(bounds.width() * 0.5), (bounds.height() - shift).max(bounds.height() * 0.5));
craft_behavior::placement::cascade_rects(bounds, size, n, CASCADE_STEP)
let size = [(bounds.width - shift).max(bounds.width * 0.5), (bounds.height - shift).max(bounds.height * 0.5)];
let mut previous = Rect::new(bounds.x - CASCADE_STEP, bounds.y - CASCADE_STEP, size[0], size[1]);
(0..n)
.map(|_| {
previous = cascade(previous, size, bounds, CASCADE_STEP);
previous
})
.collect()
}
_ => {
let cols = (count.sqrt().ceil() as usize).max(1);
let rows = n.div_ceil(cols);
let h = bounds.height() / rows as f32;
let h = bounds.height / rows as f32;
(0..n)
.map(|i| {
let (row, col) = (i / cols, i % cols);
let in_row = if row + 1 == rows { n - row * cols } else { cols };
let w = bounds.width() / in_row as f32;
Rect::from_min_size(bounds.min + egui::vec2(w * col as f32, h * row as f32), egui::vec2(w, h))
let w = bounds.width / in_row as f32;
Rect::new(bounds.x + w * col as f32, bounds.y + h * row as f32, w, h)
})
.collect()
}
-152
View File
@@ -1,152 +0,0 @@
//! The craft-ui runtime, hosted from GridCraft's own eframe `App` (craft-libs docs/craft-framework.md, section 2.2).
//! The desktop app calls [`install`] once, [`SheetApp::before_input`] in `raw_input_hook`, [`SheetApp::close_path`]
//! last in `logic`, and [`before_ui`] first in `ui`; the browser build and tests install with [`install_headless`].
//! The framework dialogs run on [`SheetApp::framework_dialogs`] after GridCraft's own UI.
//!
//! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of GridCraft's own egui
//! widgets has the keyboard. The window's Escape is read with [`escape_pressed`] and taken with [`consume_escape`];
//! the grid is declared to the runtime with [`host_canvas`], which keeps Tab, the edit chords and the clipboard
//! events in egui's input for GridCraft's shortcuts. A grid that holds egui focus keeps Escape and the clipboard
//! events in egui as one of GridCraft's own widgets does.
use std::sync::{Arc, OnceLock};
use craft_host::target::ShellInfo;
use craft_host::{AppInfo, Host};
use craft_keymap::Overrides;
use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts};
use craft_ui::runtime::commands::{CommandInput, CommandSet as _, QuitCommand};
use craft_ui::runtime::env::{RootEnv, Scale};
use craft_ui::runtime::focus::{EditSet, KeepKeys, KeyUse};
use craft_ui::runtime::frame::{FrameInput, FrameOutput};
use craft_ui::runtime::keys::{Intent, with_window_intents};
use craft_ui::shell::embed;
use craft_window::system::WindowSystem;
use crate::SheetApp;
/// Each pass of the root window, first in `App::ui`: hands the runtime the native window it answers the hit test of
/// (Windows) and fits the window to its monitor once.
#[cfg(not(target_arch = "wasm32"))]
pub use craft_ui::shell::embed::before_ui;
/// The id every OS window of the app carries, as the main window's builder sets it.
const APP_ID: &str = "ai.storyteller.gridcraft";
/// The scripts of the interface languages, for the font stack.
static SCRIPTS: I18nScripts = I18nScripts;
/// The runtime's first font stack: egui's bundled faces and no installed system fonts. GridCraft's own definitions
/// ([`SheetApp::setup_context_for_language`]) replace it before anything is drawn.
fn ui_fonts() -> UiFonts<'static> {
UiFonts::new(&SCRIPTS).system_fonts(SystemFonts::Off)
}
fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc<dyn WindowSystem>) -> Result<(), String> {
let spec = craft_ui::InstallSpec::new(shell, windows).app_id(APP_ID);
embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}"))
}
/// Installs the runtime on the desktop window's context, once, before the first pass. GridCraft draws its own title
/// bar (and, where the desktop leaves the frame to the app, its own window buttons), so no frame decision is handed
/// over and the runtime answers no hit test of the window.
#[cfg(not(target_arch = "wasm32"))]
pub fn install(ctx: &egui::Context) -> Result<(), String> {
let shell = ShellInfo::default().backend(craft_host::target::Backend::from_env());
install_with(ctx, shell, Arc::new(craft_window::system::SystemWindows))
}
/// Installs the runtime on a context with no native window of its own: the browser build's canvas and test windows.
pub fn install_headless(ctx: &egui::Context) {
if let Err(error) = install_with(ctx, ShellInfo::default(), Arc::new(craft_window::system::NoWindows)) {
log::warn!("{error}");
}
}
/// Who GridCraft is to the framework's dialogs (the update dialogs show its name and icon).
pub(crate) fn host() -> Arc<Host> {
Arc::new(
Host::builder(AppInfo { id: "gridcraft", name: "GridCraft", version: env!("CARGO_PKG_VERSION") })
.icon_png(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.gridcraft.png"))
.build(),
)
}
/// GridCraft quits through its own Quit (the macOS app menu, the last window closing, an update's restart), which
/// asks about every unsaved workbook in its window, and Ctrl+Q is no quit key on Windows and Linux (Excel's Quick
/// Analysis), so the framework's `window.quit` is unbound. Overrides are keyed by command id, which the command set
/// gives.
fn command_overrides() -> Arc<Overrides> {
static OVERRIDES: OnceLock<Arc<Overrides>> = OnceLock::new();
OVERRIDES
.get_or_init(|| {
let mut overrides = Overrides::new();
overrides.insert(QuitCommand::Quit.id(), Vec::new());
Arc::new(overrides)
})
.clone()
}
impl SheetApp {
/// The framework's part of `App::raw_input_hook`, once per frame before the first pass: takes what the runtime
/// gathered since the last frame and gives the coming passes the root values (theme mode, interface scale).
pub fn before_input(&mut self, ctx: &egui::Context) {
embed::before_input(ctx, |output| self.frame_input(output));
}
/// The root values of this frame. GridCraft registers no commands with the runtime (it unbinds the framework's
/// quit, [`command_overrides`]) and lets it toggle no chrome, so the output carries nothing it acts on. The
/// interface scale is the Interface Size preference: the runtime is the one writer of egui's zoom factor.
fn frame_input(&mut self, _output: FrameOutput) -> FrameInput {
let mode = if self.effective_dark { craft_theme::Mode::Dark } else { craft_theme::Mode::Light };
let mut root = RootEnv::new().mode(mode).scale(Scale::new(self.ui.zoom_factor()));
// GridCraft's rule for every text field, the framework's ones included (the print page's Copies): Escape
// leaves the field, and only the next Escape reaches the view (it closes File).
root.escape_leaves_fields = true;
FrameInput::new(root).commands(CommandInput::new().overrides(command_overrides())).host(Arc::clone(&self.framework_host))
}
/// The framework's part of `App::logic`, last, after GridCraft's own logic and the native windows': the root
/// window's close path, decided by [`SheetApp::close_decision`].
pub fn close_path(&mut self, ctx: &egui::Context) {
embed::logic(ctx, || self.close_decision(ctx));
}
/// The framework dialogs open on [`SheetApp::framework_dialogs`], once per frame after GridCraft's own UI.
pub(crate) fn run_framework_dialogs(&mut self, ui: &mut egui::Ui) {
self.framework_dialogs.run(ui);
}
}
/// Declares the grid `id`, drawn in this pass, as the window's document canvas. Tab, the edit chords and the
/// clipboard events stay in egui's input for GridCraft's shortcuts, as do the arrows, Enter and the page keys.
pub(crate) fn host_canvas(ctx: &egui::Context, id: egui::Id) {
const KEYS: KeyUse = KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL);
craft_ui::runtime::focus::host_canvas(ctx, id, KEYS);
}
/// Whether Escape was pressed in this pass: from egui while one of GridCraft's own widgets or popups has the
/// keyboard, otherwise the window's cancel, which the runtime routes to no component. Leaves it for later readers.
pub(crate) fn escape_pressed(ctx: &egui::Context) -> bool {
ctx.input(|i| i.key_pressed(egui::Key::Escape)) || window_cancel(ctx, false)
}
/// Takes a plain Escape pressed in this pass, from egui or as the window's cancel: no later reader sees it.
pub(crate) fn consume_escape(ctx: &egui::Context) -> bool {
ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) || take_window_cancel(ctx)
}
/// Takes the window's cancel (an Escape while nothing has framework focus) when it is there: no later reader sees it.
pub(crate) fn take_window_cancel(ctx: &egui::Context) -> bool {
window_cancel(ctx, true)
}
/// Whether the window's cancel is there and untaken; `take` takes it.
fn window_cancel(ctx: &egui::Context, take: bool) -> bool {
let mut pending = false;
with_window_intents(ctx, false, |intents| {
pending = if take { intents.take(Intent::Cancel) } else { intents.untaken(&Intent::Cancel) };
take && pending
});
pending
}
+5 -8
View File
@@ -648,22 +648,19 @@ fn handle_context_menu_and_keyboard(app: &mut SheetApp, input: &InteractionInput
if primary_clicked || resp.drag_started() {
resp.request_focus();
}
crate::framework::host_canvas(&ctx, resp.id);
keyboard(app, &ctx, resp, geo, sh);
}
/// Whether Esc was pressed this frame, with any modifiers, in egui's input or as the window's
/// cancel; every Esc press is then spent, so the grid's own Esc doesn't also drop a pending copy or
/// Format Painter.
/// Whether Esc was pressed this frame, with any modifiers; every Esc press is then spent, so the
/// grid's own Esc doesn't also drop a pending copy or Format Painter.
fn spend_escape(ctx: &egui::Context) -> bool {
let in_egui = ctx.input_mut(|i| {
ctx.input_mut(|i| {
let pressed = i.key_pressed(egui::Key::Escape);
if pressed {
i.events.retain(|e| !matches!(e, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }));
}
pressed
});
in_egui || crate::framework::take_window_cancel(ctx)
})
}
fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) {
@@ -813,7 +810,7 @@ fn handle_release(app: &mut SheetApp, input: &InteractionInput<'_>) {
Drag::Fill { target: Some(t), menu: true } => {
if let Some(p) = pos
&& t != sel.current()
&& !crate::framework::consume_escape(&ctx)
&& !ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
{
app.grid.fill_menu = Some((sel.current(), t, geo.mirror_pos(p)));
}
+2 -2
View File
@@ -221,7 +221,7 @@ pub(super) fn context_menu(app: &mut SheetApp, ui: &mut egui::Ui) {
// menu, so it doesn't count as a click elsewhere.
let opened_now = app.grid.context_menu_frame == ui.ctx().cumulative_frame_nr();
if close
|| crate::framework::escape_pressed(ui.ctx())
|| ui.input(|i| i.key_pressed(egui::Key::Escape))
|| (!opened_now
&& ui.input(|i| i.pointer.any_pressed())
&& !resp.response.contains_pointer()
@@ -428,7 +428,7 @@ pub(super) fn object_menu(app: &mut SheetApp, ui: &mut egui::Ui) {
});
});
if close
|| crate::framework::escape_pressed(ui.ctx())
|| ui.input(|i| i.key_pressed(egui::Key::Escape))
|| (ui.input(|i| i.pointer.any_pressed())
&& !resp.response.contains_pointer()
&& !resp.response.hovered()
-1
View File
@@ -407,7 +407,6 @@ fn upward_text_with_middle_align_is_centred_in_a_merged_block() {
/// One grid frame of `app` in a headless context.
fn grid_frame(app: &mut crate::SheetApp) {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let screen = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(1200.0, 800.0));
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| super::show(app, ui));
out.textures_delta.clear(); // nothing consumes the uploads in a headless test
+9 -17
View File
@@ -120,7 +120,15 @@ impl KeyTips {
} else if self.prefix.is_some() && !matches!(key, Key::ShiftLeft | Key::ShiftRight) {
handled = true;
if *key == Key::Escape {
self.back();
// Escape pops one level; at a single-letter level it
// returns to the armed root (empty prefix).
if let Some(prefix) = self.prefix.as_mut() {
if prefix.is_empty() {
self.prefix = None;
} else {
prefix.pop();
}
}
} else if key.name().len() == 1 {
let next = format!("{}{key_name}", self.prefix.as_deref().unwrap_or_default(), key_name = key.name());
match keytip_table::lookup(&next) {
@@ -163,25 +171,9 @@ impl KeyTips {
ctx.input_mut(|i| {
i.events = events.into_iter().enumerate().filter_map(|(index, event)| (!consumed.contains(&index)).then_some(event)).collect()
});
// With none of GridCraft's widgets focused (the File view), the runtime takes Escape as the
// window's cancel.
if self.prefix.is_some() && crate::framework::take_window_cancel(ctx) {
self.back();
}
actions
}
/// Escape pops one level; at a single-letter level it returns to the armed root (empty prefix).
fn back(&mut self) {
if let Some(prefix) = self.prefix.as_mut() {
if prefix.is_empty() {
self.prefix = None;
} else {
prefix.pop();
}
}
}
fn finish(&mut self, action: Action, actions: &mut Vec<Action>) {
self.prefix = None;
actions.push(action);
-11
View File
@@ -17,13 +17,10 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App {
pub mod backstage;
mod border_preview;
mod capture;
mod cell_pictures;
pub mod channel;
mod chartcache;
pub mod chartview;
pub mod code_editor;
mod combo_menu;
pub mod control;
pub mod control_ui;
mod craft_fonts_policy;
@@ -40,7 +37,6 @@ pub mod form_controls;
pub mod formula_bar;
mod formula_locale;
pub mod frame;
pub mod framework;
pub mod function_library;
pub mod grid;
pub mod i18n;
@@ -63,8 +59,6 @@ mod text_direction;
pub mod theme;
#[cfg(not(target_arch = "wasm32"))]
mod updates_ui;
#[cfg(not(target_arch = "wasm32"))]
mod viewports;
pub mod widgets;
mod window_ui;
pub mod wordart;
@@ -353,11 +347,6 @@ pub struct SheetApp {
/// The update check, the startup prompt and a running self-update (desktop only).
#[cfg(not(target_arch = "wasm32"))]
updates_rt: updates_ui::Runtime,
/// The framework dialogs GridCraft keeps as values (the update dialogs), run once per frame
/// after GridCraft's own UI in the root window's pass.
pub framework_dialogs: craft_ui::dialog::DialogHost,
/// Who GridCraft is to the framework's dialogs.
framework_host: std::sync::Arc<craft_host::Host>,
}
/// Strips the engine's error prefixes for message boxes.
+5 -5
View File
@@ -959,7 +959,7 @@ pub fn window(app: &mut SheetApp, ctx: &egui::Context, d: &mut Dialog, open: &mu
*open = false;
}
}
if crate::framework::escape_pressed(ctx) && ed.picker.is_some() {
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) && ed.picker.is_some() {
ed.picker = None;
}
prompts(app, ctx, &mut ed, open);
@@ -1110,7 +1110,7 @@ fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut
ui.label("Keep the changes the macro has made so far? They are one undo step either way.");
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button("Cancel").clicked() || crate::framework::escape_pressed(ui.ctx()) {
if ui.button("Cancel").clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
answer = Some(None);
}
if ui.button("Undo Changes").clicked() {
@@ -1147,7 +1147,7 @@ fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut
ui.label(egui::RichText::new(format!("Save changes to macro “{}”?", ed.draft.name)).strong());
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button("Cancel").clicked() || crate::framework::escape_pressed(ui.ctx()) {
if ui.button("Cancel").clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
answer = Some(None);
}
if ui.button("Don't Save").clicked() {
@@ -1880,7 +1880,7 @@ fn step_tab(app: &mut SheetApp, ui: &mut Ui, d: &mut Dialog, ed: &mut Editor) {
(CompareOp::Contains, "contains"),
];
let label = ops.iter().find(|(o, _)| *o == op).map_or("", |x| x.1);
egui::ComboBox::from_id_salt(("me_op", &path)).selected_text(label).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt(("me_op", &path)).selected_text(label).show_ui(ui, |ui| {
for (o, l) in ops {
ui.selectable_value(&mut op2, o, l);
}
@@ -2120,7 +2120,7 @@ fn inputs_tab(app: &mut SheetApp, ui: &mut Ui, d: &mut Dialog, ed: &mut Editor)
ui.label(label);
let mut ty = i.col_types.get(c).copied().unwrap_or(ColType::Any);
let before_ty = ty;
egui::ComboBox::from_id_salt(("me_ty", c)).selected_text(type_name(ty)).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt(("me_ty", c)).selected_text(type_name(ty)).show_ui(ui, |ui| {
for x in [ColType::Any, ColType::Number, ColType::Text, ColType::Date, ColType::Bool] {
ui.selectable_value(&mut ty, x, type_name(x));
}
+1 -1
View File
@@ -216,7 +216,7 @@ pub fn question_box(app: &mut SheetApp, ctx: &egui::Context) {
ui.add(egui::Label::new(&q.text).wrap());
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button("Cancel").clicked() || crate::framework::escape_pressed(ui.ctx()) {
if ui.button("Cancel").clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
answer = Some(None);
}
// Right to left: list the choices reversed, so the first one ends up next to Cancel
+2 -2
View File
@@ -332,7 +332,7 @@ fn format_chart(app: &mut SheetApp, ui: &mut Ui) {
let b = ui.add(egui::DragValue::new(&mut h).prefix("Height ").range(range(current.1)));
if a.drag_stopped() || a.lost_focus() || b.drag_stopped() || b.lost_focus() {
ui.data_mut(|d| d.remove::<(f32, f32)>(draft));
if !crate::framework::escape_pressed(ui.ctx()) {
if !ui.input(|i| i.key_pressed(egui::Key::Escape)) {
// Only an edited dimension is sent: the other keeps what the chart has, however
// large a file made it.
let mut params = serde_json::Map::new();
@@ -363,7 +363,7 @@ fn chart_slider(ui: &mut Ui, draft: egui::Id, value: u32, range: std::ops::Range
let r = ui.add(egui::Slider::new(&mut current, range).text(label));
if r.drag_stopped() || r.clicked() || r.lost_focus() {
ui.data_mut(|d| d.remove::<u32>(draft));
if crate::framework::escape_pressed(ui.ctx()) || current == value { None } else { Some(current) }
if ui.input(|i| i.key_pressed(egui::Key::Escape)) || current == value { None } else { Some(current) }
} else if r.dragged() || r.has_focus() {
ui.data_mut(|d| d.insert_temp(draft, current));
None
+3 -3
View File
@@ -9,7 +9,7 @@
use std::sync::Arc;
use egui::{Align2, Color32, FontId, Painter, Pos2, Rect, Stroke, StrokeKind, TextEdit, pos2, vec2};
use egui::{Align2, Color32, FontId, Key, Painter, Pos2, Rect, Stroke, StrokeKind, TextEdit, pos2, vec2};
use gridcraft_engine::cf::CfCache;
use gridcraft_engine::cmd::print::{self, HfContext};
use gridcraft_engine::model::{HfPage, Sheet, SheetViewMode, Workbook};
@@ -468,7 +468,7 @@ pub fn go_to(app: &mut SheetApp, footer: bool) {
/// Edits a header/footer section across left/center/right, cancels on Esc, switches sections and preserves focus/caret while the page scrolls.
fn editor(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, pg: &PageGrid) {
let Some(mut e) = app.grid.hf_edit.take() else { return };
if crate::framework::consume_escape(ui.ctx()) {
if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
app.grid.hf_edit = Some(e);
cancel(app);
return;
@@ -823,7 +823,7 @@ fn ruler_margins(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, pg: &PageGrid
ui.ctx().set_cursor_icon(if edge.horizontal() { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical });
};
if let Some(d) = app.grid.ruler_drag.clone() {
if crate::framework::consume_escape(ui.ctx()) {
if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
app.grid.ruler_drag = None;
return;
}
+1 -1
View File
@@ -181,7 +181,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) {
if ui.button(lang.tr("Calculated Field…")).clicked() {
app.run_or_alert("pivot.calculatedField", json!({"pivot": name}));
}
egui::ComboBox::from_id_salt("pv_layout")
craft_ui::ComboBox::from_id_salt("pv_layout")
.selected_text(lang.tr("Report Layout"))
.show_ui(ui, |ui| {
for (l, v) in [("Compact", "compact"), ("Outline", "outline"), ("Tabular", "tabular")] {
+25 -21
View File
@@ -1,27 +1,33 @@
//! The print page's printer controls (craft-print's `PrintPanel` over its `State`) and their
//! localized feedback. The panel's own words come from the framework host.
pub use craft_print::ui::{Destination, Discover, Duplex, Feedback, Printer, Settings, State, Submit};
//! Localized print-page wording around the shared, backend-independent controls.
use craft_ui::printing::Labels;
pub use craft_ui::printing::{Discover, Duplex, Feedback, Printer, Settings, State, Submit};
/// Draws the shared print controls and the feedback of the last discovery or job.
/// Draws the shared print controls.
///
/// `State::run` also polls the workers, on top of [`crate::SheetApp::poll_printing`] in `logic`.
/// That poll is idempotent (it only drains worker messages into the same state), and the
/// logic-side poll is what lets a hidden window and a logic-only frame see completion, so it stays.
/// `craft_ui::printing::State::show` also calls `poll`, so this path polls a second time on top of
/// [`crate::SheetApp::poll_printing`] in `logic`. That poll is idempotent (it only drains worker
/// messages into the same state), and the logic-side poll is what lets a hidden window and a
/// logic-only frame see completion, so it stays. Splitting poll out of the shared `show` API is a
/// craft-ui follow-up, not a GridCraft-local change.
pub fn show(state: &mut State, ui: &mut egui::Ui, discover: &Discover, translate: impl Fn(&str) -> String) {
ui.push_id("gridcraft_print_settings", |ui| state.run(ui, discover));
let labels = Labels {
printer: &translate("Printer"),
select_printer: &translate("Select a printer"),
refresh: &translate("Refresh printers"),
copies: &translate("Copies"),
duplex: &translate("Two-sided printing"),
printer_default: &translate("Printer default"),
one_sided: &translate("One-sided"),
long_edge: &translate("Two-sided: long edge"),
short_edge: &translate("Two-sided: short edge"),
grayscale: &translate("Grayscale"),
};
state.show(ui, egui::Id::unique("gridcraft_print_settings"), discover, &labels);
if let Some(message) = &state.message {
ui.label(feedback(message, crate::i18n::current(ui.ctx()), translate));
}
}
/// The printer queue the settings name; empty for none.
fn printer_name(settings: &Settings) -> &str {
match &settings.destination {
Destination::Printer(name) => name,
_ => "",
}
}
/// Read print settings/status, or validate an explicit update before changing anything.
/// `refresh: true` starts discovery only; this command never submits a job or opens a dialog.
pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<&Discover>) -> Result<serde_json::Value, String> {
@@ -39,7 +45,7 @@ pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<
if !state.printers.iter().any(|available| available.name == printer) {
return Err("printer must be a name from the discovered list".into());
}
next.destination = Destination::Printer(printer.to_owned());
next.printer = printer.to_owned();
}
if let Some(value) = object.get("copies") {
let copies = value.as_u64().filter(|copies| (1..=999).contains(copies)).ok_or("copies must be an integer from 1 to 999")?;
@@ -75,11 +81,10 @@ pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<
Some(Feedback::Submitted(receipt)) => ("submitted", receipt.as_str()),
Some(Feedback::Failed(error)) => ("failed", error.as_str()),
Some(Feedback::WorkerStopped) => ("workerStopped", ""),
Some(_) => ("unknown", ""),
};
Ok(json!({
"printer": printer_name(&state.settings), "copies": state.settings.copies,
"duplex": match state.settings.duplex { Some(Duplex::Off) => "off", Some(Duplex::LongEdge) => "longEdge", Some(Duplex::ShortEdge) => "shortEdge", _ => "printerDefault" },
"printer": state.settings.printer, "copies": state.settings.copies,
"duplex": match state.settings.duplex { None => "printerDefault", Some(Duplex::Off) => "off", Some(Duplex::LongEdge) => "longEdge", Some(Duplex::ShortEdge) => "shortEdge" },
"grayscale": state.settings.grayscale,
"printers": state.printers.iter().map(|printer| json!({"name": printer.name, "default": printer.default})).collect::<Vec<Value>>(),
"busy": state.busy(), "discovering": state.discovering(), "ready": state.ready(), "status": status, "detail": detail,
@@ -96,6 +101,5 @@ pub fn feedback(message: &Feedback, language: crate::i18n::Language, translate:
Feedback::Submitted(receipt) => translate("Print job submitted: {receipt}").replace("{receipt}", receipt),
Feedback::Failed(error) => translate("Print failed: {error}").replace("{error}", &language.tr_error(error)),
Feedback::WorkerStopped => translate("Print failed: the printing worker stopped."),
_ => String::new(),
}
}
+1 -1
View File
@@ -248,7 +248,7 @@ fn combo_popup(
if filter {
height += ui.spacing().interact_size.y + 4.0 * spacing + 1.0;
}
let menu = crate::combo_menu::Menu::new(ui, &field).height(height);
let menu = craft_ui::combo::Menu::new(ui, &field).height(height);
let text_id = anchor.id.with(salt).with("__combo_text");
let sel0 = st.sel;
let shown = if filter {
+3 -3
View File
@@ -107,7 +107,7 @@ pub(super) fn view(app: &mut SheetApp, ui: &mut Ui) {
"dark" => "Dark",
_ => "Light",
};
egui::ComboBox::from_id_salt("display_theme")
craft_ui::ComboBox::from_id_salt("display_theme")
.selected_text(lang.tr(label))
.width(88.0)
.show_ui(ui, |ui| {
@@ -131,7 +131,7 @@ pub(super) fn view(app: &mut SheetApp, ui: &mut Ui) {
let label = ui.label(egui::RichText::new(lang.tr("Interface size")).font(theme::ui_font(11.5)).color(t.text_dim));
let current = app.ui.interface_scale;
let text = |v: u16| if v == 100 { lang.tr("Auto").to_string() } else { format!("{v}%") };
egui::ComboBox::from_id_salt("ui_interface_size")
craft_ui::ComboBox::from_id_salt("ui_interface_size")
.width(120.0)
.selected_text(egui::RichText::new(text(current)).font(theme::ui_font(12.5)))
.show_ui(ui, |ui| {
@@ -148,7 +148,7 @@ pub(super) fn view(app: &mut SheetApp, ui: &mut Ui) {
// the current language so it stays readable; the choices are always shown in their own script.
ui.vertical(|ui| {
let label = ui.label(egui::RichText::new(lang.tr("Interface language")).font(theme::ui_font(11.5)).color(t.text_dim));
egui::ComboBox::from_id_salt("ui_language")
craft_ui::ComboBox::from_id_salt("ui_language")
.width(120.0)
.selected_text(egui::RichText::new(lang.name()).font(theme::ui_font(12.5)))
.show_ui(ui, |ui| {
+1 -1
View File
@@ -270,7 +270,7 @@ pub fn sheet_tabs(app: &mut SheetApp, ui: &mut Ui) {
ed.request_focus();
}
if ed.lost_focus() {
if !crate::framework::escape_pressed(ui.ctx()) && text != name {
if !ui.input(|i| i.key_pressed(egui::Key::Escape)) && text != name {
app.run_or_alert("sheet.rename", json!({"sheet": i, "name": text}));
}
app.grid.renaming_tab = None;
+1 -1
View File
@@ -93,7 +93,7 @@ impl SheetApp {
/// Resolve outside clicks before the ribbon/tabs can save or switch the workbook.
pub(crate) fn before_ui(app: &mut SheetApp, ctx: &egui::Context) {
let Some(ed) = &app.text_box_editor else { return };
if crate::framework::consume_escape(ctx) {
if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) {
app.cancel_text_box_edit();
ctx.memory_mut(|m| m.surrender_focus(editor_id()));
return;
-5
View File
@@ -526,11 +526,6 @@ pub(super) fn font_definitions_impl(
if let Some(ui) = fonts.families.get(&FontFamily::Name(UI.into())).cloned() {
fonts.families.insert(FontFamily::Proportional, ui);
}
// The framework's signature family follows the proportional one; a family left out draws
// missing-glyph boxes. Its semibold role falls back to the proportional family when the
// definitions have no semibold family.
let proportional = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
fonts.families.insert(craft_ui::fonts::FontRef::signature().family(), proportional);
// Installed workbook fonts, so a cell's chosen font actually renders in it. They are bound
// after the proportional chain has the script faces, which their chains end with.
for (family, faces) in installed {
+19 -43
View File
@@ -1,10 +1,8 @@
//! One background check at startup (and on Help ▸ Check for Updates…) and the modal prompt that
//! offers the new release: Update and Restart (direct self-update), Download or Later. The flow
//! itself is `craft_update::updater::Updater`; its dialogs run on the app's
//! [`DialogHost`](craft_ui::dialog::DialogHost).
//! itself is `craft_update::updater::Updater`.
use craft_ui::dialog::DialogResult;
use craft_update::stack_dialogs::{CheckChoice, UpdateCheckDialog};
use craft_update::CheckResultResponse;
use craft_update::updater::{Action, Status, Updater};
use crate::SheetApp;
@@ -37,9 +35,9 @@ pub(crate) fn start(app: &mut SheetApp, manual: bool) {
pub(crate) fn tick(app: &mut SheetApp, ctx: &egui::Context) {
let rt = &mut app.updates_rt;
if std::mem::take(&mut rt.manual) {
rt.updater.check_now();
rt.updater.check_now(ctx);
} else if rt.startup {
rt.updater.check_at_start();
rt.updater.check_at_start(ctx);
}
rt.updater.tick(ctx);
}
@@ -56,50 +54,28 @@ fn result_window_shows(status: &Status, prompt_open: bool) -> bool {
!prompt_open && !matches!(status, Status::Idle)
}
/// One frame of the update flow, before the dialog host runs: answers the result dialog closed in
/// the last pass, drives the startup prompt, and keeps the result dialog open and current while the
/// updater has something to report.
pub(crate) fn show(app: &mut SheetApp, ctx: &egui::Context) {
// The close for a ready update waits until no workbook holds unsaved work.
let clean = !app.session.documents().iter().any(|d| d.is_dirty());
// Answered before the dialog is kept open below, so a dismissed outcome does not open again at once.
match app.framework_dialogs.take::<UpdateCheckDialog>() {
Some(DialogResult::Ok(CheckChoice::CheckNow | CheckChoice::CheckAgain)) => app.updates_rt.manual = true,
// The next `run` asks the window to close once nothing is unsaved.
Some(DialogResult::Ok(CheckChoice::RestartToUpdate)) => app.updates_rt.updater.restart_to_update(),
Some(DialogResult::Ok(CheckChoice::Update)) => {
app.updates_rt.updater.request_install(clean);
match app.updates_rt.updater.show_if(ctx, clean) {
Action::OpenUrl(url) => {
if let Some(open) = &app.services.open_url {
open(&url);
}
}
Some(DialogResult::Ok(CheckChoice::Download)) => open_url(app, &crate::UPDATE_APP.releases_url()),
// Closing the dialog dismisses the outcome it showed.
Some(_) => app.updates_rt.updater.dismiss_status(),
None => {}
}
match app.updates_rt.updater.run(&mut app.framework_dialogs, clean) {
Action::OpenUrl(url) => open_url(app, &url),
// Quit closes every workbook window. The install helper starts once the app exits.
Action::Close => app.request_quit(ctx),
_ => {}
Action::None => {}
}
let updater = &app.updates_rt.updater;
let shows = result_window_shows(updater.status(), updater.prompt_open());
let (status, installing, message) = (updater.status().clone(), updater.is_installing(), updater.status_message());
let dialogs = &mut app.framework_dialogs;
if shows && !dialogs.is_open::<UpdateCheckDialog>() {
dialogs.open(UpdateCheckDialog::new(VERSION));
} else if !shows && dialogs.is_open::<UpdateCheckDialog>() {
dialogs.cancel::<UpdateCheckDialog>(ctx);
}
if let Some(dialog) = dialogs.get_mut::<UpdateCheckDialog>() {
dialog.set_status(status);
dialog.set_installing(installing);
dialog.set_message(message);
}
}
fn open_url(app: &SheetApp, url: &str) {
if let Some(open) = &app.services.open_url {
open(url);
let rt = &mut app.updates_rt;
if result_window_shows(rt.updater.status(), rt.updater.prompt_open()) {
match craft_update::CheckResultDialog::new(&crate::UPDATE_APP, VERSION).show(ctx, rt.updater.status()) {
CheckResultResponse::Close => rt.updater.dismiss_status(),
CheckResultResponse::CheckAgain => rt.updater.check_now(ctx),
// The next `show_if` asks the window to close once nothing is unsaved.
CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(),
CheckResultResponse::None => {}
}
}
}
-207
View File
@@ -1,207 +0,0 @@
//! Shows each open workbook window as an egui immediate viewport, one native window each.
//!
//! Call [`Viewports::show`] once per frame from the root viewport's UI. The root viewport stays the
//! app's: the window mapped to it with [`Viewports::set_root`] is drawn into the root UI, and every
//! other window gets its own viewport, placed one cascade step from the window used last. Close and
//! quit policy stays with the app: the driver reports [`WindowEvent`]s.
use std::collections::HashMap;
use craft_window::{WindowId, WindowList};
use egui::{Context, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportId};
/// How far right and down a new window opens from the window used last, in points: about one
/// title bar.
pub const CASCADE_STEP: f32 = 28.0;
/// How far a maximized window's frame may reach past its monitor's edges: a window rectangle that
/// starts up to this far left of or above a monitor is on that monitor.
const FRAME_OVERSHOOT: f32 = 16.0;
/// Something that happened to a window this frame. The app decides what follows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WindowEvent {
/// The window got focus. The driver has already made it the list's active window.
Focused(WindowId),
/// The user asked to close the window (its close button, Alt+F4, ⌘W through the desktop).
/// A child window stays open until the app closes it in the [`WindowList`], so the app can ask
/// to save first. The root window's close request is the app's close path to hold.
CloseRequested(WindowId),
}
/// What the driver remembers about a window between frames.
#[derive(Default)]
struct Seen {
focused: bool,
/// The window's outer rectangle as it last reported it.
outer: Option<Rect>,
inner_size: Option<Vec2>,
monitor_size: Option<Vec2>,
/// The cascade position chosen when the window was created; repeated every frame so egui sees
/// an unchanged builder.
position: Option<Pos2>,
/// The root viewport's title, sent as a command when it changes.
title: Option<String>,
}
/// The windows of a [`WindowList`] as egui viewports (see the module docs).
#[derive(Default)]
pub struct Viewports {
root: Option<WindowId>,
seen: HashMap<WindowId, Seen>,
}
impl Viewports {
/// The window drawn into the root viewport.
pub fn root(&self) -> Option<WindowId> {
self.root
}
/// Maps window `id` to the root viewport, or none.
pub fn set_root(&mut self, id: Option<WindowId>) {
if let Some(id) = id {
// The root is a different native window: forget the child's focus and title.
self.seen.insert(id, Seen::default());
}
self.root = id;
}
/// Moves window `id` into the root viewport, for when the root's own window closes while others
/// stay open. The root window takes `id`'s position and size and gets focus; `id`'s data and
/// [`WindowId`] are unchanged, so its UI state carries over.
pub fn adopt(&mut self, ctx: &Context, id: WindowId) {
let (outer, inner_size) = self.seen.get(&id).map_or((None, None), |seen| (seen.outer, seen.inner_size));
self.set_root(Some(id));
if let Some(rect) = outer {
ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::OuterPosition(rect.min));
}
if let Some(size) = inner_size {
ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::InnerSize(size));
}
ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::Focus);
}
/// The egui viewport showing window `id`.
pub fn viewport_id(&self, id: WindowId) -> ViewportId {
if self.root == Some(id) { ViewportId::ROOT } else { child_viewport_id(id) }
}
/// Brings window `id` to the front.
pub fn focus(&self, ctx: &Context, id: WindowId) {
ctx.send_viewport_cmd_to(self.viewport_id(id), ViewportCommand::Focus);
}
/// Draws every window of `windows`: the root's into `ui`, every other one in an immediate
/// viewport built by `builder` (with system decorations) and drawn by `content`. Returns what
/// happened to the windows this frame.
pub fn show<T>(
&mut self,
ui: &mut Ui,
windows: &mut WindowList<T>,
mut builder: impl FnMut(WindowId, &T) -> ViewportBuilder,
mut content: impl FnMut(&mut Ui, WindowId, &mut T),
) -> Vec<WindowEvent> {
self.seen.retain(|id, _| windows.contains(*id));
let ctx = ui.ctx().clone();
let mut events = Vec::new();
if let Some(root) = self.root.filter(|&id| windows.contains(id)) {
if let Some(title) = windows.get(root).and_then(|data| builder(root, data).title) {
let seen = self.seen.entry(root).or_default();
if seen.title.as_ref() != Some(&title) {
ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::Title(title.clone()));
seen.title = Some(title);
}
}
if let Some(data) = windows.get_mut(root) {
content(ui, root, data);
}
self.record(Snapshot::read(&ctx), windows, root, &mut events);
}
let children: Vec<WindowId> = windows.ids().filter(|&id| self.root != Some(id)).collect();
for id in children {
let Some(data) = windows.get(id) else { continue };
let mut viewport = builder(id, data).with_decorations(true);
let position = match self.seen.get(&id) {
Some(seen) => seen.position,
None => self.place(windows, id, &viewport),
};
if let Some(position) = position {
viewport = viewport.with_position(position);
}
self.seen.entry(id).or_default().position = position;
let Some(data) = windows.get_mut(id) else { continue };
let snapshot = ctx.show_viewport_immediate(child_viewport_id(id), viewport, |child_ui, _class| {
content(child_ui, id, data);
Snapshot::read(child_ui.ctx())
});
self.record(snapshot, windows, id, &mut events);
}
events
}
fn record<T>(&mut self, snapshot: Snapshot, windows: &mut WindowList<T>, id: WindowId, events: &mut Vec<WindowEvent>) {
let Snapshot { close, focused, outer, inner, monitor } = snapshot;
let seen = self.seen.entry(id).or_default();
seen.outer = outer;
seen.inner_size = inner.map(|r| r.size()).or(seen.inner_size);
seen.monitor_size = monitor.or(seen.monitor_size);
if focused && !seen.focused {
windows.focus(id);
events.push(WindowEvent::Focused(id));
}
seen.focused = focused;
if close {
events.push(WindowEvent::CloseRequested(id));
}
}
/// Where a new window opens: one cascade step from the window used most recently whose
/// rectangle is known, within that window's monitor. `None` when no window's rectangle is known.
fn place<T>(&self, windows: &WindowList<T>, id: WindowId, viewport: &ViewportBuilder) -> Option<Pos2> {
let (previous_id, previous) = windows.recent().filter(|&w| w != id).find_map(|w| Some((w, self.seen.get(&w)?.outer?)))?;
let seen = self.seen.get(&previous_id);
let frame = seen.and_then(|s| s.inner_size).map(|inner| previous.size() - inner).unwrap_or_default();
let size = viewport.inner_size.map(|s| s + frame).unwrap_or(previous.size());
let bounds = monitor_bounds(previous, seen?.monitor_size?);
Some(craft_behavior::placement::cascade(previous, size, bounds, CASCADE_STEP).min)
}
}
/// What a window reported in its pass.
struct Snapshot {
close: bool,
focused: bool,
outer: Option<Rect>,
inner: Option<Rect>,
monitor: Option<Vec2>,
}
impl Snapshot {
fn read(ctx: &Context) -> Self {
ctx.input(|i| {
let v = i.viewport();
Self {
close: v.close_requested(),
focused: v.focused.unwrap_or(false),
outer: v.outer_rect,
inner: v.inner_rect,
monitor: v.monitor_size,
}
})
}
}
/// The egui viewport of a window that is not in the root viewport.
pub fn child_viewport_id(id: WindowId) -> ViewportId {
ViewportId::from_hash_of(("craft_window", id.get()))
}
/// The monitor `window` is on, for a desktop of monitors of one `monitor` size side by side: egui
/// reports only the size of the window's monitor, not where it is.
fn monitor_bounds(window: Rect, monitor: Vec2) -> Rect {
let tile = |pos: f32, len: f32| if len > 0.0 { ((pos + FRAME_OVERSHOOT) / len).floor() * len } else { 0.0 };
Rect::from_min_size(egui::pos2(tile(window.min.x, monitor.x), tile(window.min.y, monitor.y)), monitor)
}
+2 -2
View File
@@ -303,7 +303,7 @@ pub fn committed_text(ui: &mut Ui, id: egui::Id, current: &str, width: Option<f3
let r = ui.add(egui::TextEdit::singleline(&mut text).id(id).desired_width(width));
if r.lost_focus() {
ui.data_mut(|d| d.remove::<String>(draft));
return (!crate::framework::escape_pressed(ui.ctx())).then_some(text);
return (!ui.input(|i| i.key_pressed(egui::Key::Escape))).then_some(text);
}
if r.has_focus() {
ui.data_mut(|d| d.insert_temp(draft, text));
@@ -598,7 +598,7 @@ pub fn message_box(app: &mut SheetApp, ctx: &egui::Context) {
});
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button(" OK ").clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) || crate::framework::escape_pressed(ui.ctx()) {
if ui.button(" OK ").clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter) || i.key_pressed(egui::Key::Escape)) {
close = true;
}
});
+8 -11
View File
@@ -13,17 +13,14 @@ fn editing(text: &str, formula_bar: bool) -> egui_kittest::Harness<'static, Shee
let mut session = Session::new();
session.new_workbook();
session.execute("cell.set", json!({"cell": "A1", "input": text})).unwrap();
let mut h = egui_kittest::Harness::builder()
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
.with_size(vec2(1200.0, 800.0))
.build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
SheetApp::new(session, Default::default()),
);
let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
SheetApp::new(session, Default::default()),
);
h.run_steps(4);
if formula_bar {
h.get_by_label(text).click();
-3
View File
@@ -49,7 +49,6 @@ fn primary_text_bounds(galley: &egui::Galley) -> (f32, f32) {
#[test]
fn cjk_and_latin_share_a_baseline_in_cells_and_window_titles() {
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
ctx.set_pixels_per_point(2.0);
activate(&ctx, theme::font_definitions_for_language(Language::Zh));
for role in [theme::CELL, theme::CELL_BOLD, theme::CELL_ITALIC, theme::CELL_BOLD_ITALIC, theme::UI_BOLD] {
@@ -73,7 +72,6 @@ fn mixed_script_wrapping_keeps_fixed_row_clips_alignment_and_editor_height() {
const TEXT: &str = "中文ABC2026\n文字xyz123";
for zoom in [80, 100, 280] {
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
ctx.set_pixels_per_point(2.0);
let mut session = Session::new();
session.new_workbook();
@@ -141,7 +139,6 @@ fn same_row_cells_keep_their_baseline_with_baseline_aligned_fallbacks() {
for valign in ["Top", "Bottom", "Center"] {
let mixed = if wraps[1] && valign == "Top" { "Hello\n中文" } else { "Hello 中文" };
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
ctx.set_pixels_per_point(2.0);
activate(&ctx, theme::font_definitions_for_language(Language::Zh));
let mut session = Session::new();
+3 -6
View File
@@ -14,12 +14,10 @@ use gridcraft_ui_egui::{Services, SheetApp};
pub type Harness = egui_kittest::Harness<'static, SheetApp>;
/// A kittest builder with the UI runtime, the deterministic font set and GridCraft's visuals
/// installed.
/// A kittest builder with the deterministic font set and GridCraft's visuals installed.
pub fn builder<State>() -> HarnessBuilder<State> {
egui_kittest::Harness::builder().with_context_setup(|ctx| {
gridcraft_ui_egui::framework::install_headless(ctx);
craft_ui::fonts::load(ctx, gridcraft_ui_egui::theme::pinned_font_definitions());
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
gridcraft_ui_egui::theme::apply(ctx, false);
})
}
@@ -35,7 +33,7 @@ pub fn prepare(mut app: SheetApp) -> SheetApp {
app
}
/// Drive `app`'s `logic`, its close path, then `ui` each frame in a harness built with `builder`.
/// Drive `app`'s `logic` then `ui` each frame in a harness built with `builder`.
///
/// Tests that need a non-standard size, step timing, OS or pixel ratio configure the builder
/// here so those details stay explicit; the shared font and lifecycle setup lives in `builder`
@@ -45,7 +43,6 @@ pub fn harness_with(builder: HarnessBuilder<SheetApp>, app: SheetApp, steps: usi
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.close_path(&ctx);
app.ui(ui);
},
app,
+2 -4
View File
@@ -42,7 +42,6 @@ impl Desk {
fn new(quit_with_last_window: bool) -> Desk {
INFOS.with(|i| i.borrow_mut().clear());
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
ctx.set_embed_viewports(false);
Context::set_immediate_viewport_renderer(|ctx, viewport| {
let id = viewport.ids.this;
@@ -78,7 +77,6 @@ impl Desk {
}
app.logic(&ctx);
windows.logic(app, &ctx);
app.close_path(&ctx);
windows.show(app, ui);
});
record(out);
@@ -460,8 +458,8 @@ fn arrange_all_lays_out_the_native_windows_active_first() {
// Without parameters, as a script calls it: tiled.
let r = desk.app.run("view.arrangeAll", json!({})).unwrap();
assert_eq!(r["arrange"], "tiled");
let r = |x, y, w, h| egui::Rect::from_min_size(egui::pos2(x, y), egui::vec2(w, h));
let tiled = gridcraft_ui_egui::doc_windows::arrange_rects("tiled", 3, r(0.0, 0.0, 1000.0, 800.0));
let tiled = gridcraft_ui_egui::doc_windows::arrange_rects("tiled", 3, craft_window::Rect::new(0.0, 0.0, 1000.0, 800.0));
let r = |x, y, w, h| craft_window::Rect::new(x, y, w, h);
assert_eq!(tiled, [r(0.0, 0.0, 500.0, 400.0), r(500.0, 0.0, 500.0, 400.0), r(0.0, 400.0, 1000.0, 400.0)]);
}
+7 -11
View File
@@ -25,17 +25,13 @@ fn harness(selection: &str) -> egui_kittest::Harness<'static, SheetApp> {
session.execute("home.columnWidth", json!({"cols": "A:D", "width": 100})).unwrap();
session.execute("home.rowHeight", json!({"rows": "1:4", "height": 60})).unwrap();
session.execute("selection.set", json!({"range": selection})).unwrap();
let mut h = egui_kittest::Harness::builder()
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
.with_step_dt(1.0 / 60.0)
.with_size(vec2(1200.0, 800.0))
.build_ui_state(
|ui, app: &mut SheetApp| {
app.logic(ui.ctx());
app.ui(ui);
},
SheetApp::new(session, Default::default()),
);
let mut h = egui_kittest::Harness::builder().with_step_dt(1.0 / 60.0).with_size(vec2(1200.0, 800.0)).build_ui_state(
|ui, app: &mut SheetApp| {
app.logic(ui.ctx());
app.ui(ui);
},
SheetApp::new(session, Default::default()),
);
h.run_steps(4);
h.state_mut().session.active_mut().unwrap().undo.clear();
h.state_mut().session.journal.clear();
@@ -27,7 +27,6 @@ fn ctrl_shift_a() -> Event {
/// A cell editor holding `text`, caret at the end.
fn editing(text: &str) -> (Context, SheetApp) {
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
let mut session = Session::new();
session.new_workbook();
let mut app = crate::common::app(session);
@@ -18,7 +18,6 @@ fn frame(ctx: &Context, app: &mut SheetApp) -> egui::FullOutput {
/// The caret painted while editing A1 over `fill` (`None`: no fill), with the app in `dark` mode.
fn caret(fill: Option<&str>, dark: bool) -> Color32 {
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
theme::apply(&ctx, dark);
let mut session = Session::new();
session.new_workbook();
+2 -6
View File
@@ -12,12 +12,8 @@ use serde_json::{Value as Json, json};
type Harness = egui_kittest::Harness<'static, SheetApp>;
fn harness(s: Session) -> Harness {
let mut h = egui_kittest::Harness::builder()
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
.with_os(OperatingSystem::Mac)
.with_size(vec2(1400.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
let mut h =
egui_kittest::Harness::builder().with_os(OperatingSystem::Mac).with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SheetApp| {
app.logic(ui.ctx());
app.ui(ui);
+2 -4
View File
@@ -114,8 +114,7 @@ fn escape_leaves_file_fields_before_closing_the_view() {
let copies = h.state().printing.settings.copies;
h.key_press(egui::Key::Escape);
// With GridCraft's frame input, as the shells give it: Escape leaves the framework's fields too.
crate::support::frames(&mut h, 3);
h.run_steps(3);
assert_eq!(page(&h), Some(page_id), "Esc in {label} keeps File open");
assert!(!h.ctx.text_edit_focused(), "Esc leaves {label}");
assert_eq!(h.state().session.active().unwrap().revision, revision, "Esc does not commit {label}");
@@ -126,8 +125,7 @@ fn escape_leaves_file_fields_before_closing_the_view() {
}
h.key_press(egui::Key::Escape);
// With GridCraft's frame input, as the shells give it: Escape leaves the framework's fields too.
crate::support::frames(&mut h, 3);
h.run_steps(3);
assert_eq!(page(&h), None, "the next Esc returns to the sheet");
}
}
-2
View File
@@ -38,7 +38,6 @@ fn fixture() -> (Harness, Ids) {
let button = id(s.execute("insert.button", json!({"at": "E12", "text": "Mark it", "macro": "Mark"})).unwrap());
s.execute("selection.set", json!({"cell": "A20"})).unwrap();
let mut h = egui_kittest::Harness::builder()
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
.with_size(vec2(1400.0, 900.0))
.with_step_dt(1.0 / 60.0)
.with_os(egui::os::OperatingSystem::Mac)
@@ -592,7 +591,6 @@ fn insert_tab() -> Harness {
let mut app = SheetApp::new(s, Default::default());
app.ui.ribbon_tab = "Insert".into();
let mut h = egui_kittest::Harness::builder()
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
.with_size(vec2(1400.0, 900.0))
.with_step_dt(1.0 / 60.0)
.with_os(egui::os::OperatingSystem::Mac)
-8
View File
@@ -31,7 +31,6 @@ fn visible(ctx: &Context, editor: &str) -> bool {
fn cell_formula_helpers_hide_when_scrolled_out_and_return_with_the_editor() {
for text in ["=SU", "=SUM("] {
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
let mut session = Session::new();
session.new_workbook();
@@ -58,7 +57,6 @@ fn cell_formula_helpers_hide_when_scrolled_out_and_return_with_the_editor() {
#[test]
fn hidden_row_and_column_hide_the_wrapped_editor_until_unhidden() {
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
let mut session = Session::new();
session.new_workbook();
@@ -97,7 +95,6 @@ fn paints_visible_text(output: &egui::FullOutput, text: &str, cells: Rect) -> bo
/// Formula-bar help stays visible while the sheet scrolls.
fn formula_bar_hint_remains_visible_when_the_worksheet_scrolls() {
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
let mut session = Session::new();
session.new_workbook();
@@ -115,7 +112,6 @@ fn formula_bar_hint_remains_visible_when_the_worksheet_scrolls() {
/// Cell argument help is clipped to the worksheet instead of painting over the headers.
fn cell_argument_hint_is_clipped_to_the_worksheet() {
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
let mut session = Session::new();
session.new_workbook();
@@ -135,7 +131,6 @@ fn cell_argument_hint_is_clipped_to_the_worksheet() {
/// An editor for a scrolled-out cell still handles Esc.
fn scrolled_out_cell_editor_still_handles_escape() {
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
let mut session = Session::new();
session.new_workbook();
@@ -167,7 +162,6 @@ fn scrolled_out_cell_editor_still_handles_escape() {
/// The editor and its helper clip below the frozen top row, stay hidden while the cell is under it, and return on scroll-back.
fn cell_editor_and_helper_stay_below_the_frozen_top_row() {
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
let mut session = Session::new();
session.new_workbook();
@@ -220,7 +214,6 @@ fn cell_editor_and_helper_stay_below_the_frozen_top_row() {
fn frozen_column_editor_paints_in_both_panes_on_a_right_to_left_sheet() {
for (cell, text) in [("A2", "frozen"), ("B2", "scrolling")] {
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
let mut session = Session::new();
session.new_workbook();
@@ -264,7 +257,6 @@ fn frozen_column_editor_paints_in_both_panes_on_a_right_to_left_sheet() {
fn argument_hint_shows_the_function_description() {
// #363: inside DATEDIF( the hint lists the units the third argument takes.
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
let mut session = Session::new();
session.new_workbook();
@@ -23,7 +23,6 @@ fn frames(ctx: &Context, app: &mut SheetApp) {
/// The editor's text field rect while A1 (narrow, wrap on or off) is edited with [`TEXT`].
fn editor_rect(wrap: bool) -> Rect {
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
let mut session = Session::new();
session.new_workbook();
session.execute("home.columnWidth", json!({"cols": "A:A", "chars": 12})).unwrap();
@@ -48,7 +47,6 @@ fn a_wrap_text_cell_edits_wrapped_at_the_column_width() {
#[test]
fn a_short_wrap_text_edit_stays_one_line_tall() {
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
let mut session = Session::new();
session.new_workbook();
session.execute("home.wrapText", json!({"range": "A1", "on": true})).unwrap();
@@ -66,7 +64,6 @@ fn a_short_wrap_text_edit_stays_one_line_tall() {
#[test]
fn the_editor_measures_the_text_at_the_fields_wrap_width() {
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
let mut session = Session::new();
session.new_workbook();
session.execute("home.columnWidth", json!({"cols": "A:A", "chars": 12})).unwrap();
@@ -94,7 +91,6 @@ fn the_editor_measures_the_text_at_the_fields_wrap_width() {
fn an_unwrapped_multiline_edit_shows_every_line() {
let field = |text: &str| {
let ctx = Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
let mut session = Session::new();
session.new_workbook();
let mut app = crate::common::app(session);
@@ -37,9 +37,7 @@ fn right_click_row_header(h: &mut Harness, cell: &str) {
h.input_mut().events.push(Event::PointerMoved(pos));
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE });
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });
// The runtime takes one press per frame: the release arrives in the next frame, and the frame
// after it shows what the click did.
h.run_steps(3);
h.run_steps(2);
}
#[test]
@@ -70,9 +68,7 @@ fn right_click_col_header(h: &mut Harness, cell: &str) {
h.input_mut().events.push(Event::PointerMoved(pos));
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE });
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });
// The runtime takes one press per frame: the release arrives in the next frame, and the frame
// after it shows what the click did.
h.run_steps(3);
h.run_steps(2);
}
/// As in Excel, the row and column header menus offer Format Cells… for the selected lines.
+3 -3
View File
@@ -16,11 +16,11 @@ fn interface_size_applies_persists_and_clamps() {
},
crate::common::app(session),
);
crate::support::frames(&mut h, 2);
h.run_steps(2);
assert_eq!(h.ctx.zoom_factor(), 1.0);
h.state_mut().run("view.interfaceScale", json!({"percent": 125})).unwrap();
crate::support::frames(&mut h, 2);
h.run_steps(2);
assert_eq!(h.ctx.zoom_factor(), 1.25);
let saved: UiState = serde_json::from_str(&serde_json::to_string(&h.state().ui).unwrap()).unwrap();
assert_eq!(saved.interface_scale, 125);
@@ -31,7 +31,7 @@ fn interface_size_applies_persists_and_clamps() {
assert!(h.state_mut().run("view.interfaceScale", json!({})).is_err(), "no value is an error, not a dialog");
assert!(h.state_mut().run("view.interfaceScale", json!({"percent": "huge"})).is_err());
h.state_mut().run("view.interfaceScale", json!({"percent": "auto"})).unwrap();
crate::support::frames(&mut h, 2);
h.run_steps(2);
assert_eq!(h.ctx.zoom_factor(), 1.0);
// A malformed or out-of-range ui.json keeps the other preferences.
+16 -22
View File
@@ -20,18 +20,14 @@ fn harness_with(services: Services) -> Harness {
session.new_workbook();
let mut app = SheetApp::new(session, services);
app.ui.ribbon_tab = "Automate".into();
let mut h = egui_kittest::Harness::builder()
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
.with_size(egui::vec2(1400.0, 900.0))
.build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.close_path(&ctx);
app.ui(ui);
},
app,
);
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
h.run_steps(4);
h
}
@@ -570,16 +566,14 @@ fn the_editor_fits_a_narrow_window() {
let mut session = Session::new();
session.new_workbook();
let app = SheetApp::new(session, Default::default());
let mut h =
egui_kittest::Harness::builder().with_context_setup(gridcraft_ui_egui::framework::install_headless).with_size(size).build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.close_path(&ctx);
app.ui(ui);
},
app,
);
let mut h = egui_kittest::Harness::builder().with_size(size).build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
h.run_steps(4);
three(&mut h);
h.run_steps(4);
+32 -42
View File
@@ -16,17 +16,14 @@ fn harness(tab: &str) -> Harness {
session.new_workbook();
let mut app = SheetApp::new(session, Default::default());
app.ui.ribbon_tab = tab.into();
let mut h = egui_kittest::Harness::builder()
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
.with_size(egui::vec2(1280.0, 800.0))
.build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
h.run_steps(4);
h
}
@@ -118,17 +115,14 @@ fn the_macros_dialog_lists_scripts_and_the_vba_project_beside_macros() {
s.execute("macro.save", json!({"name": "Mark", "steps": []})).unwrap();
let mut app = SheetApp::new(s, Default::default());
app.ui.ribbon_tab = "Automate".into();
let mut h = egui_kittest::Harness::builder()
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
.with_size(egui::vec2(1280.0, 800.0))
.build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
h.run_steps(3);
h.state_mut().open_dialog("macros", json!({}));
h.run_steps(2);
@@ -266,17 +260,14 @@ fn the_macros_dialog_offers_trust_for_scripts_that_came_with_a_file() {
s.active_mut().unwrap().scripts_trusted = false;
let mut app = SheetApp::new(s, Default::default());
app.ui.ribbon_tab = "Automate".into();
let mut h = egui_kittest::Harness::builder()
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
.with_size(egui::vec2(1280.0, 800.0))
.build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
h.run_steps(3);
h.state_mut().open_dialog("macros", json!({}));
h.run_steps(2);
@@ -300,15 +291,14 @@ fn the_macros_and_record_macro_dialogs_fit_a_narrow_window() {
s.new_workbook();
s.execute("macro.save", json!({"name": "Tidy", "steps": []})).unwrap();
let app = SheetApp::new(s, Default::default());
let mut h =
egui_kittest::Harness::builder().with_context_setup(gridcraft_ui_egui::framework::install_headless).with_size(size).build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
let mut h = egui_kittest::Harness::builder().with_size(size).build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
h.run_steps(3);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size);
for (dialog, labels) in [("macros", &["Run", "Delete", "Options…", "Cancel"][..]), ("recordMacro", &["OK", "Cancel"][..])] {
+1 -3
View File
@@ -39,9 +39,7 @@ fn click_cell(h: &mut Harness, cell: &str) {
Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE },
Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE },
]);
// The runtime takes one press per frame: the release arrives in the next frame, and the frame
// after it shows what the click did.
h.run_steps(3);
h.run_steps(2);
}
fn text(h: &mut Harness, text: &str) {
+7 -7
View File
@@ -1,6 +1,6 @@
//! Native print onboarding preserves engine PDF generation and submits the selected settings.
use gridcraft_engine::Session;
use gridcraft_ui_egui::printing::{Destination, Duplex, Feedback, Printer};
use gridcraft_ui_egui::printing::{Duplex, Feedback, Printer};
use gridcraft_ui_egui::{Services, SheetApp};
use serde_json::json;
use std::{cell::RefCell, rc::Rc};
@@ -25,7 +25,7 @@ fn native_print_uses_selected_settings_and_reports_spool_errors() {
let pdf = app.run("file.print", json!({"sheets":"active"})).unwrap();
assert!(pdf["base64"].as_str().is_some(), "the engine still returns PDF bytes without submitting");
assert!(jobs.borrow().is_empty(), "opening settings/exporting does not spool");
app.printing.printers.push(Printer::new("Chosen queue"));
app.printing.printers.push(Printer { name: "Chosen queue".into(), label: String::new(), default: false });
let configured = app.run("ui.printSettings", json!({"printer":"Chosen queue", "copies":3,"duplex":"shortEdge","grayscale":true})).unwrap();
assert_eq!(configured["ready"], true);
assert_eq!(configured["printers"][0]["name"], "Chosen queue");
@@ -34,7 +34,7 @@ fn native_print_uses_selected_settings_and_reports_spool_errors() {
let jobs = jobs.borrow();
assert_eq!(jobs.len(), 1);
assert!(jobs[0].0.starts_with(b"%PDF"));
assert_eq!(jobs[0].1.destination, Destination::Printer("Chosen queue".into()));
assert_eq!(jobs[0].1.printer, "Chosen queue");
assert_eq!(jobs[0].1.copies, 3);
assert_eq!(jobs[0].1.duplex, Some(Duplex::ShortEdge));
assert!(jobs[0].1.grayscale);
@@ -53,7 +53,7 @@ fn print_settings_are_visible_in_a_narrow_window() {
app.run("cell.set", json!({"cell":"A1", "input":"A sheet to print"})).unwrap();
app.services.printers = Some(Box::new(|| {
let (sender, receiver) = std::sync::mpsc::channel();
sender.send(vec![Printer::new("Test queue").is_default(true)]).unwrap();
sender.send(vec![Printer { name: "Test queue".into(), label: String::new(), default: true }]).unwrap();
receiver
}));
app.services.print_native = Some(Box::new(|_, _| {
@@ -70,7 +70,7 @@ fn print_settings_are_visible_in_a_narrow_window() {
app,
);
harness.run_steps(5);
assert!(!harness.get_by_label("Refresh").accesskit_node().is_disabled());
assert!(!harness.get_by_label("Refresh printers").accesskit_node().is_disabled());
assert!(!harness.get_by_label("Grayscale").accesskit_node().is_disabled());
harness.get_by_label("Grayscale").click();
harness.run_steps(2);
@@ -84,7 +84,7 @@ fn invalid_print_settings_are_rejected_without_partial_changes() {
let mut session = Session::new();
session.new_workbook();
let mut app = SheetApp::new(session, Services::default());
app.printing.printers.push(Printer::new("Queue").is_default(true));
app.printing.printers.push(Printer { name: "Queue".into(), label: String::new(), default: true });
let before = app.run("ui.printSettings", json!({})).unwrap();
for params in [
json!({"printer":"Missing"}),
@@ -110,7 +110,7 @@ fn repeated_fast_jobs_each_surface_an_identical_receipt() {
let mut session = Session::new();
session.new_workbook();
let mut app = SheetApp::new(session, Services::default());
app.printing.printers.push(Printer::new("Queue").is_default(true));
app.printing.printers.push(Printer { name: "Queue".into(), label: String::new(), default: true });
app.run("ui.printSettings", json!({"printer":"Queue"})).unwrap();
app.services.print_native = Some(Box::new(|_, _| {
let (sender, receiver) = std::sync::mpsc::channel();
-1
View File
@@ -53,7 +53,6 @@ fn fixture() -> (Harness, Objects) {
slicer: ObjRef::new(ObjKind::Slicer, slicer),
};
let mut h = egui_kittest::Harness::builder()
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
.with_size(vec2(1400.0, 900.0))
.with_step_dt(1.0 / 60.0)
.with_os(egui::os::OperatingSystem::Mac)

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