Compare commits

..
Author SHA1 Message Date
skylartaylor fe148ab826 nightly: open the Launcher's files, not its -- separator
The Launcher starts a nightly as `--launch-profile nightly-v1 --profile-root
<dir> --` and `launch_profile::parse` hands the window `--` followed by the
file names. The argument scan in `main` had no arm for the separator, so it
was opened as a file: every nightly launch showed the alert `--: No such file
or directory (os error 2)` (Mac smoke of run 45749038918).

The scan moves into `desktop_args`, where `--` ends the options and
everything after it is a file. `main` keeps its `--control`,
`--control-token` and `--sample` handling unchanged.

The same smoke showed a refused launch hanging on macOS with no window: the
refusal opened rfd's message box before eframe's event loop, and that alert
needs the AppKit run loop this start never reaches. `refusal_dialog` now adds
the box only where one renders on its own (Windows, X11/Wayland); macOS gets
the reason on standard error and the caller's exit status 2.

Unit tests cover both argvs the Launcher sends, a file named like a flag after
the separator, and the dialog rule.
2026-11-26 05:32:08 +01:00
skylar taylor-barrick b1216a17e8 Switch on supervised nightlies on the nightly-signer branch (#4767)
Supervised nightly switch-on, merged under Skylar's explicit Nightly 758 override after green CI, CodeRabbit on this head with no open threads, Sonar passing, and an independent adversarial review with no blockers.
2026-11-25 20:44:49 -06:00
aiongg 15373a0fe7 Merge pull request #4732 from aiongg/minimal-port-next
GridCraft: minimal port to craft-libs next
2026-11-25 19:07:46 -05:00
skylar taylor-barrick 3a37c2e882 Use the shared nightly launcher template (#4758)
Renders the plain nightly tar's launcher from craft-common-actions' shared template.

Independent check: dylanmtaylor compared all 14 app launcher PRs byte for byte with the template rendered from the registry (https://github.com/storytold/craft-common-actions/pull/367#issuecomment-7172085284); this head was re-checked against craft-common-actions main 88148a5.
2026-11-25 16:17:18 -06:00
aiongg f96096f97e The print job takes the panel's Collate; tests load their fonts as the app does 2026-11-25 20:44:58 +00:00
aiongg 966c634b1c Repin craft-libs to storytold next 8fa4db64a9 and egui to b9770908e 2026-11-25 19:15:01 +00:00
aiongg 3e43b2bce2 Repin craft-libs to storytold next aa401985d 2026-11-25 15:48:35 +00:00
aiongg 643b52cb29 Repin craft-libs to storytold next d1bdf8e5da 2026-11-25 13:43:38 +00:00
aiongg 4f7a511b9f Print page: widen the settings column so craft-print's Copies row does not wrap 2026-11-25 07:28:30 +00:00
aiongg acba6346ca Merge main into the minimal port
Conflicts: apps/gridcraft/src/main.rs (kept main's named App fields and nightly session code; kept the port's close_path, before_input and framework install/before_ui calls).
2026-11-25 06:35:12 +00:00
aiongg c2c9e2bc52 Repin egui to storytold b15ffe9bfc (what craft-libs next pins) 2026-11-25 06:32:47 +00:00
aiongg 73a2fd7148 Repin craft-libs to storytold next 16001e7210 and egui to storytold b15ffe9bfc 2026-11-25 06:31:18 +00:00
Dylan M. Taylor 33bb59307b packaging(linux): support co-installable nightly packages (#4733)
Linux nightly packaging by @dylanmtaylor, with the per-app Nightly flavor commits stacked on his branch.

Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
2026-11-24 18:29:20 -06:00
aiongg 5c54cce8dc clippy: egui's ComboBox is the combo box on craft-libs next; Escape helpers take the context by value 2026-11-24 17:19:35 +00:00
aiongg 2f585b0edd Repin to craft-libs 3ad64a26ea: grid host-canvas registration back, semibold font mapping removed 2026-11-24 16:49:09 +00:00
aiongg 30fff82145 Clicks in tests wait for the release the runtime hands on a frame later; Escape leaves framework fields as GridCraft's own; runtime in the unit harnesses that draw the app 2026-11-24 16:35:05 +00:00
aiongg 786f88c0f6 Repin craft-libs to next-host-input 2f8d73e7cf; printers map through craft-print's From 2026-11-24 16:22:34 +00:00
aiongg b467062692 Grid keeps egui's focus without a host-canvas registration; close path in the macro editor harnesses; viewports native only 2026-11-24 16:12:27 +00:00
aiongg 2c4652d3d8 Host GridCraft's egui UI on craft-libs next's runtime
The runtime's four hooks in the desktop and web shells, the close path decided by
SheetApp::close_decision, Escape read through the window's cancel where no GridCraft
widget has the keyboard, the grid as the window's host canvas, the interface scale as
the runtime's RootEnv scale, fonts through craft_ui::fonts::load with the chrome's
families, the update dialogs on a DialogHost, and app-local copies of the removed
capture slot, combo menu and window viewports; the print controls on craft-print's ui
feature. Test harnesses that run the app install the runtime.
2026-11-24 15:52:54 +00:00
aiongg cf877fb11a minimal-port rewrite: 20 edits (combo 20) 2026-11-24 15:17:08 +00:00
aiongg c09881beaa minimal-port repin: 36 edits (revs 34, features 2) 2026-11-24 15:16:47 +00:00
87 changed files with 3640 additions and 578 deletions
+5 -5
View File
@@ -2,13 +2,13 @@
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/gridcraft",
"repository_id": 1408285582,
"producer_workflow_id": null,
"producer_workflow_id": 429713469,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"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": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
+10 -7
View File
@@ -1,7 +1,8 @@
name: GridCraft release-ref nightly signer
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
# 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:
@@ -22,21 +23,23 @@ concurrency:
jobs:
release:
# Actual context guards: official repository, manual dispatch, real release branch.
# 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/release' && github.ref_type == 'branch'
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@605d58766e8f536564da8fc81d3676ac86816dea
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
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 existing release environment and export keys in its signing step.
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
+4 -4
View File
@@ -22,13 +22,13 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
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 #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
# 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"]'
Generated
+1402 -151
View File
File diff suppressed because it is too large Load Diff
+38 -30
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 = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "=0.1.0", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", features = ["ui"] }
# PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers.
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" }
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" }
# Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]).
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" }
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" }
# OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`.
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", 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 = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
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" }
# 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 = "9a6d894200221fcfedc274870c30394d404f859d", version = "0.1.0" }
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", 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 = "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" }
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" }
# foundation
thiserror = "2"
@@ -92,7 +92,15 @@ 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 = "e98299546f5c5c3c22388d16507f8b5e61a5f280", default-features = false, features = ["egui"] }
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"] }
[workspace.lints.rust]
unsafe_code = "forbid"
@@ -120,18 +128,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 = "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" }
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" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+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 = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9", version = "0.1.0" }
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" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
+3
View File
@@ -49,6 +49,7 @@ 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.
@@ -158,6 +159,7 @@ 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() {
@@ -177,6 +179,7 @@ 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 -1
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 = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9" }
craft-print = { workspace = true }
craft-update = { workspace = true }
rfd = { workspace = true }
arboard = { workspace = true, features = ["image-data"] }
+101 -31
View File
@@ -66,13 +66,12 @@ impl eframe::App for App {
}
self.app.logic(ctx);
self.windows.logic(&mut self.app, ctx);
if ctx.input(|input| input.viewport().close_requested()) && self.app.printing.busy() {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
}
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);
// 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()) {
@@ -80,7 +79,8 @@ impl eframe::App for App {
}
}
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
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 on_exit(&mut self) {
@@ -268,14 +268,23 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit
)
}
/// 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.
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
/// Tell a desktop user why a nightly launch was refused, in a native box where one renders without the
/// app's event loop (Windows, X11/Wayland), and on standard error always. 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 refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("GridCraft launch profile: {error}");
return;
@@ -330,6 +339,48 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
Some(early.args)
}
/// The app's own command line, once the launch profile's tokens are gone: `--control`,
/// `--control-token`, `--sample` and the files to open. `--` ends the options, and everything after
/// it is a file, even a name that reads like one — that is how the Launcher hands a nightly its
/// documents (`launch_profile::parse` puts the separator first), so the separator itself is never
/// opened as a file.
#[derive(Debug, Default, PartialEq)]
struct DesktopArgs {
control_port: Option<u16>,
control_token: Option<String>,
sample: Option<String>,
files: Vec<String>,
}
fn desktop_args(args: &[String], control_port: Option<u16>, control_token: Option<String>) -> DesktopArgs {
let mut parsed = DesktopArgs { control_port, control_token, ..DesktopArgs::default() };
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--" => {
parsed.files.extend(args[i + 1..].iter().cloned());
break;
}
"--control" => {
i += 1;
parsed.control_port = args.get(i).and_then(|p| p.parse().ok());
}
"--control-token" => {
i += 1;
parsed.control_token = args.get(i).cloned();
}
"--sample" => {
i += 1;
parsed.sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into()));
}
a if a.starts_with("-psn_") => {}
a => parsed.files.push(a.to_string()),
}
i += 1;
}
parsed
}
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
@@ -396,30 +447,10 @@ fn main() -> eframe::Result<()> {
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 sample: Option<String> = None;
let mut files: Vec<String> = Vec::new();
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--control" => {
i += 1;
control_port = args.get(i).and_then(|p| p.parse().ok());
}
"--control-token" => {
i += 1;
control_token = args.get(i).cloned();
}
"--sample" => {
i += 1;
sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into()));
}
a if a.starts_with("-psn_") => {}
a => files.push(a.to_string()),
}
i += 1;
}
let control_port: Option<u16> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten();
let control_token: Option<String> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten();
let parsed = desktop_args(&args, control_port, control_token);
let (control_port, control_token, sample, files) = (parsed.control_port, parsed.control_token, parsed.sample, parsed.files);
// The log file lives in the settings folder, next to the preferences; opened after the
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
// first. Runs without preferences (agents' test runs) log to standard error only, so they
@@ -543,6 +574,7 @@ fn main() -> eframe::Result<()> {
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()) {
@@ -615,3 +647,41 @@ mod packaging_tests {
}
}
}
#[cfg(test)]
mod launch_separator_tests {
use super::*;
use crate::build_flavor::BuildFlavor;
/// The argv the Launcher starts a nightly with, extended by `tail`, as the start then reads it.
fn launcher_argv(tail: &[&str]) -> Vec<String> {
let mut argv: Vec<std::ffi::OsString> = ["--launch-profile", "nightly-v1", "--profile-root", "/nightly-data/profiles/gridcraft", "--"]
.iter()
.map(std::ffi::OsString::from)
.collect();
argv.extend(tail.iter().map(std::ffi::OsString::from));
launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
}
#[test]
fn the_launchers_separator_is_never_a_file() {
let parsed = desktop_args(&launcher_argv(&[]), None, None);
assert_eq!(parsed, DesktopArgs::default(), "the separator must not reach the file list");
}
#[test]
fn files_after_the_separator_are_opened_in_order() {
assert_eq!(desktop_args(&launcher_argv(&["a.file"]), None, None).files, ["a.file"]);
let parsed = desktop_args(&launcher_argv(&["a.file", "--version", "--sample"]), None, None);
assert_eq!(parsed.files, ["a.file", "--version", "--sample"], "after -- every word is a file");
assert_eq!((parsed.sample, parsed.control_port), (None, None));
}
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
+12 -10
View File
@@ -1,15 +1,12 @@
//! Desktop spooler adapter. Discovery and submission never run on the UI thread.
use gridcraft_ui_egui::printing::{Discover, Duplex, Printer, Settings, Submit};
use gridcraft_ui_egui::printing::{Destination, 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| Printer { name: printer.name, label: printer.description, default: printer.default })
.collect();
let printers = craft_print::printers().into_iter().map(Printer::from).collect();
let _ = sender.send(printers);
});
receiver
@@ -34,12 +31,17 @@ 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: Some(settings.printer),
printer: match settings.destination {
Destination::Printer(name) => Some(name),
_ => None,
},
copies: settings.copies.clamp(1, 999),
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,
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,
}),
grayscale: settings.grayscale,
scaling: craft_print::Scaling::ShrinkToFit,
-3
View File
@@ -11,7 +11,4 @@ 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
+9 -4
View File
@@ -9,9 +9,15 @@ description = "GridCraft egui frontend (Excel-style UI); swappable — nothing b
workspace = true
[dependencies]
# 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" }
# 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 }
gridcraft-engine = { workspace = true }
gridcraft-chart = { workspace = true }
# `monochrome_emoji_fonts` restores the Noto Emoji and emoji-icon faces that 0.37 moved behind
@@ -42,7 +48,6 @@ 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.
+11 -6
View File
@@ -88,6 +88,8 @@ impl SheetApp {
arrange_windows: None,
#[cfg(not(target_arch = "wasm32"))]
updates_rt: Default::default(),
framework_dialogs: Default::default(),
framework_host: crate::framework::host(),
}
}
@@ -102,7 +104,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) {
ctx.set_fonts(theme::font_definitions_for_language(language));
craft_ui::fonts::load(ctx, theme::font_definitions_for_language(language));
theme::apply(ctx, dark);
}
@@ -123,7 +125,6 @@ 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
@@ -139,7 +140,6 @@ 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).
@@ -213,8 +213,6 @@ 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 {
@@ -257,6 +255,12 @@ 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 {
@@ -373,6 +377,7 @@ 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;
@@ -525,7 +530,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 { name: "Queue".into(), label: String::new(), default: true });
app.printing.printers.push(crate::printing::Printer::new("Queue").is_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 {
ctx.set_fonts(theme::pinned_font_definitions());
craft_ui::fonts::load(ctx, 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;
}
ctx.set_fonts(theme::font_definitions_with(self.ui.language, &used));
craft_ui::fonts::load(ctx, theme::font_definitions_with(self.ui.language, &used));
self.fonts_bound = used;
self.fonts_rebind = true;
ctx.request_repaint();
-21
View File
@@ -27,27 +27,6 @@ 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.
+19 -11
View File
@@ -1,28 +1,35 @@
use craft_ui::shell::embed::CloseDecision;
use super::{SaveAnswer, SheetApp, json};
impl SheetApp {
/// 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;
/// 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;
}
// A cell still being edited is part of the workbook, as for File › Close.
if !self.commit_edit(0, 0, false, false) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
return;
return CloseDecision::Hold;
}
// 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;
return CloseDecision::Hold;
}
if !self.session.documents().iter().any(|d| d.is_dirty()) {
return;
return CloseDecision::Close;
}
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" => {
@@ -30,6 +37,7 @@ impl SheetApp {
}
_ => self.continue_quit(ctx),
}
CloseDecision::Hold
}
/// Asks about the next unsaved workbook before quitting, in its window, or closes the app
+2 -7
View File
@@ -233,12 +233,7 @@ 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)
&& ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape))
{
if !typing && app.dialog.is_none() && app.message.is_none() && !egui::Popup::is_any_open(&ctx) && crate::framework::consume_escape(&ctx) {
out.close = true;
}
if let Some(page) = out.page {
@@ -681,7 +676,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"));
craft_ui::ComboBox::from_id_salt("backstage_save_type")
egui::ComboBox::from_id_salt("backstage_save_type")
.width(280.0)
.selected_text(lang.tr(current))
.show_ui(ui, |ui| {
+2 -2
View File
@@ -63,7 +63,7 @@ fn general_options(app: &mut SheetApp, ui: &mut Ui, lang: Language) {
"dark" => "Dark",
_ => "Light",
};
craft_ui::ComboBox::from_id_salt("backstage_theme")
egui::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"));
craft_ui::ComboBox::from_id_salt("backstage_language")
egui::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(250.0);
ui.set_width(340.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" };
craft_ui::ComboBox::from_id_salt("backstage_print_scope")
egui::ComboBox::from_id_salt("backstage_print_scope")
.width(230.0)
.selected_text(lang.tr(scope))
.show_ui(ui, |ui| {
+251
View File
@@ -0,0 +1,251 @@
//! 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
@@ -0,0 +1,491 @@
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);
}
+9 -8
View File
@@ -326,14 +326,15 @@ mod tests {
// --- frames ---
fn harness(s: Session) -> Harness {
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()),
);
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()),
);
h.run_steps(8);
h
}
+67
View File
@@ -0,0 +1,67 @@
//! 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 craft_ui::capture::CaptureSlot;
use crate::capture::CaptureSlot;
use gridcraft_engine::core::CellRef;
use serde_json::{Value as Json, json};
+1
View File
@@ -284,6 +284,7 @@ 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 ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
if crate::framework::escape_pressed(&ctx) {
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");
craft_ui::ComboBox::from_id_salt("credits_sort").selected_text(v.key.label().0).show_ui(ui, |ui| {
egui::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 -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");
craft_ui::ComboBox::from_id_salt("solverOp")
egui::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",
};
craft_ui::ComboBox::from_id_salt("solverMethod")
egui::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" => {
craft_ui::ComboBox::from_label(lang.tr("Font")).selected_text(st.font.name.clone()).show_ui(ui, |ui| {
egui::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:"));
craft_ui::ComboBox::from_id_salt("insertFunctionCategory")
egui::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() || craft_ui::ComboBox::is_open(ui.ctx(), picker.id) {
if menu_was_open || picker.has_focus() || egui::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 ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape) | i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {
if crate::framework::consume_escape(ctx) | ctx.input_mut(|i| 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 ctx.input(|i| i.key_pressed(Key::Escape)) || !win_open {
if crate::framework::escape_pressed(ctx) || !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("");
craft_ui::ComboBox::from_id_salt(("dataValidation", key))
egui::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 = craft_ui::ComboBox::from_id_salt(("col", i)).selected_text(shown).width(w).show_ui(ui, |ui| {
let r = egui::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 = craft_ui::ComboBox::from_id_salt(("by", i)).selected_text(by_label).width(w).show_ui(ui, |ui| {
let r = egui::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 = craft_ui::ComboBox::from_id_salt(("order", i)).selected_text(order_label).width(w).show_ui(ui, |ui| {
let r = egui::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);
});
+21 -29
View File
@@ -18,10 +18,12 @@
//!
//! [`Session::windows`]: gridcraft_engine::Session::windows
use craft_window::{CASCADE_STEP, Frame, Rect, Viewports, WindowEvent, WindowId, WindowList, cascade};
use craft_window::{WindowId, WindowList};
use egui::Rect;
use serde_json::json;
use crate::SheetApp;
use crate::viewports::{CASCADE_STEP, Viewports, WindowEvent};
/// The native windows (see the module docs).
pub struct DocWindows {
@@ -40,8 +42,7 @@ 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;
// 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 }
DocWindows { list: WindowList::new(), viewports: Viewports::default(), base, quit_with_last_window, root_hidden: false }
}
/// The platform default for the last window closing: macOS keeps running, others quit.
@@ -91,7 +92,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::new(0.0, 0.0, size.x, size.y));
let mut rects = arrange_rects(arrange, ids.len(), Rect::from_min_size(egui::Pos2::ZERO, size));
if arrange == "cascade" {
// The active window goes in front: the last step of the cascade.
rects.reverse();
@@ -100,8 +101,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(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))));
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))));
}
if let Some(first) = ids.first() {
self.viewports.focus(ctx, *first);
@@ -123,7 +124,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, &self.list, id),
Some(id) => self.viewports.adopt(ctx, id),
None => self.viewports.set_root(None),
}
}
@@ -205,7 +206,7 @@ impl DocWindows {
match event {
WindowEvent::Focused(_) => {}
WindowEvent::CloseRequested(id) => {
if let Some(w) = self.close_requested(app, &ctx, id) {
if let Some(w) = self.close_requested(app, id) {
requested = Some(w);
}
}
@@ -228,16 +229,13 @@ 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.
fn close_requested(&mut self, app: &mut SheetApp, ctx: &egui::Context, id: WindowId) -> Option<u64> {
let is_root = self.viewports.root() == Some(id);
/// 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> {
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}));
@@ -273,34 +271,28 @@ 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::new(bounds.x, bounds.y + h * i as f32, bounds.width, h)).collect()
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()
}
"vertical" => {
let w = bounds.width / count;
(0..n).map(|i| Rect::new(bounds.x + w * i as f32, bounds.y, w, bounds.height)).collect()
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()
}
"cascade" => {
let shift = CASCADE_STEP * (count - 1.0);
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 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 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::new(bounds.x + w * col as f32, bounds.y + h * row as f32, w, h)
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))
})
.collect()
}
+152
View File
@@ -0,0 +1,152 @@
//! 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
}
+8 -5
View File
@@ -648,19 +648,22 @@ 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; 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, 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.
fn spend_escape(ctx: &egui::Context) -> bool {
ctx.input_mut(|i| {
let in_egui = 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<'_>) {
@@ -810,7 +813,7 @@ fn handle_release(app: &mut SheetApp, input: &InteractionInput<'_>) {
Drag::Fill { target: Some(t), menu: true } => {
if let Some(p) = pos
&& t != sel.current()
&& !ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
&& !crate::framework::consume_escape(&ctx)
{
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
|| ui.input(|i| i.key_pressed(egui::Key::Escape))
|| crate::framework::escape_pressed(ui.ctx())
|| (!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
|| ui.input(|i| i.key_pressed(egui::Key::Escape))
|| crate::framework::escape_pressed(ui.ctx())
|| (ui.input(|i| i.pointer.any_pressed())
&& !resp.response.contains_pointer()
&& !resp.response.hovered()
+1
View File
@@ -407,6 +407,7 @@ 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
+17 -9
View File
@@ -120,15 +120,7 @@ impl KeyTips {
} else if self.prefix.is_some() && !matches!(key, Key::ShiftLeft | Key::ShiftRight) {
handled = true;
if *key == Key::Escape {
// 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();
}
}
self.back();
} 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) {
@@ -171,9 +163,25 @@ 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);
+10
View File
@@ -17,11 +17,13 @@ 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;
@@ -38,6 +40,7 @@ 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;
@@ -60,6 +63,8 @@ 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;
@@ -348,6 +353,11 @@ 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 ctx.input(|i| i.key_pressed(egui::Key::Escape)) && ed.picker.is_some() {
if crate::framework::escape_pressed(ctx) && 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() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
if ui.button("Cancel").clicked() || crate::framework::escape_pressed(ui.ctx()) {
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() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
if ui.button("Cancel").clicked() || crate::framework::escape_pressed(ui.ctx()) {
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);
craft_ui::ComboBox::from_id_salt(("me_op", &path)).selected_text(label).show_ui(ui, |ui| {
egui::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;
craft_ui::ComboBox::from_id_salt(("me_ty", c)).selected_text(type_name(ty)).show_ui(ui, |ui| {
egui::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() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
if ui.button("Cancel").clicked() || crate::framework::escape_pressed(ui.ctx()) {
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 !ui.input(|i| i.key_pressed(egui::Key::Escape)) {
if !crate::framework::escape_pressed(ui.ctx()) {
// 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 ui.input(|i| i.key_pressed(egui::Key::Escape)) || current == value { None } else { Some(current) }
if crate::framework::escape_pressed(ui.ctx()) || 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, Key, Painter, Pos2, Rect, Stroke, StrokeKind, TextEdit, pos2, vec2};
use egui::{Align2, Color32, FontId, 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 ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
if crate::framework::consume_escape(ui.ctx()) {
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 ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
if crate::framework::consume_escape(ui.ctx()) {
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}));
}
craft_ui::ComboBox::from_id_salt("pv_layout")
egui::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")] {
+21 -25
View File
@@ -1,33 +1,27 @@
//! 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};
//! 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};
/// Draws the shared print controls.
/// Draws the shared print controls and the feedback of the last discovery or job.
///
/// `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.
/// `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.
pub fn show(state: &mut State, ui: &mut egui::Ui, discover: &Discover, translate: impl Fn(&str) -> String) {
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);
ui.push_id("gridcraft_print_settings", |ui| state.run(ui, discover));
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> {
@@ -45,7 +39,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.printer = printer.to_owned();
next.destination = Destination::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")?;
@@ -81,10 +75,11 @@ 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": 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" },
"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" },
"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,
@@ -101,5 +96,6 @@ 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 = craft_ui::combo::Menu::new(ui, &field).height(height);
let menu = crate::combo_menu::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",
};
craft_ui::ComboBox::from_id_salt("display_theme")
egui::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}%") };
craft_ui::ComboBox::from_id_salt("ui_interface_size")
egui::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));
craft_ui::ComboBox::from_id_salt("ui_language")
egui::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 !ui.input(|i| i.key_pressed(egui::Key::Escape)) && text != name {
if !crate::framework::escape_pressed(ui.ctx()) && 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 ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) {
if crate::framework::consume_escape(ctx) {
app.cancel_text_box_edit();
ctx.memory_mut(|m| m.surrender_focus(editor_id()));
return;
+5
View File
@@ -526,6 +526,11 @@ 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 {
+43 -19
View File
@@ -1,8 +1,10 @@
//! 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`.
//! itself is `craft_update::updater::Updater`; its dialogs run on the app's
//! [`DialogHost`](craft_ui::dialog::DialogHost).
use craft_update::CheckResultResponse;
use craft_ui::dialog::DialogResult;
use craft_update::stack_dialogs::{CheckChoice, UpdateCheckDialog};
use craft_update::updater::{Action, Status, Updater};
use crate::SheetApp;
@@ -35,9 +37,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(ctx);
rt.updater.check_now();
} else if rt.startup {
rt.updater.check_at_start(ctx);
rt.updater.check_at_start();
}
rt.updater.tick(ctx);
}
@@ -54,28 +56,50 @@ 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());
match app.updates_rt.updater.show_if(ctx, clean) {
Action::OpenUrl(url) => {
if let Some(open) = &app.services.open_url {
open(&url);
}
// 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);
}
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 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 => {}
}
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);
}
}
+207
View File
@@ -0,0 +1,207 @@
//! 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 (!ui.input(|i| i.key_pressed(egui::Key::Escape))).then_some(text);
return (!crate::framework::escape_pressed(ui.ctx())).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) || i.key_pressed(egui::Key::Escape)) {
if ui.button(" OK ").clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) || crate::framework::escape_pressed(ui.ctx()) {
close = true;
}
});
+11 -8
View File
@@ -13,14 +13,17 @@ 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_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_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()),
);
h.run_steps(4);
if formula_bar {
h.get_by_label(text).click();
+3
View File
@@ -49,6 +49,7 @@ 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] {
@@ -72,6 +73,7 @@ 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();
@@ -139,6 +141,7 @@ 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();
+6 -3
View File
@@ -14,10 +14,12 @@ use gridcraft_ui_egui::{Services, SheetApp};
pub type Harness = egui_kittest::Harness<'static, SheetApp>;
/// A kittest builder with the deterministic font set and GridCraft's visuals installed.
/// A kittest builder with the UI runtime, the deterministic font set and GridCraft's visuals
/// installed.
pub fn builder<State>() -> HarnessBuilder<State> {
egui_kittest::Harness::builder().with_context_setup(|ctx| {
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
gridcraft_ui_egui::framework::install_headless(ctx);
craft_ui::fonts::load(ctx, gridcraft_ui_egui::theme::pinned_font_definitions());
gridcraft_ui_egui::theme::apply(ctx, false);
})
}
@@ -33,7 +35,7 @@ pub fn prepare(mut app: SheetApp) -> SheetApp {
app
}
/// Drive `app`'s `logic` then `ui` each frame in a harness built with `builder`.
/// Drive `app`'s `logic`, its close path, 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`
@@ -43,6 +45,7 @@ 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,
+4 -2
View File
@@ -42,6 +42,7 @@ 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;
@@ -77,6 +78,7 @@ impl Desk {
}
app.logic(&ctx);
windows.logic(app, &ctx);
app.close_path(&ctx);
windows.show(app, ui);
});
record(out);
@@ -458,8 +460,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 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);
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));
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)]);
}
+11 -7
View File
@@ -25,13 +25,17 @@ 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_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_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()),
);
h.run_steps(4);
h.state_mut().session.active_mut().unwrap().undo.clear();
h.state_mut().session.journal.clear();
@@ -27,6 +27,7 @@ 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,6 +18,7 @@ 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();
+6 -2
View File
@@ -12,8 +12,12 @@ 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_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_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(
|ui, app: &mut SheetApp| {
app.logic(ui.ctx());
app.ui(ui);
+4 -2
View File
@@ -114,7 +114,8 @@ fn escape_leaves_file_fields_before_closing_the_view() {
let copies = h.state().printing.settings.copies;
h.key_press(egui::Key::Escape);
h.run_steps(3);
// With GridCraft's frame input, as the shells give it: Escape leaves the framework's fields too.
crate::support::frames(&mut h, 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}");
@@ -125,7 +126,8 @@ fn escape_leaves_file_fields_before_closing_the_view() {
}
h.key_press(egui::Key::Escape);
h.run_steps(3);
// With GridCraft's frame input, as the shells give it: Escape leaves the framework's fields too.
crate::support::frames(&mut h, 3);
assert_eq!(page(&h), None, "the next Esc returns to the sheet");
}
}
+2
View File
@@ -38,6 +38,7 @@ 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)
@@ -591,6 +592,7 @@ 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,6 +31,7 @@ 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();
@@ -57,6 +58,7 @@ 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();
@@ -95,6 +97,7 @@ 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();
@@ -112,6 +115,7 @@ 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();
@@ -131,6 +135,7 @@ 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();
@@ -162,6 +167,7 @@ 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();
@@ -214,6 +220,7 @@ 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();
@@ -257,6 +264,7 @@ 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,6 +23,7 @@ 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();
@@ -47,6 +48,7 @@ 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();
@@ -64,6 +66,7 @@ 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();
@@ -91,6 +94,7 @@ 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,7 +37,9 @@ 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 });
h.run_steps(2);
// 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);
}
#[test]
@@ -68,7 +70,9 @@ 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 });
h.run_steps(2);
// 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);
}
/// 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),
);
h.run_steps(2);
crate::support::frames(&mut h, 2);
assert_eq!(h.ctx.zoom_factor(), 1.0);
h.state_mut().run("view.interfaceScale", json!({"percent": 125})).unwrap();
h.run_steps(2);
crate::support::frames(&mut h, 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();
h.run_steps(2);
crate::support::frames(&mut h, 2);
assert_eq!(h.ctx.zoom_factor(), 1.0);
// A malformed or out-of-range ui.json keeps the other preferences.
+22 -16
View File
@@ -20,14 +20,18 @@ 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_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,
);
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,
);
h.run_steps(4);
h
}
@@ -566,14 +570,16 @@ 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_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_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,
);
h.run_steps(4);
three(&mut h);
h.run_steps(4);
+42 -32
View File
@@ -16,14 +16,17 @@ 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_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_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,
);
h.run_steps(4);
h
}
@@ -115,14 +118,17 @@ 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_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_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,
);
h.run_steps(3);
h.state_mut().open_dialog("macros", json!({}));
h.run_steps(2);
@@ -260,14 +266,17 @@ 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_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_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,
);
h.run_steps(3);
h.state_mut().open_dialog("macros", json!({}));
h.run_steps(2);
@@ -291,14 +300,15 @@ 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_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_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,
);
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"][..])] {
+3 -1
View File
@@ -39,7 +39,9 @@ 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 },
]);
h.run_steps(2);
// 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);
}
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::{Duplex, Feedback, Printer};
use gridcraft_ui_egui::printing::{Destination, 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 { name: "Chosen queue".into(), label: String::new(), default: false });
app.printing.printers.push(Printer::new("Chosen queue"));
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.printer, "Chosen queue");
assert_eq!(jobs[0].1.destination, Destination::Printer("Chosen queue".into()));
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 { name: "Test queue".into(), label: String::new(), default: true }]).unwrap();
sender.send(vec![Printer::new("Test queue").is_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 printers").accesskit_node().is_disabled());
assert!(!harness.get_by_label("Refresh").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 { name: "Queue".into(), label: String::new(), default: true });
app.printing.printers.push(Printer::new("Queue").is_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 { name: "Queue".into(), label: String::new(), default: true });
app.printing.printers.push(Printer::new("Queue").is_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,6 +53,7 @@ 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)
+12 -8
View File
@@ -18,6 +18,7 @@ fn render_pivot_field_buttons(dark: bool) -> Vec<Shape> {
let mut app = crate::common::app(session);
app.ui.dark = dark;
let ctx = egui::Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
let mut output = egui::FullOutput::default();
for _ in 0..6 {
output = ctx.run_ui(RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), ..Default::default() }, |ui| {
@@ -76,14 +77,17 @@ fn the_field_list_scrollbar_sits_at_the_pane_edge() {
session.execute("range.setValues", json!({"range": "A1", "values": [names.clone(), (1..=14).collect::<Vec<i32>>()]})).unwrap();
session.execute("insert.pivotTable", json!({"source": "Sheet1!A1:N2", "destination": "Sheet1!A5", "rows": ["F1"], "values": ["F2"]})).unwrap();
session.execute("selection.set", json!({"cell": "A5"})).unwrap();
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()),
);
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()),
);
h.run_steps(4);
let first = h.get_by_label("F1").rect();
// A floating scrollbar is drawn while the pointer is over its area.
@@ -34,7 +34,9 @@ fn double_click(h: &mut egui_kittest::Harness<'_, SheetApp>, pos: Pos2) {
Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE },
Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE },
]);
h.run_steps(2);
// 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);
}
}
+3 -1
View File
@@ -52,7 +52,9 @@ fn click(h: &mut Harness, pos: Pos2, button: PointerButton) {
h.input_mut().events.push(Event::PointerMoved(pos));
h.input_mut().events.push(Event::PointerButton { pos, button, pressed: true, modifiers: Modifiers::NONE });
h.input_mut().events.push(Event::PointerButton { pos, button, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(2);
// 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);
}
fn open(h: &mut Harness, menu: Menu) {
+2 -1
View File
@@ -91,7 +91,8 @@ fn click_at(h: &mut H, pos: egui::Pos2) {
h.input_mut().events.push(Event::PointerMoved(pos));
press(h, pos, true);
press(h, pos, false);
h.run_steps(3);
// The runtime takes one press per frame: the release arrives in the next frame.
h.run_steps(4);
}
fn key(h: &mut H, k: Key, m: Modifiers) {
@@ -190,6 +190,7 @@ fn view_animations_sets_and_toggles_without_a_dialog() {
fn agents_find_run_and_read_the_setting_over_the_control_channel() {
let mut a = app();
let ctx = egui::Context::default();
gridcraft_ui_egui::framework::install_headless(&ctx);
let found = reply(control::handle(&mut a, &ctx, "engine.commands", &json!({"search": "animations"})));
let entry = found["result"].as_array().and_then(|all| all.iter().find(|c| c["id"] == "view.animations")).cloned().unwrap();
assert_eq!((&entry["label"], &entry["ui"]), (&json!("Animations"), &json!(true)));
+10
View File
@@ -39,3 +39,13 @@ pub fn services_harness(services: Services, steps: usize) -> Harness {
pub fn app_harness(app: SheetApp, steps: usize) -> Harness {
harness_with(builder().with_size(egui::vec2(1200.0, 800.0)), app, steps)
}
/// Runs `n` frames as the desktop and web shells do: the app hands the runtime its frame input
/// (theme mode, interface scale) before each one.
pub fn frames(h: &mut Harness, n: usize) {
for _ in 0..n {
let ctx = h.ctx.clone();
h.state_mut().before_input(&ctx);
h.step();
}
}
@@ -43,7 +43,9 @@ fn input_message_hides_while_the_list_is_open() {
h.input_mut().events.push(Event::PointerMoved(pos));
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(2);
// 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);
assert!(h.state().grid.list_picker.is_some(), "the dropdown arrow opens the list");
assert!(h.query_by_label("Green").is_some(), "the list shows its items");
@@ -202,7 +202,9 @@ fn typing_over_the_open_dropdown_replaces_it_with_the_searched_list() {
h.input_mut().events.push(Event::PointerMoved(pos));
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(2);
// 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);
assert!(h.state().grid.list_picker.is_some(), "the arrow opens the full list");
assert!(shown(&h, "Paris - France"));
+11 -8
View File
@@ -25,14 +25,17 @@ fn fixture_of(kind: &str) -> (Harness, u32) {
let shape = session.execute("insert.shape", json!({"kind": kind, "at": "D3", "width": 160, "height": height})).unwrap();
shape["shape"].as_u64().unwrap() as u32
};
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()),
);
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()),
);
h.run_steps(4);
h.state_mut().selected_object = None;
h.run_steps(2);
+49 -21
View File
@@ -1,11 +1,11 @@
# Windows, Linux and macOS release-ref nightly: supervised manual go-live
**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the
signer (`nightly-sign.yml`, release) keep only their exact context guards and run when one of the reviewed
signer (`nightly-sign.yml`, on the dedicated `nightly-signer` branch) keep only their exact context guards and run when one of the reviewed
manual actors dispatches them. There is no schedule yet. The installed policy
[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 policy
adapted from `storytold/photocraft#16594`. Once `nightly.yml` lands on `main`, populate
`producer_workflow_id` before promoting the policy to `release`, read with:
adapted from `storytold/photocraft#16594`. `producer_workflow_id` is the registered
`nightly.yml` workflow id, read with:
```bash
gh api repos/storytold/gridcraft/actions/workflows/nightly.yml --jq .id
@@ -14,16 +14,38 @@ gh api repos/storytold/gridcraft/actions/workflows/nightly.yml --jq .id
The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation
permissions are for its isolated attester; its compiler narrows to contents and Actions read
only, with no OIDC, attestation write, release environment or platform signing secrets.
Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions
main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded
lineage compares and an issue reread at the end of candidate admission) on top of
[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input
and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is reviewed
source availability, not provider, queue, native signing or crypto qualification.
Shared tooling is pinned to `be00e5ccd18b68e950c8a08532f2230e7c3d0cba`, the craft-common-actions
main commit that merged [#371](https://github.com/storytold/craft-common-actions/pull/371) (the
candidate is admitted on the built commit's own Sonar analysis, not main's latest) after
[#370](https://github.com/storytold/craft-common-actions/pull/370) (the Windows and macOS nightly
registry rows for the 14 apps) and
[#369](https://github.com/storytold/craft-common-actions/pull/369) (shared helper checkouts kept out
of the app's clean-source check, and macOS on `macos-15`), following
[#364](https://github.com/storytold/craft-common-actions/pull/364) (the signer may run on the
policy's signer branch) and [#363](https://github.com/storytold/craft-common-actions/pull/363) (the
multi-app pipeline, which makes the signer's `app-name` input required and admits any reviewed
registry app), with #342 (`a4f6fd51`, policy v3 and the `platforms` input) and #339 (`605d5876`)
earlier. Both callers name it in `uses` and `tooling-revision`. A pin is reviewed source
availability, not provider, queue, native signing or crypto qualification.
**Signer branch.** The signer runs on `refs/heads/nightly-signer`, not on the stable `release`
branch, so nightly signer files never need a stable release sync. The policy's `release_branch`
names it, the signer's guard requires it and its caller passes `app-name`. The branch only
fast-forwards to reviewed main commits, through the nightly-signer settings script's `advance` (no
queued signer run, a trust-closure scan, then the full diff of `.github/` and `packaging/`), and the
existing `release` environment must admit `nightly-signer` alongside `release` before the first
dispatch (a repository settings change, not a workflow one). Its trust closure is all of `.github/`
and `packaging/`, including `packaging/env.sh`, which `import-cert.sh` sources with the Apple keys.
On that branch only the pinned `nightly-sign.yml` caller may reach an environment: no app workflow
binds one, nothing else calls `nightly-release.yml`, and the only caller of the shared stable
`release.yml` is `release.yml`, whose callee must carry the stable-only environment guard. The
contract tests check the in-repo part on every main PR; the settings scan also resolves the callee.
Stable releases still come only from `refs/heads/release`. History does not carry over a switch
between `release` and `nightly-signer`, so the switch happens before the first publication.
Existing stable workflows are unchanged.
**First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a
listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that
listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `nightly-signer` with that
producer run ID and attempt, by a listed manual actor.
**Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the
@@ -44,13 +66,13 @@ so there is no separate Linux or macOS caller job and the signer caller has no p
## Installed policy values and their sources
Read on 2026-11-24; re-read anything that may have moved (and populate `producer_workflow_id` and
any Sonar debt snapshot) before the policy is promoted to `release`.
any Sonar debt snapshot) before `nightly-signer` is advanced to it.
| Field | Value | Source |
|---|---|---|
| `repository_id` | `1408285582` | `gh api repos/storytold/gridcraft --jq .id` |
| `producer_workflow_id` | `null` (pending `main` registration) | Read with `gh api repos/storytold/gridcraft/actions/workflows/nightly.yml --jq .id` after `nightly.yml` lands on `main` |
| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin |
| `producer_workflow_id` | `429713469` | `gh api repos/storytold/gridcraft/actions/workflows/nightly.yml` (path `.github/workflows/nightly.yml`, state `active`) |
| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `be00e5cc…` (craft-common-actions exact-analysis admission, #371 after #370 and #369, following #364) | The callers' pin |
| `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` |
| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist |
| `platforms` | three rows | Suite stable identities (Windows Authenticode publisher subject, Linux OpenPGP release key fingerprint, macOS Apple Developer ID team `DJ6XS33FX8`) |
@@ -63,8 +85,8 @@ any Sonar debt snapshot) before the policy is promoted to `release`.
- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named
`GridCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets
may be passed or inherited.
- `.github/workflows/nightly-sign.yml`: top-level release registration, enabled for manual dispatch,
and identical on main and release after reviewed promotion. It rejects wrong repository/event/actual branch,
- `.github/workflows/nightly-sign.yml`: top-level signer registration, enabled for manual dispatch
on `nightly-signer`, which carries a reviewed main commit. It rejects wrong repository/event/actual branch,
including same-name tags. Its constant whole-run concurrency (`gridcraft-nightly-release`) is distinct
from stable, cancellation is off and `queue: max` must be hosted-qualified. The caller itself passes no
credentials; only the shared callee's sign jobs bind the `release` environment.
@@ -82,6 +104,9 @@ any Sonar debt snapshot) before the policy is promoted to `release`.
- Manual actors are exactly the reviewed release managers in both `nightly.yml` and `.github/nightly-signing-policy.json`, with `automatic_signer_actors` empty.
- Root serialization in `nightly-sign.yml` remains literal (`group: gridcraft-nightly-release`, `cancel-in-progress: false`); it carries no `queue:` key while actionlint 1.7.12 rejects that key, and the value is re-added when the hosted queue is qualified.
- Installed policy v3 fields, bounds, platforms, candidate workflows, and Sonar identity match `sonar-project.properties` and the callers.
- The `nightly-signer` trust-closure scan: no app workflow binds `environment:`, only
`nightly-sign.yml` calls `nightly-release.yml` at a 40-hex SHA, and the only caller of the
shared stable `release.yml` is `release.yml`.
## GridCraft's nightly-v1 flavor (the same branch)
@@ -105,21 +130,24 @@ traversing root, a root that resolves through a link into a fenced folder, an in
`${XDG_DATA_HOME:-$HOME/.local/share}/gridcraft-nightly/profile`, a sibling of stable's
`<xdg>/gridcraft`, never an ancestor.
**Every Linux format ships a launcher, and each passes an already-supplied profile through.**
**Every Linux format ships a launcher.** The flat nightly tar's `gridcraft` is craft-common-actions'
shared launcher template (`scripts/nightly-launcher.sh.in` from #363, rendered for this app), so it always
supplies its own profile; the packaged formats pass an already-supplied profile through.
| Format | Launcher | GUI | Data root |
|---|---|---|---|
| deb/rpm | `/usr/bin/gridcraft-nightly` | `/usr/lib/gridcraft-nightly/gridcraft` | `<xdg>/gridcraft-nightly/profile` |
| AppImage | `AppRun` (a script) and `usr/bin/gridcraft-nightly` | `usr/bin/gridcraft` | same |
| flat nightly tar | `gridcraft` | `gridcraft-bin` | same |
| plain tree tarball | `bin/gridcraft-nightly` | `bin/gridcraft` | same |
| Arch handoff | `bin/gridcraft-nightly` | `.gridcraft-nightly/gridcraft` | same |
| flat nightly tar | `gridcraft` (the shared template) | `gridcraft-bin` | `<xdg>/ai.storyteller.gridcraft.nightly` |
| plain tree tarball | `bin/gridcraft-nightly` | `bin/gridcraft` | `<xdg>/gridcraft-nightly/profile` |
| Arch handoff | `bin/gridcraft-nightly` | `.gridcraft-nightly/gridcraft` | `<xdg>/gridcraft-nightly/profile` |
| Flatpak bundle | `/app/bin/gridcraft-nightly` | `/app/bin/gridcraft` | the sandbox's own `~/.local/share` |
The flat nightly tar uses the kit's standard layout: `<app>` is the launcher people run and
`<app>-bin` is the GUI ELF it starts, so the shared Unix verifier can keep requiring `gridcraft`
as the entrypoint. No launcher falls back to a relative or world-writable path for the GUI, and a
candidate that is the launcher itself is never started.
as the entrypoint. That launcher is the shared template: it resolves its own directory once and execs
`gridcraft-bin` with `--launch-profile nightly-v1 --profile-root <xdg>/ai.storyteller.gridcraft.nightly --`
and the user's arguments, asking a bare `--version`/`-V` in the Launcher's own form.
**macOS and Windows.** `GridCraft Nightly.app` (`CFBundleIdentifier
ai.storyteller.gridcraft.nightly`, associations removed) is built and verified unsigned on main and
+90 -17
View File
@@ -2,10 +2,13 @@
"""The Linux launch profile, staged the way each format ships it; no cargo build, no GUI, no network.
What is checked, all synthetic:
* `nightly-launch.sh` (the AppImage and tar launcher) passes the flavor's own tokens and nothing else;
* `nightly-tar-launch.sh` (craft-common-actions' rendered template, the plain tar's entrypoint) starts
`<app>-bin` with the template's exact tokens and the channel's own profile root;
* `nightly-launch.sh` (the AppImage and plain-tree launcher) passes the flavor's own tokens;
* `package.sh` stages the deb/rpm, AppImage and tar launchers and a nightly desktop entry, and
leaves a stable tree exactly as it was. `nfpm`, `appimagetool` and `strip` are stubs on PATH.
"""
import hashlib
import os
from pathlib import Path
import shutil
@@ -16,9 +19,13 @@ import unittest
ROOT = Path(__file__).resolve().parents[2]
LAUNCHER = ROOT / "packaging/linux/nightly-launch.sh"
TAR_LAUNCHER = ROOT / "packaging/linux/nightly-tar-launch.sh"
PACKAGE = ROOT / "packaging/linux/package.sh"
NIGHTLY_VERSION = "0.19.1-nightly.20261124.7.1.gabcdef012345"
PROFILE = "gridcraft-nightly/profile"
# The tar launcher is the shared template rendered for this app; these are its bytes.
TAR_PROFILE = "ai.storyteller.gridcraft.nightly"
TAR_LAUNCHER_SHA256 = "da4d5c6187527b57bb3d6b9f2b8791dff71c2f3421a4116cbda3cd3314b54af7"
RECORDER = """#!/bin/sh
printf '<%s>\\n' "$@"
@@ -30,7 +37,7 @@ def run(argv, cwd, env, check=True):
class MovedTreeLauncher(unittest.TestCase):
"""nightly-launch.sh as AppRun and as an unpacked tar's launcher."""
"""nightly-launch.sh as AppRun and as a plain tree tarball's launcher."""
def setUp(self):
self.scratch = tempfile.TemporaryDirectory()
@@ -43,13 +50,11 @@ class MovedTreeLauncher(unittest.TestCase):
"""Each placement puts the GUI and this launcher where its format does.
appdir: AppRun at the root, GUI in usr/bin (also usr/bin/gridcraft-nightly).
tar: the kit's flat tar, `gridcraft` launcher beside the `gridcraft-bin` GUI.
tree: a plain tree tarball, bin/gridcraft-nightly beside bin/gridcraft.
"""
tree = self.root / layout
binary, launcher_name = {
"appdir": (tree / "usr/bin/gridcraft", tree / "AppRun"),
"tar": (tree / "gridcraft-bin", tree / "gridcraft"),
"tree": (tree / "bin/gridcraft", tree / "bin/gridcraft-nightly"),
}[layout]
binary.parent.mkdir(parents=True)
@@ -66,7 +71,7 @@ class MovedTreeLauncher(unittest.TestCase):
return ["<--launch-profile>", "<nightly-v1>", "<--profile-root>", f"<{self.data / PROFILE}>", "<-->"]
def test_every_layout_starts_the_gui_through_the_launch_profile(self):
for layout in ("appdir", "tar", "tree"):
for layout in ("appdir", "tree"):
with self.subTest(layout=layout):
launcher = self.install(layout)
self.assertEqual(self.query(launcher).stdout.splitlines(), self.tokens())
@@ -92,16 +97,84 @@ class MovedTreeLauncher(unittest.TestCase):
self.assertIn("no GridCraft binary", missing.stderr)
self.assertFalse(self.data.exists(), "a refused launch creates no data folder")
def test_a_flat_tar_launcher_never_starts_itself(self):
launcher = self.install("tar")
(self.root / "tar/gridcraft-bin").unlink()
refused = run([str(launcher)], cwd=self.root, env=self.env, check=False)
self.assertEqual(refused.returncode, 2)
self.assertIn("no GridCraft binary", refused.stderr)
def test_the_launcher_is_portable_shell(self):
run(["sh", "-n", str(LAUNCHER)], cwd=self.root, env=self.env)
self.assertTrue(LAUNCHER.read_text().startswith("#!/bin/sh\n"))
for launcher in (LAUNCHER, TAR_LAUNCHER):
with self.subTest(launcher=launcher.name):
run(["sh", "-n", str(launcher)], cwd=self.root, env=self.env)
self.assertTrue(launcher.read_text().startswith("#!/bin/sh\n"))
class CanonicalTarLauncher(unittest.TestCase):
"""The plain nightly tar's entrypoint: the shared template, rendered for GridCraft."""
def setUp(self):
self.scratch = tempfile.TemporaryDirectory()
self.addCleanup(self.scratch.cleanup)
self.root = Path(self.scratch.name)
self.data = self.root / "data"
self.home = self.root / "home with space"
self.env = {"PATH": os.environ["PATH"], "XDG_DATA_HOME": str(self.data)}
def install(self):
"""The kit's flat tar: the `gridcraft` launcher beside the `gridcraft-bin` GUI."""
tree = self.root / "tar"
tree.mkdir()
(tree / "gridcraft-bin").write_text(RECORDER)
(tree / "gridcraft-bin").chmod(0o755)
shutil.copy2(TAR_LAUNCHER, tree / "gridcraft")
(tree / "gridcraft").chmod(0o755)
return tree / "gridcraft"
def prefix(self, profile_root):
return ["<--launch-profile>", "<nightly-v1>", "<--profile-root>", f"<{profile_root}>"]
def tokens(self, profile_root):
return self.prefix(profile_root) + ["<-->"]
def test_every_argument_follows_the_profile_tokens(self):
launcher = self.install()
self.assertEqual(run([str(launcher)], cwd=self.root, env=self.env).stdout.splitlines(),
self.tokens(self.data / TAR_PROFILE))
self.assertEqual(
run([str(launcher), "workbook with spaces.xlsx", "--other-name.xlsx"], cwd=self.root, env=self.env).stdout.splitlines(),
self.tokens(self.data / TAR_PROFILE) + ["<workbook with spaces.xlsx>", "<--other-name.xlsx>"],
)
def test_the_profile_root_falls_back_to_the_data_home_under_home(self):
launcher = self.install()
env = {"PATH": os.environ["PATH"], "HOME": str(self.home)}
self.assertEqual(run([str(launcher), "book.xlsx"], cwd=self.root, env=env).stdout.splitlines(),
self.tokens(self.home / ".local/share" / TAR_PROFILE) + ["<book.xlsx>"])
self.assertFalse(self.home.exists(), "the launcher creates no folder of its own")
def test_a_version_query_asks_the_gui_in_the_launcher_form(self):
launcher = self.install()
for flag in ("--version", "-V"):
with self.subTest(flag=flag):
self.assertEqual(run([str(launcher), flag], cwd=self.root, env=self.env).stdout.splitlines(),
self.prefix(self.data / TAR_PROFILE) + ["<--version>"])
def test_a_launcher_profile_argv_passes_through_unchanged(self):
# The ArtCraft Launcher names its own profile and per-install root; the app validates the pair.
launcher = self.install()
argv = ["--launch-profile", "nightly-v1", "--profile-root", str(self.root / "launcher root"), "--", "book.xlsx"]
self.assertEqual(run([str(launcher), *argv], cwd=self.root, env=self.env).stdout.splitlines(),
[f"<{arg}>" for arg in argv])
def test_a_missing_gui_fails_before_anything_runs(self):
launcher = self.install()
(self.root / "tar/gridcraft-bin").unlink()
missing = run([str(launcher), "book.xlsx"], cwd=self.root, env=self.env, check=False)
self.assertNotEqual(missing.returncode, 0)
self.assertEqual(missing.stdout, "")
def test_the_bytes_are_the_shared_template_rendered_for_gridcraft(self):
data = TAR_LAUNCHER.read_bytes()
self.assertEqual(hashlib.sha256(data).hexdigest(), TAR_LAUNCHER_SHA256,
"the tar launcher must stay byte for byte scripts/nightly-launcher.sh.in rendered for gridcraft")
self.assertIn(b'target="$dir/gridcraft-bin"', data)
self.assertIn(b'/ai.storyteller.gridcraft.nightly"', data)
self.assertNotIn(b"gridcraft-nightly/profile", data, "the profile root is the package identity")
class FlatNightlyTar(unittest.TestCase):
@@ -110,13 +183,13 @@ class FlatNightlyTar(unittest.TestCase):
def test_the_flat_tar_stages_the_kit_layout(self):
source = (ROOT / "packaging/linux/nightly.sh").read_text()
self.assertIn('cp "$NIGHTLY_GUI" "$STAGE/gridcraft-bin"', source, "the GUI is <app>-bin")
self.assertIn('"$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/gridcraft"', source, "the launcher is <app>")
self.assertIn('"$ROOT/packaging/linux/nightly-tar-launch.sh" "$STAGE/gridcraft"', source, "the launcher is <app>")
self.assertNotIn('"$STAGE/gridcraft-nightly"', source, "the flat tar's launcher is gridcraft")
policy = (ROOT / "packaging/nightly-archive.py").read_text()
self.assertIn('{"gridcraft", "gridcraft-bin", "gridcraft-nightly.png"}', policy)
self.assertIn('required = {"gridcraft", "gridcraft-bin", "gridcraft-nightly.png"', policy)
launcher = LAUNCHER.read_text()
self.assertIn('"$here/gridcraft-bin"', launcher, "the launcher starts the GUI the tar ships")
launcher = TAR_LAUNCHER.read_text()
self.assertIn('target="$dir/gridcraft-bin"', launcher, "the launcher starts the GUI the tar ships")
class StagedFormats(unittest.TestCase):
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
# Nightly launcher generated by craft-common-actions scripts/nightly-launcher.sh.in. Do not edit:
# the shared nightly producer accepts this file only byte for byte as rendered for the app.
set -eu
dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd -P)
readonly dir
target="$dir/gridcraft-bin"
readonly target
profile_root="${XDG_DATA_HOME:-$HOME/.local/share}/ai.storyteller.gridcraft.nightly"
readonly profile_root
case "${1-}" in
# The ArtCraft Launcher passes its own profile and per-install root; the app validates the pair.
--launch-profile) exec "$target" "$@" ;;
--version | -V) exec "$target" --launch-profile nightly-v1 --profile-root "$profile_root" --version ;;
esac
exec "$target" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@"
+3 -2
View File
@@ -20,10 +20,11 @@ STAGE="$NIGHTLY_WORK/stage"
mkdir -p "$STAGE"
# The kit's tar layout: `gridcraft` is the launcher people run and `gridcraft-bin` is the GUI it
# starts. An unpacked archive is isolated too, because the GUI refuses to start without a launch
# profile and the launcher is the only thing that supplies one.
# profile and the launcher is the only thing that supplies one. The launcher is craft-common-actions'
# canonical template rendered for this app (scripts/nightly_app.py launcher), not a local script.
cp "$NIGHTLY_GUI" "$STAGE/gridcraft-bin"
chmod 755 "$STAGE/gridcraft-bin"
cp "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/gridcraft"
cp "$ROOT/packaging/linux/nightly-tar-launch.sh" "$STAGE/gridcraft"
chmod 755 "$STAGE/gridcraft"
# The nightly channel's own icon (deeper field); the archive member name stays as the helper requires.
cp "$ROOT/assets/app-icon/gridcraft-nightly.png" "$STAGE/gridcraft-nightly.png"
+324 -2
View File
@@ -6,11 +6,21 @@ import hashlib
import json
from pathlib import Path
import re
import textwrap
import unittest
ROOT = Path(__file__).resolve().parents[1]
INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json"
DISPATCHER = ROOT / ".github/workflows/nightly-dispatch.yml"
SIGNER_BRANCH = "nightly-signer"
def inline_scripts(path):
"""Read literal run blocks, not a substitute for YAML/actionlint validation."""
return [textwrap.dedent(block) for block in re.findall(
r"^ run: \|\n((?: .*\n|\n)+)", path.read_text(), re.MULTILINE)]
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
# Each platform's one trust field in policy v3, and the public stable identity it must name.
NIGHTLY_TRUST = {
@@ -275,7 +285,7 @@ class NightlyEnabledCallers(unittest.TestCase):
"github.ref_type == 'branch' && (github.event_name == 'schedule' || "
"github.event_name == 'workflow_dispatch')",
"nightly-sign.yml": "github.repository == 'storytold/gridcraft' && github.event_name == 'workflow_dispatch' && "
"github.ref == 'refs/heads/release' && github.ref_type == 'branch'",
"github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'",
}
def test_enabled_jobs_keep_exact_context_guards(self):
@@ -347,7 +357,7 @@ class NightlyInstalledPolicy(unittest.TestCase):
self.assertEqual(set(self.policy), expected)
self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3")
self.assertEqual(self.policy["repository"], "storytold/gridcraft")
self.assertEqual(self.policy["release_branch"], "release")
self.assertEqual(self.policy["release_branch"], SIGNER_BRANCH, "the signer runs on its dedicated branch")
self.assertIs(type(self.policy["repository_id"]), int)
self.assertGreater(self.policy["repository_id"], 0)
# producer_workflow_id is null until nightly.yml is registered on main; once set, must be a positive int.
@@ -459,6 +469,318 @@ class NightlyInstalledPolicy(unittest.TestCase):
self.assertIn(item["type"], sonar["issue_types"])
self.assertRegex(item["hash"], r"^[0-9a-f]{32}$")
def test_sonar_policy_keeps_the_shared_candidate_contract(self):
"""The Sonar shape craft-common-actions' candidate contract() admits, refused here first.
An empty issue scope, an accepted condition outside the reviewed issue types, a metric in both
lists, a missing live gate condition or a widened security bound is refused at admission, so
this suite must catch it before a nightly run can. `debt` stays empty, so any unresolved
vulnerability on main is still refused; accepting the new-code rating only records the
reviewed A threshold instead of demanding a clean rating the live gate does not.
"""
sonar = self.policy["candidate_policy"]["sonar"]
accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL",
"security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"}
gate = {"new_reliability_rating", "new_security_rating", "new_maintainability_rating",
"new_coverage", "new_duplicated_lines_density", "new_security_hotspots_reviewed"}
self.assertTrue(sonar["issue_types"], "an empty issue scope is refused as unreviewed")
self.assertEqual(len(sonar["issue_types"]), len(set(sonar["issue_types"])))
metrics = {}
for field in ("accepted_conditions", "required_conditions"):
for condition in sonar[field]:
with self.subTest(field=field, metric=condition.get("metric")):
expected = {"metric", "comparator", "error_threshold"}
if field == "accepted_conditions":
expected.add("maximum")
self.assertEqual(set(condition), expected)
self.assertNotIn(condition["metric"], metrics, "one condition per gate metric")
metrics[condition["metric"]] = condition
self.assertIn(condition["comparator"], ("GT", "LT"))
self.assertRegex(condition["error_threshold"], r"^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$")
if field != "accepted_conditions":
continue
self.assertIn(condition["metric"], accepted, "an accepted metric outside the reviewed map")
self.assertIn(accepted[condition["metric"]], sonar["issue_types"],
"an accepted failure must lie inside the reviewed issue scope")
self.assertEqual(condition["comparator"], "GT")
self.assertRegex(condition["maximum"], r"^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$")
maximum = float(condition["maximum"])
if condition["metric"] in ("security_rating", "new_security_rating"):
self.assertEqual(int(maximum), maximum, "the A..E bound is a whole rating")
self.assertTrue(1 <= maximum <= 5, "the security bound stays A..E")
self.assertEqual(condition["error_threshold"], "1", "the reviewed A threshold stays")
else:
self.assertLessEqual(maximum, len(sonar["debt"]), "accepted failures exceed the reviewed debt")
self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"]),
"accepted conditions and reviewed issue types must cover the same scope")
self.assertEqual(set(metrics), gate, "every live gate condition stays gated exactly once")
SHARED = "storytold/craft-common-actions/.github/workflows/"
# App workflows reviewed to call the shared stable release.yml. That callee must carry the
# stable-only environment guard (dry runs and non-release refs bind no environment); the
# nightly-signer settings scan checks the resolved callee before creating or advancing the branch.
REVIEWED_STABLE_RELEASE_CALLERS = {"release.yml"}
def app_workflows():
return {path.name: path.read_text() for path in sorted((ROOT / ".github/workflows").glob("*.y*ml"))}
WORKFLOW_KEY = re.compile(r'''("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|[^\s'"#{}\[\],:&*!|>%@`?-][^:#,{}]*?|-[^\s:#][^:#,{}]*?)\s*:(?:\s+(.*))?$''')
def _workflow_key(text):
if text.startswith('"'):
return None if "\\" in text else text[1:-1]
if text.startswith("'"):
return text[1:-1].replace("''", "'")
return text
def _workflow_value(text):
"""A one-line scalar value without its comment and quotes; None when escaped or unterminated."""
text = text.strip()
if text.startswith('"'):
quoted = re.match(r'"((?:[^"\\]|\\.)*)"\s*(?:#.*)?$', text)
return None if quoted is None or "\\" in quoted.group(1) else quoted.group(1)
if text.startswith("'"):
quoted = re.match(r"'((?:[^']|'')*)'\s*(?:#.*)?$", text)
return None if quoted is None else quoted.group(1).replace("''", "'")
return re.split(r"\s+#", text, maxsplit=1)[0].strip()
def _strip_comment(text):
"""(text without its comment, unterminated) using a quote-aware scan.
As in YAML, a quote opens a quoted scalar only where a scalar starts (line start or after
`:`, `-`, `,`, `{` or `[`), and a `#` starts a comment only outside quotes, at the start or
after whitespace.
"""
quote, index = None, 0
while index < len(text):
char = text[index]
if quote == '"':
if char == "\\":
index += 2
continue
if char == '"':
quote = None
elif quote == "'":
if char == "'":
if text[index + 1:index + 2] == "'":
index += 2
continue
quote = None
elif char in "\"'" and text[:index].rstrip()[-1:] in ("", ":", "-", ",", "{", "["):
quote = char
elif char == "#" and (index == 0 or text[index - 1] in " \t"):
return text[:index].rstrip(), False
index += 1
return text.rstrip(), quote is not None
FLOW_QUOTED = re.compile(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'")
FLOW_FORBIDDEN_KEYS = {"environment", "uses"}
def workflow_entries(source):
"""Every mapping entry in a workflow, plus the YAML forms this reader refuses.
A narrow reader, not a YAML parser (none ships with the runner's Python). Each entry is
(line, key, value, multiline): plain, single- and double-quoted keys and one-line values in
block and simple one-line flow mappings. Block scalar bodies are skipped, and an entry whose
value is a block scalar or continues on the next lines is marked multiline. It refuses whatever
could hide a key from it: escaped double-quoted keys, explicit `?` keys, merge keys, anchors,
aliases, tags, tab indentation and nested or multi-line flow.
"""
lines = source.splitlines()
entries, refused, block = [], [], None
def continues(index, indent):
for follow in lines[index + 1:]:
stripped = follow.strip()
if not stripped or stripped.startswith("#"):
continue
deeper = len(follow) - len(follow.lstrip(" ")) > indent
return deeper and not stripped.startswith("- ") and WORKFLOW_KEY.match(stripped) is None
return False
for index, raw in enumerate(lines):
number = index + 1
stripped = raw.strip()
indent = len(raw) - len(raw.lstrip(" "))
if block is not None:
if not stripped or indent > block:
continue
block = None
if not stripped or stripped.startswith("#"):
continue
if "\t" in raw[:indent + 1]:
refused.append(f"line {number}: tab indentation"); continue
body, unterminated = _strip_comment(stripped)
if unterminated:
refused.append(f"line {number}: unterminated or multi-line quoted scalar"); continue
if not body:
continue
while body.startswith("- "):
body = body[2:].lstrip()
if body == "?" or body.startswith("? "):
refused.append(f"line {number}: explicit key"); continue
match = WORKFLOW_KEY.match(body)
value = body
if match is not None:
key, value = _workflow_key(match.group(1)), match.group(2) or ""
if key is None:
refused.append(f"line {number}: escaped double-quoted key"); continue
if key == "<<":
refused.append(f"line {number}: merge key"); continue
plain = re.sub(r"\$\{\{.*?\}\}", "", value).strip()
bare = re.sub(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'", "''", plain)
if re.match(r"[&*!]", plain):
refused.append(f"line {number}: anchor, alias or tag")
is_block = re.fullmatch(r"[|>][0-9+-]*", plain) is not None
if match is not None:
entries.append((number, key, _workflow_value(value),
is_block or ((value == "" or not is_block) and continues(index, indent))))
if "{" in bare and bare != "{}":
masked = re.fullmatch(r"\{([^{}\[\]]*)\}", FLOW_QUOTED.sub("''", value.strip()))
flow = re.fullmatch(r"\{([^{}\[\]]*)\}", value.strip())
if any(set(scalar[1:-1]) & set("#{}[],") for scalar in FLOW_QUOTED.findall(value)):
refused.append(f"line {number}: flow mapping quoted scalar with # or flow punctuation")
elif masked is None or flow is None:
refused.append(f"line {number}: nested or multi-line flow mapping")
else:
# The masked text only proves the shape: a quoted key ("uses", 'environment') keeps
# its identity, so the entries are read from the original mapping text, never ''.
for item in flow.group(1).split(","):
entry = WORKFLOW_KEY.match(item.strip())
key = _workflow_key(entry.group(1)) if entry else None
if key is None:
refused.append(f"line {number}: unreadable flow mapping entry")
elif key in FLOW_FORBIDDEN_KEYS:
refused.append(f"line {number}: {key} in a flow mapping (must be block style)")
else:
entries.append((number, key, _workflow_value(entry.group(2) or ""), False))
if match is not None and is_block:
block = indent
return entries, refused
def workflow_keys(source):
"""(line, key) for every mapping entry, plus the refused YAML forms."""
entries, refused = workflow_entries(source)
return [(number, key) for number, key, _, _ in entries], refused
SHARED_CALLEE = re.compile(r"storytold/craft-common-actions/\.github/workflows/([\w.-]+\.ya?ml)@(\S+)", re.IGNORECASE)
INSPECTED_KEYS = {"environment", "uses"}
def trust_closure_problems(workflows):
"""The nightly-signer trust-closure scan over app workflow sources; empty when the tree is safe.
Every key it inspects comes from workflow_entries(), never a regex over the raw text.
"""
problems, stable_callers, signer_calls = [], set(), 0
for name, source in workflows.items():
entries, refused = workflow_entries(source)
problems.extend(name + " uses YAML the scan cannot read (" + reason + ")" for reason in refused)
for number, key, value, multiline in entries:
if key not in INSPECTED_KEYS:
continue
if key == "environment":
problems.append(f"{name} binds an environment directly (line {number})")
continue
if value is None or multiline:
problems.append(f"{name} has a uses value the scan cannot read (line {number})")
continue
callee = SHARED_CALLEE.fullmatch(value)
if callee is None:
if re.search(r"craft-common-actions", value, re.IGNORECASE) and re.search(r"workflows/(nightly-)?release\.ya?ml", value, re.IGNORECASE):
problems.append(f"{name} has an unrecognised shared release caller (line {number})")
continue
workflow, ref = callee.group(1), callee.group(2)
if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"):
if name == "nightly-sign.yml":
signer_calls += 1
if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref):
problems.append(name + " calls nightly-release.yml@" + ref)
if workflow.lower() in ("release.yml", "release.yaml"):
stable_callers.add(name)
if ref != "main" and not re.fullmatch(r"[0-9a-f]{40}", ref):
problems.append(name + " calls release.yml@" + ref + "; use @main or a reviewed full SHA")
if stable_callers != REVIEWED_STABLE_RELEASE_CALLERS:
problems.append("shared release.yml callers are " + ", ".join(sorted(stable_callers)))
if signer_calls != 1:
problems.append("nightly-sign.yml must call nightly-release.yml exactly once")
return problems
class NightlySignerBranchTrustClosure(unittest.TestCase):
"""On refs/heads/nightly-signer, only the pinned signer caller may reach an environment."""
def test_trust_closure_scan_passes_on_this_tree(self):
self.assertEqual(trust_closure_problems(app_workflows()), [])
def test_trust_closure_scan_refuses_each_route_into_an_environment(self):
tree = app_workflows()
bad = {
"a workflow binds an environment": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment: release\n"},
"a double-quoted environment key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environment": release\n'},
"a single-quoted environment key": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n 'environment' : release\n"},
"an environment mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment:\n name: release\n"},
"an environment in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {runs-on: ubuntu-latest, environment: release}\n"},
"an escaped key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environ\\u006dent": release\n'},
"a merge key": {**tree, "extra.yml": "base: &b\n runs-on: ubuntu-latest\njobs:\n x:\n <<: *b\n"},
"an explicit key": {**tree, "extra.yml": "jobs:\n x:\n ? environment\n : release\n"},
"a nested flow mapping": {**tree, "extra.yml": "jobs:\n x: {steps: [{run: a}]}\n"},
"a double-quoted uses key copying the signer": {**tree, "extra.yml": 'jobs:\n x:\n "uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
"a single-quoted uses key": {**tree, "extra.yml": "jobs:\n x:\n 'uses': " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
"a quoted uses value": {**tree, "extra.yml": 'jobs:\n x:\n uses: "' + SHARED + "nightly-release.yml@" + "a" * 40 + '"\n'},
"uses in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"},
"a differently cased owner": {**tree, "extra.yml": "jobs:\n x:\n uses: Storytold/Craft-Common-Actions/.github/workflows/nightly-release.yml@" + "a" * 40 + "\n"},
"a folded uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: >-\n " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
"a continued uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "\n nightly-release.yml@" + "a" * 40 + "\n"},
"a quoted second signer call": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"] + " again:\n \"uses\": " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
"a hash inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a} # b", runs-on: ubuntu-latest, environment: release, steps: []}\n'},
"a single-quoted hash in a flow scalar": {**tree, "extra.yml": "jobs:\n x: {name: 'a # b', runs-on: ubuntu-latest}\n"},
"a comma inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a, environment: release", runs-on: ubuntu-latest}\n'},
"a bracket inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "[a]", runs-on: ubuntu-latest}\n'},
"an unterminated quote": {**tree, "extra.yml": 'jobs:\n x:\n name: "a\n b"\n runs-on: ubuntu-latest\n'},
"environment in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {environment: release}\n"},
"a double-quoted environment key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n with: {"environment": release}\n'},
"a single-quoted environment key in a flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {'environment': release}\n"},
"a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"},
"uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"},
"another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
"a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])},
"a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"},
"a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")},
}
for label, workflows in bad.items():
with self.subTest(case=label):
self.assertTrue(trust_closure_problems(workflows))
def test_quoted_keys_in_a_flow_mapping_are_read_not_masked(self):
entries, refused = workflow_entries('jobs:\n x: {runs-on: ubuntu-latest, "name": build}\n')
self.assertEqual(refused, [])
self.assertIn((2, "name", "build", False), entries, "a quoted key keeps its identity")
self.assertIn((2, "runs-on", "ubuntu-latest", False), entries)
_, refused = workflow_entries("jobs:\n x: {runs-on: ubuntu-latest, 'environment': release}\n")
self.assertEqual(refused, ["line 2: environment in a flow mapping (must be block style)"])
def test_signer_dispatch_guard_and_policy_name_the_same_branch(self):
sign = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
(_, guard), = job_conditions(sign.split("\njobs:\n", 1)[1])
self.assertIn("github.ref == 'refs/heads/" + SIGNER_BRANCH + "'", guard)
self.assertNotIn("refs/heads/release", sign, "the signer no longer runs on the stable branch")
self.assertEqual(re.findall(r"(?m)^ app-name: (\S+)$", sign), ["gridcraft"], "the shared signer needs the reviewed registry app")
# This app ships no completion dispatcher yet: that workflow forwards scheduled producers
# only, and no schedule is approved. Adding it is part of a reviewed cadence change.
self.assertFalse(DISPATCHER.exists(), "a completion dispatcher needs its own reviewed activation")
self.assertEqual(json.loads(INSTALLED_POLICY.read_text())["release_branch"], SIGNER_BRANCH)
self.assertFalse((ROOT / "docs/nightly-signing-policy.example.json").exists(),
"a policy example must then name the signer branch")
if __name__ == "__main__":
unittest.main(verbosity=2)