Compare commits

..
Author SHA1 Message Date
dependabot[bot] 9eb7b3bdb8 ci(deps): bump the actions group across 1 directory with 3 updates
Bumps the actions group with 3 updates in the / directory: [step-security/harden-runner](https://github.com/step-security/harden-runner), [storytold/craft-common-actions/.github/workflows/nightly-release.yml](https://github.com/storytold/craft-common-actions) and [storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml](https://github.com/storytold/craft-common-actions).


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

Updates `storytold/craft-common-actions/.github/workflows/nightly-release.yml` from 8389cad8b849ea6bdb5e15fbce16772c3457565a to 4ec2a14646b538253fd5ebe109bf463a3d31b061
- [Commits](https://github.com/storytold/craft-common-actions/compare/8389cad8b849ea6bdb5e15fbce16772c3457565a...4ec2a14646b538253fd5ebe109bf463a3d31b061)

Updates `storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml` from 8389cad8b849ea6bdb5e15fbce16772c3457565a to 4ec2a14646b538253fd5ebe109bf463a3d31b061
- [Commits](https://github.com/storytold/craft-common-actions/compare/8389cad8b849ea6bdb5e15fbce16772c3457565a...4ec2a14646b538253fd5ebe109bf463a3d31b061)

---
updated-dependencies:
- dependency-name: step-security/harden-runner
  dependency-version: 2.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
- dependency-name: storytold/craft-common-actions/.github/workflows/nightly-release.yml
  dependency-version: 4ec2a14646b538253fd5ebe109bf463a3d31b061
  dependency-type: direct:production
  dependency-group: actions
- dependency-name: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml
  dependency-version: 4ec2a14646b538253fd5ebe109bf463a3d31b061
  dependency-type: direct:production
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-26 11:06:32 +00:00
FredApps ccbf56c05c Merge pull request #4143 from alehel/split/cell-padding
Style model: cell padding kept in Alignment (groundwork for ODS)
2026-11-26 10:23:39 +01:00
FredApps a5709e22e0 Merge remote-tracking branch 'origin/main' into pr4143
# Conflicts:
#	docs/file-format-parity.md
2026-11-26 16:10:28 +07:00
FredApps 8fc8aa7857 Merge pull request #795 from vangel76/feat/quick-analysis-791
UI: Quick Analysis (Ctrl+Q) (#791)
2026-11-26 10:09:19 +01:00
FredApps aab64fdebc Merge pull request #4144 from alehel/split/font-outline
Fonts: outlined letters kept through XLSX open and save (groundwork for ODS)
2026-11-26 10:08:26 +01:00
FredApps 5fb3b44f69 Merge pull request #4166 from vangel76/fix/4162-nested-equation-colours
Nested equation colours stay per part after reopening a file
2026-11-26 10:07:56 +01:00
FredApps 9c7fc39563 Merge pull request #4267 from gmrmad1/fix/status-bar-stats-fit-4187
fix(ui): leave out status statistics that would overlap the mode text (#4187)
2026-11-26 10:07:24 +01:00
FredApps 6144228f45 Merge pull request #4699 from alehel/fix/cut-paste-keeps-cut-cells
paste: a cut moves only as a plain Paste onto one cell or its own size
2026-11-26 10:05:28 +01:00
skylar taylor-barrick de4e878aa8 Re-pin nightly callers to craft-common-actions 8389cad8 (signer Windows fix) (#4777)
Round-5 re-pin under Skylar's Nightly 891 signer-only roll (route A keeps the one-shared-pin invariant). Moves every nightly pin from craft-common-actions be00e5cc to 8389cad8, which carries the Windows ctime rule that stops the signer refusing a just-written JSON (#375). Only the pins and their docs move; no build or packaging code changes.
2026-11-26 00:41:08 -06: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
vangel76 731c90dcc1 Quick Analysis: use a focus ring colour that meets 3:1 on the popup in both themes
The sheet's green focus colour is only 2.5:1 on the dark popup (1.9:1 on a hovered tile).
Tiles now ring with the theme accent (3.9:1 or more on the popup, hover and pressed fills in
light and dark); the launcher sits on the sheet and keeps the sheet's focus colour. The
contrast test covers the popup pairs.
2026-11-25 20:52:50 +01:00
vangel76 8bbc760f5d Quick Analysis: name the launcher and tiles as buttons and show keyboard focus
The launcher and every tile now expose a button role with their translated label
(the launcher also its open state). The popup hands the keyboard to its first tile,
arrows move the focus between tiles, Enter or Space runs one, and the focused control
gets a visible ring. Ctrl+Q closes the popup while a tile has the keyboard.
2026-11-25 20:38:25 +01:00
vangel76 cfc0922126 Skip Office Math run styles when reading the legacy frame ink
The earlier writer saved a style-only m:rPr beside the a:rPr that carries the fill on styled runs. The legacy ink check counted it as a run without a fill and read Automatic.
2026-11-25 20:34:24 +01:00
aiongg 966c634b1c Repin craft-libs to storytold next 8fa4db64a9 and egui to b9770908e 2026-11-25 19:15:01 +00:00
vangel76 e9449b55ab Read the frame ink of equations saved before the paragraph carried it
An older writer put the frame's ink on every Office Math run and wrote no fill on the paragraph end. With a colour command in the source, such an equation now reads that shared run colour instead of Automatic.
2026-11-25 19:09:50 +01:00
vangel76 7f2ae3cff8 Merge remote-tracking branch 'sm/main' into qa795
# Conflicts:
#	docs/ui-parity.md
2026-11-25 18:52:45 +01:00
vangel76 5682daedc1 Remove Quick Analysis translations from the GridCraft locale files
Keep English keys only; the translations move to a craft-i18n PR (AGENTS.md rule 16).
2026-11-25 18:52:35 +01: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
alehel dd86b43150 paste: a cut is refused over any filter-hidden row it would land on, anchored or tall
The hidden-row check read the rows a tiled single-row paste skips, which is
empty for a paste at an explicit cell or a taller block, so those wrote into
hidden rows after the source was cleared. It now checks the cut's own
destination rows.
2026-11-24 04:38:18 +01:00
alehel 7486d1021b paste: a cut moves only as a plain Paste onto one cell or its own size
One rule in one place replaces the Paste Link and filtered-row refusals.
A cut in this workbook empties its source before the destination is
written, so every paste that would not write each cut cell once, in one
place, loses or misplaces cells: a Paste Special option (link, skip
blanks, transpose, an operation, or pasting only part such as values),
tiling over a larger or differently shaped area, or rows a filter hides.
These are refused before anything changes, and the cut stays pending,
as in Excel. A single cell or an area of the cut's size takes it.

Tests: one per refused mode, each asserting nothing changed, plus a
refused paste followed by plain pastes that still move the cut.
2026-11-23 23:26:25 +01:00
alehel 35ca6435a8 paste: a cut is refused as Paste Link or into filtered-out rows before its source is cleared
Paste Link would write links to the cells the cut empties, and a
destination over rows the filter hides would skip cells the cut has
taken; both lost the cut cells.
2026-11-23 21:46:11 +01:00
alehel 8d6e207f04 xlsx: font outline goes through the shared craft-xlsx Font
The outline flag is read with craft_xlsx::Font::read and written with
craft_xlsx::Font::to_el, so its three states (absent, stated off, on)
follow the shared SpreadsheetML handling instead of a second reader and
writer here. The app keeps the mapping to Font::outline and
DxfStated::outline.
2026-11-23 13:59:05 +01:00
alehel 0d23a0b12c Merge storytold/gridcraft main into split/cell-padding
main added the issue #778 round-trip tests where this branch added its
cell-padding test; all three are kept.
2026-11-23 12:06:37 +01:00
alehel 7d0f153f9d json goldens: kept.json states "outline" too
kept.json is built from book.json, so it is re-blessed after it.
2026-11-23 11:58:53 +01:00
alehel d5c8c079cb Merge storytold/gridcraft main into split/font-outline
main moved the dxf writer into dxf_xml; the outline flags now go there.
main's new native JSON goldens are re-blessed: every font now states
"outline" (false when off), as this branch intends. Older readers ignore
the unknown key.
2026-11-23 11:58:27 +01:00
FredApps 30013b349c Reconcile status bar statistics with current main 2026-11-23 11:33:35 +01:00
vangel76 c2a0cae3fe Reconcile Quick Analysis entries in the UI parity guide 2026-11-21 02:03:13 +01:00
vangel76 7f57431b57 Merge upstream/main into feat/quick-analysis-791 2026-11-21 02:01:53 +01:00
vangel76 1da7c3ae92 Merge upstream/main into feat/quick-analysis-791 2026-11-18 18:38:43 +01:00
vangel76 cff2302172 Merge upstream/main into fix/4162-nested-equation-colours 2026-11-18 18:38:16 +01:00
Madhav Agarwal d977856457 ci: run rustfmt over the status bar statistics test 2026-11-17 12:42:22 +05:30
vangel76 c395f2d60b Merge upstream/main into feat/quick-analysis-791 2026-11-16 21:53:15 +01:00
Madhav Agarwal 2537e5ff0a review: count egui's item spacing in the status statistics fitting budget (CodeRabbit)
The status bar reserves 10 points after each statistic with add_space, and egui
adds item_spacing.x after every label as well (6 points in the theme). Passing
only 10 to fitting_statistics could keep a sixth statistic that then painted
over the mode text. Pass the sum, and sweep the widths where the sixth label
only just fits.
2026-11-16 20:04:57 +05:30
alehel 5f73d9787c Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	docs/file-format-parity.md
2026-11-15 22:22:18 +01:00
alehel 7c3b4e288a Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	docs/file-format-parity.md
2026-11-15 22:22:18 +01:00
vangel76andClaude Sonnet 5.5 fe07dbc654 Treat an equation as GridCraft's own only while its marker matches
When another application rewrote the Office Math, the source is rebuilt
from it and the saved paragraph-end ink no longer applies: the first
run's colour is the frame ink.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 13:54:06 +01:00
vangel76andClaude Opus 5.5 8b9f9527f1 Read GridCraft's saved equation ink only from its own Office Math
The paragraph-end ink and the colour-command rule apply to GridCraft's own
Office Math only: another writer's paragraph-end formatting is not the
frame's ink, and the plain-text box of an equation outside the Office Math
subset carries the ink on its runs. Adds the external-file, text-only and
combined nested-colour save/reopen tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:29:06 +01:00
Madhav Agarwal c46a90c8c8 ui: leave out status statistics that would overlap the mode text (#4187) 2026-11-15 15:07:26 +05:30
vangel76andClaude Sonnet 5.5 7cd04cd023 Keep the frame colour of an equation apart from its coloured runs in xlsx
An equation saved with colour commands has coloured runs; reading the file took
the first run's colour as the frame's ink, so the parts the source leaves
uncoloured turned that colour and the whole equation was painted in one colour.
The writer now saves the ink on the paragraph, and the reader of GridCraft's own
equations reads it from there.

Fixes #4162

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 13:01:06 +01:00
alehel 292a0e1e8e Merge storytold/main into split/font-outline
main moved the .xls BIFF reader to craft-xls (storytold/craft-libs), deleting
crates/xlsx/src/xls/styles.rs. The round-1 .xls fOutline read is dropped with
it, and the .xls style test and docs row go back to main's: craft-xls's Font has
no outline flag yet, so reading it belongs in craft-libs.
2026-11-14 02:20:20 +01:00
alehel 60ec576e0c Fonts: outline test comments and docs dates brought up to date
Review round 2 found no defects; this rewords the dxf fixture's doc comment
(one dxf also states strike), folds the .xls fixture's outline flag into its
description, and dates the docs row and timestamp line to the round-1 fixes.
2026-11-14 02:03:38 +01:00
alehel 04c30b4901 Merge storytold/gridcraft main into split/cell-padding
Alignment gained reading_order on main; padding sits after it. The .xls reader moved to craft-xls, so its mapping in crates/xlsx/src/xls.rs sets no padding instead of the removed xls/styles.rs. file-format-parity.md keeps both histories.
2026-11-14 01:54:03 +01:00
alehel 349fb760b1 Fonts: outline cleared through Format Cells, read from .xls, dxf gate tested
Review round 1 on outlined letters:
- Font::outline is now always serialized. The Format Cells dialog sends the
  active cell's whole style to the selection through home.formatCells, which
  merges JSON; with the field skipped when false, a plain active cell never
  cleared outline on the other selected cells, while bold and the rest were
  overwritten. Older JSON without the field still opens.
- The legacy .xls reader reads the Font record's fOutline flag (0x0010), so an
  outlined .xls font no longer opens solid and is lost on save as .xlsx.
- dxf_outline_font_survives_save gains a dxf whose only font part is
  <outline val="0"/>, the case the write gate's st.outline term exists for.
2026-11-14 01:51:24 +01:00
alehel 21306e150f Style model: test that padding alone writes no <alignment>
Review fix-up. Reverting `alignment_xml` to compare the whole Alignment
left every test passing: an empty `<alignment/>` with `applyAlignment`
reads back as the default, so comparing styles could not see it. The
round-trip test now reads `xl/styles.xml` and checks that only the fully
aligned style writes `<alignment>` and `applyAlignment`.
2026-11-14 01:21:42 +01:00
vangel76andClaude Sonnet 5.5 7ee5c5ef36 Quick Analysis: refuse sparklines on a protected sheet
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 20:48:07 +01:00
vangel76andClaude Sonnet 5.5 d70646adfc Merge upstream/main
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 20:46:37 +01:00
vangel76andClaude Sonnet 5.5 ca5796662f Merge upstream/main
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 21:54:21 +01:00
alehel ba605b4f69 Fonts: a differential format's outline turned off survives save
A dxf with <outline val="0"/> read as unset and was saved without it, unlike
bold, italic and strike, which keep their stated-off form. DxfStated gains
`outline` (serde default, so older JSON opens), read in read_dxf and written
by font_xml as <outline val="0"/>.
2026-11-11 10:32:38 +00:00
alehel fd664055df Fonts: outlined letters kept through XLSX open and save
An XLSX font's <outline/> was never read, so outlined (hollow) letters came
back solid after a save. The model's Font gains `outline` (serde default
false, left out of JSON when off, part of the hand-written Hash), read in
read_font and written by font_xml after <strike/> as Excel orders it, for
cell fonts and differential formats. home.formatCells sets it through the
style JSON. GridCraft does not draw outlined text yet.

Split out of the ODS branch, which also maps style:text-outline onto it.
2026-11-11 09:19:20 +00:00
alehel 09d52cc7cd Style model: cell padding kept in Alignment
`Alignment::padding: [Option<u16>; 4]` (left, right, top, bottom, in
hundredths of a point; `None` where a file states none) holds an
OpenDocument cell's padding, which LibreOffice lays rows out with. It is
part of style equality and hashing, so styles that differ only by padding
intern apart; serde default, skipped when all `None`, so older JSON reads.

Excel has no cell padding: the XLSX and XLS readers set none, and the
XLSX writer leaves it out (a style that differs from the default only by
padding writes no `<alignment>`). GridCraft does not draw padding yet.
2026-11-11 09:02:08 +00:00
vangel76andClaude Sonnet 5.5 6315dacc9e Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 22:01:44 +01:00
vangel76andClaude Opus 5.5 d098a7dfc3 UI: Excel for Mac Control+Q opens Quick Analysis; Command+Q stays Quit
ribbon::shortcut is only reached with the command modifier, so on a Mac
Control+Q did nothing and Command+Q toggled Quick Analysis next to the
native Quit item. The keymap now maps Mac Control+Q (without Command,
Option or Shift) to Shortcut::QuickAnalysis, which shares the ribbon
handler and its single-cell alert suppression, and the ribbon Q branch
ignores Command on a Mac.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 12:41:12 +01:00
vangel76 7984f0f2bd Merge upstream/main into feat/quick-analysis-791 2026-11-08 12:37:22 +01:00
vangel76andClaude Sonnet 5.5 302019d815 Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 18:39:42 +01:00
vangel76andClaude Sonnet 5.5 2240950eb6 Quick Analysis: Esc closes the popup only; bind it to the sheet's identity
Esc used to clear the pending copy and Format Painter before the popup saw it.
The popup also remembers the sheet by its identity rather than its position,
so moving sheets cannot hand it to another sheet.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 17:39:33 +01:00
vangel76andClaude Sonnet 5.5 a7a319c5c7 Quick Analysis: close the popup when the active sheet changes
The popup remembered only the range, so another sheet with the same selection
kept it open and the tiles ran against that sheet. It now remembers the sheet
too.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 17:26:11 +01:00
vangel76andClaude Sonnet 5.5 baff2e50cc Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 04:21:06 +01:00
vangel76andClaude Sonnet 5.5 335109beb5 Quick Analysis: assert the multi-area error text
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 02:16:37 +01:00
vangel76andClaude Sonnet 5.5 4b65b85b23 Quick Analysis: keep results outside the selection, refuse multi-area, plain Ctrl+Q only
- analysis.addTotal / addSparklines place results beyond the selection's own far edge, so a
  selection reaching past the data no longer gets its totals inside it.
- Both commands refuse a multi-area selection when no range is given.
- Ctrl+Shift+Q and Ctrl+Alt+Q no longer toggle the popup.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 02:13:51 +01:00
vangel76andClaude Sonnet 5.5 155d254977 Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 02:05:08 +01:00
vangel76andClaude Sonnet 5.5 8516e5fd0d Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 23:40:36 +01:00
vangel76andClaude Sonnet 5.5 d2a608c750 Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 19:54:19 +01:00
vangel76andCodex bcac6859e3 Merge upstream/main into feat/quick-analysis-791
Keep Quick Analysis and the current checkbox-printing parity note together.

Co-Authored-By: Codex <noreply@openai.com>
2026-10-31 11:22:47 +01:00
vangel76andCodex f3b88ae36b Merge upstream/main into feat/quick-analysis-791
Combine the Quick Analysis parity note with the current upstream UI updates.

Co-Authored-By: Codex <noreply@openai.com>
2026-10-30 22:46:07 +01:00
vangel76andClaude Sonnet 5.5 946b98c375 Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-29 23:20:13 +01:00
vangel76andClaude Sonnet 5.5 4d0074e5cf Merge upstream/main into feat/quick-analysis-791
Main moved the app commands, grid drawing and shortcuts into submodules; the Quick Analysis hooks are re-applied there.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 20:13:23 +01:00
vangel76andClaude Sonnet 5.5 a98f290ec0 Quick Analysis: use Id::unique for the area ids (Id::new is deprecated upstream)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-26 00:06:42 +01:00
vangel76andClaude Sonnet 5.5 870e2658ae Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-26 00:03:24 +01:00
vangel76andClaude Sonnet 5.5 a2caeedcd9 Quick Analysis: use theme category colours after the theme change on main
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 10:26:14 +01:00
vangel76andClaude Sonnet 5.5 2a10509d65 Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 10:25:05 +01:00
vangel76andClaude Opus 5.5 2a59d7f15d Quick Analysis: keep clear of the Auto Fill Options button, tests in the shared binary
After a fill-handle drag both buttons sat at the selection's corner and
the Quick Analysis one, painted on top, took the click. The Quick
Analysis button now waits until the fill is no longer current; Ctrl+Q
still opens the popup. Drops "Bar" from the Japanese EXTRA list, now a
DIALOGS key, and moves the button tests into tests/it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 20:10:10 +02:00
vangel76andClaude Opus 5.5 818c97a632 Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 19:59:19 +02:00
vangel76 2681d7b6df Merge upstream/main into feat/quick-analysis-791 2026-10-22 19:45:19 +02:00
vangel76andClaude Sonnet 5.5 480b8a88b5 Quick Analysis: report calling command in block errors, clip tile labels
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 01:35:21 +02:00
vangel76 b82c4fbd30 PR795: merge main and retain Quick Analysis and context menu translations 2026-10-20 00:55:55 +02:00
vangel76andClaude Sonnet 5.5 cde1dbb2e4 Merge main into #795
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-13 19:10:18 +02:00
vangel76andClaude Sonnet 5.5 7d3516ab33 Calc: SUBTOTAL(10x) recalculates when Row Height, AutoFit Row Height or Ungroup reveal rows
home.rowHeight, home.autofitRowHeight and data.ungroup change row hidden
state without marking the edit structural, so SUBTOTAL(101-111) kept a stale
value. Found by the command-sequence fuzz (seed 3).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-12 21:44:04 +02:00
vangel76andClaude Sonnet 5.5 a7e1a4a99b Quick Analysis: button tests, several-areas refusal, more formatting tiles (#791)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-12 21:05:29 +02:00
vangel76andClaude Sonnet 5.5 4972675b1b UI: Quick Analysis (Ctrl+Q) (#791)
A corner button on multi-cell selections and Ctrl+Q open a popup of one-click
analyses (formatting, charts, totals, tables, sparklines). Totals and sparklines
are new engine commands, analysis.addTotal and analysis.addSparklines, each one
undo step, never overwriting data unless asked.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-12 21:03:01 +02:00
123 changed files with 5449 additions and 581 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": "8389cad8b849ea6bdb5e15fbce16772c3457565a",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@8389cad8b849ea6bdb5e15fbce16772c3457565a",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"signer_tooling_revision": "8389cad8b849ea6bdb5e15fbce16772c3457565a",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
+5 -5
View File
@@ -8,13 +8,13 @@ workflows:
'.github/workflows/house-rules.yml': []
'.github/workflows/lockfile.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
- 'step-security/harden-runner@v2.23.0'
'.github/workflows/nightly-sign.yml': []
'.github/workflows/nightly.yml': []
'.github/workflows/nix.yml': []
'.github/workflows/packaging-lint.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
- 'step-security/harden-runner@v2.23.0'
'.github/workflows/release.yml': []
'.github/workflows/sonarcloud.yml': []
'.github/workflows/windows-arm64.yml': []
@@ -24,8 +24,8 @@ dependencies:
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
owner_id: 44036562
repo_id: 197814629
'step-security/harden-runner@v2.22.4':
ref: 'v2.22.4'
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
'step-security/harden-runner@v2.23.0':
ref: 'v2.23.0'
commit: 'sha1-aebdcf6156ab6691adf63218240e476564a1ed4c'
owner_id: 88700172
repo_id: 422287306
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
uses: step-security/harden-runner@v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
+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@4ec2a14646b538253fd5ebe109bf463a3d31b061
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
tooling-revision: 8389cad8b849ea6bdb5e15fbce16772c3457565a
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.
+3 -4
View File
@@ -22,13 +22,12 @@ 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@4ec2a14646b538253fd5ebe109bf463a3d31b061
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
tooling-revision: 8389cad8b849ea6bdb5e15fbce16772c3457565a
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 8389cad8 (#375, the signer Windows fix).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
+2 -2
View File
@@ -30,7 +30,7 @@ jobs:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
uses: step-security/harden-runner@v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
@@ -47,7 +47,7 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
uses: step-security/harden-runner@v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
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" }
+1
View File
@@ -209,6 +209,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-13 | Spills: an array that grows into cells another array's spill already holds is `#SPILL!`, in automatic calculation and after Calculate Now, as in Excel; a workbook reopened from XLSX keeps the spill layout it was saved with (#964, found by the command-sequence fuzz) |
| 2026-10-13 | Grid: resizing several selected columns or rows previews on the dragged one and applies the size to all on release; Esc cancels (#1082) |
| 2026-10-12 | Next/previous sheet navigation stops at the first/last visible worksheet instead of activating a hidden boundary sheet; the current selection is retained |
| 2026-10-12 | Quick Analysis (Ctrl+Q): a corner button and popup on multi-cell selections run conditional formats, charts, totals (`analysis.addTotal`), tables, PivotTables and sparklines (`analysis.addSparklines`) in one click (#791) |
| 2026-10-12 | GETPIVOTDATA reads PivotTable values by field and items (#284) |
| 2026-10-12 | PDF writer: objects are written straight to the output, identical pictures are stored once, style operators are emitted only when they change, `q` nesting is limited to 28 and polyline joins no longer leak into later strokes (#816) |
| 2026-10-12 | Insert › Text › WordArt (`insert.wordArt`, `wordArt.set`): floating decorative text with 10 original styles, outline and shadow, in-place editing, XLSX and print (#784) |
+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"] }
+5 -4
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) {
@@ -543,6 +543,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()) {
+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
+2
View File
@@ -18,6 +18,7 @@ pub mod macros;
pub mod pivot;
pub mod print;
pub mod python;
pub mod quick_analysis;
pub mod review;
pub mod sheet;
pub mod slicer;
@@ -187,6 +188,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(forecast::specs());
v.extend(analysis::specs());
v.extend(print::specs());
v.extend(quick_analysis::specs());
v
})
}
+28 -1
View File
@@ -76,7 +76,34 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
return Err(EngineError::Other("Too many cells to paste as links at once.".into()));
}
let same_doc = s.doc()?.uid == clip.doc_uid;
let cut_move = clip.cut && same_doc && what == What::All;
// A cut in this workbook moves its cells: the source is emptied before the destination is
// written. As in Excel, it moves only as a plain Paste onto one cell or an area of its own size
// and shape. Every other way (a Paste Special option, tiling over a larger or differently shaped
// area, a row the filter hides) would write the cut cells somewhere other than one place, or not
// at all, after their source was gone, so it is refused here, before anything changes, and the
// cut stays pending.
let cut_move = clip.cut && same_doc;
if cut_move {
let plain = what == What::All && !link && !skip_blanks && !transpose && op == "none";
if !plain {
return Err(EngineError::Other("Cut cells can only be pasted with Paste. To use Paste Special, copy them instead.".into()));
}
let anchored = cell_param_on(s, p, "at", dest_sheet)?.is_some() || sel.is_single();
if !anchored && (sel.height() != h || sel.width() != w) {
return Err(EngineError::Other(
"The cut cells and the paste area aren't the same size and shape: select one cell, or an area the size of the cut cells.".into(),
));
}
// The rows the cut itself would land on, whatever the paste would skip: an anchored or
// taller block is pasted straight down, so `skip_rows` (which only a tiled single row uses)
// can't tell whether it would write into a hidden row.
if let Some(end) = at.offset(i64::from(h) - 1, i64::from(w) - 1) {
let dest = RangeRef::new(at, end);
if s.doc()?.wb.sheet(dest_sheet).is_some_and(|sh| !super::filtered_rows(sh, dest).is_empty()) {
return Err(EngineError::Other("The cut area can't be pasted into rows the filter hides.".into()));
}
}
}
let src_wb = clip.wb.clone();
let Some(src_sheet) = src_wb.sheet(clip.sheet) else { return Err(EngineError::Other("The copied sheet no longer exists.".into())) };
// The source sheet's name now: a cut whose sheet was renamed after it moves its cells,
+27
View File
@@ -870,6 +870,33 @@ mod tests {
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["num_fmt"], "0.00");
}
/// Outlined letters have no Font-group command; Format Cells' style JSON sets and clears them.
#[test]
fn format_cells_sets_outlined_letters() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap();
s.execute("home.formatCells", json!({"range": "A1", "style": {"font": {"outline": true}}})).unwrap();
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["font"]["outline"], true);
s.execute("home.formatCells", json!({"range": "A1", "style": {"font": {"outline": false}}})).unwrap();
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["font"]["outline"], false);
}
/// The Format Cells dialog sends the active cell's whole style to every selected cell, so a
/// non-outlined active cell must clear outline on the others, as it does bold.
#[test]
fn format_cells_whole_style_clears_outline_on_the_selection() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "plain"})).unwrap();
s.execute("cell.set", json!({"cell": "B1", "input": "hollow"})).unwrap();
s.execute("home.formatCells", json!({"range": "B1", "style": {"font": {"outline": true, "bold": true}}})).unwrap();
let style = s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"].clone();
s.execute("home.formatCells", json!({"range": "A1:B1", "style": style})).unwrap();
let font = s.execute("cell.get", json!({"cell": "B1"})).unwrap()["style"]["font"].clone();
assert_eq!((font["bold"].clone(), font["outline"].clone()), (json!(false), json!(false)));
}
#[test]
fn arabic_vowel_and_direction_marks_add_no_width() {
let plain = approx_text_width("محمد يدرس في المدرسة", 11.0, false);
+287
View File
@@ -0,0 +1,287 @@
//! Quick Analysis › Totals: appends totals (or per-cell percentages / running totals) next to a
//! block of numbers as ordinary formulas, in one undoable edit. The popup in the UI
//! (`ui.quickAnalysis`) is a thin front end for this command; the control channel, CLI and MCP
//! call it directly. The layout is GridCraft's own: aggregates go in the row below the block (or
//! the column to its right), per-cell results in a block of the same shape next to it.
use std::collections::BTreeSet;
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef};
use gridcraft_model::{Color, NumFmt, Sparkline, SparklineKind};
use serde_json::{Value as Json, json};
use super::{CommandSpec, EngineError, PROTECTED, Result, Session, bad, bool_param, cmd, edit, has_doc, str_param, target_range, target_sheet};
const CMD: &str = "analysis.addTotal";
const SPARK: &str = "analysis.addSparklines";
/// Most sparklines one call may add.
const MAX_SPARKLINES: u64 = 10_000;
/// Most cells one call may write (a per-cell block on a huge selection is refused).
const MAX_OUTPUT_CELLS: u64 = 200_000;
/// Largest block (after clipping to the used range) the command scans for numbers.
const MAX_SCAN_CELLS: u64 = 5_000_000;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"analysis.addTotal",
"Add Totals",
[],
None,
"{function?: sum|average|count|min|max|percentTotal|runningTotal (default sum), direction?: columns|rows (default columns: one result per column, below the block; rows: one per row, right of it; percentTotal and runningTotal write a block of the same shape to the right (columns) or below (rows)), range?: \"A1:C9\" (default: the selection; limited to the used range), overwrite?: bool (else non-empty output cells are refused)} → {function, direction, output, cells}. Quick Analysis › Totals. A header row (columns) or label column (rows) is skipped; columns without numbers get no total. One undo step.",
has_doc,
add_total
),
cmd!(
"analysis.addSparklines",
"Add Sparklines",
[],
None,
"{type?: line|column|winLoss (default line), direction?: rows|columns (default rows: one sparkline per row, in the column right of the block; columns: one per column, in the row below), markers?: bool, range?: \"A1:F9\" (default: the selection; limited to the used range), overwrite?: bool} → {output, sparklines}. Quick Analysis › Sparklines. A header row (columns) or label column (rows) is skipped; lines without numbers get none. One undo step.",
has_doc,
add_sparklines
),
]
}
#[derive(Clone, Copy, PartialEq)]
enum Func {
Aggregate(&'static str),
Percent,
Running,
}
fn parse_func(name: &str) -> Result<Func> {
Ok(match name.to_ascii_lowercase().replace(['_', '-', ' ', '%'], "").as_str() {
"sum" => Func::Aggregate("SUM"),
"average" | "avg" => Func::Aggregate("AVERAGE"),
"count" => Func::Aggregate("COUNT"),
"min" => Func::Aggregate("MIN"),
"max" => Func::Aggregate("MAX"),
"percenttotal" | "percent" => Func::Percent,
"runningtotal" | "running" => Func::Running,
_ => return Err(bad(CMD, format!("unknown function `{name}` (use sum, average, count, min, max, percentTotal or runningTotal)"))),
})
}
/// The block a Quick Analysis result is computed from.
struct Block {
sheet: usize,
/// The selection clipped to the used range.
range: RangeRef,
/// `range` without its header row (columns) or label column (rows).
data: RangeRef,
/// The columns (or, `by_rows`, the rows) of `data` that hold numbers.
lines: BTreeSet<u32>,
by_rows: bool,
/// Last row / column the results must stay clear of: the selection's own far edge, so a
/// selection reaching past the data still gets its results outside it. Whole rows or columns
/// (reaching the sheet limit) fall back to the clipped range.
edge: CellRef,
}
impl Block {
fn cell_at(&self, line: u32, i: u32) -> CellRef {
if self.by_rows { CellRef::new(line, i) } else { CellRef::new(i, line) }
}
/// First and last position along a line of `data`.
fn span_of_line(&self) -> (u32, u32) {
if self.by_rows { (self.data.start.col, self.data.end.col) } else { (self.data.start.row, self.data.end.row) }
}
fn line_range(&self, line: u32, from: u32, to: u32) -> RangeRef {
RangeRef::new(self.cell_at(line, from), self.cell_at(line, to))
}
}
fn block(s: &Session, p: &Json, by_rows: bool, cmd: &str) -> Result<Block> {
let sheet = target_sheet(s, p)?;
let sel = match str_param(p, "range") {
Some(_) => target_range(s, p)?,
None => {
// Never guess from the current area of a multi-area selection.
if s.doc()?.selection.ranges.len() > 1 {
return Err(bad(cmd, "select a single contiguous range"));
}
s.doc()?.selection.current()
}
};
if sel.is_single() {
return Err(bad(cmd, "select at least two cells"));
}
let d = s.doc()?;
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
// Whole rows / columns are limited to what holds data.
let used = sh.cells.used_range().ok_or_else(|| EngineError::Other("There is no data to analyse.".into()))?;
let r = sel.intersection(&used).ok_or_else(|| EngineError::Other("There is no data to analyse in the selection.".into()))?;
if r.count() > MAX_SCAN_CELLS {
return Err(bad(cmd, "selection too large to analyse"));
}
let is_num = |c: CellRef| sh.value(c).is_number();
let is_text = |c: CellRef| sh.value(c).is_text();
// Header row (columns) / label column (rows): text only, with at least one entry.
let lead: Vec<CellRef> = if by_rows {
(r.start.row..=r.end.row).map(|row| CellRef::new(row, r.start.col)).collect()
} else {
(r.start.col..=r.end.col).map(|c| CellRef::new(r.start.row, c)).collect()
};
let longer_than_one = if by_rows { r.width() > 1 } else { r.height() > 1 };
let has_label = longer_than_one && lead.iter().any(|c| is_text(*c)) && !lead.iter().any(|c| is_num(*c));
let data = if by_rows {
RangeRef::new(CellRef::new(r.start.row, r.start.col + u32::from(has_label)), r.end)
} else {
RangeRef::new(CellRef::new(r.start.row + u32::from(has_label), r.start.col), r.end)
};
let mut lines: BTreeSet<u32> = BTreeSet::new();
for (c, _) in sh.cells.iter_range(data) {
if is_num(c) {
lines.insert(if by_rows { c.row } else { c.col });
}
}
if lines.is_empty() {
return Err(EngineError::Other("The selection holds no numbers.".into()));
}
let edge = CellRef::new(
if sel.end.row >= MAX_ROWS - 1 { r.end.row } else { sel.end.row.max(r.end.row) },
if sel.end.col >= MAX_COLS - 1 { r.end.col } else { sel.end.col.max(r.end.col) },
);
Ok(Block { sheet, range: r, data, lines, by_rows, edge })
}
fn add_total(s: &mut Session, p: &Json) -> Result<Json> {
let func = parse_func(str_param(p, "function").unwrap_or("sum"))?;
let by_rows = match str_param(p, "direction") {
None | Some("columns") => false,
Some("rows") => true,
Some(other) => return Err(bad(CMD, format!("direction must be columns or rows, not `{other}`"))),
};
let overwrite = bool_param(p, "overwrite").unwrap_or(false);
let b = block(s, p, by_rows, CMD)?;
let (r, sheet) = (b.range, b.sheet);
let (lo, hi) = b.span_of_line();
let out_cells = match func {
Func::Aggregate(_) => b.lines.len() as u64,
_ => b.lines.len() as u64 * (u64::from(hi - lo) + 1),
};
if out_cells > MAX_OUTPUT_CELLS {
return Err(bad(CMD, "selection too large for this result"));
}
// `$` pins a part of a reference like a hand-written formula would.
let abs = |c: CellRef, row: bool, col: bool| {
let a = c.a1();
let letters: String = a.chars().take_while(|ch| ch.is_ascii_alphabetic()).collect();
let digits = &a[letters.len()..];
format!("{}{letters}{}{digits}", if col { "$" } else { "" }, if row { "$" } else { "" })
};
// (target, formula) pairs.
let mut writes: Vec<(CellRef, String)> = Vec::with_capacity(out_cells as usize);
let (height, width) = (b.edge.row - r.start.row + 1, b.edge.col - r.start.col + 1);
for &line in &b.lines {
match func {
Func::Aggregate(name) => {
let target =
if by_rows { CellRef::new(line, b.edge.col.saturating_add(1)) } else { CellRef::new(b.edge.row.saturating_add(1), line) };
writes.push((target, format!("={name}({})", b.line_range(line, lo, hi).a1())));
}
Func::Percent | Func::Running => {
for i in lo..=hi {
let src = b.cell_at(line, i);
let target = if by_rows {
CellRef::new(src.row.saturating_add(height), src.col)
} else {
CellRef::new(src.row, src.col.saturating_add(width))
};
let formula = if func == Func::Percent {
// The summed block is locked on the axis the formula is filled along.
let (a, z) = (b.cell_at(line, lo), b.cell_at(line, hi));
format!("={}/SUM({}:{})", src.a1(), abs(a, !by_rows, by_rows), abs(z, !by_rows, by_rows))
} else {
format!("=SUM({}:{})", abs(b.cell_at(line, lo), !by_rows, by_rows), src.a1())
};
writes.push((target, formula));
}
}
}
}
// Everything has to fit on the sheet and may not overwrite data.
if writes.iter().any(|(t, _)| t.row >= MAX_ROWS || t.col >= MAX_COLS) {
return Err(EngineError::Other("There's no room next to the selection for the result.".into()));
}
let sh = s.doc()?.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
if !overwrite && writes.iter().any(|(t, _)| !sh.value(*t).is_empty() || sh.cells.get(*t).is_some_and(|c| c.formula.is_some())) {
return Err(EngineError::Other("The cells next to the selection already hold data; clear them first.".into()));
}
let out = writes.iter().fold(None::<RangeRef>, |acc, (t, _)| Some(acc.map_or(RangeRef::cell(*t), |a| a.union(&RangeRef::cell(*t)))));
let percent = func == Func::Percent;
let count = writes.len();
edit(s, |cx| {
for (t, f) in &writes {
let cell = super::edit::input_to_cell(f, sheet, *t, &mut cx.wb)?.unwrap_or_default();
cx.sheet_mut(sheet)?.set_cell(*t, cell);
if percent {
let cur = cx.wb.sheet(sheet).map(|sh| sh.style_id(*t)).unwrap_or_default();
let new = cx.wb.styles.derive(cur, |st| st.num_fmt = NumFmt::new("0.0%"));
cx.sheet_mut(sheet)?.set_style(*t, new);
}
cx.touch(sheet, *t);
}
Ok(())
})?;
let name = match func {
Func::Aggregate(n) => n.to_ascii_lowercase(),
Func::Percent => "percentTotal".into(),
Func::Running => "runningTotal".into(),
};
Ok(json!({"function": name, "direction": if by_rows { "rows" } else { "columns" }, "output": out.map(|o| o.a1()), "cells": count}))
}
fn add_sparklines(s: &mut Session, p: &Json) -> Result<Json> {
let by_rows = match str_param(p, "direction") {
None | Some("rows") => true,
Some("columns") => false,
Some(other) => return Err(bad(SPARK, format!("direction must be rows or columns, not `{other}`"))),
};
let kind = match str_param(p, "type") {
None | Some("line") => SparklineKind::Line,
Some("column") => SparklineKind::Column,
Some("winLoss") => SparklineKind::WinLoss,
Some(other) => return Err(bad(SPARK, format!("type must be line, column or winLoss, not `{other}`"))),
};
let markers = bool_param(p, "markers").unwrap_or(false);
let overwrite = bool_param(p, "overwrite").unwrap_or(false);
let b = block(s, p, by_rows, SPARK)?;
if b.lines.len() as u64 > MAX_SPARKLINES {
return Err(bad(SPARK, "selection too large for this result"));
}
let (lo, hi) = b.span_of_line();
let sparks: Vec<(CellRef, String)> = b
.lines
.iter()
.map(|&line| {
let at = if by_rows { CellRef::new(line, b.edge.col.saturating_add(1)) } else { CellRef::new(b.edge.row.saturating_add(1), line) };
(at, b.line_range(line, lo, hi).a1())
})
.collect();
if sparks.iter().any(|(t, _)| t.row >= MAX_ROWS || t.col >= MAX_COLS) {
return Err(EngineError::Other("There's no room next to the selection for the sparklines.".into()));
}
let sheet = b.sheet;
let sh = s.doc()?.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
// Sparklines are not cell content, so the commit-time protection check does not see them.
if sh.is_protected() {
return Err(EngineError::Other(PROTECTED.into()));
}
if !overwrite && sparks.iter().any(|(t, _)| !sh.value(*t).is_empty() || sh.sparklines.iter().any(|x| x.cell == *t)) {
return Err(EngineError::Other("The cells next to the selection already hold data; clear them first.".into()));
}
let out = sparks.iter().fold(None::<RangeRef>, |acc, (t, _)| Some(acc.map_or(RangeRef::cell(*t), |a| a.union(&RangeRef::cell(*t)))));
let count = sparks.len();
edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
for (cell, source) in sparks {
sh.sparklines.retain(|x| x.cell != cell);
sh.sparklines.push(Sparkline { cell, source, kind, color: Color::Theme(4, 0), markers });
}
Ok(())
})?;
Ok(json!({"output": out.map(|o| o.a1()), "sparklines": count}))
}
+265
View File
@@ -5381,6 +5381,140 @@ fn a_decrypted_workbook_never_overwrites_its_encrypted_original() {
std::fs::remove_dir_all(dir).unwrap();
}
fn quick_analysis_block(s: &mut Session) {
for (a, t) in [("A1", "Item"), ("B1", "Q1"), ("C1", "Q2"), ("A2", "x"), ("A3", "y"), ("A4", "z")] {
s.execute("cell.set", json!({"cell": a, "input": t})).unwrap();
}
for (r, (q1, q2)) in [(1.0, 10.0), (2.0, 20.0), (3.0, 30.0)].into_iter().enumerate() {
s.execute("cell.set", json!({"cell": format!("B{}", r + 2), "input": q1.to_string()})).unwrap();
s.execute("cell.set", json!({"cell": format!("C{}", r + 2), "input": q2.to_string()})).unwrap();
}
}
#[test]
fn analysis_add_total_writes_formulas_in_one_undo_step() {
// Issue #791 (Quick Analysis › Totals).
let mut s = s();
quick_analysis_block(&mut s);
let before = s.doc().unwrap().undo.len();
// The header row and the text-only column are skipped; the selection is the default range.
s.execute("selection.set", json!({"range": "A1:C4"})).unwrap();
let r = s.execute("analysis.addTotal", json!({"function": "sum"})).unwrap();
assert_eq!(r["output"], "B5:C5");
assert_eq!(v(&s, "B5"), Value::Number(6.0));
assert_eq!(v(&s, "C5"), Value::Number(60.0));
assert_eq!(v(&s, "A5"), Value::Empty, "text columns get no total");
s.execute("analysis.addTotal", json!({"range": "B1:C4", "function": "average", "direction": "rows"})).unwrap();
assert_eq!(v(&s, "D2"), Value::Number(5.5));
s.execute("analysis.addTotal", json!({"range": "B1:C4", "function": "runningTotal", "overwrite": true})).unwrap();
assert_eq!(v(&s, "D4"), Value::Number(6.0), "running total down column B");
assert_eq!(v(&s, "E4"), Value::Number(60.0));
s.execute("analysis.addTotal", json!({"range": "B1:B4", "function": "percentTotal", "overwrite": true})).unwrap();
assert_eq!(v(&s, "C4"), Value::Number(0.5), "overwrite replaces the C column cell next to B");
assert_eq!(s.doc().unwrap().undo.len(), before + 4, "one undo step per call");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(v(&s, "C4"), Value::Number(30.0));
// A second sum into the occupied row is refused rather than overwriting.
assert!(s.execute("analysis.addTotal", json!({"range": "A1:C4"})).is_err());
}
#[test]
fn analysis_add_total_refuses_bad_and_huge_input() {
let mut s = s();
quick_analysis_block(&mut s);
// Empty params on a single cell, unknown function, no numbers, whole columns, no room.
assert!(s.execute("analysis.addTotal", json!({})).is_err());
assert!(s.execute("analysis.addTotal", json!({"range": "A1:C4", "function": "median"})).is_err());
assert!(s.execute("analysis.addTotal", json!({"range": "A1:A4"})).is_err());
let before = s.doc().unwrap().undo.len();
let r = s.execute("analysis.addTotal", json!({"range": "B:C"})).unwrap();
assert_eq!(r["output"], "B5:C5", "whole columns are clipped to the used range");
assert_eq!(s.doc().unwrap().undo.len(), before + 1);
s.execute("cell.set", json!({"cell": "B1048575", "input": "1"})).unwrap();
s.execute("cell.set", json!({"cell": "B1048576", "input": "2"})).unwrap();
assert!(s.execute("analysis.addTotal", json!({"range": "B1048575:C1048576"})).is_err(), "no row below the last one");
assert!(s.execute("analysis.addTotal", json!({"range": "B1:C1048576", "function": "runningTotal"})).is_err(), "per-cell block over the cap");
}
#[test]
fn analysis_results_stay_outside_a_selection_that_extends_past_the_data() {
let mut s = s();
quick_analysis_block(&mut s);
// Data ends in row 4; the selection runs to row 10, so the sum goes in row 11.
let r = s.execute("analysis.addTotal", json!({"range": "A1:C10"})).unwrap();
assert_eq!(r["output"], "B11:C11");
assert_eq!(v(&s, "B11"), Value::Number(6.0));
assert_eq!(v(&s, "B5"), Value::Empty);
// Per-row blocks and sparklines move out by the selection's size too.
let r = s.execute("analysis.addTotal", json!({"range": "B1:C10", "function": "runningTotal", "direction": "rows"})).unwrap();
assert_eq!(r["output"], "B12:C14", "per-row block lands below the selection, not inside it");
let r = s.execute("analysis.addSparklines", json!({"range": "A1:F4"})).unwrap();
assert_eq!(r["output"], "G2:G4");
let r = s.execute("analysis.addSparklines", json!({"range": "A1:C8", "direction": "columns"})).unwrap();
assert_eq!(r["output"], "B9:C9");
}
#[test]
fn analysis_overwrite_keeps_the_target_cell_style() {
let mut s = s();
quick_analysis_block(&mut s);
s.execute("cell.set", json!({"cell": "B5", "input": "1"})).unwrap();
s.execute("selection.set", json!({"cell": "B5"})).unwrap();
s.execute("home.bold", json!({})).unwrap();
s.execute("analysis.addTotal", json!({"range": "A1:C4", "overwrite": true})).unwrap();
assert_eq!(v(&s, "B5"), Value::Number(6.0));
let d = s.doc().unwrap();
let sh = d.wb.active().unwrap();
assert!(d.wb.styles.get(sh.style_id(CellRef::parse("B5").unwrap())).font.bold, "bold survives the overwrite");
}
#[test]
fn analysis_commands_refuse_a_multi_area_selection_without_a_range() {
let mut s = s();
quick_analysis_block(&mut s);
s.execute("selection.set", json!({"range": "A1:C4,E1:F4"})).unwrap();
for c in ["analysis.addTotal", "analysis.addSparklines"] {
let e = s.execute(c, json!({})).unwrap_err().to_string();
assert!(e.contains("single contiguous range"), "{c}: {e}");
}
assert_eq!(v(&s, "B5"), Value::Empty);
// An explicit range still works.
s.execute("analysis.addTotal", json!({"range": "A1:C4"})).unwrap();
assert_eq!(v(&s, "B5"), Value::Number(6.0));
}
#[test]
fn analysis_add_sparklines_one_per_row_in_one_undo_step() {
let mut s = s();
quick_analysis_block(&mut s);
let before = s.doc().unwrap().undo.len();
let r = s.execute("analysis.addSparklines", json!({"range": "A1:C4", "type": "column"})).unwrap();
assert_eq!(r["output"], "D2:D4", "header row and label column are skipped");
let sparks = s.doc().unwrap().wb.active().unwrap().sparklines.clone();
assert_eq!(sparks.len(), 3);
assert!(sparks.iter().any(|x| x.cell == CellRef::parse("D3").unwrap() && x.source == "B3:C3"));
assert_eq!(s.doc().unwrap().undo.len(), before + 1);
s.execute("edit.undo", json!({})).unwrap();
assert!(s.doc().unwrap().wb.active().unwrap().sparklines.is_empty());
assert!(s.execute("analysis.addSparklines", json!({"range": "A1:A4"})).is_err());
}
#[test]
fn analysis_add_sparklines_refuses_a_protected_sheet() {
let mut s = s();
quick_analysis_block(&mut s);
s.execute("analysis.addSparklines", json!({"range": "A1:C4"})).unwrap();
s.execute("review.protectSheet", json!({})).unwrap();
let (undo, sparks) = (s.doc().unwrap().undo.len(), s.doc().unwrap().wb.active().unwrap().sparklines.clone());
for p in [json!({"range": "A1:C4", "overwrite": true}), json!({"range": "A1:B3", "direction": "columns"})] {
assert!(s.execute("analysis.addSparklines", p).is_err());
}
assert_eq!(s.doc().unwrap().undo.len(), undo, "a refused command leaves no undo step");
assert_eq!(s.doc().unwrap().wb.active().unwrap().sparklines, sparks);
s.execute("review.unprotectSheet", json!({})).unwrap();
s.execute("analysis.addSparklines", json!({"range": "A1:C4", "overwrite": true})).unwrap();
}
#[test]
fn link_open_refuses_every_scheme_but_http_https_and_mailto() {
let mut s = s();
@@ -7657,3 +7791,134 @@ fn history_charges_the_storage_of_empty_comment_replies() {
// 500 replies of no text are still 500 elements.
assert!(crate::sheet_text_bytes(&sheet) >= 500 * std::mem::size_of::<(String, String)>());
}
/// Paste Link would write links to the cells a cut empties, losing them: a cut can't be pasted
/// as links, and nothing changes.
#[test]
fn a_cut_is_not_pasted_as_links() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2]]})).unwrap();
s.execute("edit.cut", json!({"range": "A1:B1"})).unwrap();
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "link": true, "at": "E1"})).is_err());
assert_eq!((v(&s, "A1"), v(&s, "B1"), v(&s, "E1")), (Value::Number(1.0), Value::Number(2.0), Value::Empty));
}
/// A cut pasted into a row the filter hides would skip every cell it writes, so the cells would
/// leave the sheet with the cut: it is refused and nothing changes. A visible row takes it.
#[test]
fn a_cut_is_not_pasted_into_filtered_rows() {
let mut s = s();
let mut rows = vec![json!(["Val", "Tag"])];
for i in 2..=5 {
rows.push(json!([format!("v{i}"), if i == 3 { "hide" } else { "keep" }]));
}
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
s.execute("range.setValues", json!({"range": "E1", "values": [[1, 2]]})).unwrap();
s.execute("selection.set", json!({"range": "A1:B1"})).unwrap();
s.execute("data.filter", json!({})).unwrap();
s.execute("data.filterBy", json!({"column": "B", "values": ["keep"]})).unwrap();
s.execute("edit.cut", json!({"range": "E1:F1"})).unwrap();
s.execute("selection.set", json!({"range": "A3:B3"})).unwrap();
assert!(s.execute("edit.paste", json!({})).is_err());
assert_eq!((v(&s, "E1"), v(&s, "F1")), (Value::Number(1.0), Value::Number(2.0)));
assert_eq!(v(&s, "A3"), Value::from("v3"));
s.execute("selection.set", json!({"range": "A4:B4"})).unwrap();
s.execute("edit.paste", json!({})).unwrap();
assert_eq!((v(&s, "A4"), v(&s, "B4"), v(&s, "E1")), (Value::Number(1.0), Value::Number(2.0), Value::Empty));
}
/// A taller cut, or one pasted at an explicit cell, goes straight down: refused when a row the
/// filter hides is among the rows it would land on, and nothing changes. A visible place takes it.
#[test]
fn an_anchored_cut_is_not_pasted_over_filtered_rows() {
let mut s = s();
let mut rows = vec![json!(["Val", "Tag"])];
for i in 2..=5 {
rows.push(json!([format!("v{i}"), if i == 3 { "hide" } else { "keep" }]));
}
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
s.execute("range.setValues", json!({"range": "A10", "values": [[1, 2], [3, 4]]})).unwrap();
s.execute("selection.set", json!({"range": "A1:B1"})).unwrap();
s.execute("data.filter", json!({})).unwrap();
s.execute("data.filterBy", json!({"column": "B", "values": ["keep"]})).unwrap();
s.execute("edit.cut", json!({"range": "A10:B11"})).unwrap();
assert!(s.execute("edit.paste", json!({"at": "A2"})).is_err());
assert_eq!((v(&s, "A10"), v(&s, "B11")), (Value::Number(1.0), Value::Number(4.0)));
assert_eq!((v(&s, "A2"), v(&s, "A3")), (Value::from("v2"), Value::from("v3")));
s.execute("edit.paste", json!({"at": "A4"})).unwrap();
assert_eq!((v(&s, "A4"), v(&s, "B5"), v(&s, "A10")), (Value::Number(1.0), Value::Number(4.0), Value::Empty));
}
/// Skip Blanks would empty a cut's blank cells along with their note and format, then skip them:
/// a cut takes no Paste Special option, and nothing changes.
#[test]
fn a_cut_is_not_pasted_skipping_blanks() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [[1]]})).unwrap();
s.execute("review.newNote", json!({"cell": "B1", "text": "note", "author": "Example"})).unwrap();
s.execute("home.bold", json!({"range": "B1"})).unwrap();
s.execute("edit.cut", json!({"range": "A1:B1"})).unwrap();
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "skipBlanks": true, "at": "E1"})).is_err());
let d = s.doc().unwrap();
let sh = d.wb.active().unwrap();
let b1 = CellRef::parse("B1").unwrap();
assert!(sh.comments.contains_key(&b1));
assert!(d.wb.styles.get(sh.style_id(b1)).font.bold);
assert_eq!((v(&s, "A1"), v(&s, "E1")), (Value::Number(1.0), Value::Empty));
}
/// Transposing a cut would move references to it as if it were not transposed: refused, and a
/// formula reading the cut cells still reads them.
#[test]
fn a_cut_is_not_pasted_transposed() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2]]})).unwrap();
s.execute("cell.set", json!({"cell": "H1", "input": "=B1"})).unwrap();
s.execute("edit.cut", json!({"range": "A1:B1"})).unwrap();
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "E5"})).is_err());
assert_eq!(formula_at(&s, "H1").as_deref(), Some("B1"));
assert_eq!((v(&s, "A1"), v(&s, "B1"), v(&s, "E5"), v(&s, "E6")), (Value::Number(1.0), Value::Number(2.0), Value::Empty, Value::Empty));
}
/// A cut lands in one place: onto a larger or differently shaped selection it is refused, as in
/// Excel, rather than tiled.
#[test]
fn a_cut_is_not_pasted_over_a_larger_area() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [[5]]})).unwrap();
s.execute("edit.cut", json!({"range": "A1"})).unwrap();
s.execute("selection.set", json!({"range": "E1:E3"})).unwrap();
assert!(s.execute("edit.paste", json!({})).is_err());
assert_eq!((v(&s, "A1"), v(&s, "E1"), v(&s, "E2"), v(&s, "E3")), (Value::Number(5.0), Value::Empty, Value::Empty, Value::Empty));
}
/// A paste operation or a partial paste (values only) of a cut would empty the cut cells and
/// combine or keep only part of them: refused, and nothing changes.
#[test]
fn a_cut_is_not_pasted_with_an_operation_or_in_part() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [[5]]})).unwrap();
s.execute("range.setValues", json!({"range": "E1", "values": [[2]]})).unwrap();
s.execute("edit.cut", json!({"range": "A1"})).unwrap();
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "operation": "add", "at": "E1"})).is_err());
assert!(s.execute("edit.pasteSpecial", json!({"what": "values", "at": "E1"})).is_err());
assert_eq!((v(&s, "A1"), v(&s, "E1")), (Value::Number(5.0), Value::Number(2.0)));
}
/// A refused paste leaves the cut pending: a plain Paste onto one cell, or onto an area of the cut's
/// size, still moves it.
#[test]
fn a_refused_cut_paste_leaves_the_cut_to_paste_plainly() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2]]})).unwrap();
s.execute("edit.cut", json!({"range": "A1:B1"})).unwrap();
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "E5"})).is_err());
s.execute("selection.set", json!({"range": "E1"})).unwrap();
s.execute("edit.paste", json!({})).unwrap();
assert_eq!((v(&s, "A1"), v(&s, "E1"), v(&s, "F1")), (Value::Empty, Value::Number(1.0), Value::Number(2.0)));
assert!(s.clipboard.is_none());
s.execute("edit.cut", json!({"range": "E1:F1"})).unwrap();
s.execute("selection.set", json!({"range": "C3:D3"})).unwrap();
s.execute("edit.paste", json!({})).unwrap();
assert_eq!((v(&s, "E1"), v(&s, "C3"), v(&s, "D3")), (Value::Empty, Value::Number(1.0), Value::Number(2.0)));
}
+9 -3
View File
@@ -168,7 +168,8 @@
"vert": "Baseline",
"charset": null,
"family": null,
"minor": true
"minor": true,
"outline": false
},
"fill": {
"pattern": "None",
@@ -219,6 +220,7 @@
"bold": false,
"italic": false,
"strike": false,
"outline": false,
"underline": false,
"size": false,
"name": false,
@@ -238,7 +240,8 @@
"vert": "Baseline",
"charset": null,
"family": null,
"minor": true
"minor": true,
"outline": false
},
"fill": {
"pattern": "None",
@@ -289,6 +292,7 @@
"bold": false,
"italic": false,
"strike": false,
"outline": false,
"underline": false,
"size": false,
"name": false,
@@ -308,7 +312,8 @@
"vert": "Baseline",
"charset": null,
"family": null,
"minor": true
"minor": true,
"outline": false
},
"fill": {
"pattern": "None",
@@ -359,6 +364,7 @@
"bold": false,
"italic": false,
"strike": false,
"outline": false,
"underline": false,
"size": false,
"name": false,
+6
View File
@@ -247,6 +247,7 @@
"bold": false,
"italic": false,
"name": false,
"outline": false,
"protection": false,
"scheme": null,
"size": false,
@@ -266,6 +267,7 @@
"italic": false,
"minor": true,
"name": "Calibri",
"outline": false,
"size": 11.0,
"strike": false,
"underline": "None",
@@ -317,6 +319,7 @@
"bold": false,
"italic": false,
"name": false,
"outline": false,
"protection": false,
"scheme": null,
"size": false,
@@ -336,6 +339,7 @@
"italic": false,
"minor": true,
"name": "Calibri",
"outline": false,
"size": 11.0,
"strike": false,
"underline": "None",
@@ -387,6 +391,7 @@
"bold": false,
"italic": false,
"name": false,
"outline": false,
"protection": false,
"scheme": null,
"size": false,
@@ -406,6 +411,7 @@
"italic": false,
"minor": true,
"name": "Calibri",
"outline": false,
"size": 11.0,
"strike": false,
"underline": "None",
+10
View File
@@ -637,6 +637,16 @@ mod tests {
assert_eq!(c, vec![Some([255, 0, 0]), None]);
}
#[test]
fn nested_colours_are_kept_per_glyph() {
// Green a, + and c; black b and the plain +d are left to the equation's own colour.
let l = layout("{\\color{green}a+{\\color{black}b}+c}+d").unwrap();
let g = Some([0, 128, 0]);
let c: Vec<(char, Option<[u8; 3]>)> =
l.items.iter().filter_map(|i| if let Item::Glyph(g) = i { Some((g.ch, g.color)) } else { None }).collect();
assert_eq!(c, vec![('a', g), ('+', g), ('b', None), ('+', g), ('c', g), ('+', None), ('d', None)]);
}
#[test]
fn errors_point_at_the_source() {
let e = layout("a + \\frac{1}{").unwrap_err();
+64 -1
View File
@@ -197,6 +197,11 @@ pub struct Font {
/// theme's minor font. Fonts derived from it (bold, a colour, a size) keep the link.
#[serde(default = "default_minor")]
pub minor: bool,
/// Outlined (hollow) letters: an XLSX `<outline/>`. Kept and saved; GridCraft does not
/// draw it yet (the letters render solid). Always serialized, like the other flags, so a
/// whole style sent back through `home.formatCells` (the Format Cells dialog) clears it.
#[serde(default)]
pub outline: bool,
}
fn default_minor() -> bool {
@@ -208,7 +213,7 @@ impl Hash for Font {
fn hash<H: Hasher>(&self, h: &mut H) {
self.name.hash(h);
self.size.to_bits().hash(h);
(self.bold, self.italic, self.underline, self.strike, self.color, self.vert, self.charset, self.family, self.minor).hash(h);
(self.bold, self.italic, self.underline, self.strike, self.color, self.vert, self.charset, self.family, self.minor, self.outline).hash(h);
}
}
@@ -226,6 +231,7 @@ impl Default for Font {
charset: None,
family: None,
minor: true,
outline: false,
}
}
}
@@ -370,6 +376,17 @@ pub struct Alignment {
/// Unspecified inherits in differential styles and uses context for ordinary cells.
#[serde(default)]
pub reading_order: Option<ReadingOrder>,
/// Space between the cell's edges and its text, left, right, top, bottom, in hundredths
/// of a point; `None` where the file stated none (the application's own). An OpenDocument
/// cell's padding; Excel has none. Not drawn yet.
#[serde(default, skip_serializing_if = "Alignment::no_padding")]
pub padding: [Option<u16>; 4],
}
impl Alignment {
fn no_padding(p: &[Option<u16>; 4]) -> bool {
p.iter().all(Option::is_none)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -408,6 +425,9 @@ pub struct DxfStated {
pub bold: bool,
pub italic: bool,
pub strike: bool,
/// Outlined letters turned off (`<outline val="0"/>`). Defaulted so JSON saved before it opens.
#[serde(default)]
pub outline: bool,
pub underline: bool,
pub size: bool,
pub name: bool,
@@ -529,6 +549,49 @@ mod tests {
assert!(!t.get(StyleId(999)).font.bold);
}
/// Two fonts differing only in outlined letters are different styles; JSON states the flag
/// even when off, and JSON saved before it existed reads as not outlined.
#[test]
fn outline_makes_a_distinct_style() -> Result<(), Box<dyn std::error::Error>> {
let mut t = StyleTable::default();
let outlined = t.derive(StyleId::DEFAULT, |s| s.font.outline = true);
assert_ne!(outlined, StyleId::DEFAULT);
assert_ne!(Font { outline: true, ..Font::default() }, Font::default());
assert_eq!(t.derive(outlined, |s| s.font.outline = false), StyleId::DEFAULT);
let mut json = serde_json::to_value(Font::default())?;
assert_eq!(json.get("outline"), Some(&serde_json::Value::Bool(false)));
assert!(json.as_object_mut().ok_or("none")?.remove("outline").is_some());
assert_eq!(serde_json::from_value::<Font>(json)?, Font::default());
let on = serde_json::to_value(Font { outline: true, ..Font::default() })?;
assert_eq!(on.get("outline"), Some(&serde_json::Value::Bool(true)));
let mut stated = serde_json::to_value(DxfStated::default())?;
assert!(stated.as_object_mut().ok_or("none")?.remove("outline").is_some());
assert_eq!(serde_json::from_value::<DxfStated>(stated)?, DxfStated::default());
Ok(())
}
#[test]
fn padding_keeps_styles_apart_and_survives_json() -> Result<(), Box<dyn std::error::Error>> {
let mut t = StyleTable::default();
let padded = t.derive(StyleId::DEFAULT, |s| s.align.padding = [Some(10), None, Some(0), Some(65535)]);
let other = t.derive(StyleId::DEFAULT, |s| s.align.padding = [Some(10), None, Some(0), Some(1)]);
assert_ne!(padded, StyleId::DEFAULT);
assert_ne!(padded, other);
assert_eq!(t.derive(StyleId::DEFAULT, |s| s.align.padding = [Some(10), None, Some(0), Some(65535)]), padded);
assert_eq!(t.derive(padded, |s| s.align.padding = [None; 4]), StyleId::DEFAULT);
let style = t.get(padded).clone();
let json = serde_json::to_string(&style)?;
assert!(json.contains("padding"), "{json}");
assert_eq!(serde_json::from_str::<Style>(&json)?, style);
// No padding: nothing written, and JSON written before the field existed still reads.
let plain = serde_json::to_string(&Alignment::default())?;
assert!(!plain.contains("padding"), "{plain}");
assert_eq!(serde_json::from_str::<Alignment>(&plain)?, Alignment::default());
Ok(())
}
#[test]
fn a_theme_saved_before_per_script_fonts_still_opens() -> Result<(), Box<dyn std::error::Error>> {
let mut json = serde_json::to_value(Theme::default())?;
+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.
+19 -1
View File
@@ -2,7 +2,7 @@
//!
//! `cargo run --release -p gridcraft-ui-egui --example snapshot -- [--sample sales] [--in file.xlsx]
//! [--size 1440x900] [--scale 2] [--cmd 'id={json}']... [--tab Insert] [--dark] [--language en|es|zh|ja|ko|ru|pt|de|cs|fr|tr]
//! [--pane name] [--object id] [--dialog 'name={json}'] [--refedit key=A1:B2] [--hf-edit header|footer] out.png`
//! [--pane name] [--object id] [--dialog 'name={json}'] [--quick-analysis formatting|charts|totals|tables|sparklines] [--refedit key=A1:B2] [--hf-edit header|footer] out.png`
//!
//! `--refedit key=range` collapses the open dialog to its reference box `key`, then selects
//! `range` on the grid, as a person picking a range for that box does.
@@ -25,6 +25,7 @@ fn main() {
let mut dialog: Option<String> = None;
let mut language: Option<String> = None;
let mut hf_edit: Option<String> = None;
let mut quick: Option<String> = None;
let mut refedit: Option<String> = None;
let mut out = "snapshot.png".to_string();
let mut i = 0;
@@ -72,6 +73,10 @@ fn main() {
i += 1;
dialog = args.get(i).cloned();
}
"--quick-analysis" => {
i += 1;
quick = args.get(i).cloned();
}
"--refedit" => {
i += 1;
refedit = args.get(i).cloned();
@@ -130,6 +135,19 @@ fn main() {
d.split_once('=').map(|(a, b)| (a, serde_json::from_str(b).unwrap_or(json!({})))).unwrap_or((d.as_str(), json!({})));
app.open_dialog(name, p);
}
if let Some(name) = &quick {
use gridcraft_ui_egui::quick_analysis::Tab;
app.grid.quick_analysis.tab = match name.as_str() {
"charts" => Tab::Charts,
"totals" => Tab::Totals,
"tables" => Tab::Tables,
"sparklines" => Tab::Sparklines,
_ => Tab::Formatting,
};
if let Err(e) = gridcraft_ui_egui::quick_analysis::toggle(&mut app, Some(true)) {
eprintln!("quick analysis: {e}");
}
}
// Page Layout view: edit the first page's centre header (or footer) section.
let active = app.session.active().and_then(|d| d.wb.active().cloned().map(|s| (d.wb.active_sheet(), s)));
if let (Some(part), Some((si, sh))) = (&hf_edit, active) {
+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 -1
View File
@@ -153,7 +153,7 @@ impl SheetApp {
}
/// Shows a command error: a toast for an unavailable command, else a message box.
pub(super) fn alert(&mut self, e: String) {
pub(crate) fn alert(&mut self, e: String) {
// Shown in the window the user ends up in, also after a command that switched windows.
self.follow_active_window();
if e.contains("is not available right now") {
@@ -278,6 +278,7 @@ impl SheetApp {
self.ui.language = i18n::Language::Ja;
Ok(json!({"language": i18n::Language::Ja}))
}
"ui.quickAnalysis" => crate::quick_analysis::toggle(self, p.get("open").and_then(Json::as_bool)),
"ui.backstage" => {
// `{"page": "info"}` opens File › Info; `{"page": "close"}` returns to the sheet.
match p.get("page").and_then(Json::as_str).map(str::trim) {
+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
}
+2
View File
@@ -332,6 +332,8 @@ pub struct GridState {
/// of it offers Show Details, and running it says why.
pub show_details_cells: Option<DetailsCache>,
pub header_menu: Option<(Pos2, bool)>,
/// Quick Analysis button and popup (Ctrl+Q).
pub quick_analysis: crate::quick_analysis::State,
/// Page Layout view pagination, cached per (doc uid, revision, sheet, rows, columns).
pub paper: Option<crate::paper_view::PaperCache>,
/// Header or footer being edited in place (Page Layout view).
+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)));
}
+10 -4
View File
@@ -149,10 +149,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
}
}
Key::Escape if app.selected_object.is_some() => app.selected_object = None,
Key::Escape => {
app.session.clipboard = None;
app.session.format_painter = None;
}
Key::Escape => cancel_pending(app),
Key::Space if !cmd && !shift && is_checkbox(sh, app) => app.run_or_alert("cell.toggleCheckbox", json!({})),
Key::F8 if m.alt => {
app.open_dialog("macros", json!({}));
@@ -277,3 +274,12 @@ fn form_control_event(app: &mut SheetApp, sh: &Sheet, ev: &egui::Event) -> bool
_ => false,
}
}
/// Esc with nothing else to dismiss drops the pending copy and the Format Painter. An open Quick
/// Analysis popup owns the key: it closes and the pending copy stays.
fn cancel_pending(app: &mut SheetApp) {
if app.grid.quick_analysis.open.take().is_none() {
app.session.clipboard = None;
app.session.format_painter = None;
}
}
+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
@@ -388,6 +388,7 @@ fn show_grid_interactions(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Re
fill_options_tag(app, ui, geo, sh);
object_menu(app, ui);
error_check_tag(app, ui, geo, sh);
crate::quick_analysis::show(app, ui, geo, sh);
}
fn update_zoom_glide(app: &mut SheetApp, ui: &egui::Ui, place: (u64, usize), zoom: u16, now: f64) {
+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
+9
View File
@@ -168,6 +168,8 @@ pub enum Icon {
OpenFolder,
Info,
Print,
/// Quick Analysis: a small table with a spark.
QuickAnalysis,
/// A macro: a script page with a run arrow.
Macro,
/// Record Macro: a ring around the recording dot.
@@ -872,6 +874,13 @@ fn paint_with(p: &Painter, rect: Rect, icon: Icon, c: Color32, pal: &Palette) {
g.line(&[(4.5, 9.0), (4.5, 14.5), (11.5, 14.5), (11.5, 9.0), (4.5, 9.0)], c, 1.1);
g.circle(12.3, 7.6, 0.6, Some(c), None);
}
Icon::QuickAnalysis => {
g.rect(2.0, 3.0, 12.0, 10.0, None, Some(c));
g.stroke(&[(2.0, 6.5), (14.0, 6.5)], light);
g.stroke(&[(6.0, 3.0), (6.0, 13.0)], light);
g.stroke(&[(10.0, 3.0), (10.0, 13.0)], light);
g.line(&[(10.0, 1.0), (6.5, 8.0), (9.5, 8.0), (6.5, 15.0)], blue, 1.7);
}
Icon::Macro => {
g.rect(2.5, 1.5, 9.0, 12.0, Some(paper), Some(c));
for y in [4.5, 7.0, 9.5] {
+5
View File
@@ -41,6 +41,8 @@ pub enum Shortcut {
Zoom(i32),
/// Ctrl+Alt+Shift+P: edit the active cell as Python code (Python mode).
PythonMode,
/// Excel for Mac Control+Q: Quick Analysis (Windows Ctrl+Q is in `ribbon::shortcut`).
QuickAnalysis,
}
fn run(id: &'static str) -> Shortcut {
@@ -179,6 +181,8 @@ fn lookup_control_shortcuts(ctx: LookupContext) -> Option<Shortcut> {
// Windows Ctrl+; is in `ribbon::shortcut`; Excel for Mac uses Control+; and Command+;.
Semicolon if mac && ctrl => Shortcut::Date,
Semicolon if mac && cmd && !s => Shortcut::Time,
// Control+Q only: Command+Q is the native Quit item.
Q if mac && ctrl && !m.command && !s => Shortcut::QuickAnalysis,
_ => return None,
})
}
@@ -389,6 +393,7 @@ pub(crate) fn dispatch(app: &mut SheetApp, ctx: &egui::Context, key: Key, physic
}
Shortcut::Edit => app.begin_edit(None, false),
Shortcut::PythonMode => app.toggle_python_mode(),
Shortcut::QuickAnalysis => crate::ribbon::quick_analysis(app),
Shortcut::ContextMenu => app.grid.context_menu = Some(geo.cell_rect(sh, active).center()),
Shortcut::DropDown => {
if sh.validations.iter().any(|d| d.in_cell_dropdown && d.ranges.iter().any(|r| r.contains(active))) {
+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);
+11
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;
@@ -52,6 +55,7 @@ pub mod panes;
pub mod paper_view;
pub mod pivot_pane;
pub mod printing;
pub mod quick_analysis;
pub mod ribbon;
pub mod selection_glide;
pub mod tabs;
@@ -60,6 +64,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 +354,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(),
}
}
+462
View File
@@ -0,0 +1,462 @@
//! Quick Analysis (Ctrl+Q): a small button at the bottom-right corner of a multi-cell selection
//! that opens a popup of one-click analyses. The popup is a thin front end: every tile runs an
//! engine command through `app.run` (conditional formats, charts, `analysis.addTotal`, tables,
//! pivot tables, `analysis.addSparklines`), so nothing here is UI-only logic worth testing apart
//! from which command a tile maps to ([`tiles`]).
use egui::{Align2, Color32, Id, Order, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
use gridcraft_engine::core::RangeRef;
use gridcraft_engine::model::Sheet;
use serde_json::{Value as Json, json};
use crate::SheetApp;
use crate::grid::{Drag, Geo};
use crate::icons::{self, Icon};
use crate::theme::{self, Cat, Tokens};
/// Side of the corner button, and its gap to the selection's corner (clear of the fill handle).
const BUTTON: f32 = 22.0;
const GAP: f32 = 6.0;
const TILE: egui::Vec2 = vec2(66.0, 62.0);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Tab {
#[default]
Formatting,
Charts,
Totals,
Tables,
Sparklines,
}
impl Tab {
const ALL: [Tab; 5] = [Tab::Formatting, Tab::Charts, Tab::Totals, Tab::Tables, Tab::Sparklines];
fn label(self) -> &'static str {
match self {
Tab::Formatting => "Formatting",
Tab::Charts => "Charts",
Tab::Totals => "Totals",
Tab::Tables => "Tables",
Tab::Sparklines => "Sparklines",
}
}
}
#[derive(Default)]
pub struct State {
/// The sheet (by its identity, not its position) and selection the popup was opened for; it closes when either changes.
pub open: Option<(u64, RangeRef)>,
pub tab: Tab,
/// Totals by row (results to the right) instead of by column (results below).
pub by_rows: bool,
/// The popup just opened: its first tile takes the keyboard focus so arrows, Enter and Space work.
focus_first_tile: bool,
}
/// What a tile does.
#[derive(Clone, Debug, PartialEq)]
pub enum Action {
Run(&'static str, Json),
Dialog(&'static str, Json),
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Glyph {
Icon(Icon),
Text(&'static str),
Bars,
Scale,
GreenBars,
BlueScale,
GreenScale,
Dots,
Steps,
MiniColumns,
WinLoss,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Tile {
label: &'static str,
glyph: Glyph,
pub action: Action,
}
fn tile(label: &'static str, glyph: Glyph, action: Action) -> Tile {
Tile { label, glyph, action }
}
/// The tiles of a tab for the selection `range` (A1 text) on the sheet called `sheet_name`.
pub fn tiles(tab: Tab, range: &str, sheet_name: &str, by_rows: bool) -> Vec<Tile> {
use Action::{Dialog, Run};
let cf = |rule: Json| Run("home.conditionalFormat", json!({"range": range, "rule": rule}));
let chart = |kind: &str| Run("insert.chart", json!({"range": range, "type": kind}));
let total = |f: &str| Run("analysis.addTotal", json!({"range": range, "function": f, "direction": if by_rows { "rows" } else { "columns" }}));
let spark = |kind: &str| Run("analysis.addSparklines", json!({"range": range, "type": kind}));
match tab {
Tab::Formatting => vec![
tile("Data Bars", Glyph::Bars, cf(json!({"type": "dataBar"}))),
tile("Color Scale", Glyph::Scale, cf(json!({"type": "colorScale"}))),
tile("Icon Set", Glyph::Dots, cf(json!({"type": "iconSet"}))),
tile("Greater Than…", Glyph::Text(">"), Dialog("cfQuick", json!({"type": "cellIs", "operator": "greater", "title": "Greater Than…"}))),
tile("Top 10 Items", Glyph::Text("10"), cf(json!({"type": "top10", "rank": 10}))),
tile("Clear Rules", Glyph::Icon(Icon::Eraser), Run("home.clearRules", json!({"range": range}))),
tile("Green Data Bars", Glyph::GreenBars, cf(json!({"type": "dataBar", "color": "#63BE7B"}))),
tile("Blue-White-Red Scale", Glyph::BlueScale, cf(json!({"type": "colorScale", "colors": ["#5A8AC6", "#FCFCFF", "#F8696B"]}))),
tile("White-Green Scale", Glyph::GreenScale, cf(json!({"type": "colorScale", "colors": ["#FCFCFF", "#63BE7B"]}))),
tile("Top 10%", Glyph::Text("10%"), cf(json!({"type": "top10", "rank": 10, "percent": true}))),
tile("Below Average", Glyph::Text("<avg"), cf(json!({"type": "aboveAverage", "below": true}))),
tile("Duplicate Values", Glyph::Text("=="), cf(json!({"type": "duplicate"}))),
],
Tab::Charts => vec![
tile("Clustered Column", Glyph::Icon(Icon::ChartBar), chart("column")),
tile("Line", Glyph::Icon(Icon::ChartLine), chart("line")),
tile("Pie", Glyph::Icon(Icon::ChartPie), chart("pie")),
tile("Bar", Glyph::Icon(Icon::Chart), chart("bar")),
tile("Scatter", Glyph::Icon(Icon::ChartScatter), chart("scatter")),
tile("Recommended Charts", Glyph::Icon(Icon::Chart), Run("insert.recommendedCharts", json!({"range": range}))),
],
Tab::Totals => vec![
tile("Sum", Glyph::Icon(Icon::Sum), total("sum")),
tile("Average", Glyph::Text("avg"), total("average")),
tile("Count", Glyph::Text("#"), total("count")),
tile("% Total", Glyph::Icon(Icon::Percent), total("percentTotal")),
tile("Running Total", Glyph::Steps, total("runningTotal")),
],
Tab::Tables => vec![
tile("Table", Glyph::Icon(Icon::Table), Run("insert.table", json!({"range": range}))),
tile(
"PivotTable",
Glyph::Icon(Icon::PivotTable),
Run("insert.pivotTable", json!({"source": format!("'{}'!{range}", sheet_name.replace('\'', "''"))})),
),
],
Tab::Sparklines => vec![
tile("Line", Glyph::Icon(Icon::Sparkline), spark("line")),
tile("Column", Glyph::MiniColumns, spark("column")),
tile("Win/Loss", Glyph::WinLoss, spark("winLoss")),
],
}
}
/// Ctrl+Q and the `ui.quickAnalysis` command: opens the popup for the selection (or closes it).
/// Errors for a single cell, where there is nothing to analyse.
pub fn toggle(app: &mut SheetApp, on: Option<bool>) -> Result<Json, String> {
let d = app.session.active().ok_or("no workbook open")?;
if d.selection.ranges.len() > 1 {
return Err("Quick Analysis works on one block of cells; select a single contiguous range.".into());
}
let sel = d.selection.current();
let sheet = d.wb.active().map_or(0, |s| s.uid.get());
let want = on.unwrap_or(app.grid.quick_analysis.open.is_none());
if !want {
app.grid.quick_analysis.open = None;
} else if sel.is_single() {
return Err("Select at least two cells to use Quick Analysis.".into());
} else {
app.grid.quick_analysis.open = Some((sheet, sel));
app.grid.quick_analysis.focus_first_tile = true;
}
Ok(json!({"open": app.grid.quick_analysis.open.is_some()}))
}
/// Whether the button (and popup) stay out of the way: a single cell or several areas, editing,
/// an open dialog or menu, and the paged views have no corner to hang them on.
pub fn is_hidden(app: &SheetApp, geo: &Geo, sh: &Sheet) -> bool {
let Some(d) = app.session.active() else { return true };
d.selection.ranges.len() > 1
|| d.selection.current().is_single()
|| app.editor.is_some()
|| app.dialog.is_some()
|| app.text_box_editor.is_some()
|| app.grid.context_menu.is_some()
|| geo.paper.is_some()
|| sh.view == gridcraft_engine::model::SheetViewMode::PageLayout
}
/// Where the corner button sits for `sel` (on screen), and whether the selection's corner is in
/// view. Below and right of the corner, clear of the fill handle; flipped inside at the grid edge.
pub fn button_rect(geo: &Geo, sh: &Sheet, sel: RangeRef) -> (Rect, bool) {
let corner = geo.range_rect(sh, sel).right_bottom();
let panes = geo.range_panes(RangeRef::cell(sel.end));
let visible = panes.iter().any(|p| p.contains(pos2(corner.x - 1.0, corner.y - 1.0)));
let area = geo.cells.shrink(2.0);
let x = if corner.x + GAP + BUTTON > area.right() { corner.x - GAP - BUTTON } else { corner.x + GAP };
let y = if corner.y + GAP + BUTTON > area.bottom() { corner.y - GAP - BUTTON } else { corner.y + GAP };
let at = pos2(x.clamp(area.left(), (area.right() - BUTTON).max(area.left())), y.clamp(area.top(), (area.bottom() - BUTTON).max(area.top())));
(geo.mirror_rect(Rect::from_min_size(at, vec2(BUTTON, BUTTON))), visible)
}
/// Paints the corner button and, when open, the popup. Called once per grid frame.
pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) {
let Some(d) = app.session.active() else { return };
let sel = d.selection.current();
let sheet = d.wb.active().map_or(0, |s| s.uid.get());
let hidden = is_hidden(app, geo, sh);
// The popup belongs to one selection on one sheet; a new one (or editing) closes it.
if hidden || app.grid.quick_analysis.open.is_some_and(|(opened_on, r)| opened_on != sheet || r != sel) {
app.grid.quick_analysis.open = None;
}
if hidden {
return;
}
let sheet_name = sh.name.clone();
let ctx = ui.ctx().clone();
let t = Tokens::get(&ctx);
let (button, corner_visible) = button_rect(geo, sh, sel);
let open = app.grid.quick_analysis.open.is_some();
// While the mouse is down (selecting, filling) the button stays out of the way.
let busy = app.grid.drag != Drag::None || ctx.input(|i| i.pointer.any_down());
let lang = crate::i18n::current(&ctx);
// Right after a fill-handle drag the Auto Fill Options button sits at the same corner; it wins
// until that fill is no longer current (Ctrl+Q still opens the popup).
let fill_tag = app.grid.fill_tag.is_some();
// Whether the launcher or a popup control has the keyboard, so the grid reads no keys this frame.
let mut keyboard_in_popup = false;
if corner_visible && (open || (!busy && !fill_tag)) {
let mut clicked = false;
let mut focused = false;
egui::Area::new(Id::unique("quick_analysis_button")).fixed_pos(button.min).order(Order::Foreground).show(&ctx, |ui| {
let (r, resp) = ui.allocate_exact_size(button.size(), Sense::click());
let fill = if resp.is_pointer_button_down_on() || open {
t.pressed
} else if resp.hovered() {
t.hover
} else {
t.menu_bg
};
ui.painter().rect_filled(r, 4.0, fill);
ui.painter().rect_stroke(r, 4.0, Stroke::new(1.0, t.separator), StrokeKind::Inside);
icons::paint(ui.painter(), Rect::from_center_size(r.center(), vec2(16.0, 16.0)), Icon::QuickAnalysis, t.accent);
// The launcher sits on the sheet, so its ring is the sheet's focus colour
paint_focus_ring(ui, t.sheet_focus, r, &resp);
let name = lang.tr("Quick Analysis (Ctrl+Q)");
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, open, name));
focused = resp.has_focus();
clicked = resp.on_hover_text(name).clicked();
});
keyboard_in_popup = focused;
if clicked {
let _ = toggle(app, None);
}
}
let Some((_, opened_for)) = app.grid.quick_analysis.open else { return };
let pos = pos2(button.left(), button.bottom() + 4.0);
let mut picked: Option<Action> = None;
// The frame that opened the popup (Ctrl+Q is still in the input) must not close it again.
let just_opened = app.grid.quick_analysis.focus_first_tile;
let resp = egui::Area::new(Id::unique("quick_analysis_popup")).fixed_pos(pos).order(Order::Foreground).constrain(true).show(&ctx, |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
let state = &mut app.grid.quick_analysis;
ui.horizontal(|ui| {
for tab in Tab::ALL {
let tab_button = ui.selectable_label(state.tab == tab, lang.tr(tab.label()));
keyboard_in_popup |= tab_button.has_focus();
if tab_button.clicked() {
state.tab = tab;
}
}
});
ui.separator();
if state.tab == Tab::Totals {
ui.horizontal(|ui| {
keyboard_in_popup |= ui.selectable_value(&mut state.by_rows, false, lang.tr("By Column")).has_focus();
keyboard_in_popup |= ui.selectable_value(&mut state.by_rows, true, lang.tr("By Row")).has_focus();
});
}
let items = tiles(state.tab, &opened_for.a1(), &sheet_name, state.by_rows);
let mut take_focus = std::mem::take(&mut state.focus_first_tile);
for row in items.chunks(6) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 2.0;
for item in row {
if paint_tile(ui, &t, item, lang.tr(item.label), std::mem::take(&mut take_focus), &mut keyboard_in_popup) {
picked = Some(item.action.clone());
}
}
});
}
});
});
let outside_click = ctx.input(|i| i.pointer.any_pressed())
&& ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| !resp.response.rect.contains(p) && !button.contains(p));
if let Some(action) = picked {
app.grid.quick_analysis.open = None;
match action {
Action::Run(id, params) => app.run_or_alert(id, params),
Action::Dialog(name, params) => app.open_dialog(name, params),
}
} else if outside_click
|| ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
|| (keyboard_in_popup && !just_opened && toggle_key_pressed(&ctx))
{
app.grid.quick_analysis.open = None;
}
}
/// Ctrl+Q (Control+Q on a Mac, where Command+Q stays Quit) while a tile has the keyboard: the grid
/// no longer reads keys then, so the popup closes itself on the key that opened it.
fn toggle_key_pressed(ctx: &egui::Context) -> bool {
ctx.input_mut(|i| {
let pressed = |e: &egui::Event| {
matches!(e, egui::Event::Key { key: egui::Key::Q, pressed: true, modifiers: m, .. } if m.ctrl && !m.shift && !m.alt && !m.mac_cmd)
};
let Some(at) = i.events.iter().position(pressed) else { return false };
i.events.remove(at);
true
})
}
/// A visible ring in `color` around a control that has the keyboard focus.
fn paint_focus_ring(ui: &Ui, color: Color32, rect: Rect, resp: &egui::Response) {
if resp.has_focus() {
ui.painter().rect_stroke(rect.expand(1.0), 5.0, Stroke::new(2.0, color), StrokeKind::Outside);
}
}
/// One option of the popup: a small picture over a wrapped label, a button named by that label.
/// `take_focus` gives it the keyboard focus. True when clicked.
fn paint_tile(ui: &mut Ui, t: &Tokens, item: &Tile, label: &str, take_focus: bool, has_keyboard: &mut bool) -> bool {
let (rect, resp) = ui.allocate_exact_size(TILE, Sense::click());
if take_focus {
resp.request_focus();
}
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
if resp.is_pointer_button_down_on() {
ui.painter().rect_filled(rect, 4.0, t.pressed);
} else if resp.hovered() {
ui.painter().rect_filled(rect, 4.0, t.hover);
}
let art = Rect::from_center_size(pos2(rect.center().x, rect.top() + 18.0), vec2(26.0, 26.0));
paint_glyph(ui, t, item.glyph, art);
let galley = ui.painter().layout(label.to_string(), theme::ui_font(11.0), t.text, TILE.x - 4.0);
let at = pos2(rect.center().x - galley.size().x / 2.0, rect.top() + 34.0);
ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())).galley(at, galley, t.text);
paint_focus_ring(ui, t.popup_focus_ring(), rect, &resp);
*has_keyboard |= resp.has_focus();
resp.clicked()
}
fn paint_glyph(ui: &Ui, t: &Tokens, glyph: Glyph, r: Rect) {
let p = ui.painter();
let (green, blue, red, yellow) = (t.cat(Cat::Green), t.cat(Cat::Blue), t.cat(Cat::Red), t.cat(Cat::Amber));
let cell = |i: f32, j: f32| Rect::from_min_size(r.min + vec2(i * r.width() / 3.0, j * r.height() / 3.0), vec2(r.width() / 3.0, r.height() / 3.0));
match glyph {
Glyph::Icon(icon) => icons::paint(p, r, icon, t.text),
Glyph::Text(s) => {
p.text(r.center(), Align2::CENTER_CENTER, s, theme::ui_bold(15.0), t.accent);
}
Glyph::Bars => {
for (j, w) in [0.9, 0.55, 0.3].into_iter().enumerate() {
let row = cell(0.0, j as f32).shrink2(vec2(0.0, 1.0));
p.rect_filled(Rect::from_min_size(row.min, vec2(r.width() * w, row.height())), 1.0, blue);
}
}
Glyph::Scale => {
for (i, c) in [red, yellow, green].into_iter().enumerate() {
p.rect_filled(cell(i as f32, 1.0).shrink(0.5), 1.0, c);
}
}
Glyph::GreenBars => {
for (j, w) in [0.9, 0.55, 0.3].into_iter().enumerate() {
let row = cell(0.0, j as f32).shrink2(vec2(0.0, 1.0));
p.rect_filled(Rect::from_min_size(row.min, vec2(r.width() * w, row.height())), 1.0, green);
}
}
Glyph::BlueScale | Glyph::GreenScale => {
let cols = if glyph == Glyph::BlueScale { [blue, Color32::WHITE, red] } else { [Color32::WHITE, green.gamma_multiply(0.5), green] };
for (i, c) in cols.into_iter().enumerate() {
p.rect_filled(cell(i as f32, 1.0).shrink(0.5), 1.0, c);
}
p.rect_stroke(
Rect::from_min_size(cell(0.0, 1.0).min, vec2(r.width(), r.height() / 3.0)),
1.0,
Stroke::new(1.0, t.separator),
StrokeKind::Inside,
);
}
Glyph::Dots => {
for (j, c) in [green, yellow, red].into_iter().enumerate() {
p.circle_filled(cell(1.0, j as f32).center(), 3.2, c);
}
}
Glyph::Steps => {
for i in 0..3 {
let h = r.height() * (0.35 + 0.28 * i as f32);
p.rect_filled(
Rect::from_min_max(
pos2(r.left() + i as f32 * r.width() / 3.0 + 1.0, r.bottom() - h),
pos2(r.left() + (i + 1) as f32 * r.width() / 3.0 - 1.0, r.bottom()),
),
1.0,
green,
);
}
}
Glyph::MiniColumns => {
for (i, h) in [0.5, 0.9, 0.65].into_iter().enumerate() {
let x = r.left() + i as f32 * r.width() / 3.0 + 2.0;
p.rect_filled(Rect::from_min_max(pos2(x, r.bottom() - r.height() * h), pos2(x + r.width() / 3.0 - 4.0, r.bottom())), 1.0, blue);
}
}
Glyph::WinLoss => {
let mid = r.center().y;
for (i, up) in [true, false, true].into_iter().enumerate() {
let x = r.left() + i as f32 * r.width() / 3.0 + 2.0;
let (a, b) = if up { (mid - 7.0, mid - 1.0) } else { (mid + 1.0, mid + 7.0) };
p.rect_filled(Rect::from_min_max(pos2(x, a), pos2(x + r.width() / 3.0 - 4.0, b)), 1.0, if up { green } else { red });
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use gridcraft_engine::Session;
/// A header row, a label column and two numeric columns on Sheet1.
fn session() -> (Session, String) {
let mut s = Session::new();
s.new_workbook();
for (a, v) in [("A1", "Item"), ("B1", "Q1"), ("C1", "Q2"), ("A2", "x"), ("A3", "y"), ("A4", "z")] {
s.execute("cell.set", json!({"cell": a, "input": v})).unwrap();
}
for (r, (q1, q2)) in [(1, 10), (2, 20), (3, 30)].into_iter().enumerate() {
s.execute("cell.set", json!({"cell": format!("B{}", r + 2), "input": q1.to_string()})).unwrap();
s.execute("cell.set", json!({"cell": format!("C{}", r + 2), "input": q2.to_string()})).unwrap();
}
let name = s.doc().unwrap().wb.active().unwrap().name.clone();
(s, name)
}
#[test]
fn every_engine_tile_runs_on_a_selection() {
for tab in Tab::ALL {
for by_rows in [false, true] {
let n = tiles(tab, "A1:C4", "Sheet1", by_rows).len();
for i in 0..n {
let (mut s, name) = session();
let item = tiles(tab, "A1:C4", &name, by_rows).remove(i);
if let Action::Run(id, params) = &item.action {
s.execute(id, params.clone()).unwrap_or_else(|e| panic!("{} / {}: {e}", tab.label(), item.label));
}
}
}
}
}
#[test]
fn dialog_tile_and_single_cell_are_not_engine_runs() {
let formatting = tiles(Tab::Formatting, "A1:C4", "Sheet1", false);
assert!(formatting.iter().any(|t| matches!(&t.action, Action::Dialog("cfQuick", _))));
// A programmatic open on a single cell is an error, not a popup.
let (s, _) = session();
let mut app = SheetApp::new(s, Default::default());
assert!(toggle(&mut app, Some(true)).is_err());
app.run("selection.set", json!({"range": "A1:C4"})).unwrap();
assert_eq!(toggle(&mut app, Some(true)).unwrap(), json!({"open": true}));
assert_eq!(app.run("ui.quickAnalysis", json!({"open": false})).unwrap(), json!({"open": false}));
}
}
+1
View File
@@ -37,6 +37,7 @@ use home::home;
use insert::{draw, insert};
use page_layout::page_layout;
use review::review;
pub(crate) use shortcuts::quick_analysis;
pub use shortcuts::shortcut;
pub use title_bar::{MAC_CONTENT_LEFT, MAC_TITLE_BAR, TITLE_LEFT_PAD, title_bar, window_frame};
use title_bar::{TITLE_BAR_H, TITLE_CONTROL_H};
+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 {
+16
View File
@@ -1,5 +1,15 @@
use super::{Key, Modifiers, SheetApp, json};
/// Ctrl+Q (Control+Q in Excel for Mac): Quick Analysis. A single cell has nothing to analyse,
/// which is not worth an alert, but several areas deserve to be told why nothing opened.
pub(crate) fn quick_analysis(app: &mut SheetApp) {
if let Err(e) = crate::quick_analysis::toggle(app, None)
&& app.session.active().is_some_and(|d| d.selection.ranges.len() > 1)
{
app.alert(e);
}
}
/// Command-key shortcuts when the grid has focus.
pub fn shortcut(app: &mut SheetApp, key: Key, m: Modifiers) {
let shift = m.shift;
@@ -42,6 +52,12 @@ pub fn shortcut(app: &mut SheetApp, key: Key, m: Modifiers) {
Key::T if shift => Some(("formulas.autoSum", json!({}))),
Key::T => Some(("insert.table", json!({}))),
Key::E => Some(("edit.flashFill", json!({}))),
// Plain Ctrl+Q only: Ctrl+Shift+Q and Ctrl+Alt+Q (AltGr+Q) are not Quick Analysis.
// Command+Q on a Mac is the native Quit item; Control+Q there goes through the keymap.
Key::Q if !shift && !m.alt && !m.mac_cmd => {
quick_analysis(app);
None
}
Key::Num1 => {
app.open_dialog("formatCells", json!({}));
None
+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| {
+39 -2
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;
@@ -382,6 +382,23 @@ pub fn sheet_tabs(app: &mut SheetApp, ui: &mut Ui) {
});
}
/// How many statistics, given their widths left to right, fit when drawn from the right end of
/// `room` points with `gap` points of space after each. The leftmost (lowest-priority) labels are
/// the ones left out; a label wider than the whole room leaves none.
fn fitting_statistics(widths: &[f32], room: f32, gap: f32) -> usize {
let mut used = 0.0;
let mut kept = 0;
for w in widths.iter().rev() {
let need = w + gap;
if used + need > room {
break;
}
used += need;
kept += 1;
}
kept
}
/// Draws status mode/messages, zoom controls/view-mode buttons and selection statistics.
pub fn status_bar(app: &mut SheetApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
@@ -479,7 +496,17 @@ pub fn status_bar(app: &mut SheetApp, ui: &mut Ui) {
ui.add_space(16.0);
// The layout runs right to left, so the last statistic is drawn first.
// Clicking a statistic copies its value (without the label) to the clipboard.
for p in selection_statistics(app).into_iter().rev() {
// Only the rightmost statistics that fit are drawn: on a narrow window the rest
// would paint over the mode text such as "Ready" at the left end (#4187).
let stats = selection_statistics(app);
let font = theme::ui_font(12.5);
let widths: Vec<f32> = stats.iter().map(|p| ui.painter().layout_no_wrap(p.clone(), font.clone(), t.text_dim).size().x).collect();
// Each label is followed by egui's automatic item spacing as well as the
// explicit 10 points of `add_space` below.
let gap = 10.0 + ui.spacing().item_spacing.x;
let keep = fitting_statistics(&widths, ui.available_width(), gap);
let span = stats.len();
for p in stats.into_iter().skip(span - keep).rev() {
let value = p.split_once(": ").map_or(p.as_str(), |(_, v)| v).to_owned();
let resp = ui.add(
egui::Label::new(egui::RichText::new(p).font(theme::ui_font(12.5)).color(t.text_dim))
@@ -610,6 +637,16 @@ mod tests {
assert!(italian.iter().zip(&english).all(|(it, en)| it != en), "the Italian catalog translates every label: {italian:?}");
}
#[test]
fn statistics_that_do_not_fit_are_left_out() {
// Widths left to right (Average, Count, Sum), 10 points of gap after each. Only a suffix fits.
let widths = [60.0, 50.0, 40.0];
assert_eq!(super::fitting_statistics(&widths, 300.0, 10.0), 3);
assert_eq!(super::fitting_statistics(&widths, 159.0, 10.0), 2);
assert_eq!(super::fitting_statistics(&widths, 100.0, 10.0), 1);
assert_eq!(super::fitting_statistics(&widths, 49.0, 10.0), 0);
}
#[test]
fn status_bar_shows_the_statistics_that_are_turned_on_in_order() {
let mut session = gridcraft_engine::Session::default();
+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;
+9
View File
@@ -300,6 +300,12 @@ impl Tokens {
if ctx.global_style().visuals.dark_mode { Tokens::dark() } else { Tokens::light() }
}
/// The ring around a focused control on a popup or menu surface. The sheet's own focus colour
/// is too dim on the dark popup (2.5:1), so this follows the theme's accent instead.
pub fn popup_focus_ring(&self) -> Color32 {
self.accent
}
/// One colour of the category palette.
pub fn cat(&self, c: Cat) -> Color32 {
self.cat.get(c as usize).copied().unwrap_or(self.text)
@@ -440,6 +446,9 @@ mod contrast_tests {
add("slider fill on sheet", t.sheet_fill, t.grid_bg, GLYPH);
add("slider fill on track", t.sheet_fill, t.sheet_track, GLYPH);
add("control focus ring on sheet", t.sheet_focus, t.grid_bg, GLYPH);
for (name, bg) in [("menu", t.menu_bg), ("hover", t.hover), ("pressed", t.pressed)] {
add(&format!("popup control focus ring on {name}"), t.popup_focus_ring(), bg, GLYPH);
}
add("recording dot on ribbon", t.recording, t.ribbon, GLYPH);
add("recording dot on status bar", t.recording, t.status_bar, GLYPH);
for (name, c) in [
+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.
@@ -441,3 +441,40 @@ fn ctrl_alt_letter_that_typed_text_is_not_select_all() {
assert_eq!(h.state().session.active().unwrap().selection.current().a1(), "B2");
assert_eq!(h.state().editor.as_ref().unwrap().text, "\u{e4}");
}
/// Only plain Ctrl+Q toggles Quick Analysis; Ctrl+Shift+Q and Ctrl+Alt+Q (AltGr+Q) do not.
#[test]
fn only_plain_ctrl_q_toggles_quick_analysis() {
let mut h = harness(book("A1:B3"));
key(&mut h, Key::Q, CTRL_SHIFT);
assert!(h.state().grid.quick_analysis.open.is_none(), "Ctrl+Shift+Q");
key(&mut h, Key::Q, Modifiers { alt: true, ..CTRL });
assert!(h.state().grid.quick_analysis.open.is_none(), "Ctrl+Alt+Q");
key(&mut h, Key::Q, CTRL);
assert!(h.state().grid.quick_analysis.open.is_some(), "Ctrl+Q");
}
/// Excel for Mac: Control+Q (ctrl without command) opens Quick Analysis, Command+Q is left to the
/// native Quit item, and a single cell still opens nothing without an alert.
#[test]
fn mac_control_q_toggles_quick_analysis_and_command_q_does_not() {
const MAC_CONTROL: Modifiers = Modifiers { alt: false, ctrl: true, shift: false, mac_cmd: false, command: false };
const MAC_COMMAND: Modifiers = Modifiers { alt: false, ctrl: false, shift: false, mac_cmd: true, command: true };
assert_eq!(lookup(Key::Q, Some(Key::Q), MAC_CONTROL, true), Some(Shortcut::QuickAnalysis));
assert_eq!(lookup(Key::Q, Some(Key::Q), MAC_COMMAND, true), None);
assert_eq!(lookup(Key::Q, Some(Key::Q), MAC_CONTROL, false), None, "Windows Ctrl+Q goes through ribbon::shortcut");
let mac = |sel: &str| crate::common::os_harness(book(sel), egui::os::OperatingSystem::Mac);
let mut h = mac("A1:B3");
key(&mut h, Key::Q, MAC_COMMAND);
assert!(h.state().grid.quick_analysis.open.is_none(), "Command+Q is Quit");
key(&mut h, Key::Q, Modifiers { shift: true, ..MAC_CONTROL });
assert!(h.state().grid.quick_analysis.open.is_none(), "Control+Shift+Q");
key(&mut h, Key::Q, MAC_CONTROL);
assert!(h.state().grid.quick_analysis.open.is_some(), "Control+Q opens");
key(&mut h, Key::Q, MAC_CONTROL);
assert!(h.state().grid.quick_analysis.open.is_none(), "Control+Q again closes");
let mut h = mac("B2");
key(&mut h, Key::Q, MAC_CONTROL);
assert!(h.state().grid.quick_analysis.open.is_none());
assert!(h.state().message.is_none() && h.state().toast.is_none(), "no alert for a single cell");
}
+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"][..])] {
+1
View File
@@ -96,6 +96,7 @@ mod protected_cell;
mod python_cell_edit;
mod python_hidden;
mod python_mode;
mod quick_analysis_button;
mod ref_edit;
mod ribbon_layout;
mod right_to_left;
+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.

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