Compare commits

..
Author SHA1 Message Date
Dylan M. Taylor 7495f20278 fix(xlsx): simplify nonminimal_bool in drawing.rs 2026-11-18 21:00:49 -05:00
Dylan M. Taylor 75ad3b0ffe Wire craft-xls and craft-drawingml to craft-libs main (#778) 2026-11-18 17:43:33 -05:00
Dylan M. Taylor 83ab01678a Cut over gridcraft-xlsx ODS reader to craft-ods (#4513) 2026-11-18 17:22:18 -05:00
Michael Higgins 00e8f4fae0 Drag a selected chart's data outline to change its range (#4389, #4390) (#4391)
#4389, #4390: drag a selected chart's data outline to change its range

A selected chart now outlines its data as Excel does: series names in red,
category labels in purple and the values as one blue block. The values
block has a handle on each corner. Dragging one previews the new block,
and the release points the chart at it as one undo step. Esc cancels.

The new engine command chart.setValuesRange does the move. Each series
keeps its formatting, a wider block adds series and a narrower one drops
them, and names, category labels and bubble sizes that line up with the
block follow it. PivotCharts and series that are not one block are
refused.
#4389: chart data drag review fixes

- Category labels are compared as blocks, so a reference written with a
  leading = still counts as the same labels.
- A resize keeps the orientation the series were read in, so a chart
  shrunk to one cell per series stays resizable.
- The preview stays while edge scrolling moves the chart off screen.
- A values corner hidden under frozen panes is not a handle.
- The release takes the block from the pointer's last position, even when
  it moved in the release frame.
- Esc cancels the drag with Ctrl or Cmd held too.

Each fix has a test that fails without it.
#4389: read a corner drag from the grabbed corner's own cell

A values corner lies on a cell boundary, which belongs to the next row
and column, so a press on the bottom-right corner of A1:A5 read as B6:
releasing where the press was, or dragging straight down the edge of
column A, changed the other axis too. The drag now records the offset
from the press point to the centre of the corner's cell and reads the
pointer through it, so the press point stays in its cell and each whole
cell of movement moves the corner by one.
#4389: snap a dragged chart data edge to the nearest gridline

Reading the pointer from the middle of the grabbed corner's cell let the
grabbed row's height decide when the block moved: with a tall row 5 and
a short row 6, the pointer reached the bottom of row 6 while the block
stayed at A1:A5. Each edge the corner moves now snaps to the gridline
nearest the pointer, so every row and column changes over at its own
middle. A release where the press was still changes nothing, since the
corner lies on its own gridlines, and an edge dropped on its fixed edge
keeps one row or column.
#4389: drop a chart data drag when the chart's data changes under it

A command run between frames (the control channel, a macro) could change
the chart's values block while the button was held, and the release then
put the dragged block over that change. The drag now checks, from the
session, that the chart still plots the block it started from: a move
drops a stale drag, and the release skips it.
2026-11-18 21:53:00 +07:00
neilcawse f8af138f28 XLSX: read, evaluate and write Excel 2010 conditional formats (#717)
XLSX: read, evaluate and write Excel 2010 conditional formats

Excel 2010+ keeps conditional format rules whose formulas refer to
other sheets only in the worksheet's x14:conditionalFormattings
extension, with xm:f formulas and an inline x14:dxf in place of a
dxfId. GridCraft skipped the whole extension with a warning.

Read: x14 cellIs (every operator, one or two formulas), expression,
blanks, errors, duplicate/unique, top 10, above average and time
period rules become ordinary rules, with the inline differential
format (font, fill, border, number format) and priorities that
interleave with the main section's. A data bar's linked extension
(the x14:id of a main-section rule) adds no second rule. Other x14
kinds (data bar settings, x14 icon sets) are skipped with a warning
naming the kind.

Evaluate: cross-sheet references in rule formulas already resolve;
an engine test pins cellIs and expression rules against cells on
another sheet.

Write: a cell-value or formula rule referring to another sheet is
written in the x14 extension ({78C0D931-6437-407d-A8EE-F0AAD7539E65})
with an inline x14:dxf and a unique id; other rules stay in the main
section. The extension shares one extLst with the sparklines (CF
first). Inline number formats get ids styles.xml declares.

XLSX: say which x14 conditional format rules stay in the main section

Colour scale, data bar and icon set rules are always written in the main
section, even when their cfvo formulas refer to other sheets; the parity
docs now say so. (This commit first dropped the
reader's own x14:id linking; after the rebase onto main, main's data bar
linking from #550 is the one path, so only the docs part remains.)
XLSX: correct the x14 conditional format provenance and list skipped kinds

The file that motivated the x14 conditional format work
(watchdog-report.xlsx) was saved by LibreOffice 25.2, not Excel, so
nothing observed in Excel backs the earlier commit's statement that
Excel 2010+ keeps cross-sheet rules only in the extension. MS-XLSX
2.6.27 (CT_CfRule) allows single-sheet references in xm:f but says
nothing about where Excel places such rules; the comments and docs now
say the placement follows the LibreOffice-saved file and Excel's own
is unverified.

MS-XLSX 2.6.27 forbids sheet-range-reference (3-D spans) in xm:f, so a
rule with a 3-D span now stays in the main section.

The parity docs and gaps list name the x14 kinds read (cellIs,
expression, blanks, errors, duplicate/unique, top10, aboveAverage,
timePeriod) and those skipped with a warning and lost on save (data
bars, icon sets, colour scales, containsText, notContainsText,
beginsWith, endsWith).

Styles: differential formats keep their cell protection on save

dxf_xml, which writes both styles.xml dxfs and inline x14:dxf elements, wrote font, number format, fill, alignment and border but never protection, although read_dxf reads it. A rule whose format unlocked or hid cells lost that on save. It now writes protection after border, the order CT_Dxf requires.
XLSX: solid data bars are saved with negatives in the bar colour and no axis, as GridCraft draws them
docs: order parity revision history
docs: record verified x14 conditional format placement
docs: fold the Excel check into the PR's own changelog row instead of a new dated row
docs: the Excel check covered cross-sheet expression rules, not cell-value rules
Fix differential format serialization
Preserve default dxf protection
2026-11-18 21:13:46 +07:00
Harrison Booth aef4ceb10d RATE follows Excel's iteration (#2502)
fix(functions): RATE follows Excel's iteration

RATE used Newton with fallbacks and a bracketing search, so it found roots
Excel doesn't and missed the last iterate Excel returns. It now follows
Excel's solver as observed with synthetic inputs: a secant iteration from
the guess and the guess moved 0.001 toward a larger equation value, at most
200 steps, stopping when a step is under 1e-7 and the equation is within
1e-7 of zero (or as close as its terms allow), with the result more than
1e-7 above -100%. After 200 steps the last iterate is kept if it is within
a looser 1e-4. Subnormal steps flush to zero as in Excel.

RATE(5,0,-100,0) is now -0.999999409145182 like Excel (was #NUM!), and
RATE(4,0,-0.0001,100) is #NUM! like Excel (was 30.62). A guess at or below
-1 is #VALUE!. IRR and XIRR keep their solver.

RATE test: compare with a relative tolerance, not exact equality
ROADMAP: keep the progress log in descending date order
RATE: pin Excel's #NUM! for a fractional nper with a guess near -1
2026-11-18 20:39:57 +07:00
FredApps 8f8078c134 Fix main's build and tests after the recent merges (#4474)
- Import SheetApp in the pivot pane tests.
- Move the keyboard owner check out of keyboard() to stay within the complexity limit.
- Aim the title bar button helper at the button's own node.

Fixes #4473.

Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-18 19:50:37 +07:00
FredApps c9d2883b86 Merge pull request #2028 from SoftwareBeesy/parity-crlf-windows
xtask: `parity --check` accepts a CRLF checkout of the checklist
2026-11-18 16:45:30 +07:00
Michael Higgins a3119f57c2 xlsx/csv: cap secondary reader allocations (#2159) (#2199)
* xlsx/csv: cap secondary reader allocations (#2159)
  
  - XML: at most 1M children per element, 16,384 per worksheet row (TooLarge).
  - Workbook-wide cap of 16M cell elements.
  - Array-formula ranges indexed by row (budgeted), not scanned per cell.
  - <cols> writes share a 4M budget.
  - At most 4096 sheets; duplicate names deduplicated with a HashSet.
  - Pivot: field lists capped, repeated fields used once, labels borrowed.
  - CSV: fields past MAX_COLS dropped while reading the record.
  - At most 4M shared strings.
  - Relationships looked up by id through a HashMap.

* xlsx: close the remaining secondary-reader cap gaps (#2159)
  
  - CSV: characters of a field past column 16,384 are not stored; quotes,
    delimiters and line ends in it are still followed.
  - Pivot: a field list cut at MAX_FIELDS is reported with a warning.
  - Sheet names: the prefix shortens once the (n) suffix passes (999), so
    deduplicated names stay within 31 characters.
  - Rows dropped for a bad row number still charge their <c> elements
    against MAX_CELLS.
  - Test Ctx helper gains the fields upstream added.

* #2159: describe MAX_CELLS as the reader's own cap
  
  calc::eval::MAX_CELLS has the same value but limits one array result,
  not a workbook.

* #2159: warn on capped pivot cache fields, dedupe pivot names through sets
  
  A cache cut at 16,384 fields is now reported, as the table field lists
  are. Axis filters and calculated fields are deduplicated through a set
  of lower-cased names instead of a scan per field, which was quadratic in
  the 16,384 fields allowed; the first of names equal but for case still
  wins.
2026-11-18 16:36:37 +07:00
NetterSilver 272ae54101 Delete separate rows or columns in one pass (#2385)
* Delete separate rows or columns in one pass
  
  Fixes #2287
2026-11-18 16:35:49 +07:00
NetterSilver bf48def687 Create new saved files without group/other write permission (#2567)
* Create new saved files without group/other write permission
  
  Fixes #2519
2026-11-18 16:35:20 +07:00
Michael Higgins dbf674ef48 links: spawn the Windows opener by absolute path (#2176) (#2204)
* links: spawn the Windows opener by absolute path (#2176)
  
  Explorer is now spawned as %SystemRoot%\explorer.exe (falling back to
  windir, then C:\Windows; only local drive paths are accepted), so an
  explorer.exe planted next to the app or in the CWD can't run. Space, ",
  comma and ^ are percent-encoded before Explorer parses its command line.
  macOS uses /usr/bin/open; a target starting with - or / is refused on
  every platform so it can never become an opener option.

* links: rename opener enum variant (clippy)
  
  `Os::MacOs` -> `Os::Mac` (clippy::enum_variant_names). Also give the
  desktop-theme watcher's non-Linux `Link` a non-unit type so
  clippy::let_unit_value stops firing on Windows/macOS.

* ui: leave desktop_theme Link alone (covered by #2141)

* #2176: say why the Explorer escape still encodes commas
2026-11-18 16:34:32 +07:00
FredApps 644861c132 Merge pull request #449 from neilcawse/fix/main-ci-csv-tests
CSV/text export: General numbers without exponents (integers below 1e16 exact); `&` switches to scientific past 21 characters
2026-11-18 16:34:02 +07:00
FredApps c8450fd1e5 Merge pull request #3784 from dotCooCoo/chore/craft-update-6e03f65
Updates: take craft-update from craft-libs main at e98299546
2026-11-18 16:28:11 +07:00
FredApps a492d8031a Merge pull request #3574 from SBaksa/intl-no-xlfn
XLSX: NETWORKDAYS.INTL and WORKDAY.INTL are saved without _xlfn. (fixes #3517)
2026-11-18 16:27:48 +07:00
FredApps 5b1d89f867 Merge pull request #3047 from quantforge-br/function-help-portuguese
UI: Brazilian Portuguese function help
2026-11-18 16:27:25 +07:00
FredApps 1f0d416f74 Merge pull request #3046 from quantforge-br/fix/spill-priority
Calc: a contested spill area stays with its array on full recalc and reopening (#964)
2026-11-18 16:27:02 +07:00
bmh129 82c97858df Linux: run on native Wayland again by default (revert #165) (#2789)
* Linux: run on native Wayland again by default (revert #165)
  
  winit 0.30.13 reported dropped files only on X11. The egui 0.37 migration
  (#2543) pins storytold/winit, whose patch W15 reports file drops through
  a per-seat Wayland data device (rust-windowing/winit#4729), so files
  dragged from the file manager open on native Wayland too. The XWayland
  default is no longer needed.
  
  It also costs a startup crash: winit's X11 backend loads
  libxkbcommon-x11, which the Linux packages don't depend on. Where it's
  missing (a Fedora toolbox, minimal installs), GridCraft panics before the
  window opens: "Library libxkbcommon-x11.so could not be loaded."
  
  Checked on GNOME (Wayland, Fedora 44) with a build of main plus other
  proposed changes, run with GRIDCRAFT_WAYLAND=1 (the path this revert
  makes the default): an .xlsx and a .csv dragged from Files each open as a
  workbook, and the app starts without libxkbcommon-x11 installed.
  
  This reverts commit 6f0e43c21c.
  
  Claude-Session: https://claude.ai/code/session_01Rvu8dWh26U2fsLQMSBQfH8
2026-11-18 16:26:39 +07:00
Zaxaerith 20c5742f79 fix(web): mark PDF exports in gridcraft:save (#2452) (#2535)
* fix(web): distinguish PDF exports in host save messages (#2452)
2026-11-18 16:26:01 +07:00
FredApps 21def4fa1a Merge pull request #2303 from MarekSpodBiedry/issue-2285
XLSX: write spilled text as cached strings, not shared strings (#2285)
2026-11-18 16:23:35 +07:00
FredApps 61ee368369 Merge pull request #2298 from dfendr/fix/table-style-looks
Tables: Give each style row its own look
2026-11-18 16:23:13 +07:00
FredApps d1a5c9671f Merge pull request #2293 from storytold/test/backfill-regression-tests
Regression tests for #223, #360 and #1485
2026-11-18 16:22:51 +07:00
Dominik Strebel 12dd9aea9b test: header AutoFit check measures the text as AutoFit did (#2273)
* test: header AutoFit check measures the text as AutoFit did
  
  table_filter_autofit_works_through_command_and_header_double_click
  compared the autofitted column with the engine's text-width estimate,
  but in the app AutoFit measures with the installed fonts
  (Session::text_width). Where those are narrower than the estimate (a
  Mac with Carlito, metric-compatible with Calibri), the estimate
  "overlapped" the filter button and the test failed on main. It now
  measures with the same function AutoFit used.

* test: the header AutoFit UI check measures with the app's fonts, which the app always installs
  
  The fallback to the engine's estimate never ran: SheetApp::logic installs the measure before
  AutoFit. AutoFit on the estimate is covered by the engine's autofit_filter_buttons tests.
2026-11-18 16:22:30 +07:00
FredApps 6980b00dac Merge pull request #2040 from alphazw/fix/ime-first-keystroke-bypasses-composition
IME: the first keystroke of a composition no longer lands in the cell
2026-11-18 16:22:08 +07:00
FredApps f36eaf3fbe Merge pull request #1960 from Hamza0101/checkbox-space
Space on a checkbox cell toggles it and nothing else
2026-11-18 16:21:31 +07:00
Vedran Doboš 12e1b5379b Keyboard: punctuation shortcuts follow the character the layout types (#1384) (#1385)
* Keyboard: punctuation shortcuts follow the character the layout types (#1384)
  
  On a Croatian or German keyboard Shift+, types `;`, so Excel inserts the
  date with Ctrl+Shift+,. GridCraft matched the key's US position and ran
  Decrease Font Size. Punctuation keys now go by the character typed
  (translated to the US key and Shift that type it), digits keep their
  position, and a character egui has no key for (č, ö) still falls back to
  the position. ribbon::shortcut reads the same key, so Ctrl+Shift+0
  typing `=` unhides columns instead of opening Insert, and Ctrl++ opens it.

* Keyboard: Cmd+Shift+; on a Mac doesn't insert today's date (review)
  
  ribbon::shortcut's Semicolon arm took Shift too, so the US-key mapping turned Cmd+Shift+; (and
  Cmd+Shift+. on a Croatian or German layout) into the date. Ctrl+Shift+; stays the time.

* Keyboard: tests for AZERTY and Czech, and for typing while a cell is edited (#1384)
  
  French AZERTY (`;` and `:` unshifted on the US `,` and `.` keys) and Czech (`;` on the US
  backtick key, `:` Shift+.) give the date and the time with Ctrl. The layout mapping runs only
  in the grid, which reads no shortcuts while a cell is edited; a test pins that: `;` and `:` typed
  as Shift+, and Shift+. on a Croatian or German keyboard go into the cell, and the font size stays.
2026-11-18 16:20:40 +07:00
bea2191b35 Fuzzer: undo checks follow the bounded undo history (#2332)
* Fuzzer: undo checks follow the bounded undo history

The undo history drops its oldest steps past 100 entries or 128 MB of snapshots (#1263). The
command-sequence fuzzer still compared "undo everything" with the episode's starting workbook,
so any episode whose snapshots passed the budget failed with "undoing all N steps doesn't give
back the starting workbook" although undo worked (seeds 104, 110 and 163 at 80 steps: a column
inserted next to whole-column borders, or rows deleted after filling whole columns, each made a
100 MB step).

The harness notices when an undoable command changed the workbook without the history growing,
and then compares with the state before the oldest step still in the history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fuzzer: undo and redo checks follow the reachable history boundary

Review of #2332. The harness now tracks the oldest state the undo history
can reach instead of a trimmed flag: whenever the history's oldest entry
changes without it emptying in between, the history dropped a step, and
undoing everything stops at the new oldest entry. That boundary is kept
when an edit.undo in the sequence uses up the retained history before the
episode ends, which used to fall back to the episode's start and report a
false undo mismatch.

The redo round trip no longer assumes n undos leave n redo entries: the
redo history is bounded too, so when it dropped the first step undone,
redo is expected to stop at the oldest entry it kept.

---------

Co-authored-by: nihilist-narwhal <240798405+nihilist-narwhal@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:36:17 -06:00
Neil Cawse 620174e069 Merge remote-tracking branch 'upstream/main' into fix/main-ci-csv-tests 2026-11-18 04:18:44 +00:00
Valentin KleinandClaude Opus 5.5 4c388df949 Flush a saved workbook to disk before replacing the old one (#3178)
* Flush a saved workbook to disk before the rename

write_file renamed the temporary file over the workbook without sync_all, so a power loss right after a save could leave an empty or truncated file under the workbook's name. Sync the file before the rename and, on unix, sync the folder after it (best effort).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Tolerate file systems that cannot flush when saving

On Apple targets std's sync_all asks for F_FULLFSYNC, which network mounts refuse with ENOTTY or ENOTSUP. Treat exactly those errors (and ErrorKind::Unsupported) from the temp file's sync as 'cannot flush here' and carry on with the rename, as before the flush was added. All other errors still fail the save.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Treat raw error 25 as unsupported-flush only on Unix

On Windows 25 is ERROR_SEEK, a real failure that must not be skipped.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Save: treat Apple's ENOTSUP from F_FULLFSYNC as unsupported flush

On Apple targets ENOTSUP is 45 and std leaves it uncategorized (only
EOPNOTSUPP, 102, and ENOSYS map to ErrorKind::Unsupported), so a volume
refusing F_FULLFSYNC with ENOTSUP failed the save and deleted the
temporary file. The raw code is now matched on Apple targets only;
elsewhere 45 is a different errno and stays a failed save. The check is
split into a platform-parameterised helper so each platform's codes are
tested on any host, plus an Apple-only test on the real helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-18 08:44:04 +07:00
Cheejyg 807cf23b02 Sort: Custom Sort dialog redesign (#1593)
* Sort: Custom Sort dialog redesign

* Sort: keep the dialog on its worksheet and open when sorting fails

* Improve custom sort dialog and localisation

Localise sort controls and adapt their layout to translations. Track worksheets by identity, restore selections across sheet changes, and allow additional levels to reuse columns.

* Fix sort dialog worksheet and input handling

Open Sort on the requested worksheet, reject invalid ranges, and close any open filter menu so Enter confirms the sort. Add regression tests for each case.
2026-11-18 08:43:41 +07:00
Neil Cawse 24f58a2ee4 Merge remote-tracking branch 'upstream/main' into fix/main-ci-csv-tests 2026-11-17 13:24:58 +00:00
Neil Cawse 319a3e4c2e Merge remote-tracking branch 'upstream/main' into fix/main-ci-csv-tests 2026-11-17 04:15:59 +00:00
Dylan M. Taylor d60709a173 pdf: follow up shared writer cutover with merged-library pin (#4407) 2026-11-16 22:44:24 -05:00
Dylan M. Taylor 0e5a82f084 ci: lock workflow actions through an actions.lock lockfile (#3879) 2026-11-16 21:58:36 -05:00
Dylan M. Taylor 4c943670cf pdf: move object and xref envelope writing to craft-pdf (#4398) 2026-11-16 21:58:31 -05:00
quantforge-br cf5e91ed5e Merge upstream/main into function-help-portuguese
# Conflicts:
#	docs/localization-parity.md
2026-11-16 23:13:57 -03:00
Dylan M. Taylor c8e69968c7 Merge pull request #4262 from vangel76/fix/ratex-parse-messages-i18n
Equation parse errors follow the interface language
2026-11-16 20:36:10 -05:00
Dylan M. Taylor 79742499b5 Merge pull request #3626 from vangel76/fix/i18n-hardcoded-strings
Status bar statistics, resize tips, sheet notes and macro toasts follow the interface language
2026-11-16 20:35:16 -05:00
Dylan M. Taylor d0f20a31da Merge pull request #4165 from vangel76/fix/4161-equation-fallback-font
Equation fallback text in xlsx is drawn at a normal font size
2026-11-16 20:32:51 -05:00
dotCooCoo 10506a1f1d Merge main into chore/craft-update-6e03f65 2026-11-16 17:09:15 -08:00
Dylan M. Taylor 7e4235c85b Merge pull request #4399 from storytold/dot/shared-xstring-20261117
xlsx: share SpreadsheetML string reader/writer codec (cutover stage 1)
2026-11-16 20:00:52 -05:00
Dylan M. Taylor ef87aaa590 test(xlsx): retain XML predicate for escaping oracle 2026-11-16 19:45:33 -05:00
Dylan M. Taylor 4ebc9a5127 Merge remote-tracking branch 'origin/main' into dot/shared-xstring-20261117 2026-11-16 19:44:21 -05:00
Dylan M. Taylor fc7698eb11 Merge pull request #4383 from Hamza0101/fix/table-hidden-total-row-keeps-calc
XLSX: a hidden Total Row keeps its calculations
2026-11-16 19:43:58 -05:00
Dylan M. Taylor 058ea183ec Merge pull request #4382 from Hamza0101/fix/xlsx-first-page-number
XLSX: keep Page Setup's first page number
2026-11-16 19:43:34 -05:00
Dylan M. Taylor faef1a06c8 xlsx: use shared SpreadsheetML string codec in reader and writer 2026-11-16 19:40:39 -05:00
vangel76 0c8e2f850e Merge fix/i18n-hardcoded-strings into fix/ratex-parse-messages-i18n 2026-11-16 21:55:34 +01:00
vangel76 54ebc232fb Merge upstream/main into fix/i18n-hardcoded-strings 2026-11-16 21:52:37 +01:00
Hamza 8d8716cdc0 XLSX: a hidden Total Row keeps its calculations
A table whose Total Row was turned off still holds each column's total:
Excel writes totalsRowFunction, totalsRowLabel and a custom
totalsRowFormula without totalsRowCount, and restores them when the row
is turned back on. The reader took them, but the writer wrote them only
while the row was shown, so a save lost a custom formula or an Average
and Excel brought back SUBTOTAL(109,...) instead. They are now written
whether the row is shown or not.

Fixes #4296
2026-11-16 20:10:00 +05:00
Hamza 496c13e7b4 XLSX: keep Page Setup's first page number
A sheet set to First page number 7 has pageSetup firstPageNumber="7"
useFirstPageNumber="1"; neither attribute was read, so a save reset it
to Automatic. PrintSettings now holds it (None for Automatic), the
reader takes the number when useFirstPageNumber is on, and the writer
writes both in the schema's order. A JSON workbook leaves it out when
Automatic, so existing files are written as before.

Fixes #4293
2026-11-16 20:04:07 +05:00
dotCooCoo 47b67127d5 Merge main into chore/craft-update-6e03f65 2026-11-15 17:56:30 -08:00
dotCooCoo 98bb5d6958 Merge main into chore/craft-update-6e03f65 2026-11-15 16:11:42 -08:00
quantforge-br 8a04139ef2 Calc: a spill keeps the cells it held when another array grows into them (#964)
#2483 lets a spill that already exists keep its cells, but when both
anchors held a spill, reading order decided: an array growing into a
neighbour's spill took its cells, in automatic calculation and after a
full recalculation. Excel keeps the cells the neighbour owns.

Standing now also remembers the area each anchor that held a spill
filled before the calculation. For each contested cell the anchor whose
spill held it keeps it; otherwise #2483's rules apply as before.

With the xlsx reader restoring each dynamic array's saved area, a
reopened workbook keeps its layout too, so both known limits documented
on Standing are gone. Tests now covered by #2483 are dropped, and its
grow-and-back test asserts the blocked grower.
2026-11-15 14:33:15 -03:00
quantforge-br e03780704e Merge upstream/main into fix/spill-priority 2026-11-15 14:33:09 -03:00
quantforge-br 5e692e0aba Merge upstream/main into function-help-portuguese
# Conflicts:
#	docs/localization-parity.md
2026-11-15 14:02:29 -03:00
vangel76andClaude Opus 5.5 566eeef456 Equation parse errors from RaTeX follow the interface language
RaTeX reports parse errors only as finished English text. Its fixed
messages are now catalog keys, and its messages that carry a piece of the
source are read back into templates (i18n::unfill) and filled in again
after translating. A message of any other shape stays as RaTeX wrote it.
66 new keys in all 18 catalogs.

Fixes #4261

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:26:02 +01:00
Neil Cawse 027d5d1f43 Merge remote-tracking branch 'upstream/main' into fix/main-ci-csv-tests 2026-11-14 18:05:00 +00:00
vangel76andClaude Sonnet 5.5 afd7303e48 Draw the equation plain-text stand-in at a normal size in xlsx
The text box that holds the LaTeX source (for an equation Office Math cannot
hold, and as the fallback of one it can) was written at the size the typeset
equation is drawn at, so the much wider source overflowed its frame in Excel.
It now uses 11 pt, or less when the frame itself is smaller.

Fixes #4161

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 12:56:37 +01:00
Neil Cawse 2c2699d87b Merge remote-tracking branch 'upstream/main' into fix/main-ci-csv-tests
# Conflicts:
#	crates/numfmt/src/render.rs
#	docs/function-parity.md
2026-11-13 19:44:29 +00:00
alphazw 87d2264d92 Route the first keystroke of an IME composition through the input method
When a cell wasn't in edit mode, `grid/keyboard.rs` consumed `Event::Text`
and seeded the in-cell editor with that keystroke. egui only delivers
composition events to a widget that publishes `PlatformOutput::ime` in that
frame, and only a focused `TextEdit` did so — which opens after the grid has
already handled the first key. A CJK IME therefore lost its first key: with
Wubi, typing `xta` wrote `x` into the cell and the input method only ever saw
`ta`.

The grid now publishes `IMEOutput` (egui 0.37's `IMEOutput::new`, anchored to
the active cell) on every frame it owns keyboard input, so the first key
reaches the input method. The editor is seeded from `ImeEvent::Commit`, never
from a `Preedit`; `Event::Text` still handles ASCII exactly as before. The
`context_generation` is kept in `Context` data and advances when the grid
gains IME focus. `PlatformOutput` is rebuilt each frame, so the editor's own
`TextEdit` keeps owning composition without any explicit disable.

A locked cell on a protected sheet gets no IME request: `begin_edit` refuses
those edits, so the grid applies the same merged-cell anchor and protection
check before publishing, avoiding a composition that would be discarded.
`IMEOutput` wants screen coordinates, so the cell and merged-range rectangles
are mirrored for right-to-left sheets and the caret follows the drawn cell.

Adds `tests/it/ime_composition.rs` (registered in `tests/it/main.rs`) with
eight kittest cases: the grid publishes `PlatformOutput::ime` before the first
keystroke, IME is withheld for a dialog and for locked cells but kept for
unlocked cells on a protected sheet, the right-to-left rect is mirrored, a
commit opens the editor with the committed text, a preedit alone does not, and
ASCII typing still seeds the editor. The harness allows tofu because the
suite's pinned font set has no Han face; the tests are about input routing.
2026-11-13 16:45:13 +08:00
vangel76andClaude Sonnet 5.5 c82673d9f0 Merge upstream/main into fix/i18n-hardcoded-strings
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 21:05:16 +01:00
dotCooCoo f6a75ef153 Updates: take craft-update from craft-libs main at e98299546
craft-update, craft-window and the file-format crates (craft-cfb, craft-offcrypto, craft-opc, craft-csv, craft-xls) move from bb57d422d to craft-libs main at e98299546, which includes #923: the check of whether the copy can install itself now runs on the update-check thread instead of in Updater::tick on the UI thread.
2026-11-12 09:42:40 -08:00
quantforge-br 4656391c70 Merge upstream/main into fix/spill-priority 2026-11-12 14:35:09 -03:00
dotCooCoo cb58bed1cb Merge main into chore/craft-update-6e03f65 2026-11-12 09:23:03 -08:00
dotCooCoo 71ba34f061 Updates: take craft-update from craft-libs main at 6e03f65bf 2026-11-11 09:01:44 -08:00
quantforge-br a6cb00b6a7 Merge upstream/main into fix/spill-priority
#3298 recalculates every formula when sheet protection changes
(Ctx::recalc_all), on the line where a structural edit recalculates.
A structural edit still goes through recalc_after_structural_edit; a
protection change takes recalc_all, as on main.
2026-11-11 08:10:09 -03:00
vangel76andClaude Sonnet 5.5 433602250a Merge upstream/main into fix/i18n-hardcoded-strings
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 22:00:41 +01:00
quantforge-br c8e42061fa Merge upstream/main into function-help-portuguese
# Conflicts:
#	docs/localization-parity.md
2026-11-10 13:43:43 -03:00
quantforge-br 191c3b3ff7 Merge upstream/main into function-help-portuguese
# Conflicts:
#	docs/localization-parity.md
2026-11-10 12:41:42 -03:00
quantforge-br c47bdffcd6 Calc: preserve dynamic-array kind without discarding saved spill areas (#964) 2026-11-10 09:28:58 -03:00
quantforge-br d04914bca6 Merge upstream/main into fix/spill-priority 2026-11-10 09:22:24 -03:00
quantforge-br b00e592054 Merge upstream/main into function-help-portuguese
# Conflicts:
#	docs/localization-parity.md
2026-11-10 09:16:46 -03:00
vangel76andClaude Opus 5.5 e3e03cb98e Merge upstream/main into fix/i18n-hardcoded-strings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 23:07:44 +01:00
quantforge-br 3296878d87 Merge upstream/main into function-help-portuguese
# Conflicts:
#	docs/localization-parity.md
2026-11-09 12:28:18 -03:00
Neil Cawse 56a02dcc8c Merge origin/main into fix/main-ci-csv-tests 2026-11-09 01:11:15 +00:00
vangel76andClaude Opus 5.5 a0dc48547b fix(i18n): translate the equation checks' own error messages
The equation editor translated only its "Error at character" prefix;
the checks in crates/math (macro definitions, % with a link, nesting,
length, matrix-cell and size limits, layout failure) stayed English.
Add the seven messages to all 18 catalogs and test them from the real
checks, with the expected English built from the limits. RaTeX parser
errors are open-ended text from the external crate and stay English.
The localization doc now marks its counts as a snapshot and states the
current status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 23:32:17 +01:00
vangel76andClaude Opus 5.5 c16c5865b1 fix(i18n): translate status bar statistics, resize tips, sheet notes and macro toasts
Strings that were built with format! in English now translate their
template first and fill it in once (Language::tr_fill), so a value
holding `{...}` is never filled again: status bar statistics and the
circular reference note, the column width / row height drag tip, the
formula bar text for a picture in a cell, the Move or Copy and Unhide
notes, the Format Control title, the equation editor's error prefix,
and the Goal Seek and macro recorder/runner toasts. New keys go into
every catalog.

Fixes #3600, #3602, #3603, #3605, #3607, #3608, #3609, #3610, #3611

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:38:17 +01:00
SBaksa e4e2c5292a XLSX: NETWORKDAYS.INTL and WORKDAY.INTL are saved without _xlfn. (#3517)
Both are in the file format's own function list, so a file stores them
unprefixed; LibreOffice gives #NAME? for the prefixed spelling. They are removed
from FUTURE_FUNCTIONS. A file with the prefix still reads (the parser strips it).
2026-11-08 11:24:12 +11:00
quantforge-br 113e312809 Calc: index former spill areas by 64-cell squares, not by cell, on full recalc
A crafted XLSX may declare up to 16 million dynamic-range cells per sheet, and
opening it runs a full recalculation: the former-area cell set grew with every
cell (841 MB peak, 2.4 s for 16 one-million-cell areas). The index now lists the
areas over each 64 x 64 square they cover (12 MB, 13 ms for the same sheet).
2026-11-02 16:12:40 -03:00
quantforge-br 88310f3f4d Merge upstream/main into fix/spill-priority 2026-11-02 15:39:55 -03:00
Neil Cawse d95c11b370 Merge upstream main into fix/main-ci-csv-tests 2026-11-02 00:46:06 +00:00
quantforge-br 430f53df72 Calc: former spill areas are checked through their cells, not by scanning every area 2026-10-31 17:12:33 -03:00
quantforge-br f3546f25d9 Calc: a full recalc keeps former spill areas taken until their formulas are laid out again; a structural edit doesn't 2026-10-31 16:01:49 -03:00
quantforge-br 527b884429 pt function help: FILTER keeps each row or column whose own include value is TRUE 2026-10-31 14:41:03 -03:00
quantforge-br 6c2ba27110 Calc: an array that grew into another's spill area is laid out after it on full recalc 2026-10-31 14:41:02 -03:00
quantforge-br 0925c25666 Merge remote-tracking branch 'upstream/main' into repr-fix-spill-priority
# Conflicts:
#	crates/calc/src/recalc.rs
2026-10-31 13:15:24 -03:00
quantforge-br e54cfba348 Merge remote-tracking branch 'upstream/main' into repr-function-help-portuguese 2026-10-31 13:14:01 -03:00
Neil Cawse 50e01f7646 Merge main (981fad1) into the branch 2026-10-31 12:33:28 +00:00
Neil Cawse cb4ac4d554 Merge main (1f4c67e) into the branch 2026-10-31 02:07:05 +00:00
D. Fender 0c737637e5 Merge main into fix/table-style-looks 2026-10-30 10:51:44 -07:00
Hamza 09fcfb63a7 Space on a checkbox cell toggles it and nothing else (#1951)
A space on a checkbox cell toggles it, and the same key press also arrives as
text -- and typing text starts editing the cell. So the cell toggled *and*
opened an editor holding a space, which Enter then committed over the
checkbox: the value the space had just set was replaced by a space.

A space on a checkbox cell is no longer read as text to type.

Rebased onto main, 352 commits on: the grid's keyboard handling moved from
grid.rs to grid/keyboard.rs, which already imports `is_checkbox`, so the arm
sits in front of the general text arm there. Without it the test fails on
"no editor opened" -- that is, the editor still opens.
2026-10-28 20:18:15 +05:00
D. Fender 4bc91dbc6a Tables: import what main's explicit imports now need; run table_style_looks in the it binary 2026-10-27 10:01:46 -07:00
D. Fender 2f0a986bad Merge main into fix/table-style-looks 2026-10-27 09:57:20 -07:00
Neil Cawse 65257b780c Merge main (45f5ab1) into the branch 2026-10-27 02:49:14 +00:00
Neil Cawse c0bc784197 Merge main (ad10881) into the branch 2026-10-25 21:56:37 +00:00
quantmind-br 433ef8c85d Merge remote-tracking branch 'upstream/main' into function-help-portuguese
# Conflicts:
#	ROADMAP.md
2026-10-25 11:01:39 -03:00
D. Fender f1ffb82737 Merge main into fix/table-style-looks
main (#456) moved the table style swatch's colours to theme tokens. Keep
this branch's cell-by-cell swatch, with its fallback colours taken from
the tokens (grid_bg for the background, cell_text for lines and dashes).
2026-10-24 23:01:09 -07:00
quantmind-br 9d71a809e4 Merge upstream/main into fix/spill-priority 2026-10-24 07:44:03 -03:00
quantmind-br d183fdcb5a Merge upstream/main into fix/spill-priority 2026-10-24 07:17:46 -03:00
quantmind-br c3bd68f061 Merge upstream/main into fix/spill-priority 2026-10-24 06:53:44 -03:00
quantmind-br 8ceee8ef5a Merge remote-tracking branch 'upstream/main' into function-help-portuguese
# Conflicts:
#	docs/localization-parity.md
2026-10-23 16:47:41 -03:00
D. Fender ba0009a1c3 Tables: Centre the dashes in table style swatches
Excel's gallery thumbnails draw each cell's dash across about half the
cell, centred in the space inside the cell's lines. Ours ran nearly
edge to edge and centred on the whole cell, so the dashes in the
header and last row sat a pixel toward the table's frame.

Cell edges are now on whole pixels, and each dash covers about half
the cell, centred inside the cell's own lines. As in Excel, a spare
pixel goes below the dash.
2026-10-23 11:43:58 -07:00
skylar taylor-barrick 0ee8c0d15f Merge remote-tracking branch 'origin/main' into test/backfill-regression-tests 2026-10-23 11:03:45 -06:00
D. Fender c2457bdb8c Tables: Find a table's visible edges once per paint
The grid and print checked, for every painted table cell, whether all
rows and columns between it and the table's edge were hidden. On a big
filtered table that rescans the hidden rows for every cell.

shown_edges() now finds a table's first and last visible row and
column, and the per-paint CfCache keeps it for each table. Print now
always keeps a CfCache.
2026-10-22 19:09:38 -07:00
quantmind-br cbe10f0501 Recalc: clearing an array frees its whole spill area for a blocked array
Clearing (or overwriting) a dynamic array's anchor empties its whole former
spill area, but only arrays above and left of the anchor were re-evaluated,
so an array blocked further right (F13 against C14's C14:I14) stayed
#SPILL! until the next full recalculation. Reported by iluebbe on #964.
2026-10-22 22:17:38 -03:00
MarekSpodBiedry 6535174664 XLSX: write spilled text as cached strings, not shared strings (#2285) 2026-10-22 21:02:30 +02:00
D. Fender 74f09bc672 Tables: Give each style row its own look
Table styles reused three rough templates, so every row of a family in
the Format as Table gallery looked alike. The neutral band was white
darkened about 3%, which is invisible.

Each gallery row (Light 1-7, 8-14, 15-21; Medium 1-7, 8-14, 15-21,
22-28; Dark 1-7, 8, 9-11) now has its own fills, text colours and thin
lines: header rules, row lines, a vertical grid, an outer frame or
white tile gaps, as observed in Excel's gallery. The colours are our
own theme tints. Neutral bands are now visibly grey.

One function gives each cell's look, used by the grid, print, Convert
to Range and the gallery swatches, so the swatches match the tables.
The outer frame follows hidden or filtered edge rows and columns.
Explicit cell fills, fonts and borders still win over the table's.
2026-10-22 11:44:46 -07:00
skylar taylor-barrick bc0cd89225 #1485: test that the PivotTable field-list scrollbar sits at the pane edge
#1485 let the field list take the pane's width so its scrollbar sits at the pane edge, without a test. With 14 short field names the scrollbar otherwise sits beside them, about 250 px from the edge.
2026-10-22 11:50:34 -06:00
skylar taylor-barrick 524ce912e5 #360: test that Watch Window stays inside the Formulas ribbon
#360 (#342) moved Watch Window out of a three-row column it overflowed, without a test. The test checks Watch Window's painted label ends no lower than the ribbon's last label row; as the fourth small button it ends 15 px below.
2026-10-22 11:50:34 -06:00
skylar taylor-barrick ebc986fcc9 #223: test that the title bar's Save includes the cell being typed
#223 made the title bar's Save button (and the Save Changes dialog's) commit the cell edit before saving, without a test for the button. The test types into A1, clicks Save, and reads the saved file back; with the commit_edit call removed it fails because the file lacks the value.
2026-10-22 11:50:34 -06:00
quantmind-br 66c82e0fd2 Merge remote-tracking branch 'upstream/main' into function-help-portuguese
# Conflicts:
#	ROADMAP.md
#	crates/ui-egui/src/i18n.rs
#	docs/localization-parity.md
2026-10-22 02:28:29 -03:00
quantmind-br c0db2ca597 Merge remote-tracking branch 'upstream/main' into fix/spill-priority
# Conflicts:
#	ROADMAP.md
#	crates/calc/src/tests.rs
2026-10-22 02:28:00 -03:00
Neil Cawse 77cfbda1bc docs: order parity revision history 2026-10-22 05:18:54 +00:00
Neil Cawse f8c4dac15b Merge main (06920de) into the branch 2026-10-22 05:11:38 +00:00
quantmind-br 9f3c04e9ca Merge remote-tracking branch 'origin/function-help' into function-help-portuguese 2026-10-20 08:34:15 -03:00
Cursor AgentandCRBBeesy d0033570df xtask: parity --check accepts a CRLF checkout of the checklist
On Windows with Git's default `core.autocrlf=true` (Git for Windows, GitHub's
`windows-latest` image), `docs/parity-checklist.md` is checked out with CRLF line
ends. `parity --check` compared it byte for byte with the generated text (LF), so
`cargo xtask ci` stopped at `parity` with "out of date" although the file was
current. Line ends are no longer a difference; any other change still is.

Co-authored-by: CRBBeesy <CRBBeesy@users.noreply.github.com>
2026-10-20 03:56:00 +00:00
Neil Cawse 3d19fa43f6 docs: restore the XLSX right-to-left text box row lost in the main merge 2026-10-20 03:14:18 +00:00
Neil Cawse 42d3e9adbb Merge main (23829d8) into the branch
# Conflicts:
#	docs/file-format-parity.md
2026-10-20 01:45:12 +00:00
quantmind-br dd598ba705 Merge remote-tracking branch 'origin/function-help' into function-help-portuguese
# Conflicts:
#	docs/localization-parity.md
2026-10-19 14:06:20 -03:00
Neil Cawse b0c3d8eb3b Merge main (c30fa3f) into the branch 2026-10-18 03:22:52 +00:00
Neil Cawse f410a770c1 Merge main (19f4387) into the branch 2026-10-18 00:49:17 +00:00
Neil Cawse 44526f0d2b Merge main (f1894c6) into the branch 2026-10-17 01:23:08 +00:00
quantmind-br ffe73b3bd7 UI: Brazilian Portuguese function help
Português (Brasil) translates every worksheet function description (479)
and argument name (283) in i18n/pt_functions.rs, so the argument hint,
autocomplete and Insert Function read in Portuguese. The translation is
clean-room (not Excel's text) and still needs a native review.
2026-10-15 10:49:49 -03:00
Local contributor 9cbbaaeaed Docs: CSV export wording matches the code; inferred & boundaries marked
From 1E+15, CSV export writes the shortest round-trip digits, not &'s 15 digits.
'Every digit' now applies only to integers below 1e16.

The open/save round-trip claim is narrowed to files GridCraft wrote. The doc
now lists what a foreign CSV loses on its first save: 16-17-digit decimals are
cut to 15 digits, and scientific input is rounded to its 0.00E+00 format.

The 21-character switch is Excel-verified only for positive 15-digit
mantissas. Shorter mantissas from 1E-6 to 1E-9 and negatives are marked as
inferred, and the doc states the sign isn't counted. The function-parity
'was' value is corrected to main's 0.00000001.
2026-10-14 13:51:54 -04:00
Local contributor bf9b3cb9b1 CSV/text export: integers below 1e16 keep every digit; no exponents
The 2^53 cutoff turned exact 16-digit integers (9007199254740992, 9007199254740994) into
9.00719925474099E+15. A General number is now written with &'s 15 digits but never with an
exponent: reopening a CSV gives a scientific number a 0.00E+00 format that rounds it on the next
save. 1E+15 and up are written as the shortest round-trip digits (every integer below 1e16
exactly, main's output above), small numbers as their 15 digits in full.
2026-10-14 12:59:37 -04:00
Local contributor 6ff543ce76 Values: number text switches to scientific past 21 characters below 1, as Excel
Excel caches IMCSCH("13+5j") as 1.28233995888454E-06 and IMSECH("7+25j")'s imaginary part as
0.000241377759972715: below 1, a 15-digit decimal longer than 21 characters is written in
scientific notation. 9.99999999999999E-9&"" now gives 9.99999999999999E-09, not
0.00000000999999999999999. Affects every number-to-text conversion (&, CONCAT, TEXTJOIN, IM
functions, formula printing, labels).
2026-10-14 12:59:37 -04:00
Local contributor 4dd4ff9a93 CSV/text export: integers below 2^53 keep every digit
Writing every General number as & converts it rounded 16-digit integers such as card and order numbers to 1.23456789012346E+15, so opening a CSV and saving it again changed the data. Integers that f64 holds exactly (|x| < 2^53) are now written with all their digits, as before; larger integers and non-integers keep the 15-significant-digit & text.
2026-10-14 08:23:36 -04:00
Local contributor 9331dbb474 Values: number text rounds to 15 digits before choosing decimal or scientific
number_to_text picked the decimal branch for values in [999999999999999.5, 1e15) and then rounded them up to the 16-digit integer 1000000000000000. It now rounds to 15 significant digits first and chooses the notation from the rounded exponent, so those values read 1E+15 (and -1E+15).
2026-10-14 08:23:36 -04:00
neilcawse a6d70bcafb CSV/text export: every General number as & converts it (15 significant digits)
Main writes plain General with Rust's shortest round-trip (0.30000000000000004,
100000000000000000000) and still narrows coloured/sectioned General and numbers in
Text cells to the 11-character cell display (1.24412E+11). Export now formats through
numfmt's format_value_full, which writes General as number_to_text does, replacing
io.rs's plain-General special case. Docs: merge the duplicate CSV/text rows.
2026-10-13 13:14:06 -04:00
quantmind-br 28a645ca13 Calc: a contested spill area stays with its array on full recalc and reopening (#964)
When two dynamic arrays want the same cells, the one already spilling there keeps them and
the newcomer is #SPILL!, as when the second is entered. recalc_all remembers the layout it
clears (formulas that spilled, formulas that were #SPILL!) and lays arrays out in that order,
then in reading order. The XLSX reader restores a dynamic array's saved `ref` as its spill
range, because the file can only cache #VALUE! for a blocked array.

Found by the command-sequence fuzz.
2026-10-13 08:00:40 -03:00
135 changed files with 9611 additions and 1543 deletions
+29
View File
@@ -0,0 +1,29 @@
# This file is machine-generated by `gh actions-lock`.
# Do not edit by hand; run `gh actions-lock` to update.
# Docs: https://gh.io/actions-lockfile
version: 'v0.0.3'
workflows:
'.github/workflows/ci.yml': []
'.github/workflows/freebsd.yml': []
'.github/workflows/house-rules.yml': []
'.github/workflows/lockfile.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/nix.yml': []
'.github/workflows/packaging-lint.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/release.yml': []
'.github/workflows/sonarcloud.yml': []
'.github/workflows/windows-arm64.yml': []
dependencies:
'actions/checkout@v7.0.1':
ref: 'v7.0.1'
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
owner_id: 44036562
repo_id: 197814629
'step-security/harden-runner@v2.22.4':
ref: 'v2.22.4'
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
owner_id: 88700172
repo_id: 422287306
+34
View File
@@ -0,0 +1,34 @@
name: Lockfile
# Fails when .github/workflows/actions.lock is out of sync with the workflows, or when a locked pin
# no longer verifies upstream, so a moved tag cannot slip a different commit into a run.
# Docs: https://gh.io/actions-lockfile
on:
pull_request:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
env:
GH_TOKEN: ${{ github.token }}
jobs:
lockfile:
name: Lockfile is in sync
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Install gh-actions-lock
run: gh extension install github/gh-actions-lock --pin v0.4.1
- name: Verify the lockfile
run: gh actions-lock --verify
+2 -2
View File
@@ -28,10 +28,10 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Install the pinned packaging toolchain
Generated
+118 -25
View File
@@ -922,12 +922,17 @@ dependencies = [
[[package]]
name = "craft-cfb"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e"
[[package]]
name = "craft-cfb"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
[[package]]
name = "craft-csv"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
dependencies = [
"thiserror 2.0.21",
]
@@ -935,9 +940,20 @@ dependencies = [
[[package]]
name = "craft-drawingml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e"
dependencies = [
"craft-xml",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)",
"kurbo",
"log",
"serde",
]
[[package]]
name = "craft-drawingml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
dependencies = [
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"kurbo",
"log",
"serde",
@@ -982,14 +998,43 @@ dependencies = [
]
[[package]]
name = "craft-offcrypto"
name = "craft-odf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"aes",
"base64 0.23.1",
"craft-cfb",
"craft-xml",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"flate2",
"getrandom 0.3.4",
"hmac",
"sha1 0.11.0",
"sha2 0.11.1",
"thiserror 2.0.21",
"zeroize",
]
[[package]]
name = "craft-ods"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"craft-odf",
"craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"thiserror 2.0.21",
]
[[package]]
name = "craft-offcrypto"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
dependencies = [
"aes",
"base64 0.23.1",
"craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"getrandom 0.3.4",
"hmac",
"sha1 0.11.0",
@@ -1001,14 +1046,19 @@ dependencies = [
[[package]]
name = "craft-opc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
dependencies = [
"craft-xml",
"craft-zip",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"log",
"thiserror 2.0.21",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd#ff142b3ad58aa7306676749428f4f2f9b277b5dd"
[[package]]
name = "craft-print"
version = "0.1.0"
@@ -1026,7 +1076,17 @@ dependencies = [
[[package]]
name = "craft-sheet"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
[[package]]
name = "craft-sheet"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e"
[[package]]
name = "craft-sheet"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
[[package]]
name = "craft-stream-codecs"
@@ -1062,7 +1122,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
dependencies = [
"chrono",
"dunce",
@@ -1109,7 +1169,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
dependencies = [
"egui",
"objc2 0.6.5",
@@ -1128,10 +1188,10 @@ dependencies = [
[[package]]
name = "craft-xls"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e"
dependencies = [
"craft-cfb",
"craft-sheet",
"craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)",
"craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)",
"md-5",
"miniz_oxide 0.9.1",
"sha1 0.10.7",
@@ -1141,19 +1201,39 @@ dependencies = [
[[package]]
name = "craft-xlsx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
dependencies = [
"craft-drawingml",
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"craft-opc",
"craft-sheet",
"craft-xml",
"craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
dependencies = [
"quick-xml 0.41.0",
"thiserror 2.0.21",
@@ -1162,7 +1242,17 @@ dependencies = [
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"flate2",
"thiserror 2.0.21",
"zip 9.1.0",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -2329,6 +2419,7 @@ dependencies = [
name = "gridcraft-pdf"
version = "0.19.1"
dependencies = [
"craft-pdf",
"craft-stream-codecs",
"harfrust",
"sha2 0.11.1",
@@ -2397,13 +2488,15 @@ dependencies = [
name = "gridcraft-xlsx"
version = "0.19.1"
dependencies = [
"craft-cfb",
"craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"craft-csv",
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)",
"craft-ods",
"craft-offcrypto",
"craft-opc",
"craft-xls",
"craft-xlsx",
"craft-xml",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"gridcraft-core",
"gridcraft-formula",
"gridcraft-functions",
+13 -9
View File
@@ -30,23 +30,27 @@ 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 = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "=0.1.0", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "=0.1.0", features = ["egui"] }
# PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers.
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ff142b3ad58aa7306676749428f4f2f9b277b5dd", version = "0.1.0", default-features = false }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f7e0d7fd5577e102b4634bcbe062e649eb68165f", version = "0.1.0" }
# Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]).
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
# OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`.
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", 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 = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", 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" }
# Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model.
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
# SpreadsheetML string encoding/decoding; workbook model mapping stays in gridcraft-xlsx.
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", 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 = "3b8e426a260695af840a2cd79a064d40778f939e", version = "0.1.0" }
# foundation
thiserror = "2"
@@ -86,7 +90,7 @@ skrifa = { version = "0.44", default-features = false, features = ["std"] }
epaint_default_fonts = "0.37"
# One native window per workbook: the window list, Window menu titles and the immediate-viewport
# driver. Same craft-libs revision as craft-update above.
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", default-features = false, features = ["egui"] }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", default-features = false, features = ["egui"] }
[workspace.lints.rust]
unsafe_code = "forbid"
+8 -1
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped) · **Target:** Microsoft Excel (Microsoft 365)
GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX
@@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| Date | What landed |
|---|---|
| 2026-11-16 | A selected chart outlines its data as Excel does (series names red, category labels purple, values one blue block), and dragging a corner of the values outline changes the cells the chart plots: series keep their formatting, a wider block adds series, aligned names and labels follow, one undo step, Esc cancels; `chart.setValuesRange` does the same for scripts, the CLI and MCP (#4389, #4390) |
| 2026-11-06 | A sheet keeps its own scroll position when sheets are inserted, deleted or moved before it: a new PivotTable or inserted sheet opens at the top instead of where its neighbour was scrolled; a closed window's positions are let go (#3485) |
| 2026-11-02 | Form controls: Insert › Controls places buttons, sliders (scroll bars) and spin buttons on the sheet. A slider or spin button holds a whole number from 0 to 30000 in a linked cell (a drag or a held arrow is one undo step, and editing the cell moves the control); a button runs a macro or one command through the macro policy, asking first in a workbook opened from a file; Assign Action and Format Control edit them, and XLSX files read and write them (control properties, `<controls>` and VML), alongside the form controls GridCraft keeps unchanged |
| 2026-11-02 | Dialogs take ranges by selection on the grid: reference boxes (RefEdit) with a collapse button that shrinks the dialog while the person selects, in Goal Seek, Solver (including the Model Range of Load/Save) and Data Analysis; while collapsed, the arrow keys move the selection and Shift+arrow extends it, and F4 cycles a reference's anchors |
@@ -177,14 +178,17 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-19 | Long flat operator chains (`=A1+A2+…`) up to Excel's 8,192-character limit (4,096 operands): entering, filling, inserting rows, undo, Evaluate Formula and XLSX save no longer overflow the stack; chains past 64 operands are saved as plain formulas, not dynamic arrays; Spanish formula entry accepts chains past 256 operands (#916) |
| 2026-10-19 | Linux: "Use system setting" for the theme keeps following the desktop when the XDG Desktop Portal stops answering: each read gives up after 2 s and the next poll reconnects, where one unanswered call stalled the watcher for the rest of the session |
| 2026-10-16 | Memory: undo steps share a sheet's picture bytes and the workbook's VBA project instead of copying them: 50 edits on a sheet with a 20 MB picture keep 22 MB instead of 992 MB |
| 2026-10-16 | Custom Sort dialog: header-named column dropdowns, smart Order labels, add/delete/copy/move levels, resizable window, selection follows the headers checkbox and returns on close; a selected block (such as a table's totals row) is sorted as selected |
| 2026-10-16 | Memory: floating pictures are decoded at about the size they are drawn, with limits, into a cache bounded by bytes and dropped with their workbook, instead of at full size into one that never let go; two open workbooks no longer show each other's picture. 12 large pictures scrolled through keep 40 MB of textures instead of 258 MB, and none once the workbook closes |
| 2026-10-16 | The web app keeps its preferences between visits (#1562): theme (dark mode), interface size, language, editing options and the rest of what the desktop app saves in `ui.json` and `prefs.json` are kept in the browser's `localStorage`, written as soon as they change |
| 2026-10-16 | Memory: the interface and script fallback fonts are read once per run and shared with egui instead of copied into it: an empty workbook settles at 158 MB instead of 258 MB on macOS |
| 2026-10-15 | Function help in Brazilian Portuguese: every description and argument name (479 and 283) |
| 2026-10-15 | File › Options › Formulas: Maximum Iterations and Maximum Change fields for iterative calculation, disabled while it is off, with Excel's limits (1 to 32767, 0 or more) |
| 2026-10-15 | Function help follows the interface language: argument hints, autocomplete, Insert Function (search and readable categories) and the Formulas-tab menus read per-language tables of descriptions and argument names; Spanish keeps its 10 functions in the new format |
| 2026-10-15 | Row auto-fit counts a cell's line breaks only when the cell wraps, as Excel does: a file whose unwrapped cells hold multi-line text no longer opens with tall rows (typing a break still turns wrap on and grows the row) |
| 2026-10-14 | Set precision as displayed is applied: with the option on, formula results, spills and numbers typed or reformatted are stored as their number format shows them and formulas calculate from those values; `formulas.calculationOptions` gains `precisionAsDisplayed` (turning it on rounds existing constants; locked constants on a protected sheet keep their value; numbers written to a new sheet are rounded too) (#1343) |
| 2026-10-14 | Lookups (MATCH, XMATCH, VLOOKUP, HLOOKUP, XLOOKUP, LOOKUP) compare numbers exactly like Excel, so a computed key such as `=0.1+0.2` no longer finds 0.3; `=` and COUNTIF/SUMIF keep their 15-digit comparison |
| 2026-10-14 | RATE matches Excel's solver: the same last iterate for slowly converging cases (about -100% when the future value is 0, instead of `#NUM!`) and `#NUM!` where Excel's iteration can't reach a very large rate |
| 2026-10-14 | Functions: EOMONTH, EDATE, WORKDAY, NETWORKDAYS, YEARFRAC, WEEKNUM, the bond and coupon functions, DISC, BIN2DEC, IM* and the other Analysis ToolPak functions give `#VALUE!` for a reference to more than one cell in a value argument, as Excel 365 does, instead of spilling; array constants and computed arrays still lift |
| 2026-10-14 | Protect Sheet on a protected sheet: Home › Format, its keytips (HOP, RPS) and the tab menu now read Unprotect Sheet… and unprotect (straight away without a password); a protected sheet that forbids selecting locked (or unlocked) cells is enforced for clicks, arrows and Go To, and the Protect Sheet dialog has the select options (#1346) |
| 2026-10-14 | `.xls` (Excel 97-2003) files open with their formatting: fonts, solid and pattern fills, borders (with diagonals), alignment (rotation, indent, wrap, shrink), locked and hidden cells, the workbook's custom colour palette, its Normal font and its user-defined cell styles |
@@ -201,6 +205,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-13 | XLSX export writes a picture used on several sheets once, as one `xl/media` part every drawing points to (it wrote a copy per drawing: a 16-sheet workbook with one 112 KB logo grew from 0.4 to 1.9 MB) (#985) |
| 2026-10-13 | XLSX: `[Content_Types].xml`, `_rels/.rels`, the workbook rels and `xl/workbook.xml` are the first zip entries (document properties last), so libmagic and PHP `finfo` detect the file type even with large properties (#1090) |
| 2026-10-13 | Conditional formatting: a rule gathers range statistics only when it reads them (top/bottom, above average, duplicates, scales, bars, icons) and borrows them instead of copying them per cell, so the per-frame lookup of an expression or cell-value rule no longer visits its whole range (#1098, part 1) |
| 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 | GETPIVOTDATA reads PivotTable values by field and items (#284) |
@@ -274,6 +279,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| Date | Change | Summary |
|---|---|---|
| 2026-11-16 | minor | Progress log: chart data outline in three colours, dragged from its corners (#4389, #4390) |
| 2026-11-06 | trivial | Progress log: scroll positions follow their sheet through sheet inserts, deletes and moves (#3485) |
| 2026-11-05 | minor | Reconcile upstream form-control progress with the CJK baseline update |
| 2026-11-02 | minor | Form controls; catalog 277 / 292 → 281 / 296 (Developer › Controls); progress log row |
@@ -318,6 +324,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-14 | minor | XLSX dynamic-array `cm` metadata kept on save; progress log row |
| 2026-10-14 | minor | Progress log: spill anchor reading its old spill area |
| 2026-10-14 | minor | Progress log: formulas reading an array that loses a spill conflict |
| 2026-10-14 | trivial | Progress log: RATE follows Excel's iteration |
| 2026-10-13 | trivial | Progress log: More Colors… and Recent Colors in the colour menus (#928) |
| 2026-10-13 | minor | Multi-level category axes (read, drawn, written); progress log row |
| 2026-10-13 | trivial | Progress log: shared pictures written once on XLSX export (#985) |
+56 -26
View File
@@ -12,10 +12,10 @@
//! - `gridcraft:open` (from the host): `{ name, bytes }`. It opens like a workbook picked with
//! File › Open or dropped on the window; a file over [`MAX_OPEN_BYTES`] is refused before it is
//! copied.
//! - `gridcraft:save` (to the host): `{ name, saveAs, bytes }` for every file GridCraft would
//! otherwise download: Save and Save As (an .xlsx workbook) and Export as PDF. The host stores
//! it and reports failures itself. GridCraft doesn't tell the host which saves make a file the
//! document, so `saveAs` is always `false`.
//! - `gridcraft:save` (to the host): `{ name, saveAs, bytes, export }` for every file GridCraft
//! would otherwise download. With `export: false`, the host stores the XLSX workbook; with
//! `export: true`, it stores a separate file (such as a PDF) without replacing the workbook.
//! `saveAs` remains `false`; it does not distinguish Save from Save As here.
//! - `gridcraft:dirty` whenever unsaved changes appear or go away, `gridcraft:failed` when the
//! app couldn't start.
//!
@@ -27,16 +27,16 @@ use std::cell::RefCell;
use std::rc::Rc;
use craft_web_host::web::{FileData, Host, Message};
use craft_web_host::{Mode, Outgoing, file_name, message_type};
use gridcraft_ui_egui::{Inbox, Services, SheetApp};
use wasm_bindgen::JsValue;
use crate::host_save::{SaveMessage, sync_saved};
use crate::hostmode::open_name;
/// The app id in the host messages (`gridcraft:ready`).
const APP: &str = "gridcraft";
/// Saved files that count as a workbook: the document is then clean under the name it was saved as.
const WORKBOOK_EXTS: &[&str] = &["xlsx"];
/// The largest workbook taken from the host page, refused before it is copied.
const MAX_OPEN_BYTES: u64 = 512 << 20;
@@ -46,6 +46,7 @@ const MAX_AUTHOR_CHARS: usize = 200;
#[derive(Clone)]
pub struct Bridge {
host: Rc<Host>,
save_target: Rc<SaveTarget>,
/// Names of the files handed to the host since the last frame.
saved: Rc<RefCell<Vec<String>>>,
}
@@ -55,7 +56,19 @@ impl Bridge {
/// `data-host="page"` on the canvas, an unframed `?host=parent` page (it stays the normal app
/// with downloads), or a parent on another origin.
pub fn detect(canvas: &web_sys::HtmlCanvasElement) -> Option<Self> {
Some(Self { host: Rc::new(Host::connect(APP, canvas)?), saved: Rc::default() })
let host = Host::connect(APP, canvas)?;
let save_target = match host.mode() {
Mode::Parent => {
// Host::connect already admitted only a same-origin parent. Keep that origin
// as the postMessage target so later navigation can't receive workbook bytes.
let window = web_sys::window()?;
let parent = window.parent().ok().flatten()?;
let origin = window.location().origin().ok()?;
SaveTarget::Parent { parent, origin }
}
Mode::Page => SaveTarget::Page(canvas.clone()),
};
Some(Self { host: Rc::new(host), save_target: Rc::new(save_target), saved: Rc::default() })
}
/// Send saved and exported files to the host instead of downloading them, and hear files
@@ -91,20 +104,13 @@ impl Bridge {
/// crate does not repeat a state it already reported).
pub fn sync(&self, app: &mut SheetApp) {
let saved = std::mem::take(&mut *self.saved.borrow_mut());
if let Some(name) = saved.iter().rev().find(|name| is_workbook(name))
&& let Some(doc) = app.session.active_mut()
{
doc.saved = doc.wb.clone();
if doc.path.is_none() {
doc.title = name.clone();
}
}
sync_saved(&saved, app);
self.host.post_dirty(app.session.documents().iter().any(|d| d.is_dirty()));
}
fn post_save(&self, path: &str, bytes: &[u8]) -> Result<(), String> {
let name = file_name(path);
self.host.post_save(&name, bytes, None, false)?;
let name = file_name(Some(path), "document");
self.save_target.post(SaveMessage::new(&name, bytes)).map_err(|e| e.as_string().unwrap_or_else(|| format!("{e:?}")))?;
self.saved.borrow_mut().push(name);
Ok(())
}
@@ -118,6 +124,38 @@ impl Bridge {
}
}
/// A save-only adapter: the pinned host crate's `post_save` cannot add app-specific fields.
/// All other messages and transport detection still go through `Host`.
enum SaveTarget {
Parent { parent: web_sys::Window, origin: String },
Page(web_sys::HtmlCanvasElement),
}
impl SaveTarget {
fn post(&self, save: SaveMessage<'_>) -> Result<(), JsValue> {
let buffer = js_sys::Uint8Array::from(save.bytes).buffer();
let kind = message_type(APP, Outgoing::Save.kind());
let payload = js_sys::Object::new();
let set = |key, value: JsValue| js_sys::Reflect::set(&payload, &JsValue::from_str(key), &value);
set("name", save.name.into())?;
set("bytes", buffer.clone().into())?;
set("saveAs", JsValue::FALSE)?;
set("export", JsValue::from_bool(save.export))?;
match self {
Self::Parent { parent, origin } => {
set("type", kind.as_str().into())?;
parent.post_message_with_transfer(&payload, origin, &js_sys::Array::of1(&buffer))
}
Self::Page(canvas) => {
let init = web_sys::CustomEventInit::new();
init.set_detail(&payload.into());
let event = web_sys::CustomEvent::new_with_event_init_dict(&kind, &init)?;
canvas.dispatch_event(&event).map(|_| ())
}
}
}
}
/// The file an open message carries, pushed onto the inbox for the next frame, like a dropped
/// file. A host's file is untrusted input: an oversized one is refused before it is copied into
/// the app's memory (the data's own length, not the host's claim).
@@ -133,11 +171,3 @@ fn deliver_open(inbox: &Inbox, ctx: &egui::Context, name: &str, data: &FileData)
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((open_name(name), array.to_vec()));
ctx.request_repaint();
}
fn is_workbook(name: &str) -> bool {
name.rsplit_once('.').is_some_and(|(_, ext)| WORKBOOK_EXTS.iter().any(|e| ext.eq_ignore_ascii_case(e)))
}
fn file_name(path: &str) -> String {
std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string())
}
+104
View File
@@ -0,0 +1,104 @@
//! Host save payloads and workbook receipts, shared with native regression tests.
use gridcraft_ui_egui::SheetApp;
/// Only these outputs replace the editable workbook in the host.
const WORKBOOK_EXTS: &[&str] = &["xlsx"];
pub struct SaveMessage<'a> {
pub name: &'a str,
pub bytes: &'a [u8],
pub export: bool,
}
impl<'a> SaveMessage<'a> {
pub fn new(name: &'a str, bytes: &'a [u8]) -> Self {
// All other outputs are exports, not necessarily PDFs.
Self { name, bytes, export: !is_workbook(name) }
}
}
fn is_workbook(name: &str) -> bool {
name.rsplit_once('.').is_some_and(|(_, ext)| WORKBOOK_EXTS.iter().any(|e| ext.eq_ignore_ascii_case(e)))
}
/// Preserve the bridge's existing rule: only a workbook receipt marks the document saved.
pub fn sync_saved(saved: &[String], app: &mut SheetApp) {
if let Some(name) = saved.iter().rev().find(|name| is_workbook(name))
&& let Some(doc) = app.session.active_mut()
{
doc.saved = doc.wb.clone();
if doc.path.is_none() {
doc.title = name.clone();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use gridcraft_engine::Session;
use serde_json::json;
use std::sync::Arc;
#[test]
fn save_payload_marks_exports_and_preserves_name_and_bytes() {
let bytes = [0, 1, 127, 128, 255];
for (name, export) in [("finance.xlsx", false), ("finance.XLSX", false), ("finance.pdf", true), ("finance.PDF", true)] {
let message = SaveMessage::new(name, &bytes);
assert_eq!(message.export, export, "{name}");
assert_eq!(message.name, name);
assert_eq!(message.bytes, bytes.as_slice());
assert_eq!(message.bytes.as_ptr(), bytes.as_ptr(), "the payload borrows the original bytes");
}
}
#[test]
fn other_outputs_are_exports_not_workbook_saves() {
for name in ["finance.csv", "finance.bin", "finance", "finance.xlsx.pdf", "finance.xlsx.bak"] {
assert!(SaveMessage::new(name, &[]).export, "{name}");
}
assert!(!SaveMessage::new("finance.pdf.xlsx", &[]).export);
}
fn edited_app() -> Result<SheetApp, String> {
let mut session = Session::new();
session.new_workbook();
session.execute("cell.set", json!({"cell": "A1", "input": "42"})).map_err(|e| e.to_string())?;
Ok(SheetApp::new(session, Default::default()))
}
#[test]
fn pdf_receipts_leave_the_workbook_dirty_and_its_title_unchanged() -> Result<(), String> {
for name in ["finance.pdf", "finance.PDF"] {
let mut app = edited_app()?;
let doc = app.session.active().ok_or("no active document")?;
assert!(doc.is_dirty());
let title = doc.title.clone();
let saved = doc.saved.clone();
sync_saved(&[name.to_string()], &mut app);
let doc = app.session.active().ok_or("no active document")?;
assert!(doc.is_dirty(), "{name}");
assert!(Arc::ptr_eq(&saved, &doc.saved), "an export must not replace the saved snapshot");
assert_eq!(doc.title, title);
}
Ok(())
}
#[test]
fn workbook_receipts_mark_saved_and_later_exports_do_not_replace_them() -> Result<(), String> {
for name in ["finance.xlsx", "finance.XLSX"] {
let mut app = edited_app()?;
assert!(app.session.active().ok_or("no active document")?.is_dirty());
sync_saved(&[name.to_string(), "finance.pdf".to_string()], &mut app);
let doc = app.session.active().ok_or("no active document")?;
assert!(!doc.is_dirty());
assert!(Arc::ptr_eq(&doc.saved, &doc.wb));
assert_eq!(doc.title, name);
app.session.execute("cell.set", json!({"cell": "A1", "input": "43"})).map_err(|e| e.to_string())?;
sync_saved(&["finance.PDF".to_string()], &mut app);
assert!(app.session.active().ok_or("no active document")?.is_dirty(), "a subsequent export leaves new edits unsaved");
}
Ok(())
}
}
+2
View File
@@ -26,6 +26,8 @@ mod api;
#[cfg(target_arch = "wasm32")]
mod host;
#[cfg(any(target_arch = "wasm32", test))]
mod host_save;
#[cfg(any(target_arch = "wasm32", test))]
mod hostmode;
#[cfg(any(target_arch = "wasm32", test))]
mod prefs;
-3
View File
@@ -25,9 +25,6 @@ chrono = { workspace = true }
# Icon + VERSIONINFO for gridcraft.exe; build.rs only uses it when the target is Windows.
winresource = "0.1"
[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))'.dependencies]
winit = { version = "0.30", default-features = false, features = ["x11"] }
[target.'cfg(target_os = "linux")'.dependencies]
# Retain X11 fallback; draw Wayland client-side controls without bundled title fonts.
winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] }
+11 -20
View File
@@ -17,6 +17,7 @@ mod graphics;
mod logging;
#[cfg(target_os = "macos")]
mod native_menu;
mod opener;
mod print;
use std::cell::RefCell;
@@ -218,16 +219,16 @@ fn open_with_system(target: &str) {
log::warn!("refused to open {target:?}: only http, https and mailto links are opened");
return;
};
let target = target.as_str();
let cmd = if cfg!(target_os = "macos") {
"open"
} else if cfg!(windows) {
"explorer"
} else {
"xdg-open"
// By absolute path where the platform has one (#2176): a bare `explorer` would be looked up
// in the application's directory first.
let env = |key: &str| std::env::var(key).ok();
let (system_root, windir) = (env("SystemRoot"), env("windir"));
let Some((program, arg)) = opener::opener_command(opener::Os::current(), &target, system_root.as_deref(), windir.as_deref()) else {
log::warn!("refused to open {target:?}: it could be read as an option");
return;
};
if let Err(e) = std::process::Command::new(cmd).arg(target).spawn() {
log::warn!("{cmd} {target}: {e}");
if let Err(e) = std::process::Command::new(&program).arg(&arg).spawn() {
log::warn!("{} {arg}: {e}", program.display());
}
}
@@ -358,21 +359,11 @@ fn main() -> eframe::Result<()> {
}
let window_builder = viewport.clone();
let options = eframe::NativeOptions { viewport, ..Default::default() };
#[cfg(unix)]
#[cfg(target_os = "macos")]
let mut options = options;
// Intel Macs: Metal's compiler aborts on wgpu's indirect-validation shaders (see graphics.rs).
#[cfg(target_os = "macos")]
graphics::configure_indirect_validation(&mut options, graphics::skips_indirect_validation(true, cfg!(target_arch = "x86_64")));
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
// manager showed a "no" cursor. Run through XWayland when it's there; GRIDCRAFT_WAYLAND=1
// keeps the native Wayland backend.
#[cfg(all(unix, not(target_os = "macos")))]
if std::env::var_os("DISPLAY").is_some_and(|d| !d.is_empty()) && std::env::var_os("GRIDCRAFT_WAYLAND").is_none() {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
}));
}
// Before eframe creates the wgpu instance: Windows starts on DirectX 12, or OpenGL when
// DirectX 12 has no GPU driver, and never touches Vulkan unless asked (see graphics.rs).
#[cfg(target_os = "windows")]
+151
View File
@@ -0,0 +1,151 @@
//! How a link is handed to the operating system's opener (#2176).
//!
//! The opener is spawned by absolute path where the platform has a fixed one: a bare program name
//! on Windows is searched for in the application's own directory (and the current directory)
//! before System32 and the Windows directory, so an `explorer.exe` planted next to a portable
//! GridCraft would run with the user's session. The target never becomes an option of the opener,
//! and on Windows the characters Explorer's own command-line parser treats specially are
//! percent-encoded. Pure functions, so the tests run on every OS.
use std::path::PathBuf;
/// Whose opener to use.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Os {
Mac,
Windows,
/// Linux, the BSDs and other freedesktop systems: `xdg-open`.
Other,
}
impl Os {
pub fn current() -> Os {
if cfg!(target_os = "macos") {
Os::Mac
} else if cfg!(windows) {
Os::Windows
} else {
Os::Other
}
}
}
/// Used when neither `SystemRoot` nor `windir` holds a usable path.
const DEFAULT_WINDOWS_DIR: &str = "C:\\Windows";
/// The Windows directory: `SystemRoot`, else `windir`, else `C:\Windows`. A value is used only
/// when it is a local drive path (`X:\…`) without `..` segments; relative or network values
/// would bring back the search this exists to avoid.
pub fn windows_dir(system_root: Option<&str>, windir: Option<&str>) -> String {
[system_root, windir]
.into_iter()
.flatten()
.map(str::trim)
.find(|d| is_local_drive_path(d))
.map_or(DEFAULT_WINDOWS_DIR, |d| d.trim_end_matches(['\\', '/']))
.to_string()
}
/// `X:\…` or `X:/…` (not the drive-relative `X:` or `X:dir`), with no `..` segment and no quote.
fn is_local_drive_path(d: &str) -> bool {
let mut chars = d.chars();
let drive = chars.next().is_some_and(|c| c.is_ascii_alphabetic()) && chars.next() == Some(':');
let rest = chars.as_str();
let rooted = rest.starts_with(['\\', '/']);
drive && rooted && !d.contains('"') && !rest.split(['\\', '/']).any(|seg| seg == "..")
}
/// Percent-encodes the characters Explorer's command-line parser (comma-separated switches such
/// as `/select,`), the C runtime's quoting rules and `cmd` treat specially: space, `"`, `,` and
/// `^`. Space, `"` and `^` may not appear unencoded in a URL, so encoding them leaves the address
/// unchanged. A comma may, and RFC 3986 does not treat `%2C` as equivalent to it (a `mailto:`
/// recipient list is comma-separated); it is encoded anyway because Explorer's parser separates
/// switches at commas, and a handler that percent-decodes the address sees the comma again.
pub fn escape_for_explorer(target: &str) -> String {
let mut out = String::with_capacity(target.len());
for c in target.chars() {
match c {
' ' => out.push_str("%20"),
'"' => out.push_str("%22"),
',' => out.push_str("%2C"),
'^' => out.push_str("%5E"),
_ => out.push(c),
}
}
out
}
/// The program and its single argument that open `target` (already accepted by
/// `links::classify`) on `os`. `None` when the target could be read as an option: it starts with
/// `-` or `/`, or is empty. `xdg-open` takes no `--`, so refusing is the only safe answer.
pub fn opener_command(os: Os, target: &str, system_root: Option<&str>, windir: Option<&str>) -> Option<(PathBuf, String)> {
if target.is_empty() || target.starts_with(['-', '/']) {
return None;
}
Some(match os {
Os::Mac => (PathBuf::from("/usr/bin/open"), target.to_string()),
Os::Windows => {
let exe = format!("{}\\explorer.exe", windows_dir(system_root, windir));
(PathBuf::from(exe), escape_for_explorer(target))
}
// Found on PATH: its location differs between distributions and the BSDs.
Os::Other => (PathBuf::from("xdg-open"), target.to_string()),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_opener_is_explorer_in_the_windows_directory() {
let (exe, arg) = opener_command(Os::Windows, "https://a.example/x", Some("C:\\Windows"), None).unwrap_or_default();
assert_eq!(exe, PathBuf::from("C:\\Windows\\explorer.exe"));
assert_eq!(arg, "https://a.example/x");
// Never a bare name, whatever the environment says.
for (root, windir) in [(None, None), (Some(""), Some("")), (Some("Windows"), None), (Some(".\\"), Some("explorer"))] {
let (exe, _) = opener_command(Os::Windows, "https://a.example", root, windir).unwrap_or_default();
assert_eq!(exe, PathBuf::from("C:\\Windows\\explorer.exe"), "{root:?} {windir:?}");
}
}
#[test]
fn windows_dir_prefers_system_root_then_windir_then_default() {
assert_eq!(windows_dir(Some("D:\\WINNT\\"), Some("E:\\Win")), "D:\\WINNT");
assert_eq!(windows_dir(None, Some("E:\\Win")), "E:\\Win");
assert_eq!(windows_dir(Some("relative\\dir"), Some("e:/win/")), "e:/win");
assert_eq!(windows_dir(None, None), "C:\\Windows");
assert_eq!(windows_dir(Some("D:\\"), None), "D:");
for bad in ["\\\\host\\share", "//host/share", "C:", "C:Windows", "C:\\Windows\\..\\Users\\x", "C:\\\"x", "", " ", "1:\\x"] {
assert_eq!(windows_dir(Some(bad), None), "C:\\Windows", "{bad:?}");
}
}
#[test]
fn explorer_switch_characters_are_percent_encoded() {
let (_, arg) = opener_command(Os::Windows, "https://x/,/select,C:\\Windows\\a b\"^", None, None).unwrap_or_default();
assert_eq!(arg, "https://x/%2C/select%2CC:\\Windows\\a%20b%22%5E");
assert!(!arg.contains([' ', '"', ',', '^']));
assert_eq!(escape_for_explorer("mailto:a@b.example?subject=Hi there"), "mailto:a@b.example?subject=Hi%20there");
// Other platforms get the address as it is.
let (_, arg) = opener_command(Os::Other, "https://x/a,b", None, None).unwrap_or_default();
assert_eq!(arg, "https://x/a,b");
}
#[test]
fn mac_and_freedesktop_openers() {
let (exe, arg) = opener_command(Os::Mac, "https://a.example", None, None).unwrap_or_default();
assert_eq!((exe, arg.as_str()), (PathBuf::from("/usr/bin/open"), "https://a.example"));
let (exe, _) = opener_command(Os::Other, "mailto:a@b.example", None, None).unwrap_or_default();
assert_eq!(exe, PathBuf::from("xdg-open"));
}
#[test]
fn a_target_never_becomes_an_option() {
for os in [Os::Mac, Os::Windows, Os::Other] {
for bad in ["-a", "--help", "-e calc", "/select,C:\\x", "/root,C:\\", ""] {
assert_eq!(opener_command(os, bad, None, None), None, "{os:?} {bad:?}");
}
}
}
}
+5
View File
@@ -26,6 +26,11 @@ sync_github_name = false
[people.edurbs]
sync_github_name = true
[people.Cheejyg]
real_name = "Glenn Chee"
display_name = "Cheejyg"
sync_github_name = false
[people.arcanii]
real_name = "Bryan Mark"
display_name = "Arcanii"
+73 -25
View File
@@ -59,26 +59,29 @@ pub struct Calc {
/// Who gets the cells when two arrays want the same ones. Excel (measured by a reviewer on
/// PR #2483) lets the spill that already exists keep its cells, whichever anchor comes first;
/// the other formula shows `#SPILL!`, and clearing the winner lets it spill. The rule here:
/// the other formula shows `#SPILL!`, and clearing the winner lets it spill. The rule here, for
/// each cell both want:
///
/// 1. an anchor that held a spill before this calculation outranks one that did not;
/// 2. otherwise the anchor first in reading order (row, then column) wins.
/// 1. the anchor whose spill held that cell before this calculation keeps it, so an array that
/// grows into another's area is `#SPILL!` even when it held a spill of its own;
/// 2. otherwise an anchor that held a spill before this calculation outranks one that did not;
/// 3. otherwise the anchor first in reading order (row, then column) wins.
///
/// Rule 2 alone decides when nothing is remembered, so the result never depends on hash order
/// Rule 3 alone decides when nothing is remembered, so the result never depends on hash order
/// or evaluation order. A full recalculation remembers the layout the sheet held before it
/// started (rule 1), so it agrees with the incremental one; a workbook that is calculated for
/// the first time has no such layout (rule 2 only).
///
/// Known limits: (a) the xlsx reader does not restore spill layouts, so a workbook opened from a
/// file is laid out by rule 2 alone, although Excel keeps the layout the file records; (b) when
/// both anchors held a spill and one grows into the other, rule 2 decides, where Excel keeps
/// the cells the other already owns.
/// started, so it agrees with the incremental one; a workbook that is calculated for the first
/// time has no such layout (rule 3 only). The xlsx reader restores the area each dynamic array
/// was saved spilling over, so a workbook opened from a file keeps the layout it was saved with.
#[derive(Clone, Debug, Default)]
struct Standing {
/// `true`: `keys` are the anchors that held a spill (full recalculation, which lays every
/// spill out afresh). `false`: `keys` are the formulas that held none (incremental).
held: bool,
keys: HashSet<Key>,
/// The area each anchor that held a spill filled before this calculation, for the anchors the
/// calculation lays out again (full: all of them; incremental: the formulas it recalculates).
/// Any other anchor still fills the area the sheet shows.
areas: HashMap<Key, RangeRef>,
}
impl Standing {
@@ -86,7 +89,7 @@ impl Standing {
self.keys.contains(&k) == self.held
}
/// Whether `a` takes cells from `b` when both want them.
/// Whether `a` takes cells from `b` when both want them and neither held them (rules 2, 3).
fn outranks(&self, a: Key, b: Key) -> bool {
match (self.had_spill(a), self.had_spill(b)) {
(true, false) => true,
@@ -94,6 +97,22 @@ impl Standing {
_ => (a.1.row, a.1.col) < (b.1.row, b.1.col),
}
}
/// Whether `k`'s spill held `cell` before this calculation; `now` is the area the sheet
/// shows for `k`.
fn held_cell(&self, k: Key, now: Option<RangeRef>, cell: CellRef) -> bool {
self.had_spill(k) && self.areas.get(&k).copied().or(now).is_some_and(|r| r.contains(cell))
}
/// Whether `a` takes `cell` from `b` when both want it (rule 1, then [`Self::outranks`]). Each
/// anchor comes with the area the sheet shows for it.
fn outranks_at(&self, (a, a_now): (Key, Option<RangeRef>), (b, b_now): (Key, Option<RangeRef>), cell: CellRef) -> bool {
match (self.held_cell(a, a_now, cell), self.held_cell(b, b_now, cell)) {
(true, false) => true,
(false, true) => false,
_ => self.outranks(a, b),
}
}
}
/// A set of cells by row, each row's columns in their own set: a window of rows and columns is
@@ -313,12 +332,18 @@ impl Calc {
self.rebuild(wb);
// The layout the sheets hold now decides who keeps cells two arrays both want.
// (A Python cell that holds a spill counts too, as it does in the incremental pass.)
let mut held = HashSet::default();
let mut areas: HashMap<Key, RangeRef> = HashMap::default();
for i in 0..wb.sheets.len() {
if let Some(sh) = wb.sheet(i) {
held.extend(sh.spill_ranges.keys().filter(|a| sh.cell(**a).is_some_and(|c| c.formula.is_some() || c.py.is_some())).map(|a| (i, *a)));
areas.extend(
sh.spill_ranges
.iter()
.filter(|(a, _)| sh.cell(**a).is_some_and(|c| c.formula.is_some() || c.py.is_some()))
.map(|(a, r)| ((i, *a), *r)),
);
}
}
let held = areas.keys().copied().collect();
// Spills are laid out again from the formulas where they are now (a structural edit moves
// or deletes the formulas, not the values they spilled).
for i in 0..wb.sheets.len() {
@@ -330,7 +355,7 @@ impl Calc {
}
}
let all: Vec<Key> = self.graph.nodes.keys().copied().collect();
self.standing = Standing { held: true, keys: held };
self.standing = Standing { held: true, keys: held, areas };
self.run(wb, all, true);
self.standing = Standing::default();
}
@@ -542,8 +567,15 @@ impl Calc {
if !full {
// What each formula held before this calculation touched it.
for &k in &dirty {
if seen.insert(k) && wb.sheet(k.0).is_some_and(|s| !s.spill_ranges.contains_key(&k.1)) {
self.standing.keys.insert(k);
if seen.insert(k) {
match wb.sheet(k.0).and_then(|s| s.spill_ranges.get(&k.1)) {
Some(r) => {
self.standing.areas.insert(k, *r);
}
None => {
self.standing.keys.insert(k);
}
}
}
}
}
@@ -664,7 +696,7 @@ impl Calc {
let end = CellRef::new(key.1.row.saturating_add(array.rows as u32 - 1), key.1.col.saturating_add(array.cols as u32 - 1));
let range = RangeRef::new(key.1, end);
// Two arrays that want the same cells (see [`Standing`]): a spill already laid out
// that this anchor outranks is taken over, and recalculated.
// that this anchor outranks on every cell they share is taken over, and recalculated.
let standing = &self.standing;
// A spill can only be in the way where it has cells besides its anchor, and an
// anchor itself blocks the array. When no spilled cell lies in the range, the owners
@@ -675,13 +707,18 @@ impl Calc {
sheet
.spill_ranges
.iter()
.filter(|(o, r)| **o != key.1 && r.intersects(&range) && standing.outranks(*key, (key.0, **o)))
.filter(|(o, r)| {
**o != key.1
&& r.intersection(&range).is_some_and(|shared| {
shared.iter().all(|cell| standing.outranks_at((*key, old), ((key.0, **o), Some(**r)), cell))
})
})
.map(|(o, r)| (*o, *r))
.collect()
} else {
Vec::new()
};
let blocked = spill_is_blocked(sheet, *key, range, end, standing);
let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing);
if !blocked {
for (o, r) in outranked {
for c in r.iter() {
@@ -739,11 +776,22 @@ thread_local! {
pub(crate) static OWNER_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Whether the array at `anchor` can't be laid out over `range`. A spill already laid out that
/// `anchor` outranks does not block it: it is taken over when written back.
fn spill_is_blocked(sheet: &gridcraft_model::Sheet, anchor: Key, range: RangeRef, end: CellRef, standing: &Standing) -> bool {
let outranked =
|cell: CellRef| sheet.spill_ranges.iter().any(|(o, r)| *o != anchor.1 && r.contains(cell) && standing.outranks(anchor, (anchor.0, *o)));
/// Whether the array at `anchor` (with the area the sheet showed for it) can't be laid out over
/// `range`. A spill already laid out that `anchor` outranks does not block it: it is taken over
/// when written back.
fn spill_is_blocked(
sheet: &gridcraft_model::Sheet,
(anchor, now): (Key, Option<RangeRef>),
range: RangeRef,
end: CellRef,
standing: &Standing,
) -> bool {
let outranked = |cell: CellRef| {
sheet
.spill_ranges
.iter()
.any(|(o, r)| *o != anchor.1 && r.contains(cell) && standing.outranks_at((anchor, now), ((anchor.0, *o), Some(*r)), cell))
};
end.row >= gridcraft_core::MAX_ROWS
|| end.col >= gridcraft_core::MAX_COLS
|| range.iter().any(|cell| cell != anchor.1 && (sheet.cells.has(cell) || (sheet.spill.contains_key(&cell) && !outranked(cell))))
+4 -4
View File
@@ -163,9 +163,9 @@ fn spill_hits_overlap(index: &SpillIndex, sheet: usize, hits: &[CellRef], range:
}
/// Whether an array result at `k` can't spill: it is in a table, or its area runs off the sheet,
/// overlaps merged cells, holds other cells, or the spill of another formula that outranks it
/// (see `Standing`; unless that formula is recalculated in this pass, and so may spill elsewhere
/// now). A spill it outranks gives way to it when written back.
/// overlaps merged cells, holds other cells, or the spill of another formula that outranks it on
/// a cell they share (see `Standing`; unless that formula is recalculated in this pass, and so
/// may spill elsewhere now). A spill it outranks gives way to it when written back.
fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool {
let Some(sh) = host.wb.sheet(sheet) else { return false };
let end =
@@ -182,7 +182,7 @@ fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool {
&& r.contains(c)
&& !host.exprs.contains_key(&(sheet, *o))
&& !host.python.contains_key(&(sheet, *o))
&& standing.outranks((sheet, *o), (sheet, anchor))
&& standing.outranks_at(((sheet, *o), Some(*r)), ((sheet, anchor), own.copied()), c)
})
};
end.row >= gridcraft_core::MAX_ROWS
+65
View File
@@ -368,6 +368,24 @@ fn iterative_calculation_of_text_and_errors() {
assert_eq!(t.get("B1"), Value::Error(CellError::Div0));
}
/// `&`, CONCAT and TEXTJOIN turn a number into at most 15 significant digits, decimal unless that
/// would need 16 integer digits or more than 21 characters below 1.
#[test]
fn text_joins_convert_numbers_to_15_significant_digits() {
let mut t = T::new();
for (formula, text) in [
("=(1E15-0.5)&\"\"", "1E+15"),
("=(999999999999999)&\"\"", "999999999999999"),
("=1234567890123456&\"\"", "1.23456789012346E+15"),
("=(9.99999999999999E-9)&\"\"", "9.99999999999999E-09"),
("=CONCAT(1/3*1E-5)", "3.33333333333333E-06"),
("=TEXTJOIN(\",\",TRUE,1/3*1E-4,0.1+0.2)", "0.0000333333333333333,0.3"),
] {
t.set("A1", formula);
assert_eq!(t.get("A1"), Value::from(text), "{formula}");
}
}
#[test]
fn circular_references_without_iterative_calculation() {
let mut t = T::new();
@@ -706,6 +724,53 @@ fn spill_into_the_old_area_of_a_blocked_neighbour() {
assert_eq!([t.num("C8"), t.num("D8"), t.num("C9"), t.num("D9")], [1.0, 2.0, 3.0, 4.0]);
}
#[test]
fn a_full_recalc_keeps_a_spill_from_an_array_that_grew_into_it() {
// Both arrays spill; in manual calculation F13 then grows over F14:G14, which C14's array
// fills. A full recalculation gives what an automatic one would: C14 keeps its cells and F13
// is #SPILL!, although F13 comes first in reading order.
let mut t = T::new();
t.set("J1", "1");
t.set("C14", "=SEQUENCE(1,7)");
t.set("F13", "=SEQUENCE(J1,2)");
assert_eq!([t.num("F13"), t.num("G13")], [1.0, 2.0]);
t.wb.calc.mode = gridcraft_model::CalcMode::Manual;
t.set("J1", "5");
t.calc.recalc_all(&mut t.wb);
assert_eq!(t.get("F13"), Value::Error(CellError::Spill));
assert_eq!([t.num("C14"), t.num("F14"), t.num("G14"), t.num("I14")], [1.0, 4.0, 5.0, 7.0]);
}
#[test]
fn a_full_recalc_lays_out_arrays_as_an_automatic_one_when_one_shrinks_for_another() {
// C1 grows into C3, which A3's array fills, and A3 grows into E3, which E1's array leaves.
// Automatic recalculation lays them out in reading order with each former area still filled:
// C1 is #SPILL! and A3 takes A3:E3. A full recalculation after the same edit in manual
// calculation gives the same sheet.
let build = |manual: bool| {
let mut t = T::new();
t.set("J1", "2");
t.set("C1", "=SEQUENCE(J1)");
t.set("A3", "=SEQUENCE(1,J1+1)");
t.set("E1", "=SEQUENCE(5-J1)");
assert_eq!([t.num("C2"), t.num("C3"), t.num("E3")], [2.0, 3.0, 3.0]);
if manual {
t.wb.calc.mode = gridcraft_model::CalcMode::Manual;
}
t.set("J1", "4");
if manual {
t.calc.recalc_all(&mut t.wb);
}
t
};
let (automatic, full) = (build(false), build(true));
assert_eq!(automatic.get("C1"), Value::Error(CellError::Spill));
assert_eq!([automatic.num("A3"), automatic.num("C3"), automatic.num("E3")], [1.0, 3.0, 5.0]);
for cell in ["A1", "C1", "C2", "C3", "C4", "E1", "E2", "A3", "B3", "C3", "D3", "E3"] {
assert_eq!(full.get(cell), automatic.get(cell), "{cell}");
}
}
#[test]
fn formulas_reading_an_array_that_loses_a_spill_conflict_read_spill_errors() {
// Two arrays of one recalculation want the same empty cell: the one laid out second is
+51 -4
View File
@@ -444,14 +444,27 @@ pub fn sort_compare(a: &Value, b: &Value) -> Ordering {
}
}
/// Number → text the way Excel converts in `&` and `TEXT(x,"General")`-free contexts: up to 15
/// significant digits, scientific for very large or very small magnitudes.
/// Number → text the way Excel converts in `&`, CONCAT and TEXTJOIN: at most 15 significant
/// digits, rounded first; scientific from 1E+15, below 1E-9, and wherever the decimal would be
/// longer than 21 characters, not counting the sign (`0.` plus 19 decimals). Excel-verified only
/// for positive 15-digit mantissas: `0.0000692361330972509` stays decimal and
/// `1.28233995888454E-06` does not, as Excel caches them. The limit for shorter mantissas from
/// 1E-6 to 1E-9 (e.g. `0.0000099999999999999` decimal) and for negatives (sign excluded) are
/// inferred.
pub fn number_to_text(n: f64) -> String {
if n == 0.0 || !n.is_finite() {
return "0".into();
}
// Round to 15 significant digits first, then pick decimal or scientific from the rounded
// magnitude, so 999999999999999.5 reads `1E+15`, never a 16-digit integer.
let a = n.abs();
if !(1e-9..1e15).contains(&a) && a.round() != a || a >= 1e15 {
let sci = format!("{:.14e}", n);
let (mant, exp) = sci.split_once('e').unwrap_or((&sci, "0"));
let mag: i32 = exp.parse().unwrap_or(0);
let sig = mant.bytes().filter(u8::is_ascii_digit).count() - mant.bytes().rev().take_while(|&b| b == b'0').count();
// Characters after `0.` for |n| < 1: the leading zeros, then the significant digits.
let decimals_below_one = -mag - 1 + sig as i32;
if !(-9..15).contains(&mag) || decimals_below_one > 19 {
return sci_text(n, 15);
}
// A value just below 1e15 can round up to 1e15 at 15 significant digits. Only that narrow
@@ -460,7 +473,6 @@ pub fn number_to_text(n: f64) -> String {
return sci_text(n, 15);
}
// 15 significant digits, trailing zeros trimmed.
let mag = a.log10().floor() as i32;
let decimals = (14 - mag).clamp(0, 30) as usize;
let s = format!("{:.*}", decimals, n);
trim_decimal(&s)
@@ -499,9 +511,44 @@ mod tests {
assert_eq!(number_to_text(1234567890123456.0), "1.23456789012346E+15");
assert_eq!(number_to_text(0.0001), "0.0001");
assert_eq!(number_to_text(1e-10), "1E-10");
assert_eq!(number_to_text(1e15 - 0.5), "1E+15");
assert_eq!(number_to_text(1e15 - 0.1), "1E+15");
assert_eq!(number_to_text(-(1e15 - 0.5)), "-1E+15");
assert_eq!(number_to_text(999999999999999.0), "999999999999999");
assert_eq!(number_to_text(9.999999999999999e-10), "0.000000001");
assert_eq!(number_to_text(-9.999999999999999e-10), "-0.000000001");
assert_eq!(number_to_text(1.0 / 3.0), "0.333333333333333");
}
/// Excel switches to scientific when the 15-digit decimal would be longer than 21 characters
/// (`0.` plus 19 decimals). Excel-verified: IMTAN, IMSECH, IMCSCH and IMEXP results cached by
/// Excel for Mac in the `formulas` project's test.xlsx (ENGINEERING!S53, R47, S37, V37, V39).
#[test]
fn number_text_small_magnitudes() {
assert_eq!(number_to_text(6.92361330972509e-5), "0.0000692361330972509");
assert_eq!(number_to_text(2.41377759972715e-4), "0.000241377759972715");
assert_eq!(number_to_text(1.28233995888454e-6), "1.28233995888454E-06");
assert_eq!(number_to_text(-4.48088972789593e-6), "-4.48088972789593E-06");
assert_eq!(number_to_text(5.98317105631764e-7), "5.98317105631764E-07");
assert_eq!(number_to_text(-2.99158552811404e-7), "-2.99158552811404E-07");
// Just below powers of ten: the 21-character limit, and the rounded magnitude.
assert_eq!(number_to_text(9.99999999999999e-5), "0.0000999999999999999");
assert_eq!(number_to_text(9.99999999999999e-6), "9.99999999999999E-06");
assert_eq!(number_to_text(9.9999999999999e-6), "0.0000099999999999999");
assert_eq!(number_to_text(9.99999999999999e-9), "9.99999999999999E-09");
assert_eq!(number_to_text(-9.99999999999999e-9), "-9.99999999999999E-09");
assert_eq!(number_to_text(9.99999999999999e-10), "9.99999999999999E-10");
assert_eq!(number_to_text(9.999999999999999e-6), "0.00001");
assert_eq!(number_to_text(0.00001), "0.00001");
assert_eq!(number_to_text(0.000001), "0.000001");
assert_eq!(number_to_text(1.5e-9), "0.0000000015");
// Large side: 15 significant digits, scientific from 1E+15.
assert_eq!(number_to_text(99999999999999.9), "99999999999999.9");
assert_eq!(number_to_text(999999999999999.4), "999999999999999");
assert_eq!(number_to_text(9999999999999998.0), "1E+16");
assert_eq!(number_to_text(9.99999999999999e15), "9.99999999999999E+15");
}
#[test]
fn number_text_rounds_up_to_scientific_boundary() {
assert_eq!(number_to_text(999999999999999.9), "1E+15");
+48 -2
View File
@@ -4,7 +4,9 @@
use std::collections::{HashMap, HashSet};
use gridcraft_core::{CellRef, RangeRef, Value, compare};
use gridcraft_model::{CfOperator, CfRule, CfValueKind, Color, CondFormat, PatternType, Sheet, Style, Underline, Workbook, default_icon_thresholds};
use gridcraft_model::{
CfOperator, CfRule, CfValueKind, Color, CondFormat, PatternType, Sheet, Style, Table, Underline, Workbook, default_icon_thresholds,
};
/// The conditional look of one cell.
#[derive(Clone, Debug, Default, PartialEq)]
@@ -20,10 +22,12 @@ pub struct CfLook {
pub hide_value: bool,
}
/// Precomputed statistics per rule (min/max/percentiles/top-N thresholds/duplicates).
/// Precomputed statistics per rule (min/max/percentiles/top-N thresholds/duplicates), and each
/// table's visible edges. The grid and print keep one per paint.
#[derive(Default)]
pub struct CfCache {
stats: HashMap<usize, RuleStats>,
table_edges: HashMap<RangeRef, crate::tables::ShownEdges>,
}
#[derive(Default, Clone)]
@@ -275,6 +279,11 @@ impl CfCache {
Self::default()
}
/// [`crate::tables::shown_edges`] of `t`, found once per cache.
pub fn table_edges(&mut self, sh: &Sheet, t: &Table) -> crate::tables::ShownEdges {
*self.table_edges.entry(t.range).or_insert_with(|| crate::tables::shown_edges(sh, t))
}
/// Conditional look of `c`, or `None` when no rule applies.
pub fn look(&mut self, wb: &Workbook, sheet: usize, c: CellRef) -> Option<CfLook> {
let sh = wb.sheet(sheet)?;
@@ -728,6 +737,43 @@ mod tests {
assert_eq!([look("A1"), look("A2")], [true, false]);
}
#[test]
fn rules_compare_with_cells_on_other_sheets() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "E1", "values": [["Suspended"], ["OK"], ["Terminated"], [7], [3]]})).unwrap();
let rule = |r: serde_json::Value| json!({"range": "E1:E5", "rule": r});
s.execute(
"home.conditionalFormat",
rule(json!({"type": "cellIs", "operator": "equal", "value": "='Vehicle Range'!$A$8", "preset": "redText"})),
)
.unwrap();
s.execute(
"home.conditionalFormat",
rule(json!({"type": "cellIs", "operator": "equal", "value": "='Vehicle Range'!$A$9", "preset": "redText"})),
)
.unwrap();
s.execute(
"home.conditionalFormat",
rule(json!({"type": "expression", "formula": "=AND(ISNUMBER(E1),E1>'Vehicle Range'!$B$1)", "preset": "yellowFill"})),
)
.unwrap();
s.execute("home.insertSheet", json!({"name": "Vehicle Range"})).unwrap();
s.execute("range.setValues", json!({"range": "'Vehicle Range'!A8", "values": [["Suspended"], ["Terminated"]]})).unwrap();
s.execute("range.setValues", json!({"range": "'Vehicle Range'!B1", "values": [[5]]})).unwrap();
let d = s.doc().unwrap();
let report = d.wb.sheets.iter().position(|sh| sh.name != "Vehicle Range").unwrap();
let mut cache = CfCache::new();
let mut look = |a: &str| cache.look(&d.wb, report, CellRef::parse(a).unwrap()).and_then(|l| l.style).unwrap_or_default();
let looks = ["E1", "E2", "E3", "E4", "E5"].map(&mut look);
// The cells equal to 'Vehicle Range'!A8 or A9 get the red text.
let red_text = looks[0].font.color;
assert_ne!(red_text, Color::Auto);
let red = |st: &Style| st.font.color == red_text;
let filled = |st: &Style| st.fill.pattern == PatternType::Solid;
assert_eq!(looks.each_ref().map(red), [true, false, true, false, false]);
assert_eq!(looks.each_ref().map(filled), [false, false, false, true, false]);
}
#[test]
fn text_rules_skip_error_values() {
let mut s = crate::Session::new();
+213
View File
@@ -0,0 +1,213 @@
//! Where a chart's data sits on a sheet, as the blocks a selected chart outlines: series names in
//! red, category labels in purple and values in blue (#4390). Dragging a corner of the values
//! block points the chart at other cells, and the names and categories follow it (#4389).
use gridcraft_core::{CellRef, RangeRef, col_to_letters};
use gridcraft_formula::{Expr, RefKind, SheetSel, parse, quote_sheet};
use gridcraft_model::{Chart, Series, Workbook};
/// Most series a chart takes from a dragged block (Excel's limit per chart).
pub const MAX_SERIES: u32 = 255;
/// Most cells a dragged values block may span, as for `chart.selectData`.
pub const MAX_CELLS: u64 = 1_000_000;
/// A chart's data as blocks of cells on one sheet.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ChartData {
/// The sheet the data is on.
pub sheet: usize,
/// Every series' values: one column per series (one row with `by_rows`), in series order.
pub values: RangeRef,
/// Series run across rows rather than down columns.
pub by_rows: bool,
/// The category labels every series shares, when they line up beside `values`.
pub categories: Option<RangeRef>,
/// One name cell per series, in the line beside `values`, when every series has one there.
pub names: Option<RangeRef>,
}
impl ChartData {
/// The blocks after the values move to `to`: category labels keep their column (row) and
/// span the new points, and names keep their row (column) and span the new series.
pub fn moved(&self, to: RangeRef) -> ChartData {
let (categories, names) = if self.by_rows {
(
self.categories.map(|c| RangeRef::new(CellRef::new(c.start.row, to.start.col), CellRef::new(c.start.row, to.end.col))),
self.names.map(|n| RangeRef::new(CellRef::new(to.start.row, n.start.col), CellRef::new(to.end.row, n.start.col))),
)
} else {
(
self.categories.map(|c| RangeRef::new(CellRef::new(to.start.row, c.start.col), CellRef::new(to.end.row, c.start.col))),
self.names.map(|n| RangeRef::new(CellRef::new(n.start.row, to.start.col), CellRef::new(n.start.row, to.end.col))),
)
};
ChartData { values: to, categories, names, ..*self }
}
/// The cells of series `i` within `values` (`None` past the last series).
fn line(&self, values: RangeRef, i: u32) -> Option<RangeRef> {
if self.by_rows {
let row = values.start.row.checked_add(i).filter(|r| *r <= values.end.row)?;
Some(RangeRef::new(CellRef::new(row, values.start.col), CellRef::new(row, values.end.col)))
} else {
let col = values.start.col.checked_add(i).filter(|c| *c <= values.end.col)?;
Some(RangeRef::new(CellRef::new(values.start.row, col), CellRef::new(values.end.row, col)))
}
}
/// How many series `values` holds.
fn count(&self, values: RangeRef) -> u32 {
if self.by_rows { values.height() } else { values.width() }
}
}
/// The sheet and cells a series reference names. `home` is the chart's own sheet, for an
/// unqualified reference. Literals, names, 3-D spans, other workbooks and whole rows or columns
/// are not blocks.
fn block(wb: &Workbook, home: usize, text: &str) -> Option<(usize, RangeRef)> {
let Ok(Expr::Ref(r)) = parse(text.trim().trim_start_matches('=')) else { return None };
let sheet = match &r.sheet {
SheetSel::Current => home,
SheetSel::Named(n) => wb.sheet_index(n)?,
SheetSel::Span(..) => return None,
};
matches!(r.kind, RefKind::Cell(_) | RefKind::Range(..)).then(|| (sheet, r.range()))
}
/// `chart`'s data on `home`'s workbook as blocks, when its series form one: every series' values
/// on one sheet, in adjacent columns (or rows) of the same extent, in series order. `None` for
/// any other layout, and for a PivotChart, whose series follow its PivotTable.
pub fn chart_data(wb: &Workbook, home: usize, chart: &Chart) -> Option<ChartData> {
if chart.pivot.is_some() {
return None;
}
let first = chart.series.first()?;
let (sheet, r0) = block(wb, home, &first.values)?;
let by_rows = match (r0.width(), r0.height()) {
(1, 1) => chart.by_rows,
(1, _) => false,
(_, 1) => true,
_ => return None,
};
let n = u32::try_from(chart.series.len()).ok()?;
let last = n.checked_sub(1)?;
let values = if by_rows {
RangeRef::new(r0.start, CellRef::new(r0.end.row.checked_add(last)?, r0.end.col))
} else {
RangeRef::new(r0.start, CellRef::new(r0.end.row, r0.end.col.checked_add(last)?))
};
let mut data = ChartData { sheet, values, by_rows, categories: None, names: None };
for (i, se) in (0..n).zip(&chart.series) {
if block(wb, home, &se.values) != Some((sheet, data.line(values, i)?)) {
return None;
}
}
// Category labels shared by every series, in one line beside the points. Compared as blocks,
// not text: `=Sheet1!$A$2:$A$4` and `Sheet1!$A$2:$A$4` are the same labels.
let cats = |se: &Series| se.categories.as_deref().and_then(|t| block(wb, home, t));
if let Some((s, c)) = cats(first)
&& s == sheet
&& chart.series.iter().all(|se| cats(se) == Some((s, c)))
{
let lines_up = if by_rows {
c.height() == 1
&& (c.start.col, c.end.col) == (values.start.col, values.end.col)
&& !(values.start.row..=values.end.row).contains(&c.start.row)
} else {
c.width() == 1
&& (c.start.row, c.end.row) == (values.start.row, values.end.row)
&& !(values.start.col..=values.end.col).contains(&c.start.col)
};
data.categories = lines_up.then_some(c);
}
// A name cell for every series, all in one line beside the values.
let names: Option<Vec<CellRef>> = chart
.series
.iter()
.map(|se| se.name.as_deref().and_then(|t| block(wb, home, t)).filter(|(s, r)| *s == sheet && r.is_single()).map(|(_, r)| r.start))
.collect();
if let Some(cells) = names
&& let (Some(a), Some(b)) = (cells.first(), cells.last())
{
let lines_up = (0..n).zip(&cells).all(|(i, c)| {
if by_rows {
c.col == a.col && Some(c.row) == values.start.row.checked_add(i) && !(values.start.col..=values.end.col).contains(&c.col)
} else {
c.row == a.row && Some(c.col) == values.start.col.checked_add(i) && !(values.start.row..=values.end.row).contains(&c.row)
}
});
data.names = lines_up.then(|| RangeRef::new(*a, *b));
}
Some(data)
}
/// Why [`with_values`] refused.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ValuesError {
/// The chart's series are not one block of cells ([`chart_data`] is `None`).
NotABlock,
/// The block is over [`MAX_CELLS`] cells or [`MAX_SERIES`] series.
TooLarge,
}
/// `chart` with its values moved to `to` on the data's own sheet, as dragging a corner of the
/// values outline does. Series `i` takes the `i`-th column (row) of `to` and keeps everything
/// else it had (colour, kind, axis, trendlines); a wider block adds series and a narrower one
/// drops the last ones. Category labels and names that line up follow the block; ones that don't
/// stay as they are. A data range kept for Switch Row/Column becomes the moved blocks.
pub fn with_values(wb: &Workbook, home: usize, chart: &Chart, to: RangeRef) -> Result<Chart, ValuesError> {
let data = chart_data(wb, home, chart).ok_or(ValuesError::NotABlock)?;
if to.count() > MAX_CELLS || data.count(to) > MAX_SERIES {
return Err(ValuesError::TooLarge);
}
let sheet = wb.sheet(data.sheet).ok_or(ValuesError::NotABlock)?;
let q = quote_sheet(&sheet.name);
let row = |r: u32| u64::from(r) + 1;
let range = |r: RangeRef| format!("{q}!${}${}:${}${}", col_to_letters(r.start.col), row(r.start.row), col_to_letters(r.end.col), row(r.end.row));
let cell = |c: CellRef| format!("{q}!${}${}", col_to_letters(c.col), row(c.row));
let moved = data.moved(to);
let shared_cats = chart.series.first().and_then(|se| se.categories.clone());
let mut out = chart.clone();
// Keep the orientation the series were read in: a block of one cell per series is read by
// `by_rows`, so a stale flag would make the moved series unreadable as a block.
out.by_rows = data.by_rows;
out.series = (0..data.count(to))
.filter_map(|i| {
let line = moved.line(to, i)?;
let old = chart.series.get(i as usize);
let mut se = old.cloned().unwrap_or_else(|| Series { categories: shared_cats.clone(), ..Series::default() });
se.values = range(line);
if let Some(c) = moved.categories {
se.categories = Some(range(c));
}
if let Some(n) = moved.names {
se.name =
Some(cell(if data.by_rows { CellRef::new(line.start.row, n.start.col) } else { CellRef::new(n.start.row, line.start.col) }));
}
// Bubble sizes in a line of their own beside the old points span the new ones.
if let (Some(old_line), Some(text)) = (data.line(data.values, i), se.bubble_sizes.clone())
&& let Some((s, b)) = block(wb, home, &text)
&& s == data.sheet
{
let follows = if data.by_rows {
b.height() == 1 && (b.start.col, b.end.col) == (old_line.start.col, old_line.end.col)
} else {
b.width() == 1 && (b.start.row, b.end.row) == (old_line.start.row, old_line.end.row)
};
if follows {
se.bubble_sizes = Some(range(if data.by_rows {
RangeRef::new(CellRef::new(b.start.row, to.start.col), CellRef::new(b.start.row, to.end.col))
} else {
RangeRef::new(CellRef::new(to.start.row, b.start.col), CellRef::new(to.end.row, b.start.col))
}));
}
}
Some(se)
})
.collect();
if out.source.is_some() {
let all = [moved.categories, moved.names].into_iter().flatten().fold(to, |a, r| a.union(&r));
out.source = Some(format!("{q}!{}", all.a1()));
}
Ok(out)
}
+2 -1
View File
@@ -27,6 +27,7 @@ pub use filter::filter_values;
pub(crate) use filter::{apply_filter, grow_autofilter};
use filter::{clear_filter, filter_by, reapply, toggle_filter};
use grouping::{detail, group, outline_settings, show_levels, subtotal};
pub use sort::sort_context;
use sort::{quick_sort, sort};
#[cfg(test)]
use tools::split_delimited;
@@ -212,7 +213,7 @@ fn data_target(s: &Session, p: &Json, cmd: &str) -> Result<(usize, RangeRef)> {
/// Excel's header guess: the first row is text over a column of numbers, or is bold.
fn guess_header(wb: &Workbook, sh: &Sheet, r: RangeRef) -> bool {
if let Some(t) = sh.table_at(r.start) {
return t.header_row;
return t.header_row && r.start.row == t.range.start.row;
}
if r.height() < 2 {
return false;
+18 -1
View File
@@ -28,6 +28,21 @@ fn sort_target(s: &Session, p: &Json) -> Result<(usize, RangeRef)> {
Ok((sheet, data_range(s, p)?))
}
/// The worksheet (index), range and header guess the Custom Sort dialog works on: the sheet named by
/// `sheet` or a `Sheet!` prefix on `range`, else the active one.
pub fn sort_context(s: &Session, p: &Json) -> Result<(usize, RangeRef, bool)> {
let (sheet, explicit) = sort_target(s, p)?;
let d = s.doc()?;
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
let sel = d.selection.current();
// An explicit block wins over the table range, so a selected totals row can be sorted.
let r = match sh.used_range() {
Some(used) if p.get("range").is_none() && !sel.is_single() => sel.intersection(&used).unwrap_or(sel),
_ => explicit,
};
Ok((sheet, r, bool_param(p, "header").unwrap_or_else(|| guess_header(&d.wb, sh, r))))
}
pub(super) fn quick_sort(s: &mut Session, p: &Json, asc: bool) -> Result<Json> {
let (sheet, r) = sort_target(s, p)?;
let col = col_param(p.get("column"), r.start.col).unwrap_or(s.doc()?.selection.active.col).clamp(r.start.col, r.end.col);
@@ -68,7 +83,9 @@ pub(super) fn sort(s: &mut Session, p: &Json) -> Result<Json> {
});
}
if keys.is_empty() {
s.ui_requests.push(crate::UiRequest::Dialog("sort".into(), json!({"range": r.a1(), "header": header})));
let (sheet, r, header) = sort_context(s, p)?;
let name = s.doc()?.wb.sheet(sheet).map(|sh| sh.name.clone()).ok_or(EngineError::NoDocument)?;
s.ui_requests.push(crate::UiRequest::Dialog("sort".into(), json!({"range": r.a1(), "header": header, "sheet": name})));
return ok();
}
if keys.len() > 64 {
+1 -1
View File
@@ -35,7 +35,7 @@ use go_to::go_to_special;
#[cfg(test)]
use go_to::{GO_TO_MAX_AREAS, GO_TO_RECENT, reference_parts};
use paste_special::paste_special;
pub(crate) use paste_special::{rewrite_all_formulas, rewrite_cell_links, rewrite_python_refs};
pub(crate) use paste_special::{rewrite_all_formulas_many, rewrite_cell_links, rewrite_python_refs};
use selection::{select_all, select_col, select_region, select_row, selection_move, selection_next, selection_next_corner, selection_set};
pub fn specs() -> Vec<CommandSpec> {
+29 -11
View File
@@ -566,10 +566,15 @@ fn paste_validations(
/// Applies a reference adjustment to every cell formula and defined name in the workbook.
pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &str, e: &gridcraft_formula::adjust::Edit) -> Result<()> {
rewrite_all_formulas_many(wb, target, std::slice::from_ref(e))
}
/// [`rewrite_all_formulas`] for several edits applied in order, visiting each formula once.
pub(crate) fn rewrite_all_formulas_many(wb: &mut gridcraft_model::Workbook, target: &str, edits: &[gridcraft_formula::adjust::Edit]) -> Result<()> {
use gridcraft_formula::adjust::Edit;
// Rows and columns inserted or deleted on the target sheet move its legacy array ranges too
// (a cut moves its arrays itself).
let moves_arrays = matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. });
let moves_arrays = |e: &Edit| matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. });
for si in 0..wb.sheets.len() {
let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default();
let keys: Vec<(CellRef, std::sync::Arc<Formula>)> =
@@ -577,16 +582,29 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &
if keys.is_empty() {
continue;
}
let on_target = moves_arrays && host.eq_ignore_ascii_case(target);
let on_target = host.eq_ignore_ascii_case(target);
let Some(sheet) = wb.sheet_mut(si) else { continue };
for (c, f) in keys {
// Borrows the tree and copies and prints only the formulas the edit changes. A formula
// the edit leaves alone keeps its stored text, even if that text is not canonical.
let Some(new) = f.with_expr(|x| gridcraft_formula::adjust::adjust_if_changed(x, &host, target, e)) else { continue };
let array = match f.array {
Some(a) if on_target => crate::cmd::sheet::map_range(a, e),
a => a,
// Borrows the tree and copies and prints only the formulas the edits change. A formula
// the edits leave alone keeps its stored text, even if that text is not canonical.
let Some(new) = f.with_expr(|x| {
let mut cur: Option<gridcraft_formula::Expr> = None;
for e in edits {
if let Some(n) = gridcraft_formula::adjust::adjust_if_changed(cur.as_ref().unwrap_or(x), &host, target, e) {
cur = Some(n);
}
}
cur
}) else {
continue;
};
let mut array = f.array;
for e in edits {
array = match array {
Some(a) if on_target && moves_arrays(e) => crate::cmd::sheet::map_range(a, e),
a => a,
};
}
let nf = match new {
Some(new) => Formula { array, dynamic: f.dynamic, ..Formula::from_expr(new) },
None if array != f.array => Formula { array, ..(*f).clone() },
@@ -600,12 +618,12 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &
for n in wb.names.iter_mut() {
if let Ok(expr) = gridcraft_formula::parse_name(&n.formula) {
// Names are workbook-level: unqualified refs don't occur; qualified ones adjust.
let new = gridcraft_formula::adjust::adjust(expr, "\u{0}", target, e);
let new = edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, "\u{0}", target, e));
n.formula = gridcraft_formula::print(&new);
}
}
rewrite_cell_links(wb, |host, expr| gridcraft_formula::adjust::adjust(expr, host, target, e));
rewrite_python_refs(wb, &|host, expr| gridcraft_formula::adjust::adjust(expr, host, target, e))
rewrite_cell_links(wb, |host, expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e)));
rewrite_python_refs(wb, &|host, expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e)))
}
/// Runs `f` over every reference a floating object holds (a chart's series values, categories,
+11 -1
View File
@@ -22,7 +22,7 @@ mod window;
pub(crate) use cells::is_checkbox_cell;
use cells::{background, checkbox, draw_border, new_cell_style, recently_used, theme_colors, theme_fonts, toggle_checkbox, use_in_formula};
use chart::{add_element, change_colors, format_series, move_chart, quick_layout, select_data};
use chart::{add_element, change_colors, format_series, move_chart, quick_layout, select_data, set_values_range};
use data::{from_csv, from_table_range, queries, table_resize};
use objects::{align, arrange, rotate, selection_pane, shape_fill, shape_outline};
pub(crate) use scripts::has_scripts;
@@ -61,6 +61,16 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
select_data
),
// Dragging a corner of a selected chart's values outline on the sheet (#4389).
cmd!(
"chart.setValuesRange",
"Resize Chart Data",
[],
None,
"{chart?, range: \"B2:C9\" (the block every series' values come from, one column or row per series, on the data's sheet; names and category labels that line up follow it, series keep their formatting)}",
has_doc,
set_values_range
),
cmd!("chart.changeType", "Change Chart Type…", ["Chart Design", "Type"], None, "{chart?, type, subtype?}", has_doc, |s, p| s
.execute("chart.set", p.clone())),
cmd!(
+32
View File
@@ -233,6 +233,38 @@ pub(super) fn select_data(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// Points the chart's series at another block of cells on their sheet, keeping each series'
/// formatting, as dragging a corner of the selected chart's values outline does (#4389).
pub(super) fn set_values_range(s: &mut Session, p: &Json) -> Result<Json> {
use crate::chart_data::{ValuesError, chart_data, with_values};
let text = str_param(p, "range").ok_or_else(|| bad("chart.setValuesRange", "missing `range`"))?;
let (si, ci) = find_chart(s, p)?;
let d = s.doc()?;
let chart = d.wb.sheet(si).and_then(|sh| sh.charts.get(ci)).ok_or_else(|| bad("chart", "no such chart"))?;
let Some(data) = chart_data(&d.wb, si, chart) else {
return Err(bad("chart.setValuesRange", "the chart's series are not one block of cells"));
};
let (sheet_name, body) = split_sheet(text.trim().trim_start_matches('='));
if let Some(n) = sheet_name
&& d.wb.sheet_index(&n) != Some(data.sheet)
{
return Err(bad("chart.setValuesRange", "the range must be on the sheet the chart's data is on"));
}
let to = RangeRef::parse(body).ok_or_else(|| bad("chart.setValuesRange", "not a range"))?;
let new = with_values(&d.wb, si, chart, to).map_err(|e| match e {
ValuesError::NotABlock => bad("chart.setValuesRange", "the chart's series are not one block of cells"),
ValuesError::TooLarge => bad("chart.setValuesRange", "range too large for a chart"),
})?;
let values = format!("{}!{}", gridcraft_formula::quote_sheet(d.wb.sheet(data.sheet).map_or("", |sh| sh.name.as_str())), to.a1());
with_chart(s, p, move |c| {
c.series = new.series;
c.source = new.source;
c.by_rows = new.by_rows;
Ok(())
})
.map(|r| json!({"chart": r["chart"], "values": values}))
}
pub(super) fn move_chart(s: &mut Session, p: &Json) -> Result<Json> {
let (si, ci) = find_chart(s, p)?;
let target = match p.get("sheet").and_then(Json::as_str) {
+1 -1
View File
@@ -177,7 +177,7 @@ pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str
let mut pics = PicCache::default();
for lay in layouts {
let Some(sh) = wb.sheet(lay.sheet) else { continue };
let mut cf = if sh.cond_formats.is_empty() { None } else { Some(crate::cf::CfCache::new()) };
let mut cf = crate::cf::CfCache::new();
let k = lay.k();
let (aw, ah) = lay.avail();
for (pi, (ri, ci)) in lay.pages.iter().enumerate() {
+4 -4
View File
@@ -25,12 +25,12 @@ pub(super) struct Look {
pub(super) cf: Option<crate::cf::CfLook>,
}
fn cell_look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut Option<crate::cf::CfCache>) -> Look {
fn cell_look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut crate::cf::CfCache) -> Look {
let mut style = match sh.table_at(c) {
Some(t) => crate::tables::table_cell_style(wb, si, t, c),
Some(t) => crate::tables::table_cell_shown_style(wb, si, t, cf.table_edges(sh, t), c),
None => wb.styles.get(sh.style_id(c)).clone(),
};
let cfl = cf.as_mut().and_then(|cache| cache.look(wb, si, c));
let cfl = cf.look(wb, si, c);
if let Some(st) = cfl.as_ref().and_then(|l| l.style.as_ref()) {
if st.align.reading_order.is_some() {
style.align.reading_order = st.align.reading_order;
@@ -319,7 +319,7 @@ impl<'a> Covered<'a> {
}
/// Draws the cells of a block: fills, gridlines, data bars, borders and text.
pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut Option<crate::cf::CfCache>) {
pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut crate::cf::CfCache) {
let (bx, by) = (b.xs.first().copied().unwrap_or(0.0), b.ys.first().copied().unwrap_or(0.0));
let (bw, bh) = (b.xs.last().copied().unwrap_or(bx) - bx, b.ys.last().copied().unwrap_or(by) - by);
if bw <= 0.0 || bh <= 0.0 {
+21 -18
View File
@@ -242,15 +242,20 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert:
/// Rewrites every formula reference (chart series included), sparkline source and PivotTable
/// source for a structural edit on `target`.
pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) -> Result<()> {
cx.edits.push((target.to_string(), e.clone()));
rewrite_many(cx, target, std::slice::from_ref(e))
}
/// [`rewrite`] for several edits applied in order, parsing each reference once.
fn rewrite_many(cx: &mut Ctx, target: &str, edits: &[Edit]) -> Result<()> {
cx.edits.extend(edits.iter().map(|e| (target.to_string(), e.clone())));
let wb = &mut cx.wb;
super::edit::rewrite_all_formulas(wb, target, e)?;
super::edit::rewrite_all_formulas_many(wb, target, edits)?;
for si in 0..wb.sheets.len() {
let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default();
let Some(sh) = wb.sheet_mut(si) else { continue };
let fix = |text: &str| -> String {
match gridcraft_formula::parse(text) {
Ok(expr) => gridcraft_formula::print(&gridcraft_formula::adjust::adjust(expr, &host, target, e)),
Ok(expr) => gridcraft_formula::print(&edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, &host, target, e))),
Err(_) => text.to_string(),
}
};
@@ -263,7 +268,7 @@ pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) -> Result<()> {
let body = pt.source.trim().trim_start_matches('=');
if let Ok(expr) = gridcraft_formula::parse(body) {
let before = gridcraft_formula::print(&expr);
let after = gridcraft_formula::print(&gridcraft_formula::adjust::adjust(expr, &host, target, e));
let after = gridcraft_formula::print(&edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, &host, target, e)));
if after != before {
pt.source = after;
}
@@ -378,23 +383,21 @@ fn delete_lines(s: &mut Session, p: &Json, axis: Axis) -> Result<Json> {
let out = edit(s, |cx| {
let name = cx.wb.sheet(sheet).map(|s| s.name.clone()).unwrap_or_default();
cx.protection_checked = true;
// Last area first, so the earlier ones keep their positions.
for (at, count) in areas {
{
let sh = cx.sheet_mut(sheet)?;
let block = match axis {
Axis::Rows => RangeRef::rows(at, (at + count - 1).min(MAX_ROWS - 1)),
Axis::Cols => RangeRef::cols(at, (at + count - 1).min(MAX_COLS - 1)),
};
sh.take_cells(block);
match axis {
Axis::Rows => sh.cells.shift_rows(at + count, -(count as i64)),
Axis::Cols => sh.cells.shift_cols(at + count, -(count as i64)),
}
{
let sh = cx.sheet_mut(sheet)?;
// Cells move once, past every deleted area above or left of them.
let ascending: Vec<(u32, u32)> = areas.iter().rev().copied().collect();
match axis {
Axis::Rows => sh.cells.delete_rows(&ascending),
Axis::Cols => sh.cells.delete_cols(&ascending),
}
// Last area first, so the earlier ones keep their positions.
for &(at, count) in &areas {
shift_sheet_features(sh, axis, at, count, false);
}
rewrite(cx, &name, &Edit::Delete { axis, at, count })?;
}
let edits: Vec<Edit> = areas.iter().map(|&(at, count)| Edit::Delete { axis, at, count }).collect();
rewrite_many(cx, &name, &edits)?;
cx.structural = true;
Ok(Json::Null)
})?;
+23 -7
View File
@@ -5,7 +5,7 @@ use std::sync::Mutex;
use gridcraft_core::{CellRef, RangeRef, Value};
use gridcraft_model::{Sheet, Workbook};
use gridcraft_numfmt::{Formatted, NumberFormat, format_value};
use gridcraft_numfmt::{Formatted, NumberFormat, format_value, format_value_full};
/// Parsed number formats are cached by code.
pub(crate) fn parsed(code: &str) -> NumberFormat {
@@ -116,7 +116,8 @@ pub fn formula_hidden(wb: &Workbook, sheet: &Sheet, c: CellRef) -> bool {
wb.styles.get(sheet.style_id(at)).protection.hidden
}
/// The text a cell shows (full precision General; the grid narrows General to fit the column).
/// The text a cell shows (General up to the 11-character cell width; the grid narrows General
/// further to fit the column).
pub fn cell_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
if sheet.show_formulas
&& let Some(f) = sheet.cell(c).and_then(|x| x.formula.as_ref())
@@ -124,20 +125,35 @@ pub fn cell_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
{
return format!("={}", f.text);
}
value_text(wb, sheet, c)
shown_text(wb, sheet, c)
}
/// A cell's value with its number format applied, independent of column width: no `#####`
/// and no General narrowing (Save As CSV/Text writes this). Formulas give their result.
/// and no General narrowing (Save As CSV/Text writes this). Formulas give their result. A number
/// shown as General (also through a coloured or sectioned General, or a Text format) is written
/// as [`format_value_full`] writes it, never with an exponent: `&`'s 15 significant digits below
/// 1E+15 (`124412140710`, not `1.24412E+11`), the shortest round-trip digits from 1E+15 (every
/// integer below 1e16 exactly). Excel writes the cell display.
pub fn value_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
let style = wb.styles.get(sheet.style_id(c));
with_fill_space(format_value_full(&sheet.value(c), &parsed(style.num_fmt.as_str()), wb.date_system))
}
/// A cell's value through its number format, General at the 11-character cell width.
fn shown_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
let style = wb.styles.get(sheet.style_id(c));
value_text_as(wb, &sheet.value(c), style.num_fmt.as_str())
}
/// [`value_text`] for a value and a format code given apart from a cell (print takes the code
/// from the cell's effective look, which a conditional format can override).
/// A value through a format code given apart from a cell, as a cell shows it (General at the
/// 11-character cell width). Print takes the code from the cell's effective look, which a
/// conditional format can override.
pub fn value_text_as(wb: &Workbook, v: &Value, code: &str) -> String {
let f = format(v, code, wb);
with_fill_space(format(v, code, wb))
}
/// The formatted text with a single space where a `*x` repeat fill would expand.
fn with_fill_space(f: Formatted) -> String {
match f.fill {
Some((_, pos)) => {
let mut t = f.text;
+48 -15
View File
@@ -558,20 +558,13 @@ pub fn source_path(path: &str) -> Option<std::path::PathBuf> {
/// Save As CSV/Text writes "the text and values as they are displayed in cells" with "all
/// characters in each cell" (Microsoft Support, *Excel formatting and features that are not
/// transferred to other file formats*): number formats applied, never column-width `#####`.
/// One intentional difference: a number shown as General is not narrowed to the cell width and
/// never gets an exponent (`gridcraft_numfmt::format_value_full`). Below 1E+15 it is written as
/// `&` converts it (15 significant digits); from 1E+15 as the shortest digits that read back as
/// the same value (every integer below 1e16 exactly, so long identifiers survive); small numbers
/// that `&` writes in scientific notation as their 15 digits in full.
fn csv(wb: &Workbook, sh: &Sheet, delimiter: u8) -> Result<Vec<u8>> {
gridcraft_xlsx::write_csv(sh, delimiter, |c| {
// General's grid-width formatting rounds large identifiers to scientific notation.
// Delimited files have no column width, so preserve the whole numeric value instead.
if wb.styles.get(sh.style_id(c)).num_fmt.as_str().eq_ignore_ascii_case("General")
&& let gridcraft_core::Value::Number(number) = sh.value(c)
&& number.is_finite()
{
number.to_string()
} else {
crate::display::value_text(wb, sh, c)
}
})
.map_err(|e| EngineError::Other(e.to_string()))
gridcraft_xlsx::write_csv(sh, delimiter, |c| crate::display::value_text(wb, sh, c)).map_err(|e| EngineError::Other(e.to_string()))
}
/// The active sheet as CSV of raw cell values, for automation: numbers at full precision, dates and
@@ -1062,6 +1055,12 @@ pub fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
// A brand-new file gets the restrictive default: no group/other write, whatever the umask.
#[cfg(unix)]
if prior.is_none() {
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o644);
}
let mut f = opts.open(&tmp).map_err(|e| {
let _ = std::fs::remove_file(&tmp);
EngineError::Other(format!("{path}: {e}"))
@@ -1085,16 +1084,50 @@ pub fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
if let Some(p) = &prior {
let _ = f.set_permissions(p.clone());
}
f.write_all(bytes).and_then(|()| f.flush()).map_err(|e| {
// `sync_all` before the rename: without it a power loss right after the rename can leave
// the new name pointing at an empty or truncated file while the old workbook is gone.
// A file system that cannot flush at all (some network mounts; on Apple targets std asks
// for F_FULLFSYNC, which they refuse) keeps the old behaviour: skip the flush, still rename.
let synced = |f: &std::fs::File| f.sync_all().or_else(|e| if full_sync_unsupported(&e) { Ok(()) } else { Err(e) });
f.write_all(bytes).and_then(|()| f.flush()).and_then(|()| synced(&f)).map_err(|e| {
let _ = std::fs::remove_file(&tmp);
EngineError::Other(format!("{path}: {e}"))
})?;
drop(f);
std::fs::rename(&tmp, path).map_err(|e| {
// A write or rename that fails (full disk, the workbook locked by another app) leaves
// no temporary file beside the user's workbook.
let _ = std::fs::remove_file(&tmp);
EngineError::Other(format!("{path}: {e}"))
})
})?;
// Make the rename itself durable. Best effort: the workbook is already in place, so a
// directory that can't be opened or synced (some file systems) is not a failed save.
#[cfg(unix)]
{
let dir = std::path::Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or_else(|| std::path::Path::new("."));
if let Ok(d) = std::fs::File::open(dir) {
let _ = d.sync_all();
}
}
Ok(())
}
/// True when a flush failed only because the file system cannot do it: on Unix ENOTTY (25, what
/// `fcntl(F_FULLFSYNC)` returns on such volumes; on Windows 25 is ERROR_SEEK, a real failure), on
/// Apple targets ENOTSUP (45, which std leaves uncategorized there), or an unsupported-operation
/// error (EOPNOTSUPP/ENOSYS, and ENOTSUP where it equals EOPNOTSUPP). Any other error is a real
/// failure.
#[cfg(not(target_arch = "wasm32"))]
fn full_sync_unsupported(e: &std::io::Error) -> bool {
flush_unsupported_on(e, cfg!(unix), cfg!(target_vendor = "apple"))
}
/// [`full_sync_unsupported`] for a given platform, so each platform's raw codes can be tested
/// on any host.
#[cfg(not(target_arch = "wasm32"))]
fn flush_unsupported_on(e: &std::io::Error, unix: bool, apple: bool) -> bool {
let raw = e.raw_os_error();
(unix && raw == Some(25)) || (apple && raw == Some(45)) || e.kind() == std::io::ErrorKind::Unsupported
}
/// The mode a saved file gets from the file it replaces (`old`): all of it when its group was
+159 -1
View File
@@ -78,6 +78,34 @@ fn restored_mode_drops_the_group_and_special_bits_when_the_group_is_lost() {
assert_eq!(super::restored_mode(0o104_755, false), 0o705, "setuid is dropped");
}
#[cfg(not(target_arch = "wasm32"))]
#[cfg(unix)]
#[test]
fn fresh_save_drops_group_and_other_write_under_a_permissive_umask() {
use std::os::unix::fs::PermissionsExt;
if std::env::var_os("GRIDCRAFT_UMASK_CHILD").is_none() {
// Re-run this test in a child shell whose umask is 0002.
let exe = std::env::current_exe().unwrap();
let status = std::process::Command::new("sh")
.arg("-c")
.arg("umask 0002 && exec \"$0\" --exact io::tests::fresh_save_drops_group_and_other_write_under_a_permissive_umask")
.arg(exe)
.env("GRIDCRAFT_UMASK_CHILD", "1")
.status()
.unwrap();
assert!(status.success());
return;
}
let dir = std::env::temp_dir().join(format!("gridcraft-fs-safety-umask-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let fresh = dir.join("new.xlsx");
write_file(fresh.to_str().unwrap(), b"v").unwrap();
let mode = std::fs::metadata(&fresh).unwrap().permissions().mode() & 0o777;
let _ = std::fs::remove_dir_all(&dir);
assert!(mode & 0o022 == 0, "mode {mode:o}");
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn open_refuses_directories_and_unknowable_lengths() {
@@ -344,6 +372,65 @@ fn failed_save_leaves_no_temporary_file() {
let _ = std::fs::remove_dir_all(&dir);
}
/// A save replaces an existing workbook with exactly the new bytes, and a save into a folder
/// that doesn't exist fails without creating anything. The flush to disk before the rename is
/// not covered: a power loss can't be simulated in a unit test.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn save_writes_exact_bytes_and_fails_cleanly_without_a_folder() {
let dir = std::env::temp_dir().join(format!("gridcraft-write-exact-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let dest = dir.join("Book.xlsx");
std::fs::write(&dest, b"old workbook that is longer than the new one").unwrap();
let bytes: Vec<u8> = (0..=255u8).cycle().take(100_000).collect();
write_file(dest.to_str().unwrap(), &bytes).unwrap();
assert_eq!(std::fs::read(&dest).unwrap(), bytes);
assert!(!dir.join("Book.xlsx.sctmp").exists());
let missing = dir.join("no-such-folder").join("Book.xlsx");
assert!(write_file(missing.to_str().unwrap(), b"x").is_err());
assert!(!dir.join("no-such-folder").exists());
assert_eq!(std::fs::read(&dest).unwrap(), bytes, "the existing workbook is untouched");
let _ = std::fs::remove_dir_all(&dir);
}
/// Only "this file system cannot flush" errors are tolerated when syncing a saved file.
/// The fallback on a real network mount is not tested.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn full_sync_tolerates_only_unsupported_errors() {
use std::io::{Error, ErrorKind};
assert_eq!(full_sync_unsupported(&Error::from_raw_os_error(25)), cfg!(unix));
assert!(full_sync_unsupported(&Error::from(ErrorKind::Unsupported)));
assert!(!full_sync_unsupported(&Error::from(ErrorKind::PermissionDenied)));
assert!(!full_sync_unsupported(&Error::from(ErrorKind::StorageFull)));
assert!(!full_sync_unsupported(&Error::from_raw_os_error(28)), "ENOSPC on Linux");
assert!(!full_sync_unsupported(&Error::from_raw_os_error(5)), "EIO");
}
/// Apple's ENOTSUP is 45 (EOPNOTSUPP is 102), and std maps only the latter to
/// `ErrorKind::Unsupported`: F_FULLFSYNC refused with ENOTSUP must still save. Elsewhere 45 is
/// another error (EL2NSYNC on Linux) and stays a failed save.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn full_sync_tolerates_apple_enotsup() {
use std::io::Error;
let enotsup = Error::from_raw_os_error(45);
assert!(flush_unsupported_on(&enotsup, true, true), "ENOTSUP on Apple");
assert!(!flush_unsupported_on(&enotsup, true, false), "45 on other Unix");
assert!(!flush_unsupported_on(&enotsup, false, false), "45 on Windows");
assert!(flush_unsupported_on(&Error::from_raw_os_error(25), true, true), "ENOTTY on Apple");
assert!(!flush_unsupported_on(&Error::from_raw_os_error(5), true, true), "EIO on Apple");
assert!(!flush_unsupported_on(&Error::from_raw_os_error(28), true, true), "ENOSPC on Apple");
}
/// The real helper on an Apple host: a raw ENOTSUP from F_FULLFSYNC is tolerated.
#[cfg(target_vendor = "apple")]
#[test]
fn full_sync_tolerates_raw_enotsup_on_apple() {
assert!(full_sync_unsupported(&std::io::Error::from_raw_os_error(45)));
}
/// While a script runs (#2178), file reads and writes are refused whatever command or
/// parameter asked for them; nesting and dropping the sandbox restore access.
#[cfg(not(target_arch = "wasm32"))]
@@ -527,9 +614,80 @@ fn delimited_exports_preserve_general_precision_and_explicit_number_formats() {
sheet.set_cell(CellRef::new(0, 0), Cell { value: Value::Number(124412140710.0), ..Default::default() });
sheet.set_cell(CellRef::new(0, 1), Cell { value: Value::Number(1.23456789012345), ..Default::default() });
sheet.set_cell(CellRef::new(0, 2), Cell { value: Value::Number(124412140710.0), style: scientific, ..Default::default() });
// Every integer below 1e16 that f64 holds (also 2^53 and the even integers above it) keeps
// every digit; larger numbers keep the shortest digits that read back as the same value,
// and a number `&` would write with an exponent is written out in full, so reopening the
// file can't give it a scientific format that then rounds it on the next save.
let cells = [
(1234567890123456.0, "1234567890123456"),
(-9007199254740991.0, "-9007199254740991"),
(9007199254740992.0, "9007199254740992"),
(9007199254740994.0, "9007199254740994"),
(9123456789012346.0, "9123456789012346"),
(-9999999999999998.0, "-9999999999999998"),
(12345678901234567.0, "12345678901234568"),
(1e20, "100000000000000000000"),
(1e15 - 0.5, "999999999999999.5"),
(1.0 / 3.0 * 1e-6, "0.000000333333333333333"),
(1.23456789012346e-10, "0.000000000123456789012346"),
];
for (col, (n, _)) in cells.iter().enumerate() {
sheet.set_cell(CellRef::new(0, col as u32 + 3), Cell { value: Value::Number(*n), ..Default::default() });
}
for (path, separator) in [("data.csv", ","), ("data.tsv", "\t")] {
let output = String::from_utf8(save_bytes(&workbook, path).unwrap()).unwrap();
assert_eq!(output, format!("124412140710{separator}1.23456789012345{separator}1.24E+11\r\n"));
let tail: Vec<&str> = cells.iter().map(|(_, text)| *text).collect();
assert_eq!(output, format!("124412140710{s}1.23456789012345{s}1.24E+11{s}{}\r\n", tail.join(separator), s = separator));
// Reopening the file and saving it again changes nothing.
let (reopened, _) = open_bytes(path, output.as_bytes()).unwrap();
assert_eq!(String::from_utf8(save_bytes(&reopened, path).unwrap()).unwrap(), output);
}
}
/// A number shown as General is written as `&` converts it (15 significant digits), whatever
/// colour, sections or literals the format adds, and in a Text cell. Excel writes the cell
/// display (`1.24412E+11`, `0.333333333`); GridCraft keeps the digits so part codes survive
/// (integers below 1e16 keep all their digits, and nothing gets an exponent; see the test above).
#[test]
fn delimited_exports_write_general_numbers_as_text_converts_them() {
use gridcraft_core::Value;
use gridcraft_model::{Cell, NumFmt, StyleId};
let mut wb = Workbook::new();
let mut styled = |code: &str| wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code));
let (blue, signed, red, text, unit) =
(styled("[Blue]General"), styled("General;-General"), styled("General;[Red]-General"), styled("@"), styled("General\" mm\""));
let code = 124412140710.0;
let sh = wb.sheet_mut(0).unwrap();
let cells = [
(Value::Number(1.0 / 3.0), StyleId::DEFAULT),
(Value::Number(0.1 + 0.2), StyleId::DEFAULT),
(Value::Number(1e20), StyleId::DEFAULT),
(Value::Number(code), blue),
(Value::Number(9007199254740994.0), blue),
(Value::Number(-1.0 / 3.0), blue),
(Value::Number(-code), signed),
(Value::Number(-code), red),
(Value::Number(code), text),
(Value::Number(code), unit),
];
for (col, (value, style)) in cells.into_iter().enumerate() {
sh.set_cell(CellRef::new(0, col as u32), Cell { value, formula: None, py: None, style });
}
for (path, sep) in [("out.csv", ","), ("out.txt", "\t")] {
let output = String::from_utf8(save_bytes(&wb, path).unwrap()).unwrap();
let expected = [
"0.333333333333333",
"0.3",
"100000000000000000000",
"124412140710",
"9007199254740994",
"-0.333333333333333",
"-124412140710",
"-124412140710",
"124412140710",
"124412140710 mm",
];
assert_eq!(output, format!("{}\r\n", expected.join(sep)));
}
}
+1
View File
@@ -8,6 +8,7 @@
pub mod catalog;
pub mod cf;
pub mod chart_data;
mod chart_svg;
mod clip_html;
pub mod cmd;
+252 -86
View File
@@ -2,7 +2,7 @@
//! `TableStyleLight1…21 / Medium1…28 / Dark1…11` names so files round-trip).
use gridcraft_core::{CellRef, RangeRef};
use gridcraft_model::{BorderLine, BorderStyle, Cell, Color, Fill, Formula, PatternType, Style, Table, Workbook};
use gridcraft_model::{BorderLine, BorderStyle, Borders, Cell, Color, Fill, Formula, PatternType, Sheet, Style, Table, Workbook};
/// (family, number) from a style name, e.g. `TableStyleMedium2` → ("Medium", 2).
pub fn parse_style_name(name: &str) -> (&'static str, u32) {
@@ -22,113 +22,279 @@ fn accent_for(n: u32) -> Option<u8> {
if k == 0 { None } else { Some(3 + k as u8) }
}
/// Header/band/body colours for a table style.
/// Fills, text colours and thin lines of a table style, per part of the table (the recipes in
/// plan/excel/table-style-spec.json). Band 1 is the first data row; unbanded rows use band 2.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TableLook {
pub header_fill: Option<Color>,
pub header_font: Color,
pub header_bold: bool,
pub band_fill: Option<Color>,
pub body_fill: Option<Color>,
pub line: Option<Color>,
pub total_top: Option<Color>,
pub band1: Option<Color>,
pub band2: Option<Color>,
pub body_font: Color,
pub top: Option<Color>,
pub header_bottom: Option<Color>,
pub inner_h: Option<Color>,
pub inner_v: Option<Color>,
pub sides: Option<Color>,
pub bottom: Option<Color>,
/// The totals row's double top rule (the gallery doesn't show totals).
pub total_top: Color,
}
pub fn look(style: &str) -> TableLook {
let (fam, n) = parse_style_name(style);
let acc = accent_for(n);
let base = |tint: i16| match acc {
Some(a) => Color::Theme(a, tint),
None => Color::Theme(1, if tint == 0 { 0 } else { tint.clamp(-1000, 1000) }),
// An accent tint, or the neutral column's colour.
let a = |tint: i16, neutral: Color| acc.map_or(neutral, |a| Color::Theme(a, tint));
let (black, white) = (Color::Theme(1, 0), Color::Theme(0, 0));
let (grey, mid_grey) = (Color::Theme(0, -150), Color::Theme(0, -350));
let main = a(0, black);
let plain = TableLook {
header_fill: None,
header_font: black,
band1: None,
band2: None,
body_font: black,
top: None,
header_bottom: None,
inner_h: None,
inner_v: None,
sides: None,
bottom: None,
total_top: main,
};
let neutral_light = |tint: i16| match acc {
Some(a) => Color::Theme(a, tint),
None => Color::Theme(0, -((1000 - tint).clamp(0, 1000) / 6)),
};
match fam {
"Light" => {
let group = (n - 1) / 7; // 0: lines only, 1: banded header line, 2: grid
match (fam, n.saturating_sub(1) / 7) {
("Light", 0) => {
let text = a(-250, black);
let line = Some(main);
TableLook { header_font: text, body_font: text, band1: Some(a(800, grey)), top: line, header_bottom: line, bottom: line, ..plain }
}
("Light", 1) => {
let line = Some(main);
TableLook { header_fill: line, header_font: white, top: line, inner_h: line, sides: line, bottom: line, ..plain }
}
("Light", _) => {
let line = Some(main);
TableLook { band1: Some(a(800, grey)), top: line, header_bottom: line, inner_v: line, sides: line, bottom: line, ..plain }
}
("Medium", 0) => {
let line = Some(a(400, black));
TableLook { header_fill: Some(main), header_font: white, band1: Some(a(800, grey)), top: line, sides: line, bottom: line, ..plain }
}
("Medium", 1) => TableLook {
header_fill: Some(main),
header_font: white,
band1: Some(a(600, mid_grey)),
band2: Some(a(800, grey)),
header_bottom: Some(white),
inner_v: Some(white),
..plain
},
("Medium", 2) => {
// Accent header over neutral grey bands and black rules; the neutral style adds a grid.
let line = Some(black);
let grid = if acc.is_none() { line } else { None };
let header_fill = Some(main);
TableLook {
header_fill: None,
header_font: if group == 0 { base(-250) } else { Color::Auto },
header_bold: true,
band_fill: Some(neutral_light(800)),
body_fill: None,
line: Some(base(0)),
total_top: Some(base(0)),
header_fill,
header_font: white,
band1: Some(grey),
top: line,
header_bottom: line,
inner_v: grid,
sides: grid,
bottom: line,
total_top: black,
..plain
}
}
"Dark" => TableLook {
header_fill: Some(Color::Theme(1, 0)),
header_font: Color::Theme(0, 0),
header_bold: true,
band_fill: Some(base(-250)),
body_fill: Some(base(0)),
line: None,
total_top: Some(Color::Theme(0, 0)),
},
_ => TableLook {
header_fill: Some(base(0)),
header_font: Color::Theme(0, 0),
header_bold: true,
band_fill: Some(neutral_light(800)),
body_fill: None,
line: if (n - 1) / 7 == 0 { None } else { Some(base(400)) },
total_top: Some(base(0)),
("Medium", _) => {
let line = Some(a(400, black));
let pale = Some(a(800, grey));
TableLook { header_fill: pale, band1: Some(a(600, mid_grey)), band2: pale, top: line, inner_v: line, sides: line, bottom: line, ..plain }
}
("Dark", 0) => TableLook {
header_fill: Some(black),
header_font: white,
band1: Some(a(-250, Color::Theme(1, 250))),
band2: Some(a(0, Color::Theme(1, 450))),
body_font: white,
header_bottom: Some(white),
total_top: white,
..plain
},
_ if n == 8 => TableLook { header_fill: Some(black), header_font: white, band1: Some(mid_grey), band2: Some(grey), ..plain },
_ => {
// Dark 9-11 pair accents 1+2, 3+4 and 5+6: the header takes the even one.
let k = n.clamp(9, 11) as u8 - 8;
let (head, body) = (Color::Theme(3 + 2 * k, 0), 2 + 2 * k);
let band1 = Some(Color::Theme(body, 600));
TableLook { header_fill: Some(head), header_font: white, band1, band2: Some(Color::Theme(body, 800)), total_top: head, ..plain }
}
}
}
/// The style a table gives a cell (merged over the cell's own style: explicit fills/fonts win).
/// Which parts of a table are on (the Table Style Options checkboxes).
#[derive(Clone, Copy, Debug)]
pub struct TableParts {
pub header_row: bool,
pub totals_row: bool,
pub banded_rows: bool,
pub banded_cols: bool,
pub first_col: bool,
pub last_col: bool,
}
impl TableParts {
pub fn of(t: &Table) -> TableParts {
TableParts {
header_row: t.header_row,
totals_row: t.totals_row,
banded_rows: t.banded_rows,
banded_cols: t.banded_cols,
first_col: t.first_col,
last_col: t.last_col,
}
}
}
/// What a table style paints on one cell of a `rows` x `cols` table (`row`, `col` from its
/// top-left). Each line has one owner: a horizontal line is a cell's bottom (top only on the
/// first row and the totals row), a vertical one a cell's right (left only on the first column).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct CellLook {
pub fill: Option<Color>,
pub font: Color,
pub bold: bool,
pub borders: Borders,
}
pub fn cell_look(lk: &TableLook, p: TableParts, row: u32, col: u32, rows: u32, cols: u32) -> CellLook {
let last_row = rows.saturating_sub(1);
let last_col = cols.saturating_sub(1);
let is_header = p.header_row && row == 0;
let is_total = p.totals_row && row == last_row && !is_header;
let thin = |c: Option<Color>| c.map(|color| BorderLine { style: BorderStyle::Thin, color }).unwrap_or_default();
let mut b = Borders::default();
if row == 0 {
b.top = thin(lk.top);
}
b.bottom = thin(if row == last_row {
lk.bottom
} else if is_header {
lk.header_bottom
} else if p.totals_row && row.saturating_add(1) == last_row {
None // the totals row draws its own top rule
} else {
lk.inner_h
});
if col == 0 {
b.left = thin(lk.sides);
}
b.right = thin(if col == last_col { lk.sides } else { lk.inner_v });
let mut out = CellLook { borders: b, font: lk.body_font, ..Default::default() };
if is_header {
out.fill = lk.header_fill;
out.font = lk.header_font;
out.bold = true;
} else if is_total {
out.fill = lk.band2;
out.bold = true;
out.borders.top = BorderLine { style: BorderStyle::Double, color: lk.total_top };
} else {
let data_row = row.saturating_sub(p.header_row as u32);
let band1 = (p.banded_rows && data_row.is_multiple_of(2)) || (p.banded_cols && col.is_multiple_of(2));
out.fill = if band1 { lk.band1 } else { lk.band2 };
}
if (p.first_col && col == 0) || (p.last_col && col == last_col) {
out.bold = true;
}
out
}
/// The style a table gives a cell (merged over the cell's own style: explicit fills, fonts and
/// borders win).
pub fn table_cell_style(wb: &Workbook, sheet: usize, t: &Table, c: CellRef) -> Style {
let own = wb.sheet(sheet).map(|sh| wb.styles.get(sh.style_id(c)).clone()).unwrap_or_default();
let (start, end) = (t.range.start, t.range.end);
let rows = end.row.saturating_sub(start.row).saturating_add(1);
let cols = end.col.saturating_sub(start.col).saturating_add(1);
let lk = cell_look(&look(&t.style), TableParts::of(t), c.row.saturating_sub(start.row), c.col.saturating_sub(start.col), rows, cols);
let mut s = own.clone();
let lk = look(&t.style);
let is_header = t.header_row && c.row == t.range.start.row;
let is_total = t.totals_row && c.row == t.range.end.row;
let data_row = c.row.saturating_sub(t.range.start.row + t.header_row as u32);
let data_col = c.col - t.range.start.col;
let explicit_fill = own.fill.pattern != PatternType::None;
if is_header {
if let Some(f) = lk.header_fill
&& !explicit_fill
{
s.fill = Fill::solid(f);
}
if own.font.color == Color::Auto {
s.font.color = lk.header_font;
}
s.font.bold = s.font.bold || lk.header_bold;
if let Some(l) = lk.line {
s.borders.bottom = BorderLine { style: BorderStyle::Thin, color: l };
}
} else if is_total {
s.font.bold = true;
if let Some(l) = lk.total_top {
s.borders.top = BorderLine { style: BorderStyle::Double, color: l };
}
} else {
let band = (t.banded_rows && data_row.is_multiple_of(2)) || (t.banded_cols && data_col.is_multiple_of(2));
if !explicit_fill {
if band {
if let Some(f) = lk.band_fill {
s.fill = Fill::solid(f);
}
} else if let Some(f) = lk.body_fill {
s.fill = Fill::solid(f);
}
}
if let Some(l) = lk.line
&& t.style.contains("Light")
&& c.row == t.range.end.row
{
s.borders.bottom = BorderLine { style: BorderStyle::Thin, color: l };
if let Some(f) = lk.fill
&& own.fill.pattern == PatternType::None
{
s.fill = Fill::solid(f);
}
if own.font.color == Color::Auto {
s.font.color = lk.font;
}
s.font.bold = s.font.bold || lk.bold;
for (side, line) in [
(&mut s.borders.top, lk.borders.top),
(&mut s.borders.bottom, lk.borders.bottom),
(&mut s.borders.left, lk.borders.left),
(&mut s.borders.right, lk.borders.right),
] {
if side.is_none() {
*side = line;
}
}
if (t.first_col && c.col == t.range.start.col) || (t.last_col && c.col == t.range.end.col) {
s.font.bold = true;
s
}
/// A table's first and last visible row and column (hidden or filtered lines skipped).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ShownEdges {
pub top: u32,
pub bottom: u32,
pub left: u32,
pub right: u32,
}
/// Finds [`ShownEdges`]. It scans the hidden lines at each edge, so the grid and print call it
/// once per table per paint (through [`crate::cf::CfCache::table_edges`]), not once per cell.
pub fn shown_edges(sh: &Sheet, t: &Table) -> ShownEdges {
let (start, end) = (t.range.start, t.range.end);
let row_shown = |r: &u32| sh.row_height(*r) > 0.0;
let col_shown = |k: &u32| sh.col_width(*k) > 0.0;
// With every row (or column) hidden, each cell takes both edges' lines; nothing is drawn.
ShownEdges {
top: (start.row..=end.row).find(row_shown).unwrap_or(end.row),
bottom: (start.row..=end.row).rev().find(row_shown).unwrap_or(start.row),
left: (start.col..=end.col).find(col_shown).unwrap_or(end.col),
right: (start.col..=end.col).rev().find(col_shown).unwrap_or(start.col),
}
if t.style.starts_with("TableStyleDark") && !is_header && own.font.color == Color::Auto {
s.font.color = Color::Theme(0, 0);
}
/// The style the grid and print draw for a table cell. Like [`table_cell_style`], but the
/// table's outer frame follows hidden rows and columns: the last visible row takes the table's
/// bottom line, the last visible column its right side, and the first visible row and column its
/// top line and left side. (Each frame line is owned by the edge cell, which is never drawn while
/// it is hidden or filtered out.) Convert to Range uses [`table_cell_style`], the table as it is.
pub fn table_cell_shown_style(wb: &Workbook, sheet: usize, t: &Table, e: ShownEdges, c: CellRef) -> Style {
let mut s = table_cell_style(wb, sheet, t, c);
let Some(sh) = wb.sheet(sheet) else { return s };
let (start, end) = (t.range.start, t.range.end);
let below = c.row < end.row && c.row >= e.bottom;
let above = c.row > start.row && c.row <= e.top;
let right = c.col < end.col && c.col >= e.right;
let left = c.col > start.col && c.col <= e.left;
if !(below || above || right || left) {
return s;
}
let own = wb.styles.get(sh.style_id(c)).borders;
if below && own.bottom.is_none() {
s.borders.bottom = table_cell_style(wb, sheet, t, CellRef::new(end.row, c.col)).borders.bottom;
}
if above && own.top.is_none() {
s.borders.top = table_cell_style(wb, sheet, t, CellRef::new(start.row, c.col)).borders.top;
}
if right && own.right.is_none() {
s.borders.right = table_cell_style(wb, sheet, t, CellRef::new(c.row, end.col)).borders.right;
}
if left && own.left.is_none() {
s.borders.left = table_cell_style(wb, sheet, t, CellRef::new(c.row, start.col)).borders.left;
}
s
}
+98 -9
View File
@@ -869,6 +869,65 @@ fn deleting_a_multi_area_row_selection_removes_every_area_and_undoes_once() {
assert_eq!((v(&s, "A1"), v(&s, "B1"), v(&s, "C1")), (Value::Number(2.0), Value::Number(4.0), Value::Empty));
}
#[test]
#[allow(clippy::disallowed_methods)] // native-only test: timing the two deletes
fn deleting_many_separate_rows_takes_about_as_long_as_one_block() {
// #2287: every 10th row of a 12,000-row sheet, as 1,200 single-row areas.
let (rows, step) = (12_000u32, 10u32);
let values: Vec<serde_json::Value> = (0..rows).map(|r| json!([r, r + 100_000, r + 200_000])).collect();
let deleted = |r: u32| r >= 1 && (r - 1).is_multiple_of(step);
let list = (0..rows).filter(|&r| deleted(r)).map(|r| format!("{0}:{0}", r + 1)).collect::<Vec<_>>().join(",");
let build = || {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap();
s.execute("cell.set", json!({"cell": "E1", "input": format!("=SUM(A1:A{rows})")})).unwrap();
s.execute("cell.set", json!({"cell": "E3", "input": "=B25"})).unwrap();
s
};
let mut block = build();
let t = std::time::Instant::now();
block.execute("home.deleteRows", json!({"rows": format!("2:{}", rows / step + 1)})).unwrap();
let block_time = t.elapsed();
let mut s = build();
let t = std::time::Instant::now();
s.execute("home.deleteRows", json!({"rows": list})).unwrap();
let separate_time = t.elapsed();
let kept: Vec<u32> = (0..rows).filter(|&r| !deleted(r)).collect();
let d = s.doc().unwrap();
let sh = d.wb.active().unwrap();
assert_eq!(sh.used_range().unwrap().end.row as usize, kept.len() - 1);
for (i, r) in kept.iter().enumerate() {
assert_eq!(sh.value(CellRef::new(i as u32, 0)), Value::Number(*r as f64));
assert_eq!(sh.value(CellRef::new(i as u32, 2)), Value::Number((*r + 200_000) as f64));
}
assert_eq!(s.execute("cell.get", json!({"cell": "E1"})).unwrap()["formula"], format!("=SUM(A1:A{})", kept.len()));
// B25 loses rows 2, 12 and 22 above it; the formula itself moves from E3 to E2.
assert_eq!(s.execute("cell.get", json!({"cell": "E2"})).unwrap()["formula"], "=B22");
assert!(
separate_time < block_time * 20 + std::time::Duration::from_millis(500),
"separate rows took {separate_time:?}, one block took {block_time:?}"
);
}
#[test]
fn deleting_many_separate_columns_matches_per_area_result() {
let mut s = s();
let values: Vec<serde_json::Value> = (0..50).map(|r| json!((0..40).map(|c| r * 100 + c).collect::<Vec<_>>())).collect();
s.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap();
s.execute("cell.set", json!({"cell": "A60", "input": "=SUM(A1:AN1)+H2"})).unwrap();
// Columns B, E, H (refs) and F:G.
s.execute("home.deleteColumns", json!({"cols": "B:B,E:E,H:H,F:G"})).unwrap();
let kept: Vec<u32> = (0..40).filter(|c| ![1, 4, 5, 6, 7].contains(c)).collect();
for r in 0..50u32 {
for (i, c) in kept.iter().enumerate() {
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::new(r, i as u32)), Value::Number((r * 100 + c) as f64));
}
}
assert_eq!(s.execute("cell.get", json!({"cell": "A60"})).unwrap()["formula"], "=SUM(A1:AI1)+#REF!");
}
#[test]
fn move_columns_reorders_without_overwriting_and_undoes_once() {
let mut s = s();
@@ -3078,9 +3137,10 @@ fn overlapping_spills_keep_the_one_that_exists_whichever_anchor_is_first() {
#[test]
fn a_spill_growing_into_another_and_back_matches_a_full_recalc_at_every_step() {
use gridcraft_core::CellError::Spill;
// Both arrays already spill; F8 (first in reading order) grows down over E10's spill, takes
// its cells, shrinks back and lets it spill again, then the steps are undone, redone, edited
// inside the contested area and cleared. Every state must match a full recalc.
// Both arrays already spill; F8 (first in reading order) grows down over E10's spill, is
// #SPILL! because E10 holds those cells (as in Excel), shrinks back and spills again, then the
// steps are undone, redone, edited inside the contested area and cleared. Every state must
// match a full recalc.
let mut s = s();
s.execute("cell.set", json!({"cell": "H1", "input": "1"})).unwrap();
s.execute("cell.set", json!({"cell": "F8", "input": "=SEQUENCE(H1)"})).unwrap();
@@ -3102,18 +3162,18 @@ fn a_spill_growing_into_another_and_back_matches_a_full_recalc_at_every_step() {
s.execute(id, params.clone()).unwrap();
assert_matches_full_recalc(&s);
if i == 0 {
// Both held a spill: reading order gives F8 the cells.
assert_eq!(v(&s, "F12"), Value::Number(5.0));
assert_eq!(v(&s, "E10"), Value::Error(Spill));
// Both held a spill: E10 holds F10, so it keeps it and F8 is blocked.
assert_eq!(v(&s, "F8"), Value::Error(Spill));
assert_eq!(v(&s, "F10"), Value::Number(20.0));
}
if i == 2 {
assert_eq!(v(&s, "E10"), Value::Number(10.0));
assert_eq!(v(&s, "F10"), Value::Number(20.0));
}
if i == 3 {
// Undone back to the grown F8.
assert_eq!(v(&s, "F12"), Value::Number(5.0));
assert_eq!(v(&s, "E10"), Value::Error(Spill));
// Undone back to the grown F8, blocked again.
assert_eq!(v(&s, "F8"), Value::Error(Spill));
assert_eq!(v(&s, "F10"), Value::Number(20.0));
}
if i == 8 {
assert_eq!((v(&s, "F8"), v(&s, "E10"), v(&s, "F9")), (Value::Empty, Value::Empty, Value::Empty));
@@ -3355,6 +3415,21 @@ fn a_spill_that_goes_away_unblocks_another() {
assert_eq!((v(&s, "E10"), v(&s, "G10")), (Value::Number(1.0), Value::Number(3.0)));
}
#[test]
fn a_contested_spill_area_stays_with_its_array_after_reopening() {
// F13's array wants F14:G14, which C14's array already fills, so F13 is #SPILL!. The file
// can only cache #VALUE! for it; reopening (which recalculates) used to hand the area to F13
// for coming first in reading order.
let mut s = s();
s.execute("cell.set", json!({"cell": "C14", "input": "=SEQUENCE(1,7)"})).unwrap();
s.execute("cell.set", json!({"cell": "F13", "input": "=SEQUENCE(5,2)"})).unwrap();
assert_eq!(v(&s, "F13"), Value::Error(gridcraft_core::CellError::Spill));
let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
s.execute("file.open", json!({"name": "contested.xlsx", "base64": saved["base64"]})).unwrap();
assert_eq!(v(&s, "F13"), Value::Error(gridcraft_core::CellError::Spill));
assert_eq!((v(&s, "C14"), v(&s, "G14"), v(&s, "I14")), (Value::Number(1.0), Value::Number(5.0), Value::Number(7.0)));
}
#[test]
fn an_array_reading_another_arrays_spill_is_updated() {
// G5 is evaluated before D11 in the same pass, so it first reads D11's old spill.
@@ -3379,6 +3454,19 @@ fn indirect_reads_a_spill_laid_out_in_the_same_pass() {
assert_eq!(v(&s, "E5"), Value::Number(9.0));
}
#[test]
fn inserting_rows_lays_out_spills_where_the_formulas_moved() {
// D1's array grows with the inserted rows to D1:D10 and C10's array moves down to C12:E14:
// the area C10:E12 it filled before the insertion blocks neither of them.
let mut s = s();
s.execute("cell.set", json!({"cell": "D1", "input": "=SEQUENCE(ROWS(A2:A9))"})).unwrap();
s.execute("cell.set", json!({"cell": "C8", "input": "=1"})).unwrap();
s.execute("cell.set", json!({"cell": "C10", "input": "=SEQUENCE(3,3)"})).unwrap();
s.execute("home.insertRows", json!({"rows": "3:4"})).unwrap();
assert_eq!((v(&s, "D1"), v(&s, "D10")), (Value::Number(1.0), Value::Number(10.0)));
assert_eq!((v(&s, "C12"), v(&s, "D12"), v(&s, "E14")), (Value::Number(1.0), Value::Number(2.0), Value::Number(9.0)));
}
#[test]
fn every_command_survives_empty_params() {
let mut s = Session::new();
@@ -6624,6 +6712,7 @@ fn a_script_cannot_switch_windows() {
assert_eq!(v(&s, "A1"), Value::number(2.0));
}
mod chart_data;
mod controls;
mod equation;
mod json_golden;
+177
View File
@@ -0,0 +1,177 @@
//! A chart's data as blocks on the sheet, and `chart.setValuesRange`, which dragging a corner of a
//! selected chart's values outline runs (#4389, #4390).
use gridcraft_core::RangeRef;
use gridcraft_model::{Chart, Color};
use serde_json::json;
use super::s;
use crate::Session;
use crate::chart_data::{ChartData, chart_data};
fn r(a: &str) -> RangeRef {
RangeRef::parse(a).unwrap()
}
fn chart(s: &Session) -> Chart {
s.doc().unwrap().wb.active().unwrap().charts[0].clone()
}
fn data(s: &Session) -> Option<ChartData> {
chart_data(&s.doc().unwrap().wb, 0, &chart(s))
}
/// Points each plotted series has, as the chart resolves them.
fn points(s: &Session) -> Vec<usize> {
gridcraft_chart::resolve(&s.doc().unwrap().wb, 0, &chart(s)).series.iter().map(|se| se.values.len()).collect()
}
/// 10..80 down A1:A8, charted from A1:A5 only.
fn single_column() -> Session {
let mut s = s();
let values: Vec<_> = (1..=8).map(|i| json!([i * 10])).collect();
s.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap();
s.execute("selection.set", json!({"range": "A1:A5"})).unwrap();
s.execute("insert.chart", json!({"type": "column"})).unwrap();
s
}
/// Region names across row 1, quarters down column A, charted from A1:C4.
fn table() -> Session {
let mut s = s();
s.execute(
"range.setValues",
json!({"range": "A1", "values": [
["", "North", "South", "East"],
["Q1", 10, 15, 12],
["Q2", 20, 25, 22],
["Q3", 30, 35, 32],
["Q4", 40, 45, 42],
["Q5", 50, 55, 52],
]}),
)
.unwrap();
s.execute("selection.set", json!({"range": "A1:C4"})).unwrap();
s.execute("insert.chart", json!({"type": "column"})).unwrap();
s
}
#[test]
fn a_plain_column_chart_is_one_values_block() {
let s = single_column();
assert_eq!(data(&s), Some(ChartData { sheet: 0, values: r("A1:A5"), by_rows: false, categories: None, names: None }));
}
#[test]
fn a_table_chart_has_names_categories_and_values_blocks() {
let s = table();
assert_eq!(data(&s), Some(ChartData { sheet: 0, values: r("B2:C4"), by_rows: false, categories: Some(r("A2:A4")), names: Some(r("B1:C1")) }));
}
#[test]
fn dragging_the_values_down_plots_the_new_rows_and_undo_puts_them_back() {
let mut s = single_column();
assert_eq!(points(&s), [5]);
let out = s.execute("chart.setValuesRange", json!({"range": "A1:A8"})).unwrap();
assert_eq!(out["values"], "Sheet1!A1:A8");
assert_eq!(chart(&s).series[0].values, "Sheet1!$A$1:$A$8");
assert_eq!(points(&s), [8]);
assert_eq!(data(&s).unwrap().values, r("A1:A8"));
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(points(&s), [5]);
assert_eq!(chart(&s).series[0].values, "Sheet1!$A$1:$A$5");
}
#[test]
fn a_wider_block_adds_series_and_existing_series_keep_their_formatting() {
let mut s = table();
s.execute("chart.formatSelection", json!({"series": 1, "color": "#C00000"})).unwrap();
let south = chart(&s).series[1].color;
assert!(south.is_some());
s.execute("chart.setValuesRange", json!({"range": "B2:D6"})).unwrap();
let c = chart(&s);
assert_eq!(c.series.len(), 3);
assert_eq!(c.series[1].color, south, "South keeps its colour");
assert_eq!(c.series[2].color, None::<Color>, "the new series takes the automatic colour");
let names: Vec<_> = c.series.iter().map(|se| se.name.clone().unwrap()).collect();
assert_eq!(names, ["Sheet1!$B$1", "Sheet1!$C$1", "Sheet1!$D$1"], "names follow along the header row");
assert!(c.series.iter().all(|se| se.categories.as_deref() == Some("Sheet1!$A$2:$A$6")), "labels span the new points");
assert_eq!(c.series[2].values, "Sheet1!$D$2:$D$6");
assert_eq!(c.source.as_deref(), Some("Sheet1!A1:D6"), "Switch Row/Column sees the moved blocks");
assert_eq!(points(&s), [5, 5, 5]);
assert_eq!(data(&s), Some(ChartData { sheet: 0, values: r("B2:D6"), by_rows: false, categories: Some(r("A2:A6")), names: Some(r("B1:D1")) }));
// A narrower block drops the last series.
s.execute("chart.setValuesRange", json!({"range": "B2:B3"})).unwrap();
let c = chart(&s);
assert_eq!(c.series.len(), 1);
assert_eq!(c.series[0].categories.as_deref(), Some("Sheet1!$A$2:$A$3"));
s.execute("chart.switchRowColumn", json!({})).unwrap();
}
#[test]
fn series_in_rows_grow_across_the_columns() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]})).unwrap();
s.execute("selection.set", json!({"range": "A1:E2"})).unwrap();
s.execute("insert.chart", json!({"type": "line"})).unwrap();
assert_eq!(data(&s).map(|d| (d.values, d.by_rows)), Some((r("A1:E2"), true)));
s.execute("chart.setValuesRange", json!({"range": "A1:G2"})).unwrap();
assert_eq!(points(&s), [7, 7]);
assert_eq!(chart(&s).series[1].values, "Sheet1!$A$2:$G$2");
}
/// Changes the first chart on the first sheet in place, as a file can leave it.
fn edit_chart(s: &mut Session, f: impl FnOnce(&mut Chart)) {
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
f(&mut wb.sheet_mut(0).unwrap().charts[0]);
}
#[test]
fn category_labels_written_with_and_without_equals_are_one_block() {
let mut s = table();
edit_chart(&mut s, |c| c.series[1].categories = Some("=Sheet1!$A$2:$A$4".into()));
assert_eq!(data(&s).unwrap().categories, Some(r("A2:A4")));
s.execute("chart.setValuesRange", json!({"range": "B2:C6"})).unwrap();
assert!(chart(&s).series.iter().all(|se| se.categories.as_deref() == Some("Sheet1!$A$2:$A$6")), "both series' labels follow");
}
#[test]
fn series_read_in_rows_stay_resizable_after_shrinking_to_one_cell_each() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]})).unwrap();
s.execute("selection.set", json!({"range": "A1:E2"})).unwrap();
s.execute("insert.chart", json!({"type": "line"})).unwrap();
// A file can carry series in rows without saying so; the layout is read from the series.
edit_chart(&mut s, |c| c.by_rows = false);
assert_eq!(data(&s).map(|d| d.by_rows), Some(true));
s.execute("chart.setValuesRange", json!({"range": "A1:A2"})).unwrap();
assert!(chart(&s).by_rows);
assert_eq!(data(&s).map(|d| (d.values, d.by_rows)), Some((r("A1:A2"), true)), "still one block, still in rows");
s.execute("chart.setValuesRange", json!({"range": "A1:C2"})).unwrap();
assert_eq!(points(&s), [3, 3]);
}
#[test]
fn set_values_range_refuses_what_it_cannot_do() {
let mut s = table();
let before = chart(&s);
for (params, why) in [
(json!({}), "missing `range`"),
(json!({"range": "not a range"}), "not a range"),
(json!({"range": "A1:Z100000"}), "too large"),
(json!({"range": "A1:JA2"}), "too large"),
(json!({"range": "Sheet2!B2:C4"}), ""),
(json!({"chart": 999, "range": "B2:C4"}), "chart"),
] {
let err = s.execute("chart.setValuesRange", params.clone()).unwrap_err();
assert!(err.to_string().contains(why), "{params}: {err}");
assert_eq!(chart(&s), before, "{params} left the chart as it was");
}
// Series with a gap between them are not one block.
s.execute("selection.set", json!({"range": "A1:D4"})).unwrap();
s.execute("chart.selectData", json!({"range": "A1:D4"})).unwrap();
s.execute("chart.selectData", json!({"removeSeries": [1]})).unwrap();
assert_eq!(data(&s), None);
let err = s.execute("chart.setValuesRange", json!({"range": "B2:C4"})).unwrap_err();
assert!(err.to_string().contains("not one block"), "{err}");
}
@@ -35,7 +35,7 @@ use std::sync::Arc;
use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, col_to_letters};
use gridcraft_engine::calc::Calc;
use gridcraft_engine::model::{CalcMode, Formula, Sheet, SheetViewMode, Workbook};
use gridcraft_engine::{EngineError, Session, command_specs, find_command, io};
use gridcraft_engine::{EngineError, HistoryEntry, Session, command_specs, find_command, io};
use serde_json::{Value as Json, json};
const SAMPLES: [&str; 3] = ["sales", "budget", "grades"];
@@ -219,8 +219,24 @@ fn shrink(sample: &str, steps: &[Step], kind: &str) -> Vec<Step> {
struct Harness {
s: Session,
/// The workbook at the start of the current episode (what undoing everything gives back).
base: Arc<Workbook>,
/// What undoing everything gives back: the workbook at the start of the current episode or,
/// once the undo history has dropped its oldest steps (it is bounded by count and by the
/// memory its snapshots hold), the state before the oldest step it kept.
floor: Arc<Workbook>,
/// The workbook of the oldest undo step when the history was last looked at, to notice the
/// history dropping it.
oldest: Option<Arc<Workbook>>,
}
/// Where redoing the `n` steps just undone ends. The first of them went onto the redo history
/// with the final workbook `end`. The redo history is bounded like undo and drops its oldest
/// entries first, so when that entry is gone every older one is too, and redo stops after fewer
/// than `n` steps at the oldest entry it kept.
fn redo_target(end: &Arc<Workbook>, redo: &[HistoryEntry], n: usize) -> Arc<Workbook> {
if n == 0 || redo.iter().rev().take(n).any(|e| Arc::ptr_eq(&e.wb, end)) {
return end.clone();
}
redo.first().map_or_else(|| end.clone(), |e| e.wb.clone())
}
fn fail(step: usize, kind: &'static str, what: impl Into<String>) -> Failure {
@@ -243,8 +259,8 @@ impl Harness {
fn new(sample: &str) -> Harness {
let mut s = Session::new();
s.execute("file.new", json!({"sample": sample})).expect("sample opens");
let base = s.doc().expect("document").wb.clone();
Harness { s, base }
let floor = s.doc().expect("document").wb.clone();
Harness { s, floor, oldest: None }
}
fn wb(&self) -> Arc<Workbook> {
@@ -262,6 +278,7 @@ impl Harness {
return Err(fail(i, "documents", format!("`{id}` changed the number of open documents; exclude it in EXCLUDED")));
}
let after = self.wb();
self.track_history();
let spec = find_command(id).expect("generated ids are registered");
if !spec.undoable
&& !matches!(id, "edit.undo" | "edit.redo")
@@ -293,6 +310,7 @@ impl Harness {
/// and reload; the next episode starts from here with an empty history.
fn end_episode(&mut self, i: usize) -> Result<(), Failure> {
let end = self.wb();
self.track_history();
let mut n = 0;
while !self.s.doc().expect("document").undo.is_empty() {
if let Err(EngineError::Internal(_, msg)) = self.s.execute("edit.undo", json!({})) {
@@ -304,7 +322,7 @@ impl Harness {
}
}
let undone = self.wb();
if let Some(diff) = workbook_diff(&self.base, &undone) {
if let Some(diff) = workbook_diff(&self.floor, &undone) {
return Err(fail(i, "undo", format!("undoing all {n} steps doesn't give back the starting workbook: {diff}")));
}
if watch_list(&end) != watch_list(&undone) {
@@ -312,23 +330,39 @@ impl Harness {
}
self.check_state(i)?;
// Only the steps undone here: an `edit.undo {steps}` in the sequence may have left more.
let target = redo_target(&end, &self.s.doc().expect("document").redo, n);
for _ in 0..n {
if let Err(EngineError::Internal(_, msg)) = self.s.execute("edit.redo", json!({})) {
return Err(fail(i, "panic", format!("`edit.redo` panicked while redoing everything: {msg}")));
}
}
if let Some(diff) = workbook_diff(&end, &self.wb()) {
return Err(fail(i, "redo", format!("redoing all {n} steps doesn't give back the final workbook: {diff}")));
if let Some(diff) = workbook_diff(&target, &self.wb()) {
let what = if Arc::ptr_eq(&target, &end) { "the final workbook" } else { "the newest step the redo history kept" };
return Err(fail(i, "redo", format!("redoing all {n} steps doesn't give back {what}: {diff}")));
}
self.check_state(i)?;
guarded(i, "xlsx roundtrip", || roundtrip_diff(&end))?;
let d = self.s.active_mut().expect("document");
d.undo.clear();
d.redo.clear();
self.base = d.wb.clone();
self.floor = d.wb.clone();
self.oldest = None;
Ok(())
}
/// Notices the undo history dropping its oldest step: its oldest entry changed without the
/// history emptying in between. From then on undoing everything stops at the new oldest entry,
/// including after an `edit.undo` in the sequence has already used up what is left.
fn track_history(&mut self) {
let oldest = self.s.doc().expect("document").undo.first().map(|e| e.wb.clone());
if let (Some(was), Some(now)) = (&self.oldest, &oldest)
&& !Arc::ptr_eq(was, now)
{
self.floor = now.clone();
}
self.oldest = oldest;
}
fn finish(&mut self, steps: usize) -> Result<(), Failure> {
self.end_episode(steps)
}
@@ -1135,3 +1169,42 @@ fn view_mode_switch_is_not_an_undo_difference() {
assert!(failure.is_none(), "`{id}`: {failure:?}");
}
}
/// Review of #2332: once the undo history has dropped its oldest steps, an `edit.undo` in the
/// sequence can use up everything it kept before the episode ends. Undoing everything then has
/// nothing left to do, and the workbook is the state before the oldest step kept, not the
/// episode's start.
#[test]
fn a_trimmed_history_undone_in_the_sequence_stops_at_its_oldest_step() {
let mut h = Harness::new("sales");
// Past the engine's 100-step undo limit, so it drops the oldest 5 steps.
for i in 0..105 {
h.s.execute("cell.set", json!({"cell": format!("Z{}", i + 1), "input": i.to_string()})).expect("cell.set");
h.track_history();
}
assert_eq!(h.s.doc().expect("document").undo.len(), 100, "the history dropped its oldest steps");
if let Err(f) = h.step(0, "edit.undo", &json!({"steps": 100})) {
panic!("{f:?}");
}
assert!(h.s.doc().expect("document").undo.is_empty());
if let Err(f) = h.end_episode(0) {
panic!("{f:?}");
}
}
/// Review of #2332: the redo history is bounded too, so undoing `n` steps may leave fewer than
/// `n` to redo, and redo then stops at the oldest entry it kept rather than at the final workbook.
#[test]
fn redo_stops_at_the_oldest_step_its_history_kept() {
let h = Harness::new("sales");
let selection = h.s.doc().expect("document").selection.clone();
let entry = |wb: &Arc<Workbook>| HistoryEntry { label: String::new(), wb: wb.clone(), selection: selection.clone(), retained_bytes: 0 };
let end = Arc::new((*h.wb()).clone());
let kept = Arc::new((*h.wb()).clone());
// Both steps kept: the first one undone went onto the redo history with the final workbook.
assert!(Arc::ptr_eq(&redo_target(&end, &[entry(&end), entry(&kept)], 2), &end));
// Its entry dropped: redo stops at the oldest entry left.
assert!(Arc::ptr_eq(&redo_target(&end, &[entry(&kept)], 2), &kept));
// Nothing undone, so nothing to redo, whatever an earlier `edit.undo` left there.
assert!(Arc::ptr_eq(&redo_target(&end, &[entry(&kept)], 0), &end));
}
+1
View File
@@ -32,6 +32,7 @@ mod sparse_clear_invalidation;
mod stored_list_shape;
mod structural_edit_rewrite;
mod table_resize_overlap;
mod table_style_looks;
mod table_total_row_last_row;
mod trace_error;
mod workbook_author;
+243
View File
@@ -0,0 +1,243 @@
//! Table styles look like the Format as Table gallery: every row of the gallery (Light 1-7, 8-14,
//! 15-21, Medium 1-7, …) has its own fills and lines, as recorded in plan/excel/table-style-spec.json.
use gridcraft_core::CellRef;
use gridcraft_engine::Session;
use gridcraft_engine::model::*;
use gridcraft_engine::tables::{ShownEdges, shown_edges, table_cell_shown_style, table_cell_style};
use serde_json::json;
const ROWS: u32 = 6; // header + 5 data rows
const COLS: u32 = 5;
fn session() -> Session {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [["a", "b", "c", "d", "e"]]})).unwrap();
s.execute("insert.table", json!({"range": "A1:E6", "header": true})).unwrap();
s
}
/// The look of every cell of a 6x5 table (header on, banded rows) in `style`, row by row.
fn grid_with(s: &Session, style: &str, edit: impl Fn(&mut Table)) -> Vec<Vec<Style>> {
let wb = &s.doc().unwrap().wb;
let mut t = wb.sheet(0).unwrap().tables[0].clone();
t.style = format!("TableStyle{style}");
edit(&mut t);
(0..ROWS).map(|r| (0..COLS).map(|c| table_cell_style(wb, 0, &t, CellRef::new(r, c))).collect()).collect()
}
fn grid(style: &str) -> Vec<Vec<Style>> {
grid_with(&session(), style, |_| {})
}
fn thin(color: Color) -> BorderLine {
BorderLine { style: BorderStyle::Thin, color }
}
const NONE: BorderLine = BorderLine { style: BorderStyle::None, color: Color::Auto };
const BLACK: Color = Color::Theme(1, 0);
const WHITE: Color = Color::Theme(0, 0);
#[test]
fn each_row_of_the_gallery_has_its_own_look() {
// Same accent (or neutral) across the gallery's rows, so only the row-group differs.
for set in [
&["Light1", "Light8", "Light15", "Medium1", "Medium8", "Medium15", "Medium22", "Dark1", "Dark8"][..],
&["Light2", "Light9", "Light16", "Medium2", "Medium9", "Medium16", "Medium23", "Dark2", "Dark9"][..],
] {
let looks: Vec<_> = set.iter().map(|s| grid(s)).collect();
for (i, a) in looks.iter().enumerate() {
for (j, b) in looks.iter().enumerate().skip(i + 1) {
assert_ne!(a, b, "{} and {} look the same", set[i], set[j]);
}
}
}
}
#[test]
fn neutral_bands_are_visibly_grey() {
let theme = Theme::default();
let fill = |style: &str, row: usize| grid(style)[row][0].fill.fg.resolve(&theme).unwrap();
// lt1 -150 (about #D9D9D9) and lt1 -350 (about #A6A6A6).
for ch in fill("Light1", 1) {
assert!((210..=225).contains(&ch), "Light1 band {:?}", fill("Light1", 1));
}
for ch in fill("Medium8", 1) {
assert!((160..=172).contains(&ch), "Medium8 band1 {:?}", fill("Medium8", 1));
}
}
#[test]
fn light15_has_a_vertical_grid_and_no_row_lines() {
let g = grid("Light15");
assert_eq!(g[0][0].borders.top, thin(BLACK));
assert_eq!(g[0][2].borders.bottom, thin(BLACK), "header bottom");
assert_eq!(g[2][1].borders.right, thin(BLACK), "inner vertical");
assert_eq!(g[0][1].borders.right, thin(BLACK), "inner vertical in the header");
assert_eq!(g[2][0].borders.left, thin(BLACK), "left side");
assert_eq!(g[2][4].borders.right, thin(BLACK), "right side");
assert_eq!(g[5][2].borders.bottom, thin(BLACK), "bottom");
assert_eq!(g[2][1].borders.bottom, NONE, "no inner horizontal");
assert_eq!(g[2][1].borders.top, NONE, "no inner horizontal");
assert_eq!(g[1][0].fill.fg, Color::Theme(0, -150));
}
#[test]
fn medium2_has_a_pale_accent_frame_and_no_row_lines() {
let g = grid("Medium2");
let line = thin(Color::Theme(4, 400));
assert_eq!(g[0][0].fill.fg, Color::Theme(4, 0));
assert_eq!(g[0][0].font.color, WHITE);
assert_eq!(g[0][2].borders.top, line);
assert_eq!(g[0][0].borders.left, line, "the sides run down the header too");
assert_eq!(g[3][0].borders.left, line);
assert_eq!(g[3][4].borders.right, line);
assert_eq!(g[5][2].borders.bottom, line);
assert_eq!(g[0][2].borders.bottom, NONE, "no header bottom");
assert_eq!(g[2][2].borders.bottom, NONE, "no inner horizontal");
assert_eq!(g[2][2].borders.right, NONE, "no inner vertical");
assert_eq!(g[1][2].fill.fg, Color::Theme(4, 800));
assert_eq!(g[2][2].fill.pattern, PatternType::None);
}
#[test]
fn medium9_has_white_verticals_and_header_bottom() {
let g = grid("Medium9");
assert_eq!(g[0][1].borders.bottom, thin(WHITE));
assert_eq!(g[0][1].borders.right, thin(WHITE));
assert_eq!(g[3][1].borders.right, thin(WHITE));
assert_eq!(g[3][1].borders.bottom, NONE);
assert_eq!(g[3][0].borders.left, NONE, "no frame");
assert_eq!(g[5][4].borders.bottom, NONE, "no frame");
assert_eq!(g[1][0].fill.fg, Color::Theme(4, 600));
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 800));
}
#[test]
fn dark2_bands_in_shaded_and_full_accent_under_a_black_header() {
let g = grid("Dark2");
assert_eq!(g[0][0].fill.fg, BLACK);
assert_eq!(g[0][0].borders.bottom, thin(WHITE));
assert_eq!(g[1][0].fill.fg, Color::Theme(4, -250));
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 0));
assert_eq!(g[2][0].font.color, WHITE);
assert_eq!(g[2][0].borders, Borders::default());
}
#[test]
fn dark9_pairs_two_accents() {
let g = grid("Dark9");
assert_eq!(g[0][0].fill.fg, Color::Theme(5, 0));
assert_eq!(g[0][0].font.color, WHITE);
assert_eq!(g[1][0].fill.fg, Color::Theme(4, 600));
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 800));
assert_eq!(g[2][0].font.color, BLACK);
let g = grid("Dark11");
assert_eq!(g[0][0].fill.fg, Color::Theme(9, 0));
assert_eq!(g[1][0].fill.fg, Color::Theme(8, 600));
}
#[test]
fn table_options_change_the_look() {
let s = session();
// Banded rows off: every data row looks like the second band.
let g = grid_with(&s, "Medium9", |t| t.banded_rows = false);
assert_eq!(g[1][0].fill.fg, Color::Theme(4, 800));
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 800));
// Banded columns alternate by column.
let g = grid_with(&s, "Medium9", |t| {
t.banded_rows = false;
t.banded_cols = true;
});
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 600));
assert_eq!(g[2][1].fill.fg, Color::Theme(4, 800));
// Header off: the top line moves to the first data row, and nothing is drawn as a header.
let g = grid_with(&s, "Light15", |t| t.header_row = false);
assert_eq!(g[0][2].borders.top, thin(BLACK));
assert_eq!(g[0][2].borders.bottom, NONE);
assert!(!g[0][2].font.bold);
// Totals row: bold, double top rule, no banding.
let g = grid_with(&s, "Medium2", |t| t.totals_row = true);
assert!(g[5][1].font.bold);
assert_eq!(g[5][1].borders.top, BorderLine { style: BorderStyle::Double, color: Color::Theme(4, 0) });
assert_eq!(g[5][1].borders.bottom, thin(Color::Theme(4, 400)));
// First and last column bold.
let g = grid_with(&s, "Medium2", |t| {
t.first_col = true;
t.last_col = true;
});
assert!(g[2][0].font.bold && g[2][4].font.bold && !g[2][2].font.bold);
}
#[test]
fn explicit_formatting_wins() {
let mut s = session();
s.execute("home.fillColor", json!({"range": "B3", "color": "#FF0000"})).unwrap();
s.execute("home.fontColor", json!({"range": "B3", "color": "#00FF00"})).unwrap();
s.execute("home.borders", json!({"range": "B3", "preset": "bottom"})).unwrap();
let g = grid_with(&s, "Dark2", |_| {});
assert_eq!(g[2][1].fill, Fill::solid(Color::Rgb(0xFF0000)));
assert_eq!(g[2][1].font.color, Color::Rgb(0x00FF00));
assert_eq!(g[2][1].borders.bottom.style, BorderStyle::Thin);
assert_eq!(g[2][1].borders.bottom.color, Color::Auto);
}
#[test]
fn every_style_name_is_safe() {
for name in ["Light0", "Light99", "Medium0", "Medium4000000000", "Dark0", "Dark12", "Dark99", "Bogus"] {
let _ = grid(name);
}
}
/// What the grid and print draw: like `grid_with`, but through the hidden-row/column aware
/// `table_cell_shown_style`.
fn shown_with(s: &Session, style: &str, edit: impl Fn(&mut Table)) -> Vec<Vec<Style>> {
let wb = &s.doc().unwrap().wb;
let mut t = wb.sheet(0).unwrap().tables[0].clone();
t.style = format!("TableStyle{style}");
edit(&mut t);
let e = shown_edges(wb.sheet(0).unwrap(), &t);
(0..ROWS).map(|r| (0..COLS).map(|c| table_cell_shown_style(wb, 0, &t, e, CellRef::new(r, c))).collect()).collect()
}
#[test]
fn frame_follows_the_last_visible_row_and_column() {
let frame = thin(Color::Theme(4, 400));
// Nothing hidden: the shown look is the table look.
let s = session();
assert_eq!(shown_with(&s, "Medium2", |_| {}), grid_with(&s, "Medium2", |_| {}));
// Last data row (and the one before it) and last column hidden: the frame moves in.
let mut s = session();
s.execute("home.hideRows", json!({"rows": "5:6"})).unwrap();
s.execute("home.hideColumns", json!({"cols": "E:E"})).unwrap();
let t = &s.doc().unwrap().wb.sheet(0).unwrap().tables[0];
assert_eq!(shown_edges(s.doc().unwrap().wb.sheet(0).unwrap(), t), ShownEdges { top: 0, bottom: 3, left: 0, right: 3 });
let g = shown_with(&s, "Medium2", |_| {});
for (c, cell) in g[3].iter().take(4).enumerate() {
assert_eq!(cell.borders.bottom, frame, "bottom frame on row 4, col {c}");
}
for (r, row) in g.iter().take(4).enumerate() {
assert_eq!(row[3].borders.right, frame, "right frame on col D, row {r}");
}
// Rows above the last visible one keep their inner look (Medium 2 has no row lines).
assert_eq!(g[2][1].borders.bottom, NONE);
// Convert to Range and friends still see the table as it is.
assert_eq!(grid_with(&s, "Medium2", |_| {})[3][1].borders.bottom, NONE);
// Header off and the first data row filtered out: the top line moves down.
let mut s = session();
s.execute("home.hideRows", json!({"rows": "1:1"})).unwrap();
s.execute("home.hideColumns", json!({"cols": "A:A"})).unwrap();
let g = shown_with(&s, "Light15", |t| t.header_row = false);
assert_eq!(g[1][2].borders.top, thin(BLACK));
assert_eq!(g[2][1].borders.left, thin(BLACK));
// Explicit borders still win.
let mut s = session();
s.execute("home.borders", json!({"range": "B5", "preset": "none"})).unwrap();
s.execute("home.fillColor", json!({"range": "B5", "color": "#FF0000"})).unwrap();
s.execute("home.borders", json!({"range": "C5", "preset": "bottom"})).unwrap();
s.execute("home.hideRows", json!({"rows": "6:6"})).unwrap();
let g = shown_with(&s, "Medium2", |_| {});
assert_eq!(g[4][1].borders.bottom, frame);
assert_eq!(g[4][2].borders.bottom.color, Color::Auto);
}
+5
View File
@@ -617,6 +617,11 @@ mod tests {
cx(ev("IMCSC", vec![t("4+3i")]), -0.075_489_832_915_863_7, 0.064_877_471_370_635_5);
is_text(ev("IMSECH", vec![t("0")]), "1");
is_err(ev("IMCSCH", vec![t("0")]), CellError::Num);
// Excel-cached results (Excel for Mac, `formulas` project test.xlsx, ENGINEERING sheet): a
// part needing more than 21 characters as a decimal is written in scientific notation.
is_text(ev("IMCSCH", vec![t("13+5j")]), "1.28233995888454E-06+4.33496947416312E-06j");
is_text(ev("IMEXP", vec![t("-13+25j")]), "2.24044486393732E-06-2.99158552811404E-07j");
is_text(ev("IMSECH", vec![t("7+25j")]), "0.00180771853884451+0.000241377759972715j");
// sech z · cosh z = 1
let Value::Text(c) = ev("IMCOSH", vec![t("4+3i")]) else { panic!() };
let Value::Text(sc) = ev("IMSECH", vec![t("4+3i")]) else { panic!() };
+76
View File
@@ -33,6 +33,82 @@ fn tvm() {
is_err(ev("CUMIPMT", vec![n(0.01), n(360.0), n(125000.0), n(1.0), n(1.0), n(2.0)]), CellError::Num);
}
/// RATE with the given arguments, as a number or an error.
fn rate_of(args: &[f64]) -> Value {
ev("RATE", args.iter().map(|x| n(*x)).collect())
}
#[track_caller]
fn rate_is(args: &[f64], expected: f64) {
close_tol(rate_of(args), expected, 1e-15);
}
/// Expected values observed in Excel 365 with these synthetic inputs.
#[test]
fn rate_follows_excel_iteration() {
// No payments and a zero future value: the answer is -100%, which the iteration
// approaches without reaching. Excel returns the last iterate, bit for bit.
rate_is(&[5.0, 0.0, -100.0, 0.0], -0.999_999_409_145_182_5);
rate_is(&[3.0, 0.0, -50.0, 0.0], -0.999_999_744_782_979_9);
rate_is(&[10.0, 0.0, -1.0, 0.0], -0.999_998_741_101_371_3);
rate_is(&[5.0, 0.0, -100.0, 0.0, 0.0, 0.5], -0.999_999_408_783_809_4);
rate_is(&[5.0, 0.0, -100.0, 0.0, 0.0, -0.99], -0.999_999_411_730_630_3);
// Second starting point goes the other way when the equation is positive at the guess.
rate_is(&[5.0, 0.0, 100.0, 0.0], -0.999_999_409_810_240_3);
rate_is(&[5.0, 0.0, -100.0, 1e-29], -0.999_999_260_333_075_4);
rate_is(&[5.0, 0.0, -100.0, 1e4], 1.511_886_431_510_563_3);
rate_is(&[4.0, 0.0, -1.0, 100.0], 2.162_277_660_168_009);
// Within 1e-7 by step but not by value: Excel keeps going.
rate_is(&[5.0, 0.0, -1e25, 0.0], -0.999_999_628_525_605_1);
// 200 steps without converging: the last iterate when it is within 1e-4, else #NUM!.
rate_is(&[20.0, 0.0, -1.0, 0.0], -0.999_112_071_912_539_3);
rate_is(&[36.0, 0.0, -1.0, 0.0, 0.0, -0.994], -0.999_875_315_309_626_9);
is_err(rate_of(&[12.0, 0.0, -1.0, 0.0]), CellError::Num);
is_err(rate_of(&[25.0, 0.0, -1.0, 0.0]), CellError::Num);
is_err(rate_of(&[20.0, 0.0, -1e60, 0.0]), CellError::Num);
// Large rates the iteration can't reach are #NUM! in Excel.
is_err(rate_of(&[4.0, 0.0, -0.0001, 100.0]), CellError::Num);
is_err(rate_of(&[5.0, 0.0, -100.0, 1e5]), CellError::Num);
is_err(rate_of(&[10.0, -300.0, 1000.0]), CellError::Num);
// ...but are found from a closer guess.
rate_is(&[4.0, 0.0, -0.1, 100.0, 0.0, 4.0], 4.623_413_251_903_489);
close_tol(rate_of(&[10.0, -300.0, 1000.0, 0.0, 0.0, 0.3]), 0.273_198_424_105_560_4, 1e-12);
// Converging on a rate at or below -100% (or within 1e-7 of it) is #NUM!.
is_err(rate_of(&[1.0, 0.0, -1.0, 0.0]), CellError::Num);
is_err(rate_of(&[10.0, -1000.0, 1000.0]), CellError::Num);
is_err(rate_of(&[1.0, 0.0, -100.0, 1e-5]), CellError::Num);
rate_is(&[1.0, 0.0, -100.0, 2e-5], -0.999_999_8);
is_err(rate_of(&[5.0, 0.0, -1e30, 0.0]), CellError::Num);
is_err(rate_of(&[0.5, 0.0, -1.0, 0.0]), CellError::Num);
// A value that never gets near zero is #NUM!, however small the step.
is_err(rate_of(&[4.0, 0.0, 100.0, 100.0]), CellError::Num);
is_err(rate_of(&[4.0, 0.0, -1e-12, 1e-6]), CellError::Num);
rate_is(&[4.0, 0.0, -1e-14, 1e-8], 0.099_000_000_283_235_72);
// Subnormal steps are flushed to zero.
rate_is(&[3.0, 0.0, -1e-305, 0.0], 0.101);
is_err(rate_of(&[4.0, 0.0, 0.0, 100.0]), CellError::Num);
// Guess at or below -1 is #VALUE!; type is 0 or anything else (1).
is_err(rate_of(&[10.0, -100.0, 1000.0, 0.0, 0.0, -1.0]), CellError::Value);
is_err(rate_of(&[0.0, -100.0, 1000.0]), CellError::Num);
// Excel does not step the second point back to -1: a fractional nper with a guess near -1 is #NUM!
// even though a root exists at -0.99, and the same case from a guess of -0.99 finds it.
is_err(rate_of(&[0.5, 0.0, -1.0, 0.1, 0.0, -0.9995]), CellError::Num);
is_err(rate_of(&[0.5, 0.0, -1.0, 0.1, 0.0, -0.5]), CellError::Num);
close_tol(rate_of(&[0.5, 0.0, -1.0, 0.1, 0.0, -0.99]), -0.99, 1e-7);
assert_eq!(rate_of(&[10.0, -100.0, 1000.0, 0.0, 2.0]), rate_of(&[10.0, -100.0, 1000.0, 0.0, 1.0]));
// Ordinary loans, and large amounts that can't get within 1e-7 of zero.
close_tol(rate_of(&[360.0, -1000.0, 150000.0]), 0.005_850_253_376_759_637, 1e-11);
close_tol(rate_of(&[360.0, -1000.0, 150000.0, 0.0, 1.0]), 0.005_898_953_457_098_463, 1e-11);
close_tol(rate_of(&[1000.0, -1e6, 1e8]), 0.009_999_522_655_994_865, 1e-12);
close_tol(rate_of(&[360.0, -1e9, 1.5e11]), 0.005_850_253_376_759_668, 1e-12);
close_tol(rate_of(&[10.0, -50.0, 1000.0]), -0.109_560_293_684_682_5, 1e-14);
// Roots at 0% come out as rounding noise in both, so only the absolute size matters.
match rate_of(&[10.0, -100.0, 1000.0]) {
Value::Number(x) => assert!(x.abs() < 1e-8, "{x}"),
other => panic!("{other:?}"),
}
}
/// PMT within about 4 ULPs of Excel's (Value2 of synthetic probes; libm differs by an ULP across
/// platforms). The old `(1 + rate)^nper` form was 25 to 91 ULPs off on these, enough to flip a loan schedule's final `IF(p - SUM(r) > 0, ...)`.
#[test]
+73 -9
View File
@@ -218,21 +218,85 @@ fn solve_rate(f: impl Fn(f64) -> f64, guess: f64) -> R<f64> {
Err(CellError::Num)
}
/// RATE's equation at rate `r`: the loan and the payments grown to the end of the term, plus
/// `fv`. RATE returns the rate where it is zero. The second value is the size of its terms, to
/// judge how close to zero the first can get in floating point.
fn rate_equation(r: f64, np: f64, pmt: f64, pv: f64, fv: f64, typ: f64) -> (f64, f64) {
if r == 0.0 {
return (pv + pmt * np + fv, pv.abs() + (pmt * np).abs() + fv.abs());
}
let p = (1.0 + r).powf(np);
let (a, b) = (pv * p, pmt * (1.0 / r + typ) * (p - 1.0));
(a + b + fv, a.abs() + b.abs() + fv.abs())
}
/// Excel works with subnormal numbers flushed to zero: a secant step that underflows doesn't
/// move. Observed with RATE(3,0,-1E-305,0), which is 0.101 (the second starting point).
fn flush_subnormal(x: f64) -> f64 {
if x.abs() < f64::MIN_POSITIVE { 0.0 } else { x }
}
/// Excel's RATE solver, reconstructed by observing Excel with synthetic inputs (not from its
/// code; its documentation says only "iteration", 20 steps and 0.0000001):
///
/// - A secant iteration starting at the guess and at the guess moved 0.001 toward a larger
/// value of the equation, for at most 200 steps.
/// - It stops at the first iterate that moved less than 1e-7 and where the equation is within
/// 1e-7 of zero (or as close as its terms allow, for very large amounts). Excel returns that
/// iterate, not the exact root, so a slowly converging case such as no payments and a zero
/// future value (exact answer -100%) gives a rate just above -1.
/// - The result must be above -1 by more than the tolerance; otherwise it is #NUM!.
/// - After 200 steps without that, Excel still returns the last iterate if it is within a
/// looser 1e-4 (step, equation value and distance above -1); otherwise #NUM!. So a root the
/// iteration can't reach (a very large rate) is #NUM! even though it exists.
fn rate_solve(f: impl Fn(f64) -> (f64, f64), guess: f64) -> R<f64> {
const STEPS: usize = 200;
const TOL: f64 = 1e-7;
const LOOSE: f64 = 1e-4;
let eval = |x: f64| {
let (y, size) = f(x);
if y.is_finite() { Ok((y, size)) } else { Err(CellError::Num) }
};
let near_zero = |y: f64, size: f64| y.abs() < TOL || y.abs() <= 1e-12 * size;
let (mut x0, (mut f0, _)) = (guess, eval(guess)?);
let mut x1 = if f0 < 0.0 { guess + 0.001 } else { guess - 0.001 };
let (mut f1, mut size1) = eval(x1)?;
for _ in 0..STEPS {
let den = flush_subnormal(f1 - f0);
if den == 0.0 {
// The secant is flat: done if the iteration had already settled.
if (x1 - x0).abs() < TOL && near_zero(f1, size1) && x1 - TOL > -1.0 {
return Ok(x1);
}
return Err(CellError::Num);
}
let x2 = x1 - flush_subnormal(f1 * (x1 - x0)) / den;
if !x2.is_finite() {
return Err(CellError::Num);
}
let (f2, size2) = eval(x2)?;
if (x2 - x1).abs() < TOL && near_zero(f2, size2) {
return if x2 - TOL > -1.0 { Ok(x2) } else { Err(CellError::Num) };
}
(x0, f0, x1, f1, size1) = (x1, f1, x2, f2, size2);
}
if (x1 - x0).abs() < LOOSE && f1.abs() < LOOSE && x1 - LOOSE > -1.0 {
return Ok(x1);
}
Err(CellError::Num)
}
pub(super) fn rate(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
let (np, pmt, pv) = (num(a, 0)?, num(a, 1)?, num(a, 2)?);
let (fv, typ, guess) = (opt_num(a, 3, 0.0)?, type_arg(a, 4)?, opt_num(a, 5, 0.1)?);
if np <= 0.0 {
return Err(CellError::Num);
}
let f = |r: f64| {
if r.abs() < 1e-12 {
pv + pmt * np + fv
} else {
let p = (1.0 + r).powf(np);
pv * p + pmt * (1.0 + r * typ) * (p - 1.0) / r + fv
}
};
num_val(solve_rate(f, guess)?)
// Excel: a guess at or below -100% is #VALUE!, not #NUM!.
if guess <= -1.0 {
return Err(CellError::Value);
}
num_val(rate_solve(|r| rate_equation(r, np, pmt, pv, fv, typ), guess)?)
}
pub(super) fn npv(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
+19
View File
@@ -53,6 +53,11 @@ pub struct PrintSettings {
/// sheet is more than one page wide and tall.
#[serde(default)]
pub page_order: PageOrder,
/// Page Setup › Page › First page number: the number the sheet's first printed page takes,
/// or `None` for Automatic (XLSX `pageSetup firstPageNumber` with `useFirstPageNumber`). Left
/// out of a JSON workbook when Automatic, so files without it are written as before.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub first_page_number: Option<u32>,
}
fn yes() -> bool {
@@ -187,6 +192,7 @@ impl Default for PrintSettings {
hf_scale_with_doc: true,
hf_align_with_margins: true,
page_order: PageOrder::DownThenOver,
first_page_number: None,
}
}
}
@@ -281,4 +287,17 @@ mod tests {
p = serde_json::from_value(saved).unwrap();
assert_eq!(p, PrintSettings::default());
}
#[test]
fn first_page_number_is_saved_only_when_set() {
// Automatic writes nothing, so a JSON workbook without a first page number is unchanged and
// one saved before the field existed loads as Automatic.
let saved = serde_json::to_value(PrintSettings::default()).unwrap();
assert!(saved.get("first_page_number").is_none(), "{saved}");
assert_eq!(serde_json::from_value::<PrintSettings>(saved).unwrap().first_page_number, None);
let p = PrintSettings { first_page_number: Some(7), ..Default::default() };
let saved = serde_json::to_value(&p).unwrap();
assert_eq!(saved["first_page_number"], 7);
assert_eq!(serde_json::from_value::<PrintSettings>(saved).unwrap(), p);
}
}
+38
View File
@@ -290,6 +290,44 @@ impl CellStore {
let moved = self.take_rows(0..=u32::MAX, from..=u32::MAX);
self.put_rows(moved.into_iter().map(|(row, cols)| (row, shift_keys(cols, delta))));
}
/// Deletes the rows in `spans` (`(first, count)`, ascending and disjoint) and closes the gaps
/// in one pass: each later cell moves up once by the number of deleted rows above it.
pub fn delete_rows(&mut self, spans: &[(u32, u32)]) {
self.delete_lines(spans, true);
}
/// Column form of [`CellStore::delete_rows`].
pub fn delete_cols(&mut self, spans: &[(u32, u32)]) {
self.delete_lines(spans, false);
}
fn delete_lines(&mut self, spans: &[(u32, u32)], rows: bool) {
let Some(&(first, _)) = spans.first() else { return };
// Lines deleted before the end of each span, for mapping a kept line to its new place.
let mut before = Vec::with_capacity(spans.len());
let mut total = 0u32;
for &(_, count) in spans {
total = total.saturating_add(count);
before.push(total);
}
let map = |v: u32| -> Option<u32> {
let i = spans.partition_point(|&(at, _)| at <= v);
let Some(i) = i.checked_sub(1) else { return Some(v) };
let (at, count) = spans.get(i).copied().unwrap_or_default();
if v - at < count { None } else { Some(v - before.get(i).copied().unwrap_or_default()) }
};
let keys: Vec<CellRef> = if rows {
let r = RangeRef::new(CellRef::new(first, 0), CellRef::new(gridcraft_core::MAX_ROWS - 1, gridcraft_core::MAX_COLS - 1));
self.iter_range(r).map(|(c, _)| c).collect()
} else {
self.iter().filter(|(c, _)| c.col >= first).map(|(c, _)| c).collect()
};
let moved: Vec<(CellRef, Cell)> = keys.into_iter().filter_map(|c| self.remove(c).map(|cell| (c, cell))).collect();
for (c, cell) in moved {
let to = if rows { map(c.row).map(|r| CellRef::new(r, c.col)) } else { map(c.col).map(|x| CellRef::new(c.row, x)) };
if let Some(to) = to {
self.set(to, cell);
}
}
}
/// Shifts cells within rows `r0..=r1` and columns `>= from` horizontally (Insert/Delete Cells
/// with shift right/left).
pub fn shift_cols_in_rows(&mut self, r0: u32, r1: u32, from: u32, delta: i64) {
+40 -12
View File
@@ -293,23 +293,22 @@ impl NumberFormat {
}
/// Formats a number. The flag is true when the value cannot be shown (date out of range).
fn format_number(&self, n: f64, sys: DateSystem) -> (Formatted, bool) {
let general = |n: f64| Formatted {
text: format_general_fit(n, GENERAL_WIDTH).unwrap_or_else(|| OVERFLOW.into()),
color: None,
fill: None,
numeric: true,
};
/// With `full`, General is not narrowed to the cell width but written by [`general_full`].
fn format_number(&self, n: f64, sys: DateSystem, full: bool) -> (Formatted, bool) {
let general_text = |n: f64, width: usize| if full { Some(general_full(n)) } else { format_general_fit(n, width) };
let general =
|n: f64| Formatted { text: general_text(n, GENERAL_WIDTH).unwrap_or_else(|| OVERFLOW.into()), color: None, fill: None, numeric: true };
if self.is_general() {
return (general(n), false);
}
let Some((sec, drop_sign)) = self.select(n) else { return (general(n), false) };
let minus = n < 0.0 && !drop_sign;
let out: Option<Out> = match sec.kind {
SecKind::Text => Some(render::render_text(sec, &format_general_fit(n, GENERAL_WIDTH).unwrap_or_default())),
SecKind::Text => Some(render::render_text(sec, &general_text(n, GENERAL_WIDTH).unwrap_or_default())),
SecKind::General => {
let width = if minus { GENERAL_WIDTH - 1 } else { GENERAL_WIDTH };
Some(render::render_general(sec, n.abs(), width))
let text = general_text(n.abs(), width).unwrap_or_else(|| "#".repeat(width.clamp(1, 11)));
Some(render::render_general(sec, &text))
}
SecKind::Date => {
if minus {
@@ -405,16 +404,45 @@ impl NumberFormat {
/// Formats a cell value for display.
pub fn format_value(v: &Value, fmt: &NumberFormat, sys: DateSystem) -> Formatted {
format_value_with(v, fmt, sys, false)
}
/// Formats a cell value as Save As CSV/Text writes it: like [`format_value`], except that a number
/// shown as General (a General or Text section, with or without colour and literals) is not
/// narrowed to the cell width but written by `general_full`: `124412140710`, not `1.24412E+11`.
/// Excel writes the cell display here; GridCraft keeps the digits.
pub fn format_value_full(v: &Value, fmt: &NumberFormat, sys: DateSystem) -> Formatted {
format_value_with(v, fmt, sys, true)
}
/// General for Save As CSV/Text: the text `&` gives (15 significant digits), but never with an
/// exponent, because reopening the file would give the cell a scientific format that rounds it
/// on the next save. Where `&` writes an exponent, a number of 1 or more is written as the
/// shortest digits that read back as the same value (every integer f64 holds below 1e16 exactly,
/// so 16-digit card numbers survive), and a smaller one as its 15 significant digits in full.
fn general_full(n: f64) -> String {
let text = gridcraft_core::number_to_text(n);
if !text.contains('E') {
text
} else if n.abs() >= 1.0 {
format!("{n}")
} else {
let mag: i32 = format!("{n:.14e}").split_once('e').and_then(|(_, e)| e.parse().ok()).unwrap_or(0);
gridcraft_core::value::trim_decimal(&format!("{:.*}", (14 - mag).max(0) as usize, n))
}
}
fn format_value_with(v: &Value, fmt: &NumberFormat, sys: DateSystem, full: bool) -> Formatted {
match v {
Value::Empty => Formatted::default(),
Value::Number(n) if !n.is_finite() => Formatted { text: CellError::Num.as_str().into(), ..Formatted::default() },
Value::Number(n) => fmt.format_number(*n, sys).0,
Value::Number(n) => fmt.format_number(*n, sys, full).0,
Value::Text(t) => fmt.format_text(t),
Value::Bool(b) => Formatted { text: if *b { "TRUE" } else { "FALSE" }.into(), ..Formatted::default() },
Value::Error(e) => Formatted { text: e.as_str().into(), ..Formatted::default() },
Value::Array(a) => match a.data.first() {
Some(Value::Array(_)) | None => Formatted::default(),
Some(first) => format_value(first, fmt, sys),
Some(first) => format_value_with(first, fmt, sys, full),
},
}
}
@@ -525,7 +553,7 @@ pub fn text_function(v: &Value, code: &str, sys: DateSystem) -> Result<String, C
if !n.is_finite() {
return Err(CellError::Num);
}
let (f, overflow) = fmt.format_number(n, sys);
let (f, overflow) = fmt.format_number(n, sys, false);
if overflow { Err(CellError::Value) } else { Ok(f.text) }
}
+5 -4
View File
@@ -6,7 +6,7 @@ use gridcraft_core::DateSystem;
use gridcraft_core::date::{datetime_from_serial, max_serial};
use crate::calendar::Calendar;
use crate::decimal::{decimal_digits, fixed, fixed_from_digits, format_general_fit};
use crate::decimal::{decimal_digits, fixed, fixed_from_digits};
use crate::parse::{DatePart, Section, Tok};
/// Text being built plus the first repeat-fill position.
@@ -81,12 +81,13 @@ pub(crate) fn render_text_within(sec: &Section, text: &str, max_units: usize) ->
Some(out)
}
/// Renders a number through a General section (literals around the General keyword).
pub(crate) fn render_general(sec: &Section, v: f64, width: usize) -> Out {
/// Renders a number through a General section: `general` (the number already written as General)
/// with the section's literals around it.
pub(crate) fn render_general(sec: &Section, general: &str) -> Out {
let mut out = Out::default();
for t in &sec.toks {
match t {
Tok::General => out.push(&format_general_fit(v, width).unwrap_or_else(|| "#".repeat(width.clamp(1, 11)))),
Tok::General => out.push(general),
Tok::Fill(c) => out.fill(*c),
other => out.push_tok(other),
}
+1 -1
View File
@@ -668,7 +668,7 @@ fn text_uncached(v: &Value, code: &str, sys: DateSystem) -> Result<String, CellE
if !n.is_finite() {
return Err(CellError::Num);
}
let (f, overflow) = fmt.format_number(n, sys);
let (f, overflow) = fmt.format_number(n, sys, false);
if overflow { Err(CellError::Value) } else { Ok(f.text) }
}
+1
View File
@@ -10,6 +10,7 @@ readme = "README.md"
workspace = true
[dependencies]
craft-pdf.workspace = true
craft-stream-codecs.workspace = true
harfrust = "=0.12.0"
skrifa = { workspace = true }
+7 -10
View File
@@ -10,7 +10,7 @@ use skrifa::{
};
use unicode_bidi::BidiInfo;
use crate::{CID_FONT, Error, Font, TextDirection, dict_obj, n, needs_cid, pdf_string, pdf_utf16_string, stream_obj};
use crate::{CID_FONT, Error, Font, TextDirection, n, needs_cid, pdf_string, pdf_utf16_string};
include!(concat!(env!("OUT_DIR"), "/arabic_fonts.rs"));
@@ -490,7 +490,7 @@ impl Subset {
}
/// Writes the subset fonts into `out` and returns their page resource entries.
pub(crate) fn write_objects(&self, next: &mut u32, out: &mut Vec<u8>, offsets: &mut Vec<usize>) -> String {
pub(crate) fn write_objects(&self, next: &mut u32, out: &mut craft_pdf::classic::Writer) -> Result<String, Error> {
let mut resources = String::new();
for (batch, glyphs) in self.glyphs.chunks(255).enumerate() {
let id = *next;
@@ -507,7 +507,7 @@ impl Subset {
let _ = write!(names, "/g{code} ");
let _ = write!(widths, "{} ", n(glyph.width));
let body = glyph_procedure(glyph);
stream_obj(out, offsets, *next, "", body.as_bytes());
out.stream(*next, "", body.as_bytes())?;
*next += 1;
bounds[0] = bounds[0].min(glyph.bounds[0]);
bounds[1] = bounds[1].min(glyph.bounds[1]);
@@ -526,11 +526,8 @@ impl Subset {
cmap.push_str("endbfchar\n");
}
cmap.push_str("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");
stream_obj(out, offsets, cmap_id, "", cmap.as_bytes());
dict_obj(
out,
offsets,
id,
out.stream(cmap_id, "", cmap.as_bytes())?;
out.object(id,
&format!(
"<< /Type /Font /Subtype /Type3 /Name /GridCraftArabic /FontBBox [{} {} {} {}] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << {procs}>> /Encoding << /Type /Encoding /Differences [1 {names}] >> /FirstChar 1 /LastChar {} /Widths [{widths}] /Resources << >> /ToUnicode {cmap_id} 0 R >>",
n(bounds[0]),
@@ -539,10 +536,10 @@ impl Subset {
n(bounds[3]),
glyphs.len()
),
);
)?;
let _ = write!(resources, "/A{} {id} 0 R ", batch + 1);
}
resources
Ok(resources)
}
}
+29 -88
View File
@@ -1,4 +1,4 @@
//! A tiny, self-contained PDF 1.7 writer for GridCraft's print and PDF export.
//! PDF 1.7 drawing for GridCraft print/export, with shared object and xref framing.
//!
//! - The 14 standard fonts (no embedding) with WinAnsiEncoding, plus approximate width tables
//! ([`text_width`]) so callers can measure, align and wrap text. Characters outside
@@ -52,7 +52,7 @@ impl TextDirection {
}
}
/// A PDF export could not preserve the requested text.
/// A PDF export could not preserve the requested text or serialize its object envelope.
#[derive(Clone, Debug)]
pub struct Error(String);
@@ -63,6 +63,12 @@ impl std::fmt::Display for Error {
}
impl std::error::Error for Error {}
impl From<craft_pdf::classic::Error> for Error {
fn from(error: craft_pdf::classic::Error) -> Self {
Self(error.to_string())
}
}
use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher;
use std::fmt::Write as _;
@@ -1001,49 +1007,6 @@ fn pdf_text_string(text: &str) -> String {
s
}
/// Starts object `id` at the current end of `out` and records its offset for the xref table.
fn begin_obj(out: &mut Vec<u8>, offsets: &mut Vec<usize>, id: u32) {
let i = id as usize;
if offsets.len() <= i {
offsets.resize(i + 1, 0);
}
if let Some(slot) = offsets.get_mut(i) {
*slot = out.len();
}
let _ = writeln!(Utf8(out), "{id} 0 obj");
}
/// Writes `id 0 obj <body> endobj`.
fn dict_obj(out: &mut Vec<u8>, offsets: &mut Vec<usize>, id: u32, body: &str) {
begin_obj(out, offsets, id);
out.extend_from_slice(body.as_bytes());
out.extend_from_slice(b"\nendobj\n");
}
/// Writes a stream object: `dict` (the dictionary entries without `<<`, `>>` and `/Length`, may be
/// empty) and `data` as the stream body.
fn stream_obj(out: &mut Vec<u8>, offsets: &mut Vec<usize>, id: u32, dict: &str, data: &[u8]) {
begin_obj(out, offsets, id);
out.extend_from_slice(b"<<");
if !dict.is_empty() {
out.push(b' ');
out.extend_from_slice(dict.as_bytes());
}
let _ = write!(Utf8(out), " /Length {} >>\nstream\n", data.len());
out.extend_from_slice(data);
out.extend_from_slice(b"\nendstream\nendobj\n");
}
/// Lets `write!` append text to a byte buffer.
struct Utf8<'a>(&'a mut Vec<u8>);
impl std::fmt::Write for Utf8<'_> {
fn write_str(&mut self, s: &str) -> std::fmt::Result {
self.0.extend_from_slice(s.as_bytes());
Ok(())
}
}
impl PdfDoc {
pub fn new() -> PdfDoc {
PdfDoc::default()
@@ -1097,7 +1060,8 @@ impl PdfDoc {
/// numbered during writing (fonts, then per page its new images, content stream and page
/// dictionary), with the catalog, page tree and info dictionary last.
///
/// Returns an error if the Arabic font is unusable or Arabic text exceeds a size limit.
/// Returns an error if the Arabic font is unusable, text exceeds a size limit, or the
/// shared envelope writer refuses object counts, offsets or an allocation.
pub fn finish(mut self) -> Result<Vec<u8>, Error> {
if let Some(error) = self.pages.iter().find_map(|page| page.error.clone()) {
return Err(error);
@@ -1131,9 +1095,7 @@ impl PdfDoc {
let contents: Vec<String> = self.pages.iter_mut().map(|p| std::mem::take(&mut p.content)).collect();
let page_links: Vec<Vec<LinkAnnotation>> = self.pages.iter_mut().map(|p| std::mem::take(&mut p.links)).collect();
let reserve = contents.iter().fold(4096usize, |acc, c| acc.saturating_add(c.len()).saturating_add(1024));
let mut out: Vec<u8> = Vec::with_capacity(reserve);
out.extend_from_slice(b"%PDF-1.7\n%\xE2\xE3\xCF\xD3\n");
let mut offsets: Vec<usize> = vec![0; 4];
let mut out = craft_pdf::classic::Writer::with_capacity(reserve)?;
let mut kids = Vec::new();
let mut annotations = Vec::new();
let page_count = self.pages.len();
@@ -1143,42 +1105,34 @@ impl PdfDoc {
let _ = write!(font_dict, "/F{} {} 0 R ", i + 1, id);
if i == CID_FONT {
let (cid_id, desc_id) = (id + 1, id + 2);
dict_obj(
&mut out,
&mut offsets,
out.object(
*id,
&format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{CID_BASE_FONT} /Encoding /UniGB-UTF16-H /DescendantFonts [{cid_id} 0 R] >>"
),
);
dict_obj(
&mut out,
&mut offsets,
cid_id,
)?;
out.object(cid_id,
&format!(
"<< /Type /Font /Subtype /CIDFontType0 /BaseFont /{CID_BASE_FONT} /CIDSystemInfo << /Registry (Adobe) /Ordering (GB1) /Supplement 4 >> /FontDescriptor {desc_id} 0 R /DW {CID_WIDTH} >>"
),
);
dict_obj(
&mut out,
&mut offsets,
desc_id,
)?;
out.object(desc_id,
&format!(
"<< /Type /FontDescriptor /FontName /{CID_BASE_FONT} /Flags 6 /FontBBox [-25 -254 1000 880] /ItalicAngle 0 /Ascent 880 /Descent -120 /CapHeight 880 /StemV 93 >>"
),
);
)?;
continue;
}
let name = Font::ALL.get(i).copied().unwrap_or_default().base_name();
let enc = if name.starts_with("Symbol") { "" } else { " /Encoding /WinAnsiEncoding" };
dict_obj(&mut out, &mut offsets, *id, &format!("<< /Type /Font /Subtype /Type1 /BaseFont /{name}{enc} >>"));
out.object(*id, &format!("<< /Type /Font /Subtype /Type1 /BaseFont /{name}{enc} >>"))?;
}
}
// Images already written, by content hash: (page, image, object id). A hash match is
// confirmed by comparing the pixels before an object is shared.
let mut written: HashMap<u64, Vec<(usize, usize, u32)>> = HashMap::new();
for (pi, ((page, content), links)) in self.pages.iter().zip(contents).zip(page_links).enumerate() {
let arabic_fonts = page.arabic.write_objects(&mut next, &mut out, &mut offsets);
let arabic_fonts = page.arabic.write_objects(&mut next, &mut out)?;
let page_fonts = format!("{font_dict}{arabic_fonts}");
let mut xobjects = String::new();
for (k, img) in page.images.iter().enumerate() {
@@ -1204,13 +1158,13 @@ impl PdfDoc {
let _ = write!(dict, " /SMask {id} 0 R");
}
dict.push_str(" /Filter /RunLengthDecode");
stream_obj(&mut out, &mut offsets, img_id, &dict, &run_length(&img.rgb));
out.stream(img_id, &dict, &run_length(&img.rgb))?;
if let (Some(id), Some(a)) = (smask_id, &img.alpha) {
let dict = format!(
"/Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /RunLengthDecode",
img.width, img.height
);
stream_obj(&mut out, &mut offsets, id, &dict, &run_length(a));
out.stream(id, &dict, &run_length(a))?;
}
written.entry(img.hash).or_default().push((pi, k, img_id));
img_id
@@ -1221,7 +1175,7 @@ impl PdfDoc {
let content_id = next;
let page_id = next + 1;
next += 2;
stream_obj(&mut out, &mut offsets, content_id, "", content.as_bytes());
out.stream(content_id, "", content.as_bytes())?;
drop(content);
let xo = if xobjects.is_empty() { String::new() } else { format!(" /XObject << {xobjects}>>") };
let mut link_refs = String::new();
@@ -1235,9 +1189,7 @@ impl PdfDoc {
annotations.push((id, link));
}
let annots = if link_refs.is_empty() { String::new() } else { format!(" /Annots [{link_refs}]") };
dict_obj(
&mut out,
&mut offsets,
out.object(
page_id,
&format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources << /Font << {}>>{} >> /Contents {} 0 R{} >>",
@@ -1248,7 +1200,7 @@ impl PdfDoc {
content_id,
annots
),
);
)?;
kids.push(page_id);
}
for (id, link) in annotations {
@@ -1261,16 +1213,11 @@ impl PdfDoc {
format!("/Dest [{page_id} 0 R /XYZ {} {} null]", n(x), n(height - y))
}
};
dict_obj(
&mut out,
&mut offsets,
id,
&format!("<< /Type /Annot /Subtype /Link /Rect [{} {} {} {}] /Border [0 0 0] {action} >>", n(x0), n(y0), n(x1), n(y1)),
);
out.object(id, &format!("<< /Type /Annot /Subtype /Link /Rect [{} {} {} {}] /Border [0 0 0] {action} >>", n(x0), n(y0), n(x1), n(y1)))?;
}
dict_obj(&mut out, &mut offsets, 1, "<< /Type /Catalog /Pages 2 0 R >>");
out.object(1, "<< /Type /Catalog /Pages 2 0 R >>")?;
let kids_s: Vec<String> = kids.iter().map(|k| format!("{k} 0 R")).collect();
dict_obj(&mut out, &mut offsets, 2, &format!("<< /Type /Pages /Kids [{}] /Count {} >>", kids_s.join(" "), kids.len()));
out.object(2, &format!("<< /Type /Pages /Kids [{}] /Count {} >>", kids_s.join(" "), kids.len()))?;
let creator = if self.info.creator.is_empty() { "GridCraft" } else { &self.info.creator };
let mut info = format!("<< /Producer {} /Creator {}", pdf_text_string("GridCraft PDF"), pdf_text_string(creator));
if !self.info.title.is_empty() {
@@ -1280,15 +1227,9 @@ impl PdfDoc {
let _ = write!(info, " /Author {}", pdf_text_string(&self.info.author));
}
info.push_str(" >>");
dict_obj(&mut out, &mut offsets, 3, &info);
out.object(3, &info)?;
let xref = out.len();
let _ = write!(Utf8(&mut out), "xref\n0 {}\n0000000000 65535 f \n", next);
for off in offsets.iter().skip(1) {
let _ = writeln!(Utf8(&mut out), "{off:010} 00000 n ");
}
let _ = write!(Utf8(&mut out), "trailer\n<< /Size {} /Root 1 0 R /Info 3 0 R >>\nstartxref\n{}\n%%EOF\n", next, xref);
Ok(out)
out.finish(1, Some(3)).map_err(Error::from)
}
}
+4 -1
View File
@@ -1136,7 +1136,10 @@ fn explicit_rtl_standard_text_reorders_without_an_arabic_font() {
let page = doc.add_page(300.0, 100.0);
page.text_with_direction(Point::new(10.0, 30.0), 12.0, Font::Helvetica, [0, 0, 0], source, TextDirection::RightToLeft);
assert!(page.content.contains("(! ABC) Tj"), "{}", page.content);
assert!(page.arabic.write_objects(&mut 4, &mut Vec::new(), &mut Vec::new()).is_empty());
let mut objects = craft_pdf::classic::Writer::with_capacity(0).unwrap();
let mut next = 4;
assert!(page.arabic.write_objects(&mut next, &mut objects).unwrap().is_empty());
assert_eq!(next, 4, "Latin-only RTL text must not allocate Arabic font objects");
assert_eq!(text_width_with_direction(Font::Helvetica, 12.0, source, TextDirection::RightToLeft), text_width(Font::Helvetica, 12.0, source));
let pdf = doc.finish().unwrap();
assert_eq!(utf16_entry(&pdf, "/ActualText").unwrap(), source);
+3
View File
@@ -26,6 +26,9 @@ impl SheetApp {
if matches!(id, "file.save" | "file.saveAs" | "file.saveBytes") {
self.store_view_state();
}
if let Some(refused) = dialogs::refuse_sheet_change(self, id) {
return Err(refused);
}
if matches!(
id,
"sheet.activate"
+86 -1
View File
@@ -298,9 +298,12 @@ pub(crate) fn paint_objects(app: &SheetApp, p: &Painter, geo: &Geo, wb: &Arc<Wor
return painted;
}
// Source outlines stay in cell space beneath every floating object.
if let Some(ch) = sh.charts.iter().find(|ch| app.selected_chart() == Some(ch.id))
if let Some((_, data)) = selected_chart_data(app, geo, wb, si, sh, p.clip_rect()) {
paint_chart_data(p, geo, sh, &data);
} else if let Some(ch) = sh.charts.iter().find(|ch| app.selected_chart() == Some(ch.id))
&& anchor_rect(geo, sh, &ch.anchor).intersects(p.clip_rect())
{
// Series that are not one block of cells: each series' values on this sheet.
for s in &ch.series {
if let Ok(gridcraft_engine::formula::Expr::Ref(rf)) = gridcraft_engine::formula::parse(&s.values)
&& rf.sheet_name().is_none_or(|n| n.eq_ignore_ascii_case(&sh.name))
@@ -550,6 +553,88 @@ fn selection_frame(p: &Painter, r: Rect) {
}
}
/// How far from a corner of a selected chart's values outline a press still grabs it.
const DATA_HANDLE_REACH: f32 = 6.0;
/// The corners of a values outline, which drag it (#4389).
const DATA_HANDLES: [crate::objects::Handle; 4] =
[crate::objects::Handle::TopLeft, crate::objects::Handle::TopRight, crate::objects::Handle::BottomLeft, crate::objects::Handle::BottomRight];
/// The selected chart and its data as blocks on sheet `si` (`sh`), while the chart lies on screen
/// within `clip`: the blocks a drag of its values outline previews, else where they are. `None`
/// when no chart is selected, its data is on another sheet or its series are not one block.
pub(crate) fn selected_chart_data(
app: &SheetApp,
geo: &Geo,
wb: &Workbook,
si: usize,
sh: &Sheet,
clip: Rect,
) -> Option<(u32, gridcraft_engine::chart_data::ChartData)> {
if objects_hidden(wb) {
return None;
}
let id = app.selected_chart()?;
let ch = sh.charts.iter().find(|ch| ch.id == id)?;
let dragged = match app.grid.drag {
crate::grid::Drag::ChartData { chart, to, .. } if chart == id => Some(to),
_ => None,
};
// A drag that scrolls the chart away keeps its preview: the block is still being dragged.
if dragged.is_none() && !anchor_rect(geo, sh, &ch.anchor).intersects(clip) {
return None;
}
let data = gridcraft_engine::chart_data::chart_data(wb, si, ch).filter(|d| d.sheet == si)?;
Some((id, dragged.flatten().map_or(data, |to| data.moved(to))))
}
/// Where the handle on corner `h` of the values outline `rr` is painted.
fn data_handle_rect(h: crate::objects::Handle, rr: Rect) -> Rect {
Rect::from_center_size(h.pos(rr), vec2(7.0, 7.0))
}
/// Outlines a chart's data as Excel does: series names in red, category labels in purple and
/// values in blue (#4390), with a handle on each corner of the values (#4389). Each pane clips
/// its own part, so frozen panes show the block once.
fn paint_chart_data(p: &Painter, geo: &Geo, sh: &Sheet, data: &gridcraft_engine::chart_data::ChartData) {
let t = Tokens::get(p.ctx());
let blocks = [(data.names, 1, false), (data.categories, 2, false), (Some(data.values), 0, true)];
for (range, color, handles) in blocks.into_iter().filter_map(|(r, c, h)| r.map(|r| (r, t.ref_color(c, true), h))) {
let rr = geo.range_rect(sh, range);
for pane in geo.range_panes(range) {
let pp = p.with_clip_rect(pane.intersect(p.clip_rect()));
pp.rect_stroke(rr, 0.0, Stroke::new(1.5, color), StrokeKind::Inside);
if handles {
for h in DATA_HANDLES {
pp.rect_filled(data_handle_rect(h, rr), 0.0, Color32::WHITE);
pp.rect_filled(data_handle_rect(h, rr).shrink(1.0), 0.0, color);
}
}
}
}
}
/// The corner of the selected chart's values outline under `p`, with the chart and its values
/// block. Like [`hit`], only over the cell area and while objects show; the caller asks
/// [`hit`] first, since objects paint over the outline.
pub fn chart_data_handle(app: &SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) -> Option<(u32, gridcraft_engine::core::RangeRef, crate::objects::Handle)> {
if !geo.cells.contains(p) {
return None;
}
let wb = &app.session.active()?.wb;
let (id, data) = selected_chart_data(app, geo, wb, wb.active_sheet(), sh, geo.cells)?;
let rr = geo.range_rect(sh, data.values);
// Only a corner some pane paints: with frozen panes, a corner scrolled under the frozen band
// is hidden, and the frozen cells it lies under keep the press.
let panes = geo.range_panes(data.values);
DATA_HANDLES
.into_iter()
.filter(|h| panes.iter().any(|pane| pane.intersects(data_handle_rect(*h, rr))))
.map(|h| (h, h.pos(rr).distance(p)))
.filter(|(_, d)| *d <= DATA_HANDLE_REACH)
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(h, _)| (id, data.values, h))
}
/// Where object `o` sits on the sheet (logical coordinates), when it exists on `sh`.
pub fn object_rect(geo: &Geo, sh: &Sheet, o: ObjRef) -> Option<Rect> {
sh.object_anchor(o).map(|a| anchor_rect(geo, sh, &a))
+23 -1
View File
@@ -455,7 +455,7 @@ pub fn open_format(app: &SheetApp, params: &Json) -> Option<Dialog> {
"print": c.print,
"locked": c.locked,
});
let title = if text_only { "Edit Text".to_string() } else { format!("Format Control: {}", c.display_name()) };
let title = if text_only { "Edit Text".to_string() } else { app.ui.language.tr_fill("Format Control: {name}", &[("name", &c.display_name())]) };
Some(Dialog::custom("formatControl", &title, v))
}
@@ -567,3 +567,25 @@ pub fn format_dialog(app: &mut SheetApp, ui: &mut Ui, d: &mut Dialog, open: &mut
}
}
}
#[cfg(test)]
mod format_title_tests {
use super::*;
use crate::i18n::Language;
use gridcraft_engine::Session;
#[test]
fn the_format_control_title_follows_the_interface_language() {
let mut session = Session::new();
session.new_workbook();
let mut app = SheetApp::new(session, Default::default());
let v = app.run("insert.button", json!({"at": "B2", "text": "Go"})).unwrap();
let id = v["control"].as_u64().unwrap();
let name = control(&app, id as u32).unwrap().display_name();
assert_eq!(open_format(&app, &json!({"id": id})).unwrap().title, format!("Format Control: {name}"));
app.ui.language = Language::It;
let want = Language::It.tr("Format Control: {name}").replace("{name}", &name);
assert_eq!(open_format(&app, &json!({"id": id})).unwrap().title, want);
assert!(!want.starts_with("Format Control"));
}
}
+57 -7
View File
@@ -26,6 +26,7 @@ mod names;
mod paste;
mod ref_edit;
mod show;
mod sort_dialog;
mod spelling;
mod zoom;
@@ -38,6 +39,7 @@ use names::pasteable_names;
pub(crate) use ref_edit::SHEET_DELETED;
pub(crate) use show::build_params;
pub use show::show;
pub(crate) use sort_dialog::{grid_sense, refuse_sheet_change};
use zoom::zoom_preset;
/// A form field. `Ref` is a range reference that can also be picked by selecting on the grid
@@ -64,6 +66,8 @@ pub struct Dialog {
pub tab: String,
pub search: String,
pub list_index: usize,
/// Custom Sort's own state: the selection to restore and the column choices.
sort: sort_dialog::State,
pub result: Option<Json>,
/// "Show password" is ticked: password fields show their text.
pub show_password: bool,
@@ -233,6 +237,7 @@ impl Dialog {
tab: String::new(),
search: String::new(),
list_index: 0,
sort: Default::default(),
result: None,
show_password: false,
focus_first_field: true,
@@ -258,6 +263,7 @@ impl Dialog {
tab: String::new(),
search: String::new(),
list_index: 0,
sort: Default::default(),
result: None,
show_password: false,
focus_first_field: false,
@@ -359,7 +365,7 @@ impl Dialog {
vec![
Number { key: "to", label: "Before sheet (position, 0 = first):" },
Check { key: "copy", label: "Create a copy" },
Note(format!("Sheets: {}", sheets.join(", "))),
Note(app.ui.language.tr_fill("Sheets: {sheets}", &[("sheets", &sheets.join(", "))])),
],
json!({"to": 0, "copy": false}),
);
@@ -476,7 +482,10 @@ impl Dialog {
"unhideSheet",
"Unhide",
"sheet.unhide",
vec![Text { key: "sheet", label: "Unhide sheet:" }, Note(format!("Hidden: {}", opts.join(", ")))],
vec![
Text { key: "sheet", label: "Unhide sheet:" },
Note(app.ui.language.tr_fill("Hidden: {sheets}", &[("sheets", &opts.join(", "))])),
],
json!({"sheet": first}),
);
d.values.insert("sheet".into(), json!(first));
@@ -986,11 +995,7 @@ impl Dialog {
}],
json!({"kind": "blanks"}),
),
"sort" => {
// Seed "Sort by" from the column the user is actually in (#1906).
let col = app.session.active().map(|d| gridcraft_engine::core::col_to_letters(d.selection.active.col)).unwrap_or_else(|| "A".into());
Dialog::custom("sort", "Sort", json!({"header": true, "levels": [{"column": col, "order": "asc"}]}))
}
"sort" => sort_dialog::open(app, &params)?,
"nameManager" => Dialog::custom("nameManager", "Name Manager", json!({})),
"pasteName" => {
// F3 opens it only when the workbook has names to paste, as in Excel.
@@ -1140,6 +1145,51 @@ impl Dialog {
mod tests {
use super::*;
/// The text of the dialog's note.
fn note(d: &Dialog) -> String {
d.fields.iter().find_map(|f| if let Field::Note(text) = f { Some(text.clone()) } else { None }).unwrap_or_default()
}
#[test]
fn sheet_notes_follow_the_interface_language() {
use crate::i18n::Language;
let mut session = gridcraft_engine::Session::default();
session.new_workbook();
let mut app = SheetApp::new(session, Default::default());
app.run("home.insertSheet", json!({})).unwrap();
let unhide = json!({"sheets": ["Sheet2"]});
assert_eq!(note(&Dialog::open(&mut app, "moveSheet", json!({})).unwrap()), "Sheets: Sheet1, Sheet2");
assert_eq!(note(&Dialog::open(&mut app, "unhideSheet", unhide.clone()).unwrap()), "Hidden: Sheet2");
let it = Language::It;
app.ui.language = it;
let moved = note(&Dialog::open(&mut app, "moveSheet", json!({})).unwrap());
assert_eq!(moved, it.tr("Sheets: {sheets}").replace("{sheets}", "Sheet1, Sheet2"));
assert!(!moved.starts_with("Sheets"));
let hidden = note(&Dialog::open(&mut app, "unhideSheet", unhide).unwrap());
assert_eq!(hidden, it.tr("Hidden: {sheets}").replace("{sheets}", "Sheet2"));
assert!(!hidden.starts_with("Hidden"));
}
#[test]
fn goal_seek_success_toast_follows_the_interface_language() {
use crate::i18n::Language;
let mut session = gridcraft_engine::Session::default();
session.new_workbook();
let mut app = SheetApp::new(session, Default::default());
app.run("cell.set", json!({"cell": "B1", "input": "=A1*2"})).unwrap();
let it = Language::It;
app.ui.language = it;
let mut d = Dialog::custom("goalSeek", "Goal Seek", json!({"set": "B1", "to": "10", "changing": "A1"}));
let ctx = egui::Context::default();
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| analysis::goal_seek(&mut app, ui, &mut d, &mut true, &mut true));
out.textures_delta.clear();
assert_eq!(app.message, None);
// The value is shown as before (the JSON number the command returns).
let want = it.tr("Goal Seeking found a solution: {value}").replace("{value}", "5.0");
assert_eq!(app.toast.map(|t| t.0), Some(want.clone()));
assert!(!want.starts_with("Goal Seeking"));
}
#[test]
fn remove_duplicates_prefills_the_selection_and_submits_the_edited_range() {
let mut session = gridcraft_engine::Session::default();
+4 -1
View File
@@ -34,7 +34,10 @@ pub(super) fn goal_seek(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, c
}
if *confirm {
match app.run("data.goalSeek", json!({"set": set, "to": to.parse::<f64>().unwrap_or(0.0), "changing": changing})) {
Ok(r) => app.toast = Some((format!("Goal Seeking found a solution: {}", r["value"]), crate::now_ms())),
Ok(r) => {
let text = app.ui.language.tr_fill("Goal Seeking found a solution: {value}", &[("value", &r["value"].to_string())]);
app.toast = Some((text, crate::now_ms()));
}
Err(e) => app.message = Some(("Goal Seek".into(), crate::clean_error(&e))),
}
}
+3 -104
View File
@@ -1,7 +1,7 @@
#[cfg(test)]
use super::show::build_params;
use super::show::{form_fields, ok_cancel};
use super::{Dialog, Field, Icon, Json, SheetApp, json, vec2};
use super::{Dialog, Field, Json, SheetApp, json, vec2};
/// Initial values of the Data Validation form: the rule stored on the active cell, so OK without
/// edits keeps it; a plain list rule when the cell has none.
@@ -180,109 +180,8 @@ pub(super) fn advanced_filter_form(app: &SheetApp, ui: &mut egui::Ui, d: &mut Di
ui.allocate_ui(vec2(ui.available_width(), ui.spacing().interact_size.y + 8.0), |ui| ok_cancel(ui, confirm, open));
}
/// Draws the sort-level editor: header toggle, column/by/order controls, add/remove level, and `data.sort` on confirmation.
pub(super) fn sort(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool) {
let lang = app.ui.language;
let mut header = d.values.get("header").and_then(Json::as_bool).unwrap_or(true);
ui.checkbox(&mut header, "My list has headers");
d.values.insert("header".into(), json!(header));
let mut levels: Vec<Json> = d.values.get("levels").and_then(Json::as_array).cloned().unwrap_or_default();
// Columns of the region around the active cell, labelled with their header (or first value).
let columns: Vec<(String, String)> = app
.session
.active()
.and_then(|d| {
let sh = d.wb.active()?;
let region = gridcraft_engine::selection::current_region(sh, d.selection.active);
Some(
(region.start.col..=region.end.col)
.map(|c| {
let letter = gridcraft_engine::core::col_to_letters(c);
// The region starts at the header row when one is present, so the
// label always comes from start.row: header text with headers on,
// first data value with them off.
let label_row = region.start.row;
let text = gridcraft_engine::display::cell_text(&d.wb, sh, gridcraft_engine::core::CellRef::new(label_row, c));
let text: String = text.chars().take(24).collect();
(letter.clone(), if text.is_empty() { letter } else { format!("{letter}: {text}") })
})
.collect(),
)
})
.unwrap_or_default();
let mut remove = None;
for (i, lv) in levels.iter_mut().enumerate() {
ui.horizontal(|ui| {
let label = ui.label(lang.tr(if i == 0 { "Sort by" } else { "Then by" }));
let mut col = lv["column"].as_str().unwrap_or("A").to_string();
if columns.is_empty() {
ui.add(egui::TextEdit::singleline(&mut col).desired_width(50.0)).labelled_by(label.id);
} else {
// The closed box shows the same "B: Revenue" label as the list, not the bare letter (#3446).
let shown =
columns.iter().find(|(letter, _)| letter.eq_ignore_ascii_case(&col)).map_or_else(|| col.clone(), |(_, label)| label.clone());
craft_ui::ComboBox::from_id_salt(("sort_col", i))
.selected_text(shown)
.show_ui(ui, |ui| {
for (letter, label) in &columns {
ui.selectable_value(&mut col, letter.clone(), label.as_str());
}
})
.response
.labelled_by(label.id);
}
lv["column"] = json!(col.to_ascii_uppercase());
let mut by = lv["by"].as_str().unwrap_or("values").to_string();
craft_ui::ComboBox::from_id_salt(("by", i))
.selected_text(match by.as_str() {
"cellColor" => "Cell Color",
"fontColor" => "Font Color",
_ => "Cell Values",
})
.show_ui(ui, |ui| {
ui.selectable_value(&mut by, "values".into(), "Cell Values");
ui.selectable_value(&mut by, "cellColor".into(), "Cell Color");
ui.selectable_value(&mut by, "fontColor".into(), "Font Color");
})
.response
.accessible_name(lang.tr("Sort On"));
lv["by"] = json!(by);
let mut desc = lv["order"].as_str() == Some("desc");
ui.radio_value(&mut desc, false, "A to Z");
ui.radio_value(&mut desc, true, "Z to A");
lv["order"] = json!(if desc { "desc" } else { "asc" });
if crate::widgets::icon_button(ui, Icon::Close, crate::theme::Tokens::get(ui.ctx()).text_dim, "Remove level", vec2(18.0, 18.0)).clicked()
{
remove = Some(i);
}
});
}
if let Some(i) = remove
&& levels.len() > 1
{
levels.remove(i);
}
if ui.button("+ Add Level").clicked() {
let used: Vec<String> = levels.iter().filter_map(|l| l.get("column").and_then(Json::as_str).map(str::to_string)).collect();
let next = columns
.iter()
.map(|(l, _)| l)
.find(|l| !used.contains(l))
.cloned()
.or_else(|| columns.last().map(|(l, _)| l.clone()))
.unwrap_or_else(|| "B".into());
levels.push(json!({"column": next, "order": "asc"}));
}
d.values.insert("levels".into(), Json::Array(levels.clone()));
let mut open = true;
ok_cancel(ui, confirm, &mut open);
if *confirm {
app.run_or_alert("data.sort", json!({"header": header, "keys": levels}));
}
if !open {
*confirm = true;
}
}
// Custom Sort lives in its own module; `show` reaches it from here.
pub(super) use super::sort_dialog::sort;
#[cfg(test)]
mod data_validation_tests {
+2
View File
@@ -326,6 +326,8 @@ fn active_sheet_name(app: &SheetApp) -> String {
/// dialog about to run its command must not, since references without a sheet name would be
/// read against the sheet still shown.
pub(super) fn end_pick(app: &mut SheetApp, d: &mut Dialog) -> Result<(), String> {
// Custom Sort puts back the selection it changed whenever it lets go of the grid.
super::sort_dialog::restore_selection(app, d);
d.refs.target = None;
d.refs.collapsed = None;
let Some(home) = d.refs.home.as_mut() else { return Ok(()) };
+1
View File
@@ -174,6 +174,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
"advancedFilter" => window.default_height(0.0),
_ => window,
};
let window = super::sort_dialog::window(window, &d.name, ctx, app.ui.language);
let (window, collapsed) = place_window(app, ctx, &mut d, window, window_id);
let shown = window.show(ctx, |ui| {
if let Some(key) = &collapsed {
+416
View File
@@ -0,0 +1,416 @@
//! Custom Sort (Data › Sort): sort levels with column, sort-on and order pickers.
//!
//! The dialog restores the grid selection it changed when it lets go of the grid (see
//! [`restore_selection`], called from `ref_edit::end_pick`) and keeps the worksheet it opened on.
use gridcraft_engine::Selection;
use gridcraft_engine::core::{CellRef, RangeRef, Value, col_to_letters};
use super::show::ok_cancel;
use super::{Dialog, Json, Sense, SheetApp, json, vec2};
use crate::i18n::Language;
use crate::icons::Icon;
use crate::theme::Tokens;
/// Commands that change which worksheet is shown or which worksheets exist: refused while Sort is
/// open, so Sort always acts on the worksheet it opened on.
const SHEET_COMMANDS: [&str; 8] =
["sheet.activate", "sheet.next", "sheet.previous", "sheet.move", "sheet.hide", "sheet.unhide", "home.insertSheet", "home.deleteSheet"];
/// What the dialog keeps besides its field values.
#[derive(Clone, Debug, Default)]
pub(super) struct State {
/// The exact selection to restore when Sort closes, including ranges and the shift anchor.
restore: Option<Selection>,
/// The workbook and worksheet Sort opened on, by identity: the only one it may sort. A sheet's
/// position changes when sheets are inserted, deleted, moved or undone, its [`SheetUid`] does not.
home: Option<(u64, u64)>,
choices: Option<ChoicesCache>,
}
/// The column choices for one sheet revision, range, header setting and language.
#[derive(Clone, Debug)]
struct ChoicesCache {
language: Language,
doc_uid: Option<u64>,
sheet_index: Option<usize>,
revision: Option<u64>,
range: Option<String>,
header: bool,
choices: Vec<Choice>,
}
/// A column of the sorted range: its letters, its label and whether its values are numbers.
type Choice = (String, String, bool);
/// Opens Custom Sort on the range, worksheet and header guess of `data.sort`, seeding "Sort by" from the
/// active column (#1906). A request that can't be resolved is reported and opens nothing.
pub(super) fn open(app: &mut SheetApp, params: &Json) -> Option<Dialog> {
let (sheet, range, header) = match gridcraft_engine::cmd::data::sort_context(&app.session, params) {
Ok(context) => context,
Err(e) => {
app.message = Some(("Sort".into(), crate::clean_error(&e.to_string())));
return None;
}
};
// Sort works on the worksheet shown, so a request for another one shows it first.
if app.session.active().is_some_and(|doc| doc.wb.active_sheet() != sheet)
&& let Err(e) = app.run("sheet.activate", json!({"sheet": sheet}))
{
app.message = Some(("Sort".into(), crate::clean_error(&e)));
return None;
}
// An open filter menu would take the Enter that confirms Sort (and apply its filter).
app.grid.filter_menu = None;
let restore = app.session.active().map(|doc| doc.selection.clone());
let home = sheet_key(app);
let active_col = app.session.active().map(|doc| doc.selection.active.col);
let first = col_to_letters(active_col.filter(|c| (range.start.col..=range.end.col).contains(c)).unwrap_or(range.start.col));
if header && range.height() > 1 {
let _ = app.run("selection.set", json!({"range": body_of(range).a1()}));
}
let mut d = Dialog::custom("sort", "Sort", json!({"header": header, "range": range.a1(), "levels": [{"column": first, "order": "asc"}]}));
d.sort.restore = restore;
d.sort.home = home;
Some(d)
}
/// `r` without its header row.
fn body_of(r: RangeRef) -> RangeRef {
RangeRef::new(CellRef::new(r.start.row.saturating_add(1), r.start.col), r.end)
}
/// The active workbook and worksheet by identity (document uid, [`SheetUid`]).
///
/// [`SheetUid`]: gridcraft_engine::model::SheetUid
fn sheet_key(app: &SheetApp) -> Option<(u64, u64)> {
let doc = app.session.active()?;
Some((doc.uid, doc.wb.active()?.uid.get()))
}
/// Puts back the selection from before Sort opened (once) on the worksheet it opened on: the
/// selection shown while that sheet is active, else the one the sheet keeps for when it is shown
/// again. Nothing is restored once that sheet is gone. Runs whenever a dialog lets go of the grid.
pub(super) fn restore_selection(app: &mut SheetApp, d: &mut Dialog) {
let Some((doc_uid, sheet_uid)) = d.sort.home.filter(|_| d.name == "sort") else { return };
let Some(doc) = app.session.active_mut().filter(|doc| doc.uid == doc_uid) else { return };
let Some(index) = doc.wb.sheets.iter().position(|s| s.uid.get() == sheet_uid) else { return };
let Some(selection) = d.sort.restore.take() else { return };
if index == doc.wb.active_sheet() {
doc.selection = selection;
} else {
if doc.sheet_selections.len() < doc.wb.sheets.len() {
doc.sheet_selections.resize(doc.wb.sheets.len(), Selection::default());
}
if let Some(slot) = doc.sheet_selections.get_mut(index) {
*slot = selection;
}
}
}
/// The reason `id` is refused while Sort is open, if it is.
pub(crate) fn refuse_sheet_change(app: &SheetApp, id: &str) -> Option<String> {
(app.dialog.as_ref().is_some_and(|d| d.name == "sort") && SHEET_COMMANDS.contains(&id))
.then(|| "Close the Sort dialog before switching or changing worksheets.".into())
}
/// The grid ignores the mouse while Sort is open, so the selection cannot change under the dialog.
pub(crate) fn grid_sense(app: &SheetApp) -> Sense {
if app.dialog.as_ref().is_some_and(|d| d.name == "sort") { Sense::hover() } else { Sense::click_and_drag() }
}
/// Sort moves and resizes. Its minimum width fits the whole toolbar row (the level buttons and the
/// headers checkbox) in the interface language, so a longer translation widens the window instead
/// of overlapping or wrapping the row.
pub(super) fn window<'a>(window: egui::Window<'a>, name: &str, ctx: &egui::Context, lang: Language) -> egui::Window<'a> {
if name != "sort" {
return window;
}
let width = toolbar_width(ctx, lang).max(480.0);
window.resizable(true).min_width(width).min_height(260.0).default_width(width.max(500.0)).default_height(320.0)
}
/// The width of the toolbar row of [`sort`] with its labels on one line, plus the window frame.
fn toolbar_width(ctx: &egui::Context, lang: Language) -> f32 {
let style = ctx.global_style();
let painter = ctx.layer_painter(egui::LayerId::background());
let text = |font: egui::FontId, key: &str| painter.layout_no_wrap(lang.tr(key).to_string(), font, egui::Color32::PLACEHOLDER).size().x;
let button_font = crate::theme::ui_font(12.5);
// Mirrors `small_button_accent`: a 24px icon cell and the label plus 6px.
let buttons: f32 = ["Add Level", "Delete Level", "Copy Level"].iter().map(|key| 24.0 + text(button_font.clone(), key) + 6.0).sum();
let arrows = 2.0 * 24.0;
let spacing = &style.spacing;
let checkbox = spacing.icon_width + spacing.icon_spacing + text(egui::TextStyle::Body.resolve(&style), "My list has headers");
// Five buttons and the checkbox, with the gaps between them, and the window's inner margin.
(buttons + arrows + checkbox + 6.0 * spacing.item_spacing.x + 2.0 * style.spacing.window_margin.left as f32 + 16.0).ceil()
}
/// The label of a column that has no header text: `Column A`, in the interface language.
fn column_label(lang: Language, letters: &str) -> String {
lang.tr("Column {letters}").replace("{letters}", letters)
}
/// The columns of `range` with their labels: header text, or `Column A`, `Column B`… without headers.
fn column_choices(app: &SheetApp, range: Option<RangeRef>, header: bool) -> Vec<Choice> {
let Some(r) = range else { return Vec::new() };
let lang = app.ui.language;
let sh = app.session.active().and_then(|doc| doc.wb.active());
let body_start = r.start.row.saturating_add(u32::from(header));
let cols = r.end.col.saturating_sub(r.start.col).saturating_add(1).max(1) as usize;
// Total sampled cells are bounded across all columns, not per column.
let rows_per_col = (200_000 / cols).max(1);
(r.start.col..=r.end.col)
.map(|c| {
let letters = col_to_letters(c);
let text = match (header, sh) {
(true, Some(sh)) => sh.value(CellRef::new(r.start.row, c)).display().trim().to_string(),
_ => String::new(),
};
let label = if text.is_empty() { column_label(lang, &letters) } else { text };
let numeric =
sh.is_some_and(|sh| values_are_numeric((body_start..=r.end.row).take(rows_per_col).map(|row| sh.value(CellRef::new(row, c)))));
(letters, label, numeric)
})
.collect()
}
/// The column choices, recomputed only when the sheet, range, header setting or language changed.
fn cached_choices(app: &SheetApp, d: &mut Dialog, range: Option<RangeRef>, header: bool) -> Vec<Choice> {
let language = app.ui.language;
let (doc_uid, sheet_index, revision) =
app.session.active().map(|doc| (Some(doc.uid), Some(doc.wb.active_sheet()), Some(doc.revision))).unwrap_or_default();
let range_key = range.map(|r| r.a1());
if let Some(cache) = &d.sort.choices
&& cache.language == language
&& cache.doc_uid == doc_uid
&& cache.sheet_index == sheet_index
&& cache.revision == revision
&& cache.range == range_key
&& cache.header == header
{
return cache.choices.clone();
}
let choices = column_choices(app, range, header);
d.sort.choices = Some(ChoicesCache { language, doc_uid, sheet_index, revision, range: range_key, header, choices: choices.clone() });
choices
}
/// The column a new level starts on: the first column no level uses, and once every column is used
/// the selected level's column (as Copy Level would give), so more levels can always be added.
fn next_level_column(choices: &[Choice], levels: &[Json], selected: usize) -> Option<String> {
let used: Vec<&str> = levels.iter().filter_map(|l| l["column"].as_str()).collect();
choices
.iter()
.map(|(l, _, _)| l.as_str())
.find(|l| !used.contains(l))
.or_else(|| levels.get(selected).and_then(|l| l["column"].as_str()))
.or_else(|| choices.first().map(|(l, _, _)| l.as_str()))
.map(str::to_string)
}
/// Draws the sort-level editor: header toggle, level actions, the level rows and OK/Cancel; OK runs `data.sort`.
pub(super) fn sort(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool) {
let mut header = d.values.get("header").and_then(Json::as_bool).unwrap_or(true);
let was_header = header;
let range = d.values.get("range").and_then(Json::as_str).and_then(RangeRef::parse);
let lang = app.ui.language;
let choices = cached_choices(app, d, range, header);
let mut levels: Vec<Json> = d.values.get("levels").and_then(Json::as_array).cloned().unwrap_or_default();
let mut selected = d.list_index.min(levels.len().saturating_sub(1));
let t = Tokens::get(ui.ctx());
ui.horizontal_wrapped(|ui| {
// Levels are not limited by the columns, allow the same column twice (up to 64 levels).
let next_column = next_level_column(&choices, &levels, selected);
if text_icon_button(ui, Icon::Plus, t.accent, "Add Level", levels.len() < 64 && next_column.is_some()).clicked()
&& let Some(next) = next_column
{
levels.push(json!({"column": next, "order": "asc"}));
selected = levels.len() - 1;
}
if text_icon_button(ui, Icon::Close, t.danger, "Delete Level", !levels.is_empty()).clicked() && selected < levels.len() {
levels.remove(selected);
selected = selected.saturating_sub(1);
}
if text_icon_button(ui, Icon::Copy, t.text, "Copy Level", !levels.is_empty() && levels.len() < 64).clicked()
&& let Some(lv) = levels.get(selected).cloned()
{
levels.insert(selected + 1, lv);
selected += 1;
}
if icon_button(ui, Icon::ChevronUp, t.text, "Move Up", selected > 0).clicked() {
levels.swap(selected, selected - 1);
selected -= 1;
}
if icon_button(ui, Icon::Chevron, t.text, "Move Down", selected + 1 < levels.len()).clicked() {
levels.swap(selected, selected + 1);
selected += 1;
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.checkbox(&mut header, lang.tr("My list has headers"));
});
});
d.values.insert("header".into(), json!(header));
if header != was_header
&& let Some(r) = range
{
let shown = if header && r.height() > 1 { body_of(r) } else { r };
let _ = app.run("selection.set", json!({"range": shown.a1()}));
}
ui.add_space(4.0);
let table_height = (ui.available_height() - 48.0).max(60.0);
egui::ScrollArea::vertical().max_height(table_height).min_scrolled_height(table_height).auto_shrink([false, false]).show(ui, |ui| {
levels_table(ui, &mut levels, &mut selected, &choices, lang);
});
d.list_index = selected;
d.values.insert("levels".into(), Json::Array(levels.clone()));
let mut open = true;
ok_cancel(ui, confirm, &mut open);
if *confirm && !levels.is_empty() {
let mut p = json!({"header": header, "keys": levels});
if let Some(r) = d.values.get("range").and_then(Json::as_str) {
p["range"] = json!(r);
}
// The range has no sheet name, so it must not be read against another worksheet.
let failure = if sheet_key(app) != d.sort.home {
Some("Return to the original worksheet to sort, or cancel.".to_string())
} else {
app.run("data.sort", p).err().map(|e| crate::clean_error(&e))
};
if let Some(message) = failure {
app.message = Some((d.title.clone(), message));
*confirm = false;
}
}
if !open {
*confirm = true;
}
}
/// The selectable level rows: "Sort by"/"Then by" with the column, sort-on and order pickers.
fn levels_table(ui: &mut egui::Ui, levels: &mut [Json], selected: &mut usize, choices: &[Choice], lang: Language) {
let gap = ui.spacing().item_spacing.x;
// The row label column grows with the translated words, so a longer one is never wrapped or cut.
let font = egui::TextStyle::Body.resolve(ui.style());
let label_w = ["Sort by", "Then by"]
.iter()
.map(|key| ui.painter().layout_no_wrap(lang.tr(key).to_string(), font.clone(), egui::Color32::PLACEHOLDER).size().x.ceil() + 4.0)
.fold(64.0, f32::max);
let row_h = 26.0;
let rest = (ui.available_width() - 16.0 - label_w - 3.0 * gap).max(300.0);
let w = rest / 3.0;
let cell = |ui: &mut egui::Ui, w: f32, h: f32, add: &mut dyn FnMut(&mut egui::Ui)| {
ui.allocate_ui_with_layout(vec2(w, h), egui::Layout::left_to_right(egui::Align::Center), |ui| {
ui.set_min_size(vec2(w, h));
add(ui);
});
};
ui.horizontal(|ui| {
cell(ui, label_w + gap + w, 18.0, &mut |ui| {
ui.strong(lang.tr("Sort|Column"));
});
cell(ui, w, 18.0, &mut |ui| {
ui.strong(lang.tr("Sort On"));
});
cell(ui, w, 18.0, &mut |ui| {
ui.strong(lang.tr("Order"));
});
});
let accent = Tokens::get(ui.ctx()).accent;
for (i, lv) in levels.iter_mut().enumerate() {
let row_rect = egui::Rect::from_min_size(ui.cursor().min, vec2(ui.available_width(), row_h));
let row = ui.interact(row_rect, ui.scope_id().with(("sortRow", i)), Sense::click());
if i == *selected {
ui.painter().rect_filled(row_rect, 3.0, accent.gamma_multiply(0.18));
} else if row.hovered() {
ui.painter().rect_filled(row_rect, 3.0, accent.gamma_multiply(0.07));
}
if row.clicked() {
*selected = i;
}
ui.allocate_ui_with_layout(row_rect.size(), egui::Layout::left_to_right(egui::Align::Center), |ui| {
cell(ui, label_w, row_h, &mut |ui| {
ui.add(egui::Label::new(lang.tr(if i == 0 { "Sort by" } else { "Then by" })).selectable(false));
});
let mut col = lv["column"].as_str().unwrap_or("A").to_string();
// The closed box names the column as its open list does (#3446), whatever the case of the stored letter.
let shown = choices
.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| {
for (letters, label, _) in choices {
ui.selectable_value(&mut col, letters.clone(), label);
}
});
r.response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, lang.tr("Sort|Column")));
if r.response.clicked() {
*selected = i;
}
lv["column"] = json!(col.to_ascii_uppercase());
let mut by = lv["by"].as_str().unwrap_or("values").to_string();
let by_label = lang.tr(match by.as_str() {
"cellColor" => "Cell Color",
"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| {
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"));
});
r.response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, lang.tr("Sort On")));
if r.response.clicked() {
*selected = i;
}
lv["by"] = json!(by);
let numeric = choices.iter().find(|(l, _, _)| lv["column"].as_str() == Some(l.as_str())).is_some_and(|(_, _, n)| *n);
let (asc_label, desc_label) = if numeric { ("Smallest to Largest", "Largest to Smallest") } else { ("A to Z", "Z to A") };
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| {
ui.selectable_value(&mut desc, false, asc_label);
ui.selectable_value(&mut desc, true, desc_label);
});
r.response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, lang.tr("Order")));
if r.response.clicked() {
*selected = i;
}
lv["order"] = json!(if desc { "desc" } else { "asc" });
});
}
}
/// A bordered icon-only button with a tooltip, greyed out when disabled.
fn icon_button(ui: &mut egui::Ui, icon: Icon, color: egui::Color32, tip: &str, enabled: bool) -> egui::Response {
let color = if enabled { color } else { Tokens::get(ui.ctx()).text_disabled };
let response = ui.add_enabled_ui(enabled, |ui| crate::widgets::icon_button(ui, icon, color, tip, vec2(24.0, 24.0))).inner;
button_border(ui, response.rect);
response
}
/// A bordered button with a coloured icon and a text label, greyed out when disabled.
fn text_icon_button(ui: &mut egui::Ui, icon: Icon, color: egui::Color32, label: &str, enabled: bool) -> egui::Response {
let response = ui.add_enabled_ui(enabled, |ui| crate::widgets::small_button_accent(ui, icon, Some(color), label, label, false)).inner;
button_border(ui, response.rect);
response
}
/// Draws the visible border around a button's `rect`.
fn button_border(ui: &egui::Ui, rect: egui::Rect) {
let t = Tokens::get(ui.ctx());
ui.painter().rect_stroke(rect, 4.0, egui::Stroke::new(1.0, t.separator), egui::StrokeKind::Inside);
}
/// Whether the values are numbers (blanks aside), which picks "Smallest to Largest" over "A to Z".
fn values_are_numeric(values: impl IntoIterator<Item = Value>) -> bool {
let mut has_number = false;
for value in values {
match value {
Value::Empty => {}
Value::Number(_) => has_number = true,
_ => return false,
}
}
has_number
}
+261 -4
View File
@@ -129,6 +129,70 @@ fn insert_snippet(ctx: &egui::Context, id: egui::Id, text: &mut String, snippet:
ctx.data_mut(|m| m.insert_temp(id.with("refocus"), true));
}
/// The RaTeX parser messages that carry a piece of the source (a command, a token, a count).
/// RaTeX reports an error only as finished English text, so a message is matched against these
/// shapes (from `ratex-parser` 0.1.14) and the catalog's template is filled with the same pieces;
/// RaTeX's fixed messages are plain catalog keys. A shape comes before a shorter one that also
/// matches its messages, and a message of any other shape stays as RaTeX wrote it.
const RATEX_TEMPLATES: &[&str] = &[
"Undefined control sequence: {name}",
"Expected '{expected}', got '{got}'",
"Expected group after '{symbol}'",
"Expected delimiter as argument to '{function}'",
"Expected group as argument to '{function}'",
"Got function '{function}' with no arguments as superscript",
"Got function '{function}' with no arguments as subscript",
"Got function '{function}' with no arguments as argument to '{parent}'",
"Got function '{function}' with no arguments as \\tag",
"Can't use function '{function}' in text mode",
"Can't use function '{function}' in math mode",
"Invalid color: '{color}'",
"Invalid size: '{size}'",
"Invalid unit: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'",
"Invalid delimiter type '{type}' after '{function}'",
"Invalid delimiter type '{type}'",
"No such environment: {name}",
"Expected argument to \\begin{{name}}",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}",
"{command} valid only within array environment",
"Mismatched {command}",
"Expected & or \\\\ or \\cr or \\end, got '{got}'",
"Unknown column alignment: {alignment}",
"Too many math in a row: expected {expected}, but got {got}",
"Unknown CD directive: @{directive}",
"Expected argument for {command}",
"{command} needs {count} premise(s), but only {available} available",
"{command} valid only as a supported bussproofs command within prooftree",
"prooftree ended with {count} proof stack item(s), expected 1",
"\\@char has non-numeric argument {argument}",
"\\@char with invalid code point {code}",
"Invalid environment name character: {character}",
];
/// A parse error message in the interface language: GridCraft's own checks and RaTeX's fixed
/// messages by their catalog key, RaTeX's messages with a piece of the source by their template.
fn parse_error_message(lang: crate::i18n::Language, message: &str) -> String {
let translated = lang.tr_error(message);
if translated != message {
return translated;
}
RATEX_TEMPLATES
.iter()
.find_map(|template| crate::i18n::unfill(template, message).map(|values| lang.tr_fill(template, &values)))
.unwrap_or(translated)
}
/// The line under the equation source for a parse error: where it is (the 1-based character),
/// then the message, both in the interface language.
fn parse_error_text(lang: crate::i18n::Language, position: Option<usize>, message: &str) -> String {
let message = parse_error_message(lang, message);
match position {
Some(p) => lang.tr_fill("Error at character {position}: {message}", &[("position", &p.to_string()), ("message", &message)]),
None => message,
}
}
/// The editor's body: quick-insert buttons, the LaTeX source with its error underlined, a live
/// preview on a sheet-coloured card, and OK/Cancel.
pub fn editor(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool, open: &mut bool) {
@@ -164,10 +228,7 @@ pub fn editor(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &m
ui.add_space(4.0);
match &pv.result {
Err(e) if !text.trim().is_empty() => {
let msg = match e.char_pos(&text) {
Some(p) => format!("Error at character {p}: {}", e.message),
None => e.message.clone(),
};
let msg = parse_error_text(app.ui.language, e.char_pos(&text), &e.message);
ui.colored_label(t.danger, msg);
}
_ => {
@@ -500,6 +561,202 @@ fn triangulate(pts: &[Pos2]) -> Vec<[usize; 3]> {
mod tests {
use super::*;
#[test]
fn parse_errors_follow_the_interface_language() {
use crate::i18n::Language;
assert_eq!(parse_error_text(Language::En, Some(3), "Missing }"), "Error at character 3: Missing }");
assert_eq!(parse_error_text(Language::En, None, "Empty {group}"), "Empty {group}");
let it = Language::It;
// The message is filled in once: its own `{message}` stays as it is.
let want = it.tr("Error at character {position}: {message}").replace("{position}", "3").replace("{message}", "Bad {message}");
assert_eq!(parse_error_text(it, Some(3), "Bad {message}"), want);
assert!(!want.starts_with("Error at character"));
}
/// RaTeX's fixed parser messages that an equation can reach; each is a catalog key.
const RATEX_MESSAGES: &[&str] = &[
"Double superscript",
"Double subscript",
"Extra }",
"Unexpected end of input in a macro argument",
"Expected \\right after \\left",
"\\middle must be within \\left and \\right",
"Invalid environment name",
"Expected \\end after environment body",
"Expected URL",
"\\tag requires an argument",
"only one infix operator per group",
"Expected color token",
"Expected size for \\raisebox",
"Expected size for \\rule width",
"Expected size for \\rule height",
"Cannot use both \\tag and \\nonumber in the same row",
"Multiple \\tag in a row",
"\\tag must appear at the end of the row after the equation body",
"Multiple \\nonumber in a row",
"\\nonumber must appear at the end of the row",
"Too many tab characters: &",
"Invalid column alignment for array",
"Expected column alignment character",
"Expected l or c or r",
"Expected ]",
"Unexpected end of CD row after @",
"Invalid column alignment for subarray",
"{subarray} can contain only one column",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command",
"Recursion limit exceeded",
"Too many expansions: infinite loop or need to increase maxExpand setting",
"Expected raw style for \\htmlStyle",
"\\verb assertion failed",
];
/// RaTeX's messages, as `layout` reports them for real sources, follow the interface language:
/// a fixed message by its catalog key, a message with a piece of the source by its template
/// with the same pieces filled in. The English is checked first, so a reworded RaTeX message
/// fails here instead of silently staying English.
#[test]
fn ratex_parse_errors_follow_the_interface_language() {
use crate::i18n::Language;
use gridcraft_engine::math::layout;
/// Source, RaTeX's English message, its catalog key or template, and the template's pieces.
type Case = (&'static str, &'static str, &'static str, &'static [(&'static str, &'static str)]);
#[rustfmt::skip]
let cases: &[Case] = &[
("x^1^2", "Double superscript", "Double superscript", &[]),
("x_1_2", "Double subscript", "Double subscript", &[]),
("x^\\frac", "Unexpected end of input in a macro argument", "Unexpected end of input in a macro argument", &[]),
("\\middle|", "\\middle must be within \\left and \\right", "\\middle must be within \\left and \\right", &[]),
("a \\over b \\over c", "only one infix operator per group", "only one infix operator per group", &[]),
("\\begin{array}{l}a&b\\end{array}", "Too many tab characters: &", "Too many tab characters: &", &[]),
("\\begin{subarray}{lc}x\\end{subarray}", "{subarray} can contain only one column", "{subarray} can contain only one column", &[]),
("\\begin{aligned}a\\tag1\\tag2\\end{aligned}", "Multiple \\tag in a row", "Multiple \\tag in a row", &[]),
("\\begin{CD}A @", "Unexpected end of CD row after @", "Unexpected end of CD row after @", &[]),
("\\verb", "\\verb assertion failed", "\\verb assertion failed", &[]),
("\\foo", "Undefined control sequence: \\foo", "Undefined control sequence: {name}", &[("name", "\\foo")]),
("x^{2", "Expected '}', got 'EOF'", "Expected '{expected}', got '{got}'", &[("expected", "}"), ("got", "EOF")]),
("x^", "Expected group after '^'", "Expected group after '{symbol}'", &[("symbol", "^")]),
("\\left\\frac x\\right)", "Expected delimiter as argument to '\\left'", "Expected delimiter as argument to '{function}'", &[("function", "\\left")]),
("\\text{\\frac12}", "Can't use function '\\frac' in text mode", "Can't use function '{function}' in text mode", &[("function", "\\frac")]),
("\\)", "Can't use function '\\)' in math mode", "Can't use function '{function}' in math mode", &[("function", "\\)")]),
("\\color{zz!}{x}", "Invalid color: 'zz!'", "Invalid color: '{color}'", &[("color", "zz!")]),
("\\rule{abc}{1em}", "Invalid size: 'abc'", "Invalid size: '{size}'", &[("size", "abc")]),
("\\rule{1xx}{1em}", "Invalid unit: 'xx'", "Invalid unit: '{unit}'", &[("unit", "xx")]),
("\\bigl x", "Invalid delimiter 'x' after '\\bigl'", "Invalid delimiter '{delimiter}' after '{function}'", &[("delimiter", "x"), ("function", "\\bigl")]),
("\\bigl{x}", "Invalid delimiter type 'ordgroup' after '\\bigl'", "Invalid delimiter type '{type}' after '{function}'", &[("type", "ordgroup"), ("function", "\\bigl")]),
("\\begin{foo}x\\end{foo}", "No such environment: foo", "No such environment: {name}", &[("name", "foo")]),
("\\begin{matrix}x\\end{pmatrix}", "Mismatch: \\begin{matrix} matched by \\end{pmatrix}", "Mismatch: \\begin{{begin}} matched by \\end{{end}}", &[("begin", "matrix"), ("end", "pmatrix")]),
("\\hline", "\\hline valid only within array environment", "{command} valid only within array environment", &[("command", "\\hline")]),
("\\begin{matrix}a", "Expected & or \\\\ or \\cr or \\end, got 'EOF'", "Expected & or \\\\ or \\cr or \\end, got '{got}'", &[("got", "EOF")]),
("\\begin{array}{q}x\\end{array}", "Unknown column alignment: q", "Unknown column alignment: {alignment}", &[("alignment", "q")]),
("\\begin{alignedat}{1}a&b&c&d\\end{alignedat}", "Too many math in a row: expected 1, but got 2", "Too many math in a row: expected {expected}, but got {got}", &[("expected", "1"), ("got", "2")]),
("\\begin{CD}A @Q B\\end{CD}", "Unknown CD directive: @Q", "Unknown CD directive: @{directive}", &[("directive", "Q")]),
("\\begin{prooftree}\\BinaryInfC{x}\\end{prooftree}", "\\BinaryInfC needs 2 premise(s), but only 0 available", "{command} needs {count} premise(s), but only {available} available", &[("command", "\\BinaryInfC"), ("count", "2"), ("available", "0")]),
("\\begin{prooftree}\\frac\\end{prooftree}", "\\frac valid only as a supported bussproofs command within prooftree", "{command} valid only as a supported bussproofs command within prooftree", &[("command", "\\frac")]),
("\\begin{prooftree}\\AxiomC{x}\\AxiomC{y}\\end{prooftree}", "prooftree ended with 2 proof stack item(s), expected 1", "prooftree ended with {count} proof stack item(s), expected 1", &[("count", "2")]),
("\\char\"FFFFFFF", "\\@char with invalid code point 268435455", "\\@char with invalid code point {code}", &[("code", "268435455")]),
];
let it = Language::It;
for (src, english, template, values) in cases {
let message = layout(src).err().unwrap_or_else(|| panic!("{src:?} lays out")).message;
assert_eq!(&message, english, "{src:?}");
assert_eq!(parse_error_message(Language::En, &message), message, "English stays as RaTeX wrote it");
let want = values.iter().fold(it.tr(template).to_string(), |text, (name, value)| text.replace(&format!("{{{name}}}"), value));
assert_eq!(parse_error_message(it, &message), want, "{src:?}");
assert_ne!(want, message, "{src:?} stays English in Italian");
}
let want = it.tr("Error at character {position}: {message}").replace("{position}", "2").replace("{message}", it.tr("Double superscript"));
assert_eq!(parse_error_text(it, Some(2), "Double superscript"), want);
}
/// Every RaTeX shape is read by its own template (not by a shorter one listed earlier), and
/// every catalog translates it with the same placeholders; every fixed message is translated in
/// every catalog.
#[test]
fn ratex_messages_are_translated_in_every_catalog() {
use crate::i18n::{Language, fill, unfill};
let placeholders = |s: &str| {
let mut names = s.split('{').skip(1).filter_map(|rest| rest.split_once('}').map(|(name, _)| name.to_string())).collect::<Vec<_>>();
names.sort();
names
};
for template in RATEX_TEMPLATES {
// A sample piece per placeholder: `\a1`, `\a2`, …
let names = unfill(template, template).unwrap_or_else(|| panic!("{template:?} does not read itself"));
let samples = (1..=names.len()).map(|i| format!("\\a{i}")).collect::<Vec<_>>();
let values = names.iter().zip(&samples).map(|((name, _), sample)| (*name, sample.as_str())).collect::<Vec<_>>();
let message = fill(template, &values);
let first = RATEX_TEMPLATES.iter().find(|t| unfill(t, &message).is_some());
assert_eq!(first, Some(template), "{message:?}");
assert_eq!(parse_error_message(Language::En, &message), message);
for language in Language::ALL.into_iter().filter(|l| *l != Language::En) {
let text = language.tr(template);
assert_eq!(placeholders(text), placeholders(template), "{}: {template:?} => {text:?}", language.code());
assert!(!text.contains('\n'), "{}: {template:?} => {text:?}", language.code());
assert_eq!(parse_error_message(language, &message), fill(text, &values), "{}", language.code());
assert_ne!(parse_error_message(language, &message), message, "{} leaves {template:?} in English", language.code());
}
}
for message in RATEX_MESSAGES {
for language in Language::ALL.into_iter().filter(|l| *l != Language::En) {
let shown = parse_error_message(language, message);
assert_ne!(&shown, message, "{} leaves {message:?} in English", language.code());
assert_eq!(placeholders(&shown), placeholders(message), "{}: {message:?} => {shown:?}", language.code());
}
}
}
/// A message of no known shape, such as RaTeX's internal ones or the chemistry parser's, stays
/// as RaTeX wrote it in every language.
#[test]
fn unknown_parser_messages_stay_as_ratex_wrote_them() {
use crate::i18n::Language;
for message in ["Null argument, please report this as a bug", "\\ce: unexpected token", "Expected group as atom", ""] {
for language in Language::ALL {
assert_eq!(parse_error_message(language, message), message, "{}", language.code());
}
}
}
/// The equation checks' own messages are translated in every catalog. Each comes from the real check, and the expected English is
/// built from the limits, so a changed limit fails here instead of silently falling back to
/// English (the catalogs key the message with the number in it).
#[test]
fn equation_check_messages_are_translated_in_every_catalog() {
use crate::i18n::Language;
use gridcraft_engine::math::{MAX_CELLS, MAX_DEPTH, MAX_SOURCE_BYTES, layout};
let cases = [
("\\def\\x{1} x".to_string(), "Macro definitions are not supported in equations.".to_string()),
("50% \\href{https://example.com}{x}".to_string(), "A % can't be combined with a link in an equation.".to_string()),
(format!("{}x{}", "{".repeat(MAX_DEPTH + 1), "}".repeat(MAX_DEPTH + 1)), format!("Equations can nest at most {MAX_DEPTH} levels deep.")),
("x".repeat(MAX_SOURCE_BYTES + 1), format!("An equation can be at most {MAX_SOURCE_BYTES} bytes long.")),
(
"\\begin{alignedat}{99999999}a\\end{alignedat}".to_string(),
format!("An equation can have at most {MAX_CELLS} matrix cells (rows times the widest row)."),
),
("\\rule{99999999em}{1em}".to_string(), "This equation is too large to draw.".to_string()),
];
let mut messages = Vec::new();
for (src, want) in cases {
let got = layout(&src).err().unwrap_or_else(|| panic!("{src:?} lays out")).message;
assert_eq!(got, want, "{src:?} hits another check");
messages.push(got);
}
// Only a panic inside the layout reaches this one.
messages.push("This equation could not be laid out.".to_string());
for message in &messages {
for language in Language::ALL {
let shown = parse_error_text(language, None, message);
assert!(!shown.contains('\n'), "{}: {message:?} => {shown:?}", language.code());
if language != Language::En {
assert_ne!(&shown, message, "{} leaves {message:?} in English", language.code());
}
}
}
let it = Language::It;
let want = it.tr("Error at character {position}: {message}").replace("{position}", "1").replace("{message}", it.tr(&messages[0]));
assert_eq!(parse_error_text(it, Some(1), &messages[0]), want);
}
#[test]
fn ear_clipping_covers_a_concave_polygon() {
// An L shape: area 3 unit squares.
+27 -1
View File
@@ -280,7 +280,8 @@ fn active_input(app: &SheetApp) -> String {
let Some(sh) = d.wb.active() else { return String::new() };
let a = sh.merge_at(d.selection.active).map(|m| m.start).unwrap_or(d.selection.active);
if let Some(picture) = sh.cell_pictures.get(&a) {
return if picture.alt.is_empty() { "Picture in cell".into() } else { format!("Picture: {}", picture.alt) };
let lang = app.ui.language;
return if picture.alt.is_empty() { lang.tr("Picture in cell").into() } else { lang.tr_fill("Picture: {alt}", &[("alt", &picture.alt)]) };
}
// Python code is shown as it is: it isn't a formula to translate or a value to format. Like
// a formula, it stays out of view in a Hidden cell on a protected sheet.
@@ -942,6 +943,31 @@ mod spill_tests {
SheetApp::new(s, Default::default())
}
#[test]
fn a_picture_in_a_cell_is_named_in_the_interface_language() {
use crate::i18n::Language;
use gridcraft_engine::core::CellRef;
use gridcraft_engine::model::CellPicture;
let mut app = app();
let put = |app: &mut SheetApp, cell: &str, alt: &str| {
let at = CellRef::parse(cell).unwrap();
let picture = std::sync::Arc::new(CellPicture { data: vec![], mime: "image/png".into(), alt: alt.into() });
std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().wb).sheet_mut(0).unwrap().set_picture(at, picture);
};
put(&mut app, "A1", "");
put(&mut app, "A2", "Logo {alt}");
select(&mut app, "A1");
assert_eq!(active_input(&app), "Picture in cell");
select(&mut app, "A2");
assert_eq!(active_input(&app), "Picture: Logo {alt}");
app.ui.language = Language::It;
select(&mut app, "A1");
assert_eq!(active_input(&app), Language::It.tr("Picture in cell"));
assert_ne!(active_input(&app), "Picture in cell");
select(&mut app, "A2");
assert_eq!(active_input(&app), Language::It.tr("Picture: {alt}").replace("{alt}", "Logo {alt}"));
}
fn set(app: &mut SheetApp, cell: &str, input: &str) {
app.run("cell.set", json!({"cell": cell, "input": input})).unwrap();
}
+5
View File
@@ -160,6 +160,11 @@ mod tests {
assert_eq!(sig("IF", En, Language::Es), "IF(prueba_lógica, [valor_si_verdadero], [valor_si_falso])");
assert_eq!(sig("SUM", En, Language::Es), "SUM(número1, [número2], ...)");
assert_eq!(description("IF", En, Language::Es).as_deref(), Some("Devuelve un valor según una condición."));
// Portuguese help, including brackets that open and close on different arguments.
assert_eq!(sig("IF", En, Language::PtBr), "IF(teste_lógico, [valor_se_verdadeiro], [valor_se_falso])");
assert_eq!(description("IF", En, Language::PtBr).as_deref(), Some("Retorna um valor quando uma condição é TRUE e outro quando é FALSE."));
assert_eq!(sig("SWITCH", En, Language::PtBr), "SWITCH(expressão, valor1, resultado1, [padrão_ou_valor2, resultado2], ...)");
assert_eq!(sig("LAMBDA", En, Language::PtBr), "LAMBDA([parâmetro1, ...], cálculo)");
// Spanish names and separators, from a localized name.
assert_eq!(sig("suma", Es, Language::Es), "SUMA(número1; [número2]; ...)");
assert_eq!(description("SUMA", Es, Language::Es).as_deref(), Some("Suma los números."));
+8
View File
@@ -151,6 +151,14 @@ pub enum Drag {
/// step of an earlier drag.
stepped: bool,
},
/// Dragging a corner of the selected chart's values outline (#4389): `to` is the previewed
/// block, which the release gives the chart.
ChartData {
chart: u32,
orig: RangeRef,
corner: crate::objects::Handle,
to: Option<RangeRef>,
},
}
/// The fill a left-drag of the handle just made, which the Auto Fill Options button can redo
+1 -1
View File
@@ -31,7 +31,7 @@ pub(super) fn center_across_end(start: u32, limit: u32, continues: impl Fn(u32)
pub(super) fn look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut CfCache) -> (Look, Option<CfLook>) {
let mut style = wb.styles.get(sh.style_id(c)).clone();
if let Some(t) = sh.table_at(c) {
style = gridcraft_engine::tables::table_cell_style(wb, si, t, c);
style = gridcraft_engine::tables::table_cell_shown_style(wb, si, t, cf.table_edges(sh, t), c);
}
let cfl = cf.look(wb, si, c);
if let Some(l) = &cfl
+4 -2
View File
@@ -57,7 +57,7 @@ fn drag_cursor(drag: &Drag, rtl: bool) -> Option<CursorIcon> {
Drag::ResizeCol { .. } => Some(CursorIcon::ResizeColumn),
Drag::ResizeRow { .. } => Some(CursorIcon::ResizeRow),
Drag::Freeze { cols, .. } => Some(if *cols { CursorIcon::ResizeHorizontal } else { CursorIcon::ResizeVertical }),
Drag::Object { handle: Some(h), .. } => Some(h.cursor(rtl)),
Drag::Object { handle: Some(h), .. } | Drag::ChartData { corner: h, .. } => Some(h.cursor(rtl)),
}
}
@@ -87,7 +87,9 @@ fn hover_cursor(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response, poin
let mods = ctx.input(|i| i.modifiers);
let works = hit.is_some_and(|(o, _)| o.kind == ObjKind::Control && app.selected_object != Some(o) && !mods.command && !mods.ctrl);
let on_object = hit.is_some();
if let Some(h) = object_handle {
// A corner of the selected chart's values outline resizes the chart's data, where no object covers it.
let data_handle = if idle && !on_object { crate::chartview::chart_data_handle(app, geo, sh, p).map(|(.., h)| h) } else { None };
if let Some(h) = object_handle.or(data_handle) {
ctx.set_cursor_icon(h.cursor(geo.rtl));
} else if works {
ctx.set_cursor_icon(CursorIcon::PointingHand);
+165 -13
View File
@@ -157,6 +157,20 @@ pub(super) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Respo
}
return;
}
// A corner of the selected chart's values outline drags the block the chart plots
// (#4389); a click on it keeps the chart selected.
if let Some(p) = at
&& app.editor.is_none()
&& let Some((chart, orig, corner)) = crate::chartview::chart_data_handle(app, geo, sh, p)
{
if primary_drag {
app.grid.drag = Drag::ChartData { chart, orig, corner, to: None };
if let Some(now) = pos {
drag_chart_data(app, geo, sh, now);
}
}
return;
}
app.selected_object = None;
}
// A right-click on a chart, picture, shape, slicer or form control opens the object's menu, not
@@ -630,22 +644,30 @@ fn handle_context_menu_and_keyboard(app: &mut SheetApp, input: &InteractionInput
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.
fn spend_escape(ctx: &egui::Context) -> bool {
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
})
}
fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) {
let (geo, sh, wb, sel, pos) = (input.geo, input.sheet, input.workbook, &input.selection, input.position);
let resp = input.response;
// Esc during a header-boundary drag cancels it: undo the preview, ignore the release. egui
// aborts the drag on Esc, so `resp.dragged()` is already false in this frame. The key is
// spent on the drag, so the grid's Esc doesn't also drop a pending copy or Format Painter.
if matches!(app.grid.drag, Drag::ResizeCol { .. } | Drag::ResizeRow { .. })
&& input.context.input_mut(|i| {
let pressed = i.key_pressed(egui::Key::Escape);
if pressed {
// With any modifiers, as before: the drag is cancelled and every Esc press spent.
i.events.retain(|e| !matches!(e, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }));
}
pressed
})
{
// Esc during a drag of a chart's values outline drops it: the chart keeps its data, whatever
// modifiers are held (egui ends the drag on any Esc, so the release must not apply it).
if matches!(app.grid.drag, Drag::ChartData { .. }) && spend_escape(&input.context) {
app.grid.drag = Drag::None;
}
if matches!(app.grid.drag, Drag::ResizeCol { .. } | Drag::ResizeRow { .. }) && spend_escape(&input.context) {
// Undo back to where the drag began, but never past it into an earlier edit.
let steps = resize_steps(app);
if steps > 0 {
@@ -711,8 +733,7 @@ fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) {
}
Drag::ResizeCol { col, start, orig, to } => {
let w = nan_safe_size(orig + (p.x - start) / geo.z);
app.toast =
Some((format!("Width: {:.2} ({} pixels)", gridcraft_engine::cmd::format::points_to_chars(w as f64), w.round()), crate::now_ms()));
app.toast = Some((column_width_tip(app.ui.language, w), crate::now_ms()));
// Preview on the dragged column only; the release applies it to the selection. A
// rejected size leaves the last shown preview (and `to`) as it was.
let ok = app.session.run("home.columnWidth", json!({"cols": RangeRef::cols(col, col).a1(), "width": w.round()})).is_ok();
@@ -721,7 +742,7 @@ fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) {
}
Drag::ResizeRow { row, start, orig, to } => {
let h = nan_safe_size(orig + (p.y - start) / geo.z);
app.toast = Some((format!("Height: {:.2} ({} pixels)", h * 0.75, h.round()), crate::now_ms()));
app.toast = Some((row_height_tip(app.ui.language, h), crate::now_ms()));
let ok = app.session.run("home.rowHeight", json!({"rows": format!("{}:{}", row + 1, row + 1), "height": h.round()})).is_ok();
coalesce_resize_undo(app);
app.grid.drag = Drag::ResizeRow { row, start, orig, to: if ok { Some(h) } else { to } };
@@ -743,6 +764,10 @@ fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) {
scroll_by(app, auto);
}
Drag::Object { .. } => drag_object(app, geo, sh, p),
Drag::ChartData { .. } => {
drag_chart_data(app, geo, sh, p);
scroll_by(app, auto);
}
Drag::None => {}
}
}
@@ -823,6 +848,23 @@ fn handle_release(app: &mut SheetApp, input: &InteractionInput<'_>) {
coalesce_resize_undo(app);
}
}
// The release may be the first frame to report the pointer's last position, so the
// block is taken from there. (Esc already dropped a cancelled drag, and so did a
// change to the chart's data; one in the release's own frame is caught here.)
Drag::ChartData { chart, orig, corner, to } => {
let to = if resp.drag_stopped()
&& let Some(p) = pos
{
Some(chart_data_target(geo, sh, orig, corner, p))
} else {
to
};
if let Some(to) = to.filter(|to| *to != orig)
&& chart_still_plots(app, chart, orig)
{
app.run_or_alert("chart.setValuesRange", json!({"chart": chart, "range": to.a1()}));
}
}
Drag::MoveCols { source, before: Some(before) } => {
if let Err(e) = app.run("sheet.moveColumns", json!({"cols": source.a1(), "before": before})) {
app.message = Some(("GridCraft".into(), crate::clean_error(&e)));
@@ -1031,6 +1073,20 @@ fn scroll_by(app: &mut SheetApp, d: egui::Vec2) {
}
}
/// The tip while a column border is dragged to `width` pixels: the width in characters, then in
/// pixels (`Width: 8.43 (64 pixels)`).
pub(crate) fn column_width_tip(lang: crate::i18n::Language, width: f32) -> String {
let chars = format!("{:.2}", gridcraft_engine::cmd::format::points_to_chars(f64::from(width)));
lang.tr_fill("Width: {chars} ({pixels} pixels)", &[("chars", &chars), ("pixels", &width.round().to_string())])
}
/// The tip while a row border is dragged to `height` pixels: the height in points, then in pixels
/// (`Height: 15.00 (20 pixels)`).
pub(crate) fn row_height_tip(lang: crate::i18n::Language, height: f32) -> String {
let points = format!("{:.2}", height * 0.75);
lang.tr_fill("Height: {points} ({pixels} pixels)", &[("points", &points), ("pixels", &height.round().to_string())])
}
fn fill_target(src: RangeRef, pc: CellRef) -> RangeRef {
let below = pc.row as i64 - src.end.row as i64;
let above = src.start.row as i64 - pc.row as i64;
@@ -1188,6 +1244,69 @@ fn drag_object(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) {
}
}
/// Previews the selected chart's values block with the grabbed corner dragged to `p` (logical
/// coordinates); the opposite corner stays. The release gives the chart the block
/// (`chart.setValuesRange`).
fn drag_chart_data(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) {
let Drag::ChartData { chart, orig, corner, .. } = app.grid.drag else { return };
// The chart's data changed under the drag: drop it, as Esc does, rather than preview a
// block the release would put over that change.
if !chart_still_plots(app, chart, orig) {
app.grid.drag = Drag::None;
return;
}
app.grid.drag = Drag::ChartData { chart, orig, corner, to: Some(chart_data_target(geo, sh, orig, corner, p)) };
}
/// Whether chart `chart` on the active sheet still plots the values block `orig` its drag
/// started from. A command run between frames (the control channel, a macro) may have changed
/// or removed it, and the dragged block would then overwrite that change. Read from the session,
/// not the frame's workbook, which predates such a command.
fn chart_still_plots(app: &SheetApp, chart: u32, orig: RangeRef) -> bool {
let Some(wb) = app.session.active().map(|d| &d.wb) else { return false };
let si = wb.active_sheet();
wb.sheet(si)
.and_then(|sh| sh.charts.iter().find(|ch| ch.id == chart))
.and_then(|ch| gridcraft_engine::chart_data::chart_data(wb, si, ch))
.is_some_and(|data| data.sheet == si && data.values == orig)
}
/// The values block `orig` with its `corner` dragged to `p`. Each edge the corner moves snaps
/// to the gridline nearest the pointer, so every row and column changes over at its own middle
/// whatever its height or width, and a release where the press was (on the corner's own
/// gridlines) changes nothing. The block may flip past its fixed edges, as a selection does; a
/// moving edge dropped on its fixed edge keeps one row or column.
fn chart_data_target(geo: &Geo, sh: &Sheet, orig: RangeRef, corner: crate::objects::Handle, p: Pos2) -> RangeRef {
let (sx, sy) = corner.sides();
let (x, y) = (p.x.clamp(geo.cells.left() + 1.0, geo.cells.right() - 1.0), p.y.clamp(geo.cells.top() + 1.0, geo.cells.bottom() - 1.0));
// Gridline `k` is the top (left) edge of row (column) `k`; the last one closes the sheet.
let row = geo.row_at(sh, y);
let row_line = nearest_line(geo.y(sh, row), sh.row_height(row) * geo.z, row, y, MAX_ROWS);
let col = geo.col_at(sh, x);
let col_line = nearest_line(geo.x(sh, col), sh.col_width(col) * geo.z, col, x, MAX_COLS);
let (r0, r1) = between_lines(if sy < 0 { orig.end.row.saturating_add(1) } else { orig.start.row }, row_line, sy);
let (c0, c1) = between_lines(if sx < 0 { orig.end.col.saturating_add(1) } else { orig.start.col }, col_line, sx);
RangeRef::new(CellRef::new(r0, c0), CellRef::new(r1, c1))
}
/// The gridline nearest `v` for line `index`, which starts at `start` and is `size` long: its
/// own start, or the next line's past its middle (never past `last`).
fn nearest_line(start: f32, size: f32, index: u32, v: f32, last: u32) -> u32 {
if v - start < size / 2.0 { index } else { index.saturating_add(1).min(last) }
}
/// The rows (columns) from gridline `fixed` to gridline `moving`. A moving edge on the fixed one
/// keeps one line on its own side: after it for a bottom or right edge (`dir` > 0), before it
/// for a top or left edge.
fn between_lines(fixed: u32, moving: u32, dir: i8) -> (u32, u32) {
let moving = match (moving == fixed, dir > 0) {
(false, _) => moving,
(true, true) => fixed.saturating_add(1),
(true, false) => fixed.saturating_sub(1),
};
(fixed.min(moving), fixed.max(moving).saturating_sub(1))
}
/// A click on a hyperlink. References select; web and e-mail addresses ask first (the dialog's
/// OK calls `Session::open_confirmed_link`, since `link.open` refuses them for programmatic
/// callers, #2181); every other kind is refused with a message. The decision is the engine's
@@ -1240,6 +1359,28 @@ pub fn point_move(app: &mut SheetApp, ed: &mut EditState, dr: i64, dc: i64, exte
mod resize_tests {
use super::*;
#[test]
fn a_chart_data_edge_snaps_to_the_nearest_gridline_of_any_size() {
// Row 5 starts at 100 and is 20 tall: before its middle the line is its own, past it the next.
assert_eq!(nearest_line(100.0, 20.0, 5, 109.0, MAX_ROWS), 5);
assert_eq!(nearest_line(100.0, 20.0, 5, 111.0, MAX_ROWS), 6);
// A 100-tall row changes over at 50 into it, not at the grabbed row's middle.
assert_eq!(nearest_line(100.0, 100.0, 5, 149.0, MAX_ROWS), 5);
assert_eq!(nearest_line(100.0, 100.0, 5, 151.0, MAX_ROWS), 6);
assert_eq!(nearest_line(0.0, 20.0, MAX_ROWS - 1, 19.0, MAX_ROWS), MAX_ROWS);
// A1:A5 (lines 0 and 5) by its bottom edge: on line 5 it stays, on 8 it grows, on 2 it shrinks.
assert_eq!(between_lines(0, 5, 1), (0, 4));
assert_eq!(between_lines(0, 8, 1), (0, 7));
assert_eq!(between_lines(0, 2, 1), (0, 1));
// Dropped on its fixed edge it keeps one row; past it the block flips.
assert_eq!(between_lines(4, 4, 1), (4, 4));
assert_eq!(between_lines(4, 2, 1), (2, 3));
// By its top edge (fixed line 5, below A5).
assert_eq!(between_lines(5, 0, -1), (0, 4));
assert_eq!(between_lines(5, 5, -1), (4, 4));
assert_eq!(between_lines(5, 7, -1), (5, 6));
}
#[test]
fn resize_targets_follow_the_selection_only_when_the_dragged_line_is_in_it() {
let sel = [RangeRef::cols(0, 0), RangeRef::cols(2, 3)];
@@ -1262,6 +1403,17 @@ mod resize_tests {
mod tests {
use super::*;
#[test]
fn resize_tips_follow_the_interface_language() {
use crate::i18n::Language;
assert_eq!(column_width_tip(Language::En, 64.0), "Width: 8.43 (64 pixels)");
assert_eq!(row_height_tip(Language::En, 20.0), "Height: 15.00 (20 pixels)");
let de = Language::De;
assert_eq!(column_width_tip(de, 64.0), de.tr("Width: {chars} ({pixels} pixels)").replace("{chars}", "8.43").replace("{pixels}", "64"));
assert_eq!(row_height_tip(de, 20.0), de.tr("Height: {points} ({pixels} pixels)").replace("{points}", "15.00").replace("{pixels}", "20"));
assert!(!column_width_tip(de, 64.0).starts_with("Width"));
}
#[test]
fn the_pen_preview_is_the_ink_the_stroke_commits() {
// #1786: the preview was always blue at 2 pt, whatever the pen.
+97 -9
View File
@@ -2,8 +2,10 @@ use super::geo::Geo;
use super::menus::is_checkbox;
use super::{CellRef, Drag, Sheet, SheetApp, json};
/// Grid keyboard handling when no text field has focus.
pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: &Geo, sh: &Sheet) {
/// Whether something other than the grid owns the keyboard this frame: an editor, a dialog, a
/// message, a menu or another focused widget. Kept out of [`keyboard`] to hold its complexity
/// within the workspace limit.
fn keyboard_elsewhere(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response) -> bool {
// Focus left on an editor that no longer exists goes back to the grid.
let stale = [egui::Id::unique("gridcraft.cell_editor"), egui::Id::unique("gridcraft.formula_bar"), crate::text_box::editor_id()];
let editing = app.editor.is_some() || app.text_box_editor.is_some();
@@ -14,7 +16,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
// An open filter menu owns the keyboard even when a click inside it left focus on nothing (#1516).
// So do the fill menu (its Esc closes it, not the copy) and the right-drag that opens it (an
// arrow key would move the selection the menu fills from), and a macro's question.
if editing
editing
|| app.dialog.is_some()
|| other_focus
|| app.message.is_some()
@@ -22,7 +24,11 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|| app.grid.fill_menu.is_some()
|| matches!(app.grid.drag, Drag::Fill { menu: true, .. })
|| app.macros.question.is_some()
{
}
/// Grid keyboard handling when no text field has focus.
pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: &Geo, sh: &Sheet) {
if keyboard_elsewhere(app, ctx, resp) {
return;
}
if ctx.memory(|m| m.focused()).is_none() {
@@ -32,6 +38,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
ctx.memory_mut(|m| {
m.set_focus_lock_filter(resp.id, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true })
});
request_grid_ime(app, ctx, resp, geo, sh);
let events = grid_events(app, ctx, sh);
// A shortcut key that also types a character (Shift+Space sends Text(" ")) must not start an edit.
let shortcut_pressed = events.iter().any(|e| {
@@ -43,6 +50,11 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
// a shortcut ran, that text must not start an edit over what it just did.
let mut shortcut_ran = false;
for ev in events {
// IME events are handled outside the match to keep this loop's complexity down. Any
// non-commit IME event (preedit, delete-surrounding) falls through to `_ => {}` below.
if handle_ime_commit(app, &ev, shortcut_pressed, shortcut_ran) {
return;
}
match ev {
egui::Event::Copy => {
app.copy_to_clipboard(ctx, "edit.copy");
@@ -58,11 +70,13 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
// insert text at, so a middle click on a cell is deliberately not a paste.
egui::Event::MiddleClickPaste { .. } => {}
egui::Event::Text(_) if shortcut_pressed || shortcut_ran => {}
// A space on a checkbox cell toggles it (the `Key::Space` arm below). The same key
// press also arrives as text, and typing text starts editing the cell -- so the cell
// toggled *and* opened an editor holding a space, which Enter then committed over the
// checkbox (#1951).
egui::Event::Text(text) if text == " " && is_checkbox(sh, app) => {}
egui::Event::Text(text) if text.chars().all(|c| !c.is_control()) && !text.is_empty() => {
app.begin_edit(Some(text), false);
if let Some(ed) = app.editor.as_mut() {
ed.caret = ed.text.chars().count();
}
seed_editor(app, text);
return;
}
egui::Event::Key { key, physical_key, pressed: true, modifiers: m, .. } => {
@@ -146,7 +160,9 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
// Ctrl+Shift+letter (⌘⇧letter) runs the macro with that shortcut, unless GridCraft uses it.
_ if cmd && shift && !m.alt && crate::macro_ui::run_shortcut(app, key) => {}
_ if cmd && !crate::keymap::altgr_text(ctx, m, ctx.os() == egui::os::OperatingSystem::Mac) => {
crate::ribbon::shortcut(app, key, m)
// The same key the English table reads: Ctrl+Shift+, typing `;` is Ctrl+;.
let (key, shift) = crate::keymap::us_key(key, physical_key, shift).unwrap_or((key, shift));
crate::ribbon::shortcut(app, key, egui::Modifiers { shift, ..m });
}
_ => {}
}
@@ -156,6 +172,78 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
}
}
/// Open the in-cell editor with typed or committed text and put the caret after it.
fn seed_editor(app: &mut SheetApp, text: String) {
app.begin_edit(Some(text), false);
if let Some(ed) = app.editor.as_mut() {
ed.caret = ed.text.chars().count();
}
}
/// Seed the editor from a finished composition, if `ev` is one.
///
/// Only `ImeEvent::Commit` is finished text; a preedit is the input method's in-progress
/// spelling and must not seed the editor. `Event::Ime` and `Event::Text` are mutually
/// exclusive for one keystroke, so accepting a commit cannot double-insert a character.
/// Returns whether the caller should stop handling this frame's events.
fn handle_ime_commit(app: &mut SheetApp, ev: &egui::Event, shortcut_pressed: bool, shortcut_ran: bool) -> bool {
let egui::Event::Ime(egui::ImeEvent::Commit(text)) = ev else { return false };
if shortcut_pressed || shortcut_ran || text.is_empty() {
return false;
}
seed_editor(app, text.clone());
true
}
/// Ask the OS to route keystrokes through the input method while the grid owns keyboard input.
///
/// egui enables IME only for a widget that publishes `PlatformOutput::ime` in that frame. The
/// in-cell `TextEdit` opens *after* the grid has consumed the first keystroke, so without this
/// the first key of a CJK composition is delivered as raw `Event::Text` and lands in the cell
/// (Wubi `xta` writes `x` and the input method only ever sees `ta`). The request must be
/// published on every focused frame, not in response to a key: winit applies it at the end of
/// the frame, so a key arriving while IME is still off cannot be recovered.
///
/// `PlatformOutput` is rebuilt every frame, so returning early (an editor, a dialog or another
/// widget taking focus) simply leaves `ime` as `None` and the input method turns off.
fn request_grid_ime(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: &Geo, sh: &Sheet) {
if !ctx.memory(|m| m.owns_ime_events(resp.id)) {
return;
}
let Some(d) = app.session.active() else { return };
let active = d.selection.active;
let merged = sh.merge_at(active);
// `begin_edit` refuses a locked cell on a protected sheet. Publishing an IME request for
// one would let the user compose text that is then discarded, so skip it up front, using
// the same merged-cell anchor and protection check as `SheetApp::begin_edit`.
let anchor = merged.map(|m| m.start).unwrap_or(active);
if app.session.locked_cell_message(d.wb.active_sheet(), anchor).is_some() {
return;
}
// `cell_rect`/`range_rect` are logical coordinates, but `IMEOutput` needs screen ones.
// On a right-to-left sheet the grid is mirrored, so publishing the logical rect puts the
// candidate window on the opposite side. After mirroring, `rect.min` is the screen-side
// start of the cell in both layouts, which is where the caret belongs.
let rect = match merged {
Some(m) => geo.mirror_rect(geo.range_rect(sh, m)),
None => geo.mirror_rect(geo.cell_rect(sh, active)),
};
let cursor_rect = egui::Rect::from_min_size(rect.min, egui::vec2(1.0, rect.height()));
// egui 0.37 identifies an IME context by (owner, generation). The generation must change
// when this owner gains focus and stay stable for ordinary text and selection updates.
let gained_focus = resp.gained_focus();
let generation = ctx.data_mut(|data| {
let g: &mut u64 = data.get_temp_mut_or_default(egui::Id::unique("gridcraft.grid_ime_generation"));
if gained_focus || *g == 0 {
*g = g.wrapping_add(1);
}
*g
});
ctx.output_mut(|o| {
o.ime = Some(egui::output::IMEOutput::new(resp.id, generation, egui::IMEPurpose::Normal, rect, cursor_rect));
});
}
/// This frame's input events, without those the focused form control took.
fn grid_events(app: &mut SheetApp, ctx: &egui::Context, sh: &Sheet) -> Vec<egui::Event> {
let events = ctx.input(|i| i.events.clone());
+1 -1
View File
@@ -53,7 +53,7 @@ pub fn show(app: &mut SheetApp, ui: &mut egui::Ui) {
} else {
Rect::from_min_max(available.min, pos2(available.right() - bar, available.bottom()))
};
let resp = ui.allocate_rect(rect, Sense::click_and_drag());
let resp = ui.allocate_rect(rect, crate::dialogs::grid_sense(app));
app.grid.rect = Some(rect);
let Some(d) = app.session.active() else { return };
let wb: Arc<Workbook> = d.wb.clone();
+177
View File
@@ -21,6 +21,7 @@ mod ko;
mod nl;
mod pl;
mod pt;
mod pt_functions;
mod ro;
mod ru;
mod sr;
@@ -222,6 +223,11 @@ impl Language {
}
}
/// Translates `template`, then fills in its `{name}` placeholders (see [`fill`]).
pub fn tr_fill(self, template: &str, values: &[(&str, &str)]) -> String {
fill(self.tr(template), values)
}
pub(crate) fn tr_error(self, message: &str) -> String {
let message = if message.starts_with("command `") { crate::clean_error(message) } else { message.to_owned() };
@@ -247,11 +253,82 @@ impl Language {
fn function_help(self) -> Option<(HelpTable, HelpTable)> {
match self {
Self::Es => Some((es_functions::DESCRIPTIONS, es_functions::ARGUMENTS)),
Self::PtBr => Some((pt_functions::DESCRIPTIONS, pt_functions::ARGUMENTS)),
_ => None,
}
}
}
/// Fills in the `{name}` placeholders of a translated template in one pass, so a value that itself
/// holds `{…}` (a macro or sheet name) is shown as it is and never filled again. A placeholder
/// without a value stays as written.
pub fn fill(template: &str, values: &[(&str, &str)]) -> String {
let mut out = String::with_capacity(template.len());
let mut rest = template;
while let Some((before, after)) = rest.split_once('{') {
out.push_str(before);
let value = after.split_once('}').and_then(|(name, tail)| values.iter().find(|(key, _)| *key == name).map(|(_, value)| (*value, tail)));
match value {
Some((value, tail)) => {
out.push_str(value);
rest = tail;
}
None => {
out.push('{');
rest = after;
}
}
}
out.push_str(rest);
out
}
/// The values that [`fill`] puts into `template` to give `text`, or `None` when `text` has
/// another shape. A `{name}` of lowercase letters and `_` is a placeholder; any other `{` is
/// text. Each placeholder takes the text up to the first copy of the literal after it (the last
/// one takes the rest), and a match counts only when filling the values back in gives `text`.
pub fn unfill<'a>(template: &'a str, text: &'a str) -> Option<Vec<(&'a str, &'a str)>> {
enum Part<'a> {
Text(String),
Value(&'a str),
}
let mut parts = Vec::new();
let mut literal = String::new();
let mut rest = template;
while let Some((before, after)) = rest.split_once('{') {
literal.push_str(before);
match after.split_once('}').filter(|(name, _)| !name.is_empty() && name.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')) {
Some((name, tail)) => {
parts.push(Part::Text(std::mem::take(&mut literal)));
parts.push(Part::Value(name));
rest = tail;
}
None => {
literal.push('{');
rest = after;
}
}
}
literal.push_str(rest);
parts.push(Part::Text(literal));
// `parts` alternates text and placeholder, starting and ending with (maybe empty) text.
let mut values = Vec::new();
let mut rest = text;
for (i, part) in parts.iter().enumerate() {
match part {
Part::Text(literal) => rest = rest.strip_prefix(literal.as_str())?,
Part::Value(name) => {
let Some(Part::Text(next)) = parts.get(i + 1) else { return None };
let len = if i + 2 == parts.len() { rest.strip_suffix(next.as_str())?.len() } else { rest.find(next.as_str())? };
values.push((*name, &rest[..len]));
rest = &rest[len..];
}
}
}
(rest.is_empty() && fill(template, &values) == text).then_some(values)
}
/// English text and its translation, sorted by the English.
type HelpTable = &'static [(&'static str, &'static str)];
@@ -418,6 +495,106 @@ mod tests {
}
}
/// The Custom Sort dialog's own strings have a row in every catalog (no silent English
/// fallback), keep the `{letters}` placeholder, and read as plain English in English.
#[test]
fn custom_sort_strings_are_translated_in_every_catalog() {
let keys = [
"Sort by",
"Then by",
"My list has headers",
"Cell Values",
"Cell Color",
"Font Color",
"A to Z",
"Z to A",
"Add Level",
"Delete Level",
"Copy Level",
"Move Up",
"Move Down",
"Order",
"Sort On",
"Sort|Column",
"Column {letters}",
"Smallest to Largest",
"Largest to Smallest",
"Close the Sort dialog before switching or changing worksheets.",
"Return to the original worksheet to sort, or cancel.",
];
for key in keys {
let english = key.rsplit_once('|').map_or(key, |(_, label)| label);
assert_eq!(Language::En.tr(key), english);
for language in Language::ALL.into_iter().filter(|l| *l != Language::En) {
let code = language.code();
let shown = language.translated(key).unwrap_or_else(|| panic!("{code}: no row for {key:?}"));
assert!(!shown.trim().is_empty() && !shown.contains('|'), "{code}: bad translation of {key:?}: {shown:?}");
assert_eq!(shown.contains("{letters}"), key.contains("{letters}"), "{code}: placeholder of {key:?}: {shown:?}");
}
}
}
#[test]
fn fill_puts_each_value_in_once() {
// A value holding a placeholder (a macro named `{steps}`) is shown as it is.
assert_eq!(fill("Ran macro “{name}” ({steps} steps)", &[("name", "{steps}"), ("steps", "3")]), "Ran macro “{steps}” (3 steps)");
assert_eq!(fill("{a} and {b}, {a}", &[("a", "1")]), "1 and {b}, 1", "a placeholder without a value stays");
assert_eq!(fill("{ unclosed", &[("unclosed", "x")]), "{ unclosed");
assert_eq!(fill("50% {}", &[]), "50% {}");
assert_eq!(Language::En.tr_fill("Sheets: {sheets}", &[("sheets", "Sheet1, Sheet2")]), "Sheets: Sheet1, Sheet2");
}
#[test]
fn unfill_reads_back_what_fill_put_in() {
assert_eq!(unfill("Expected '{expected}', got '{got}'", "Expected '}', got 'EOF'"), Some(vec![("expected", "}"), ("got", "EOF")]));
assert_eq!(
unfill("Mismatch: \\begin{{begin}} matched by \\end{{end}}", "Mismatch: \\begin{a} matched by \\end{b}"),
Some(vec![("begin", "a"), ("end", "b")])
);
assert_eq!(unfill("{command} valid only here", "\\hline valid only here"), Some(vec![("command", "\\hline")]));
assert_eq!(unfill("Undefined control sequence: {name}", "Undefined control sequence: \\foo"), Some(vec![("name", "\\foo")]));
assert_eq!(unfill("Double superscript", "Double superscript"), Some(vec![]));
// The last placeholder runs to the closing literal, so a longer message is read whole.
assert_eq!(unfill("Invalid type '{type}'", "Invalid type 'a' after 'b'"), Some(vec![("type", "a' after 'b")]));
assert_eq!(unfill("Expected '{expected}', got '{got}'", "Expected } here"), None);
assert_eq!(unfill("Expected '{expected}'", "Expected 'x' later"), None);
assert_eq!(unfill("Mismatched {command}", "Mismatch: x"), None);
}
/// The templates the UI translates first and fills in after (status bar, toasts, dialog
/// notes and titles) keep their placeholders in every catalog, so no value goes missing.
#[test]
fn filled_in_templates_keep_their_placeholders() {
let placeholders = |s: &str| {
let mut names = s.split('{').skip(1).filter_map(|rest| rest.split_once('}').map(|(name, _)| name.to_string())).collect::<Vec<_>>();
names.sort();
names
};
for template in [
"Circular References: {cell}",
"Goal Seeking found a solution: {value}",
"Width: {chars} ({pixels} pixels)",
"Height: {points} ({pixels} pixels)",
"Picture: {alt}",
"Sheets: {sheets}",
"Hidden: {sheets}",
"Format Control: {name}",
"Error at character {position}: {message}",
"Saved macro “{name}” ({steps} step)",
"Saved macro “{name}” ({steps} steps)",
"without {key}: another macro took it while recording",
"Macro “{name}” stopped: {message}",
"Ran macro “{name}” ({steps} step)",
"Ran macro “{name}” ({steps} steps)",
] {
for language in Language::ALL {
let text = language.tr(template);
assert_eq!(placeholders(text), placeholders(template), "{}: {template:?} => {text:?}", language.code());
assert!(!text.contains('\n'), "{}: {template:?} => {text:?}", language.code());
}
}
}
#[test]
fn translations_never_show_the_context_prefix() {
// `tr` returns a found translation as it is, so a catalog that keeps `context|` in its
+128
View File
@@ -600,6 +600,134 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "Zobrazit",
"Collapse dialog" => "Sbalit dialogové okno",
"Expand dialog" => "Rozbalit dialogové okno",
"My list has headers" => "Data obsahují záhlaví",
"Sort by" => "Seřadit podle",
"Then by" => "Potom podle",
"Cell Values" => "Hodnoty buněk",
"Cell Color" => "Barva buňky",
"A to Z" => "Od A do Z",
"Z to A" => "Od Z do A",
"Add Level" => "Přidat úroveň",
"Delete Level" => "Odstranit úroveň",
"Copy Level" => "Kopírovat úroveň",
"Move Up" => "Posunout nahoru",
"Move Down" => "Posunout dolů",
"Order" => "Pořadí",
"Sort On" => "Seřadit podle",
"Sort|Column" => "Sloupec",
"Column {letters}" => "Sloupec {letters}",
"Smallest to Largest" => "Od nejmenšího po největší",
"Largest to Smallest" => "Od největšího po nejmenší",
"Close the Sort dialog before switching or changing worksheets." => "Před přepnutím nebo změnou listů zavřete dialogové okno Seřadit.",
"Return to the original worksheet to sort, or cancel." => "Chcete-li řadit, vraťte se na původní list, nebo akci zrušte.",
"Numerical Count" => "Počet čísel",
"Minimum" => "Minimum",
"Maximum" => "Maximum",
"Circular References: {cell}" => "Cyklické odkazy: {cell}",
"Width: {chars} ({pixels} pixels)" => "Šířka: {chars} (pixelů: {pixels})",
"Height: {points} ({pixels} pixels)" => "Výška: {points} (pixelů: {pixels})",
"Picture in cell" => "Obrázek v buňce",
"Picture: {alt}" => "Obrázek: {alt}",
"Format Control: {name}" => "Formát ovládacího prvku: {name}",
"Error at character {position}: {message}" => "Chyba na znaku {position}: {message}",
"Macro definitions are not supported in equations." => "Definice maker nejsou v rovnicích podporovány.",
"A % can't be combined with a link in an equation." => "Znak % nelze v rovnici kombinovat s odkazem.",
"Equations can nest at most 32 levels deep." => "Rovnice lze vnořit nejvýše do 32 úrovní.",
"An equation can be at most 4096 bytes long." => "Rovnice může mít nejvýše 4096 bajtů.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"Rovnice může mít nejvýše 2500 buněk matice (řádky krát nejširší řádek)."
}
"This equation is too large to draw." => "Tato rovnice je příliš velká na vykreslení.",
"This equation could not be laid out." => "Tuto rovnici nelze vysázet.",
"Saved macro “{name}” ({steps} step)" => "Makro „{name}“ uloženo ({steps} krok)",
"Saved macro “{name}” ({steps} steps)" => "Makro „{name}“ uloženo (počet kroků: {steps})",
"without {key}: another macro took it while recording" => "bez {key}: během záznamu ji převzalo jiné makro",
"Recording stopped" => "Záznam zastaven",
"Macro “{name}” stopped: {message}" => "Makro „{name}“ se zastavilo: {message}",
"Ran macro “{name}” ({steps} step)" => "Makro „{name}“ spuštěno ({steps} krok)",
"Ran macro “{name}” ({steps} steps)" => "Makro „{name}“ spuštěno (počet kroků: {steps})",
"Average" => "Průměr",
"Count" => "Počet",
"Sum" => "Součet",
"Goal Seeking found a solution: {value}" => "Hledání řešení našlo výsledek: {value}",
"Sheets: {sheets}" => "Listy: {sheets}",
"Hidden: {sheets}" => "Skryté: {sheets}",
"Double superscript" => "Dvojitý horní index",
"Double subscript" => "Dvojitý dolní index",
"Extra }" => "Nadbytečná }",
"Unexpected end of input in a macro argument" => "Neočekávaný konec vstupu v argumentu makra",
"Expected \\right after \\left" => "Po \\left se očekává \\right",
"\\middle must be within \\left and \\right" => "\\middle musí být mezi \\left a \\right",
"Invalid environment name" => "Neplatný název prostředí",
"Expected \\end after environment body" => "Po obsahu prostředí se očekává \\end",
"Expected URL" => "Očekává se adresa URL",
"\\tag requires an argument" => "\\tag vyžaduje argument",
"only one infix operator per group" => "Ve skupině smí být jen jeden infixový operátor",
"Expected color token" => "Očekává se barva",
"Expected size for \\raisebox" => "Pro \\raisebox se očekává velikost",
"Expected size for \\rule width" => "Pro šířku \\rule se očekává velikost",
"Expected size for \\rule height" => "Pro výšku \\rule se očekává velikost",
"Cannot use both \\tag and \\nonumber in the same row" => "\\tag a \\nonumber nelze použít ve stejném řádku",
"Multiple \\tag in a row" => "Více \\tag v jednom řádku",
"\\tag must appear at the end of the row after the equation body" => "\\tag musí být na konci řádku za obsahem rovnice",
"Multiple \\nonumber in a row" => "Více \\nonumber v jednom řádku",
"\\nonumber must appear at the end of the row" => "\\nonumber musí být na konci řádku",
"Too many tab characters: &" => "Příliš mnoho tabulačních znaků: &",
"Invalid column alignment for array" => "Neplatné zarovnání sloupců pro array",
"Expected column alignment character" => "Očekává se znak zarovnání sloupce",
"Expected l or c or r" => "Očekává se l, c nebo r",
"Expected ]" => "Očekává se ]",
"Unexpected end of CD row after @" => "Neočekávaný konec řádku CD po @",
"Invalid column alignment for subarray" => "Neplatné zarovnání sloupců pro subarray",
"{subarray} can contain only one column" => "{subarray} může obsahovat jen jeden sloupec",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"prooftree obsahuje \\LeftLabel nebo \\RightLabel bez následujícího odvozovacího příkazu"
}
"Recursion limit exceeded" => "Překročen limit rekurze",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"Příliš mnoho rozvinutí maker: nekonečná smyčka nebo příliš nízké nastavení maxExpand"
}
"Expected raw style for \\htmlStyle" => "Pro \\htmlStyle se očekává surový styl",
"\\verb assertion failed" => "Kontrola \\verb selhala",
"Undefined control sequence: {name}" => "Nedefinovaná řídicí sekvence: {name}",
"Expected '{expected}', got '{got}'" => "Očekává se '{expected}', nalezeno '{got}'",
"Expected group after '{symbol}'" => "Po '{symbol}' se očekává skupina",
"Expected delimiter as argument to '{function}'" => "Jako argument '{function}' se očekává oddělovač",
"Expected group as argument to '{function}'" => "Jako argument '{function}' se očekává skupina",
"Got function '{function}' with no arguments as superscript" => "Funkce '{function}' bez argumentů použita jako horní index",
"Got function '{function}' with no arguments as subscript" => "Funkce '{function}' bez argumentů použita jako dolní index",
"Got function '{function}' with no arguments as argument to '{parent}'" => {
"Funkce '{function}' bez argumentů použita jako argument '{parent}'"
}
"Got function '{function}' with no arguments as \\tag" => "Funkce '{function}' bez argumentů použita jako \\tag",
"Can't use function '{function}' in text mode" => "Funkci '{function}' nelze použít v textovém režimu",
"Can't use function '{function}' in math mode" => "Funkci '{function}' nelze použít v matematickém režimu",
"Invalid color: '{color}'" => "Neplatná barva: '{color}'",
"Invalid size: '{size}'" => "Neplatná velikost: '{size}'",
"Invalid unit: '{unit}'" => "Neplatná jednotka: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "Neplatný oddělovač '{delimiter}' po '{function}'",
"Invalid delimiter type '{type}' after '{function}'" => "Neplatný typ oddělovače '{type}' po '{function}'",
"Invalid delimiter type '{type}'" => "Neplatný typ oddělovače '{type}'",
"No such environment: {name}" => "Neznámé prostředí: {name}",
"Expected argument to \\begin{{name}}" => "Pro \\begin{{name}} se očekává argument",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "Neshoda: \\begin{{begin}} uzavřeno pomocí \\end{{end}}",
"{command} valid only within array environment" => "{command} je platné jen uvnitř prostředí array",
"Mismatched {command}" => "{command} bez protějšku",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "Očekává se &, \\\\, \\cr nebo \\end, nalezeno '{got}'",
"Unknown column alignment: {alignment}" => "Neznámé zarovnání sloupce: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "Příliš mnoho vzorců v řádku: očekáváno {expected}, nalezeno {got}",
"Unknown CD directive: @{directive}" => "Neznámá direktiva CD: @{directive}",
"Expected argument for {command}" => "Pro {command} se očekává argument",
"{command} needs {count} premise(s), but only {available} available" => {
"{command} potřebuje {count} předpoklad(ů), ale k dispozici je jen {available}"
}
"{command} valid only as a supported bussproofs command within prooftree" => {
"{command} je v prooftree platné jen jako podporovaný příkaz bussproofs"
}
"prooftree ended with {count} proof stack item(s), expected 1" => "prooftree skončilo s {count} položkami v zásobníku důkazu, očekávána 1",
"\\@char has non-numeric argument {argument}" => "\\@char má nečíselný argument {argument}",
"\\@char with invalid code point {code}" => "\\@char s neplatným kódovým bodem {code}",
"Invalid environment name character: {character}" => "Neplatný znak v názvu prostředí: {character}",
_ => return None,
})
}
+130
View File
@@ -520,6 +520,136 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "Anzeigen",
"Collapse dialog" => "Dialogfeld reduzieren",
"Expand dialog" => "Dialogfeld erweitern",
"My list has headers" => "Daten haben Überschriften",
"Sort by" => "Sortieren nach",
"Then by" => "Anschließend nach",
"Cell Values" => "Zellenwerte",
"Cell Color" => "Zellenfarbe",
"A to Z" => "A bis Z",
"Z to A" => "Z bis A",
"Add Level" => "Ebene hinzufügen",
"Delete Level" => "Ebene löschen",
"Copy Level" => "Ebene kopieren",
"Move Up" => "Nach oben",
"Move Down" => "Nach unten",
"Order" => "Reihenfolge",
"Sort On" => "Sortieren nach",
"Sort|Column" => "Spalte",
"Column {letters}" => "Spalte {letters}",
"Smallest to Largest" => "Vom Kleinsten zum Größten",
"Largest to Smallest" => "Vom Größten zum Kleinsten",
"Close the Sort dialog before switching or changing worksheets." => {
"Schließen Sie das Dialogfeld „Sortieren“, bevor Sie das Blatt wechseln oder Blätter ändern."
}
"Return to the original worksheet to sort, or cancel." => "Kehren Sie zum ursprünglichen Blatt zurück, um zu sortieren, oder brechen Sie ab.",
"Numerical Count" => "Numerische Zählung",
"Minimum" => "Minimum",
"Maximum" => "Maximum",
"Circular References: {cell}" => "Zirkelbezüge: {cell}",
"Width: {chars} ({pixels} pixels)" => "Breite: {chars} ({pixels} Pixel)",
"Height: {points} ({pixels} pixels)" => "Höhe: {points} ({pixels} Pixel)",
"Picture in cell" => "Bild in Zelle",
"Picture: {alt}" => "Bild: {alt}",
"Format Control: {name}" => "Steuerelement formatieren: {name}",
"Error at character {position}: {message}" => "Fehler bei Zeichen {position}: {message}",
"Macro definitions are not supported in equations." => "Makrodefinitionen werden in Formeln nicht unterstützt.",
"A % can't be combined with a link in an equation." => "Ein % kann in einer Formel nicht mit einem Link kombiniert werden.",
"Equations can nest at most 32 levels deep." => "Formeln können höchstens 32 Ebenen tief verschachtelt werden.",
"An equation can be at most 4096 bytes long." => "Eine Formel darf höchstens 4096 Byte lang sein.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"Eine Formel darf höchstens 2500 Matrixzellen haben (Zeilen mal breiteste Zeile)."
}
"This equation is too large to draw." => "Diese Formel ist zu groß zum Zeichnen.",
"This equation could not be laid out." => "Diese Formel konnte nicht gesetzt werden.",
"Saved macro “{name}” ({steps} step)" => "Makro „{name}“ gespeichert ({steps} Schritt)",
"Saved macro “{name}” ({steps} steps)" => "Makro „{name}“ gespeichert ({steps} Schritte)",
"without {key}: another macro took it while recording" => {
"ohne {key}: ein anderes Makro hat die Tastenkombination während der Aufzeichnung übernommen"
}
"Recording stopped" => "Aufzeichnung beendet",
"Macro “{name}” stopped: {message}" => "Makro „{name}“ angehalten: {message}",
"Ran macro “{name}” ({steps} step)" => "Makro „{name}“ ausgeführt ({steps} Schritt)",
"Ran macro “{name}” ({steps} steps)" => "Makro „{name}“ ausgeführt ({steps} Schritte)",
"Average" => "Mittelwert",
"Count" => "Anzahl",
"Sum" => "Summe",
"Goal Seeking found a solution: {value}" => "Zielwertsuche hat eine Lösung gefunden: {value}",
"Sheets: {sheets}" => "Blätter: {sheets}",
"Hidden: {sheets}" => "Ausgeblendet: {sheets}",
"Double superscript" => "Doppelter Exponent",
"Double subscript" => "Doppelter Index",
"Extra }" => "Überzählige }",
"Unexpected end of input in a macro argument" => "Unerwartetes Ende der Eingabe in einem Makroargument",
"Expected \\right after \\left" => "\\right nach \\left erwartet",
"\\middle must be within \\left and \\right" => "\\middle muss zwischen \\left und \\right stehen",
"Invalid environment name" => "Ungültiger Umgebungsname",
"Expected \\end after environment body" => "\\end nach dem Umgebungsinhalt erwartet",
"Expected URL" => "URL erwartet",
"\\tag requires an argument" => "\\tag benötigt ein Argument",
"only one infix operator per group" => "Nur ein Infix-Operator pro Gruppe",
"Expected color token" => "Farbangabe erwartet",
"Expected size for \\raisebox" => "Größe für \\raisebox erwartet",
"Expected size for \\rule width" => "Größe für die Breite von \\rule erwartet",
"Expected size for \\rule height" => "Größe für die Höhe von \\rule erwartet",
"Cannot use both \\tag and \\nonumber in the same row" => "\\tag und \\nonumber können nicht in derselben Zeile stehen",
"Multiple \\tag in a row" => "Mehrere \\tag in einer Zeile",
"\\tag must appear at the end of the row after the equation body" => "\\tag muss am Ende der Zeile nach dem Formelinhalt stehen",
"Multiple \\nonumber in a row" => "Mehrere \\nonumber in einer Zeile",
"\\nonumber must appear at the end of the row" => "\\nonumber muss am Ende der Zeile stehen",
"Too many tab characters: &" => "Zu viele Tabulatorzeichen: &",
"Invalid column alignment for array" => "Ungültige Spaltenausrichtung für array",
"Expected column alignment character" => "Zeichen für die Spaltenausrichtung erwartet",
"Expected l or c or r" => "l, c oder r erwartet",
"Expected ]" => "] erwartet",
"Unexpected end of CD row after @" => "Unerwartetes Ende der CD-Zeile nach @",
"Invalid column alignment for subarray" => "Ungültige Spaltenausrichtung für subarray",
"{subarray} can contain only one column" => "{subarray} darf nur eine Spalte enthalten",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"prooftree enthält \\LeftLabel oder \\RightLabel ohne folgenden Schlussbefehl"
}
"Recursion limit exceeded" => "Rekursionsgrenze überschritten",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"Zu viele Makroexpansionen: Endlosschleife oder maxExpand-Einstellung zu niedrig"
}
"Expected raw style for \\htmlStyle" => "Rohstil für \\htmlStyle erwartet",
"\\verb assertion failed" => "Prüfung für \\verb fehlgeschlagen",
"Undefined control sequence: {name}" => "Unbekannte Steuersequenz: {name}",
"Expected '{expected}', got '{got}'" => "'{expected}' erwartet, '{got}' gefunden",
"Expected group after '{symbol}'" => "Gruppe nach '{symbol}' erwartet",
"Expected delimiter as argument to '{function}'" => "Begrenzer als Argument für '{function}' erwartet",
"Expected group as argument to '{function}'" => "Gruppe als Argument für '{function}' erwartet",
"Got function '{function}' with no arguments as superscript" => "Funktion '{function}' ohne Argumente als Exponent",
"Got function '{function}' with no arguments as subscript" => "Funktion '{function}' ohne Argumente als Index",
"Got function '{function}' with no arguments as argument to '{parent}'" => "Funktion '{function}' ohne Argumente als Argument für '{parent}'",
"Got function '{function}' with no arguments as \\tag" => "Funktion '{function}' ohne Argumente als \\tag",
"Can't use function '{function}' in text mode" => "Funktion '{function}' ist im Textmodus nicht verwendbar",
"Can't use function '{function}' in math mode" => "Funktion '{function}' ist im Mathematikmodus nicht verwendbar",
"Invalid color: '{color}'" => "Ungültige Farbe: '{color}'",
"Invalid size: '{size}'" => "Ungültige Größe: '{size}'",
"Invalid unit: '{unit}'" => "Ungültige Einheit: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "Ungültiger Begrenzer '{delimiter}' nach '{function}'",
"Invalid delimiter type '{type}' after '{function}'" => "Ungültiger Begrenzertyp '{type}' nach '{function}'",
"Invalid delimiter type '{type}'" => "Ungültiger Begrenzertyp '{type}'",
"No such environment: {name}" => "Unbekannte Umgebung: {name}",
"Expected argument to \\begin{{name}}" => "Argument für \\begin{{name}} erwartet",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "Keine Übereinstimmung: \\begin{{begin}} wird mit \\end{{end}} geschlossen",
"{command} valid only within array environment" => "{command} ist nur in einer array-Umgebung gültig",
"Mismatched {command}" => "{command} ohne Gegenstück",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "&, \\\\, \\cr oder \\end erwartet, '{got}' gefunden",
"Unknown column alignment: {alignment}" => "Unbekannte Spaltenausrichtung: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "Zu viele Formeln in einer Zeile: {expected} erwartet, {got} gefunden",
"Unknown CD directive: @{directive}" => "Unbekannte CD-Anweisung: @{directive}",
"Expected argument for {command}" => "Argument für {command} erwartet",
"{command} needs {count} premise(s), but only {available} available" => {
"{command} braucht {count} Prämisse(n), aber nur {available} vorhanden"
}
"{command} valid only as a supported bussproofs command within prooftree" => {
"{command} ist in prooftree nur als unterstützter bussproofs-Befehl gültig"
}
"prooftree ended with {count} proof stack item(s), expected 1" => "prooftree endete mit {count} Beweisstapel-Element(en), erwartet 1",
"\\@char has non-numeric argument {argument}" => "\\@char hat ein nicht numerisches Argument {argument}",
"\\@char with invalid code point {code}" => "\\@char mit ungültigem Codepunkt {code}",
"Invalid environment name character: {character}" => "Ungültiges Zeichen im Umgebungsnamen: {character}",
_ => return None,
})
}
+121 -1
View File
@@ -884,7 +884,21 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Cell Color" => "Χρώμα κελιού",
"A to Z" => "Α έως Ω",
"Z to A" => "Ω έως Α",
"+ Add Level" => "+ Προσθήκη επιπέδου",
"Add Level" => "Προσθήκη επιπέδου",
"Delete Level" => "Διαγραφή επιπέδου",
"Copy Level" => "Αντιγραφή επιπέδου",
"Move Up" => "Μετακίνηση πάνω",
"Move Down" => "Μετακίνηση κάτω",
"Order" => "Σειρά",
"Sort On" => "Ταξινόμηση ως προς",
"Sort|Column" => "Στήλη",
"Column {letters}" => "Στήλη {letters}",
"Smallest to Largest" => "Από το μικρότερο στο μεγαλύτερο",
"Largest to Smallest" => "Από το μεγαλύτερο στο μικρότερο",
"Close the Sort dialog before switching or changing worksheets." => {
"Κλείστε το παράθυρο διαλόγου Ταξινόμηση πριν αλλάξετε ή τροποποιήσετε φύλλα εργασίας."
}
"Return to the original worksheet to sort, or cancel." => "Επιστρέψτε στο αρχικό φύλλο εργασίας για να ταξινομήσετε ή ακυρώστε.",
"New…" => "Νέο…",
"Edit…" => "Επεξεργασία…",
"Name" => "Όνομα",
@@ -1015,6 +1029,112 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "Εμφάνιση",
"Collapse dialog" => "Σύμπτυξη παραθύρου διαλόγου",
"Expand dialog" => "Ανάπτυξη παραθύρου διαλόγου",
"Numerical Count" => "Αριθμητικό πλήθος",
"Minimum" => "Ελάχιστο",
"Maximum" => "Μέγιστο",
"Circular References: {cell}" => "Κυκλικές αναφορές: {cell}",
"Width: {chars} ({pixels} pixels)" => "Πλάτος: {chars} ({pixels} pixel)",
"Height: {points} ({pixels} pixels)" => "Ύψος: {points} ({pixels} pixel)",
"Picture in cell" => "Εικόνα σε κελί",
"Picture: {alt}" => "Εικόνα: {alt}",
"Format Control: {name}" => "Μορφοποίηση στοιχείου ελέγχου: {name}",
"Error at character {position}: {message}" => "Σφάλμα στον χαρακτήρα {position}: {message}",
"Macro definitions are not supported in equations." => "Οι ορισμοί μακροεντολών δεν υποστηρίζονται στις εξισώσεις.",
"A % can't be combined with a link in an equation." => "Ένα % δεν μπορεί να συνδυαστεί με σύνδεσμο σε μια εξίσωση.",
"Equations can nest at most 32 levels deep." => "Οι εξισώσεις μπορούν να έχουν έως 32 επίπεδα ένθεσης.",
"An equation can be at most 4096 bytes long." => "Μια εξίσωση μπορεί να έχει έως 4096 byte.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"Μια εξίσωση μπορεί να έχει έως 2500 κελιά πίνακα (γραμμές επί τη φαρδύτερη γραμμή)."
}
"This equation is too large to draw." => "Αυτή η εξίσωση είναι πολύ μεγάλη για να σχεδιαστεί.",
"This equation could not be laid out." => "Δεν ήταν δυνατή η στοιχειοθέτηση αυτής της εξίσωσης.",
"Saved macro “{name}” ({steps} step)" => "Η μακροεντολή «{name}» αποθηκεύτηκε ({steps} βήμα)",
"Saved macro “{name}” ({steps} steps)" => "Η μακροεντολή «{name}» αποθηκεύτηκε ({steps} βήματα)",
"without {key}: another macro took it while recording" => "χωρίς {key}: το πήρε άλλη μακροεντολή κατά την καταγραφή",
"Recording stopped" => "Η καταγραφή σταμάτησε",
"Macro “{name}” stopped: {message}" => "Η μακροεντολή «{name}» σταμάτησε: {message}",
"Ran macro “{name}” ({steps} step)" => "Η μακροεντολή «{name}» εκτελέστηκε ({steps} βήμα)",
"Ran macro “{name}” ({steps} steps)" => "Η μακροεντολή «{name}» εκτελέστηκε ({steps} βήματα)",
"Double superscript" => "Διπλός εκθέτης",
"Double subscript" => "Διπλός δείκτης",
"Extra }" => "Περιττό }",
"Unexpected end of input in a macro argument" => "Απρόσμενο τέλος εισόδου σε όρισμα μακροεντολής",
"Expected \\right after \\left" => "Αναμενόταν \\right μετά από \\left",
"\\middle must be within \\left and \\right" => "Το \\middle πρέπει να βρίσκεται μεταξύ \\left και \\right",
"Invalid environment name" => "Μη έγκυρο όνομα περιβάλλοντος",
"Expected \\end after environment body" => "Αναμενόταν \\end μετά το σώμα του περιβάλλοντος",
"Expected URL" => "Αναμενόταν URL",
"\\tag requires an argument" => "Το \\tag απαιτεί όρισμα",
"only one infix operator per group" => "Μόνο ένας ενδοθετικός τελεστής ανά ομάδα",
"Expected color token" => "Αναμενόταν χρώμα",
"Expected size for \\raisebox" => "Αναμενόταν μέγεθος για το \\raisebox",
"Expected size for \\rule width" => "Αναμενόταν μέγεθος για το πλάτος του \\rule",
"Expected size for \\rule height" => "Αναμενόταν μέγεθος για το ύψος του \\rule",
"Cannot use both \\tag and \\nonumber in the same row" => "Δεν μπορούν να χρησιμοποιηθούν \\tag και \\nonumber στην ίδια γραμμή",
"Multiple \\tag in a row" => "Πολλά \\tag σε μία γραμμή",
"\\tag must appear at the end of the row after the equation body" => {
"Το \\tag πρέπει να βρίσκεται στο τέλος της γραμμής, μετά το σώμα της εξίσωσης"
}
"Multiple \\nonumber in a row" => "Πολλά \\nonumber σε μία γραμμή",
"\\nonumber must appear at the end of the row" => "Το \\nonumber πρέπει να βρίσκεται στο τέλος της γραμμής",
"Too many tab characters: &" => "Πάρα πολλοί χαρακτήρες στηλοθέτη: &",
"Invalid column alignment for array" => "Μη έγκυρη στοίχιση στηλών για array",
"Expected column alignment character" => "Αναμενόταν χαρακτήρας στοίχισης στήλης",
"Expected l or c or r" => "Αναμενόταν l, c ή r",
"Expected ]" => "Αναμενόταν ]",
"Unexpected end of CD row after @" => "Απρόσμενο τέλος γραμμής CD μετά το @",
"Invalid column alignment for subarray" => "Μη έγκυρη στοίχιση στηλών για subarray",
"{subarray} can contain only one column" => "Το {subarray} μπορεί να περιέχει μόνο μία στήλη",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"Το prooftree έχει \\LeftLabel ή \\RightLabel χωρίς επόμενη εντολή συμπερασμού"
}
"Recursion limit exceeded" => "Υπέρβαση ορίου αναδρομής",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"Πάρα πολλές αναπτύξεις μακροεντολών: ατέρμων βρόχος ή πολύ χαμηλή ρύθμιση maxExpand"
}
"Expected raw style for \\htmlStyle" => "Αναμενόταν ακατέργαστο στυλ για το \\htmlStyle",
"\\verb assertion failed" => "Αποτυχία ελέγχου του \\verb",
"Undefined control sequence: {name}" => "Μη ορισμένη ακολουθία ελέγχου: {name}",
"Expected '{expected}', got '{got}'" => "Αναμενόταν '{expected}', βρέθηκε '{got}'",
"Expected group after '{symbol}'" => "Αναμενόταν ομάδα μετά από '{symbol}'",
"Expected delimiter as argument to '{function}'" => "Αναμενόταν οριοθέτης ως όρισμα του '{function}'",
"Expected group as argument to '{function}'" => "Αναμενόταν ομάδα ως όρισμα του '{function}'",
"Got function '{function}' with no arguments as superscript" => "Η συνάρτηση '{function}' χωρίς ορίσματα χρησιμοποιήθηκε ως εκθέτης",
"Got function '{function}' with no arguments as subscript" => "Η συνάρτηση '{function}' χωρίς ορίσματα χρησιμοποιήθηκε ως δείκτης",
"Got function '{function}' with no arguments as argument to '{parent}'" => {
"Η συνάρτηση '{function}' χωρίς ορίσματα χρησιμοποιήθηκε ως όρισμα του '{parent}'"
}
"Got function '{function}' with no arguments as \\tag" => "Η συνάρτηση '{function}' χωρίς ορίσματα χρησιμοποιήθηκε ως \\tag",
"Can't use function '{function}' in text mode" => "Η συνάρτηση '{function}' δεν μπορεί να χρησιμοποιηθεί σε λειτουργία κειμένου",
"Can't use function '{function}' in math mode" => "Η συνάρτηση '{function}' δεν μπορεί να χρησιμοποιηθεί σε μαθηματική λειτουργία",
"Invalid color: '{color}'" => "Μη έγκυρο χρώμα: '{color}'",
"Invalid size: '{size}'" => "Μη έγκυρο μέγεθος: '{size}'",
"Invalid unit: '{unit}'" => "Μη έγκυρη μονάδα: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "Μη έγκυρος οριοθέτης '{delimiter}' μετά από '{function}'",
"Invalid delimiter type '{type}' after '{function}'" => "Μη έγκυρος τύπος οριοθέτη '{type}' μετά από '{function}'",
"Invalid delimiter type '{type}'" => "Μη έγκυρος τύπος οριοθέτη '{type}'",
"No such environment: {name}" => "Άγνωστο περιβάλλον: {name}",
"Expected argument to \\begin{{name}}" => "Αναμενόταν όρισμα για το \\begin{{name}}",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "Αναντιστοιχία: το \\begin{{begin}} κλείνει με \\end{{end}}",
"{command} valid only within array environment" => "Το {command} ισχύει μόνο μέσα σε περιβάλλον array",
"Mismatched {command}" => "{command} χωρίς αντίστοιχο",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "Αναμενόταν &, \\\\, \\cr ή \\end, βρέθηκε '{got}'",
"Unknown column alignment: {alignment}" => "Άγνωστη στοίχιση στήλης: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "Πάρα πολλοί τύποι σε μία γραμμή: αναμένονταν {expected}, βρέθηκαν {got}",
"Unknown CD directive: @{directive}" => "Άγνωστη οδηγία CD: @{directive}",
"Expected argument for {command}" => "Αναμενόταν όρισμα για το {command}",
"{command} needs {count} premise(s), but only {available} available" => {
"Το {command} χρειάζεται {count} προκείμενες, αλλά υπάρχουν μόνο {available}"
}
"{command} valid only as a supported bussproofs command within prooftree" => {
"Το {command} ισχύει στο prooftree μόνο ως υποστηριζόμενη εντολή bussproofs"
}
"prooftree ended with {count} proof stack item(s), expected 1" => {
"Το prooftree τελείωσε με {count} στοιχεία στη στοίβα απόδειξης, αναμενόταν 1"
}
"\\@char has non-numeric argument {argument}" => "Το \\@char έχει μη αριθμητικό όρισμα {argument}",
"\\@char with invalid code point {code}" => "\\@char με μη έγκυρο σημείο κώδικα {code}",
"Invalid environment name character: {character}" => "Μη έγκυρος χαρακτήρας στο όνομα περιβάλλοντος: {character}",
_ => return None,
})
}
+130
View File
@@ -526,6 +526,136 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "Mostrar",
"Collapse dialog" => "Contraer diálogo",
"Expand dialog" => "Expandir diálogo",
"My list has headers" => "Mis datos tienen encabezados",
"Sort by" => "Ordenar por",
"Then by" => "Luego por",
"Cell Values" => "Valores de celda",
"Cell Color" => "Color de celda",
"A to Z" => "De A a Z",
"Z to A" => "De Z a A",
"Add Level" => "Agregar nivel",
"Delete Level" => "Eliminar nivel",
"Copy Level" => "Copiar nivel",
"Move Up" => "Subir",
"Move Down" => "Bajar",
"Order" => "Orden",
"Sort On" => "Ordenar según",
"Sort|Column" => "Columna",
"Column {letters}" => "Columna {letters}",
"Smallest to Largest" => "De menor a mayor",
"Largest to Smallest" => "De mayor a menor",
"Close the Sort dialog before switching or changing worksheets." => {
"Cierre el cuadro de diálogo Ordenar antes de cambiar de hoja o modificar las hojas."
}
"Return to the original worksheet to sort, or cancel." => "Vuelva a la hoja original para ordenar o cancele.",
"Numerical Count" => "Recuento numérico",
"Minimum" => "Mínimo",
"Maximum" => "Máximo",
"Circular References: {cell}" => "Referencias circulares: {cell}",
"Width: {chars} ({pixels} pixels)" => "Ancho: {chars} ({pixels} píxeles)",
"Height: {points} ({pixels} pixels)" => "Alto: {points} ({pixels} píxeles)",
"Picture in cell" => "Imagen en celda",
"Picture: {alt}" => "Imagen: {alt}",
"Format Control: {name}" => "Formato de control: {name}",
"Error at character {position}: {message}" => "Error en el carácter {position}: {message}",
"Macro definitions are not supported in equations." => "Las definiciones de macros no se admiten en las ecuaciones.",
"A % can't be combined with a link in an equation." => "Un % no se puede combinar con un vínculo en una ecuación.",
"Equations can nest at most 32 levels deep." => "Las ecuaciones pueden anidarse como máximo 32 niveles.",
"An equation can be at most 4096 bytes long." => "Una ecuación puede tener como máximo 4096 bytes.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"Una ecuación puede tener como máximo 2500 celdas de matriz (filas por la fila más ancha)."
}
"This equation is too large to draw." => "Esta ecuación es demasiado grande para dibujarla.",
"This equation could not be laid out." => "No se pudo componer esta ecuación.",
"Saved macro “{name}” ({steps} step)" => "Macro “{name}” guardada ({steps} paso)",
"Saved macro “{name}” ({steps} steps)" => "Macro “{name}” guardada ({steps} pasos)",
"without {key}: another macro took it while recording" => "sin {key}: otra macro lo tomó durante la grabación",
"Recording stopped" => "Grabación detenida",
"Macro “{name}” stopped: {message}" => "La macro “{name}” se detuvo: {message}",
"Ran macro “{name}” ({steps} step)" => "Macro “{name}” ejecutada ({steps} paso)",
"Ran macro “{name}” ({steps} steps)" => "Macro “{name}” ejecutada ({steps} pasos)",
"Average" => "Promedio",
"Count" => "Recuento",
"Sum" => "Suma",
"Goal Seeking found a solution: {value}" => "Buscar objetivo encontró una solución: {value}",
"Sheets: {sheets}" => "Hojas: {sheets}",
"Hidden: {sheets}" => "Ocultas: {sheets}",
"Double superscript" => "Superíndice doble",
"Double subscript" => "Subíndice doble",
"Extra }" => "} sobrante",
"Unexpected end of input in a macro argument" => "Fin inesperado de la entrada en un argumento de macro",
"Expected \\right after \\left" => "Se esperaba \\right después de \\left",
"\\middle must be within \\left and \\right" => "\\middle debe estar entre \\left y \\right",
"Invalid environment name" => "Nombre de entorno no válido",
"Expected \\end after environment body" => "Se esperaba \\end después del cuerpo del entorno",
"Expected URL" => "Se esperaba una URL",
"\\tag requires an argument" => "\\tag requiere un argumento",
"only one infix operator per group" => "Solo un operador infijo por grupo",
"Expected color token" => "Se esperaba un color",
"Expected size for \\raisebox" => "Se esperaba un tamaño para \\raisebox",
"Expected size for \\rule width" => "Se esperaba un tamaño para el ancho de \\rule",
"Expected size for \\rule height" => "Se esperaba un tamaño para el alto de \\rule",
"Cannot use both \\tag and \\nonumber in the same row" => "No se pueden usar \\tag y \\nonumber en la misma fila",
"Multiple \\tag in a row" => "Varios \\tag en una fila",
"\\tag must appear at the end of the row after the equation body" => "\\tag debe ir al final de la fila, después del cuerpo de la ecuación",
"Multiple \\nonumber in a row" => "Varios \\nonumber en una fila",
"\\nonumber must appear at the end of the row" => "\\nonumber debe ir al final de la fila",
"Too many tab characters: &" => "Demasiados caracteres de tabulación: &",
"Invalid column alignment for array" => "Alineación de columna no válida para array",
"Expected column alignment character" => "Se esperaba un carácter de alineación de columna",
"Expected l or c or r" => "Se esperaba l, c o r",
"Expected ]" => "Se esperaba ]",
"Unexpected end of CD row after @" => "Fin inesperado de la fila CD después de @",
"Invalid column alignment for subarray" => "Alineación de columna no válida para subarray",
"{subarray} can contain only one column" => "{subarray} solo puede contener una columna",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"prooftree tiene un \\LeftLabel o \\RightLabel sin un comando de inferencia a continuación"
}
"Recursion limit exceeded" => "Se superó el límite de recursión",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"Demasiadas expansiones de macros: bucle infinito o ajuste maxExpand demasiado bajo"
}
"Expected raw style for \\htmlStyle" => "Se esperaba un estilo sin formato para \\htmlStyle",
"\\verb assertion failed" => "Falló la comprobación de \\verb",
"Undefined control sequence: {name}" => "Secuencia de control no definida: {name}",
"Expected '{expected}', got '{got}'" => "Se esperaba '{expected}', se encontró '{got}'",
"Expected group after '{symbol}'" => "Se esperaba un grupo después de '{symbol}'",
"Expected delimiter as argument to '{function}'" => "Se esperaba un delimitador como argumento de '{function}'",
"Expected group as argument to '{function}'" => "Se esperaba un grupo como argumento de '{function}'",
"Got function '{function}' with no arguments as superscript" => "Función '{function}' sin argumentos usada como superíndice",
"Got function '{function}' with no arguments as subscript" => "Función '{function}' sin argumentos usada como subíndice",
"Got function '{function}' with no arguments as argument to '{parent}'" => {
"Función '{function}' sin argumentos usada como argumento de '{parent}'"
}
"Got function '{function}' with no arguments as \\tag" => "Función '{function}' sin argumentos usada como \\tag",
"Can't use function '{function}' in text mode" => "No se puede usar la función '{function}' en modo texto",
"Can't use function '{function}' in math mode" => "No se puede usar la función '{function}' en modo matemático",
"Invalid color: '{color}'" => "Color no válido: '{color}'",
"Invalid size: '{size}'" => "Tamaño no válido: '{size}'",
"Invalid unit: '{unit}'" => "Unidad no válida: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "Delimitador '{delimiter}' no válido después de '{function}'",
"Invalid delimiter type '{type}' after '{function}'" => "Tipo de delimitador '{type}' no válido después de '{function}'",
"Invalid delimiter type '{type}'" => "Tipo de delimitador '{type}' no válido",
"No such environment: {name}" => "Entorno desconocido: {name}",
"Expected argument to \\begin{{name}}" => "Se esperaba un argumento para \\begin{{name}}",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "No coinciden: \\begin{{begin}} cerrado con \\end{{end}}",
"{command} valid only within array environment" => "{command} solo es válido dentro de un entorno array",
"Mismatched {command}" => "{command} sin pareja",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "Se esperaba &, \\\\, \\cr o \\end, se encontró '{got}'",
"Unknown column alignment: {alignment}" => "Alineación de columna desconocida: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "Demasiadas fórmulas en una fila: se esperaban {expected}, hay {got}",
"Unknown CD directive: @{directive}" => "Directiva CD desconocida: @{directive}",
"Expected argument for {command}" => "Se esperaba un argumento para {command}",
"{command} needs {count} premise(s), but only {available} available" => "{command} necesita {count} premisa(s), pero solo hay {available}",
"{command} valid only as a supported bussproofs command within prooftree" => {
"{command} solo es válido como comando bussproofs admitido dentro de prooftree"
}
"prooftree ended with {count} proof stack item(s), expected 1" => {
"prooftree terminó con {count} elemento(s) en la pila de prueba; se esperaba 1"
}
"\\@char has non-numeric argument {argument}" => "\\@char tiene un argumento no numérico {argument}",
"\\@char with invalid code point {code}" => "\\@char con un punto de código no válido {code}",
"Invalid environment name character: {character}" => "Carácter no válido en el nombre del entorno: {character}",
_ => return None,
})
}
+132
View File
@@ -486,6 +486,138 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "Afficher",
"Collapse dialog" => "Réduire la boîte de dialogue",
"Expand dialog" => "Développer la boîte de dialogue",
"My list has headers" => "Mes données ont des en-têtes",
"Sort by" => "Trier par",
"Then by" => "Puis par",
"Cell Values" => "Valeurs de cellule",
"Cell Color" => "Couleur de cellule",
"A to Z" => "De A à Z",
"Z to A" => "De Z à A",
"Add Level" => "Ajouter un niveau",
"Delete Level" => "Supprimer le niveau",
"Copy Level" => "Copier le niveau",
"Move Up" => "Monter",
"Move Down" => "Descendre",
"Order" => "Ordre",
"Sort On" => "Trier sur",
"Sort|Column" => "Colonne",
"Column {letters}" => "Colonne {letters}",
"Smallest to Largest" => "Du plus petit au plus grand",
"Largest to Smallest" => "Du plus grand au plus petit",
"Close the Sort dialog before switching or changing worksheets." => {
"Fermez la boîte de dialogue Trier avant de changer de feuille ou de modifier les feuilles."
}
"Return to the original worksheet to sort, or cancel." => "Revenez à la feuille d’origine pour trier, ou annulez.",
"Numerical Count" => "Nombre de valeurs numériques",
"Minimum" => "Minimum",
"Maximum" => "Maximum",
"Circular References: {cell}" => "Références circulaires : {cell}",
"Width: {chars} ({pixels} pixels)" => "Largeur : {chars} ({pixels} pixels)",
"Height: {points} ({pixels} pixels)" => "Hauteur : {points} ({pixels} pixels)",
"Picture in cell" => "Image dans la cellule",
"Picture: {alt}" => "Image : {alt}",
"Format Control: {name}" => "Format de contrôle : {name}",
"Error at character {position}: {message}" => "Erreur au caractère {position} : {message}",
"Macro definitions are not supported in equations." => "Les définitions de macros ne sont pas prises en charge dans les équations.",
"A % can't be combined with a link in an equation." => "Un % ne peut pas être combiné avec un lien dans une équation.",
"Equations can nest at most 32 levels deep." => "Les équations peuvent comporter au plus 32 niveaux d’imbrication.",
"An equation can be at most 4096 bytes long." => "Une équation peut contenir au plus 4096 octets.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"Une équation peut contenir au plus 2500 cellules de matrice (lignes multipliées par la ligne la plus large)."
}
"This equation is too large to draw." => "Cette équation est trop grande pour être dessinée.",
"This equation could not be laid out." => "Impossible de mettre en page cette équation.",
"Saved macro “{name}” ({steps} step)" => "Macro « {name} » enregistrée ({steps} étape)",
"Saved macro “{name}” ({steps} steps)" => "Macro « {name} » enregistrée ({steps} étapes)",
"without {key}: another macro took it while recording" => "sans {key} : une autre macro l’a pris pendant l’enregistrement",
"Recording stopped" => "Enregistrement arrêté",
"Macro “{name}” stopped: {message}" => "Macro « {name} » arrêtée : {message}",
"Ran macro “{name}” ({steps} step)" => "Macro « {name} » exécutée ({steps} étape)",
"Ran macro “{name}” ({steps} steps)" => "Macro « {name} » exécutée ({steps} étapes)",
"Average" => "Moyenne",
"Count" => "Nombre",
"Sum" => "Somme",
"Goal Seeking found a solution: {value}" => "Valeur cible a trouvé une solution : {value}",
"Sheets: {sheets}" => "Feuilles : {sheets}",
"Hidden: {sheets}" => "Masquées : {sheets}",
"Double superscript" => "Exposant double",
"Double subscript" => "Indice double",
"Extra }" => "} en trop",
"Unexpected end of input in a macro argument" => "Fin inattendue de l'entrée dans un argument de macro",
"Expected \\right after \\left" => "\\right attendu après \\left",
"\\middle must be within \\left and \\right" => "\\middle doit se trouver entre \\left et \\right",
"Invalid environment name" => "Nom d'environnement non valide",
"Expected \\end after environment body" => "\\end attendu après le corps de l'environnement",
"Expected URL" => "URL attendue",
"\\tag requires an argument" => "\\tag nécessite un argument",
"only one infix operator per group" => "Un seul opérateur infixe par groupe",
"Expected color token" => "Couleur attendue",
"Expected size for \\raisebox" => "Taille attendue pour \\raisebox",
"Expected size for \\rule width" => "Taille attendue pour la largeur de \\rule",
"Expected size for \\rule height" => "Taille attendue pour la hauteur de \\rule",
"Cannot use both \\tag and \\nonumber in the same row" => "\\tag et \\nonumber ne peuvent pas figurer dans la même ligne",
"Multiple \\tag in a row" => "Plusieurs \\tag dans une ligne",
"\\tag must appear at the end of the row after the equation body" => "\\tag doit figurer à la fin de la ligne, après le corps de l'équation",
"Multiple \\nonumber in a row" => "Plusieurs \\nonumber dans une ligne",
"\\nonumber must appear at the end of the row" => "\\nonumber doit figurer à la fin de la ligne",
"Too many tab characters: &" => "Trop de caractères de tabulation : &",
"Invalid column alignment for array" => "Alignement de colonne non valide pour array",
"Expected column alignment character" => "Caractère d'alignement de colonne attendu",
"Expected l or c or r" => "l, c ou r attendu",
"Expected ]" => "] attendu",
"Unexpected end of CD row after @" => "Fin inattendue de la ligne CD après @",
"Invalid column alignment for subarray" => "Alignement de colonne non valide pour subarray",
"{subarray} can contain only one column" => "{subarray} ne peut contenir qu'une seule colonne",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"prooftree contient un \\LeftLabel ou \\RightLabel sans commande d'inférence qui le suit"
}
"Recursion limit exceeded" => "Limite de récursion dépassée",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"Trop d'expansions de macros : boucle infinie ou paramètre maxExpand trop bas"
}
"Expected raw style for \\htmlStyle" => "Style brut attendu pour \\htmlStyle",
"\\verb assertion failed" => "Échec de la vérification de \\verb",
"Undefined control sequence: {name}" => "Séquence de contrôle non définie : {name}",
"Expected '{expected}', got '{got}'" => "'{expected}' attendu, '{got}' trouvé",
"Expected group after '{symbol}'" => "Groupe attendu après '{symbol}'",
"Expected delimiter as argument to '{function}'" => "Délimiteur attendu comme argument de '{function}'",
"Expected group as argument to '{function}'" => "Groupe attendu comme argument de '{function}'",
"Got function '{function}' with no arguments as superscript" => "Fonction '{function}' sans arguments utilisée comme exposant",
"Got function '{function}' with no arguments as subscript" => "Fonction '{function}' sans arguments utilisée comme indice",
"Got function '{function}' with no arguments as argument to '{parent}'" => {
"Fonction '{function}' sans arguments utilisée comme argument de '{parent}'"
}
"Got function '{function}' with no arguments as \\tag" => "Fonction '{function}' sans arguments utilisée comme \\tag",
"Can't use function '{function}' in text mode" => "La fonction '{function}' n'est pas utilisable en mode texte",
"Can't use function '{function}' in math mode" => "La fonction '{function}' n'est pas utilisable en mode mathématique",
"Invalid color: '{color}'" => "Couleur non valide : '{color}'",
"Invalid size: '{size}'" => "Taille non valide : '{size}'",
"Invalid unit: '{unit}'" => "Unité non valide : '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "Délimiteur '{delimiter}' non valide après '{function}'",
"Invalid delimiter type '{type}' after '{function}'" => "Type de délimiteur '{type}' non valide après '{function}'",
"Invalid delimiter type '{type}'" => "Type de délimiteur '{type}' non valide",
"No such environment: {name}" => "Environnement inconnu : {name}",
"Expected argument to \\begin{{name}}" => "Argument attendu pour \\begin{{name}}",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "Non-correspondance : \\begin{{begin}} fermé par \\end{{end}}",
"{command} valid only within array environment" => "{command} n'est valide que dans un environnement array",
"Mismatched {command}" => "{command} sans correspondance",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "&, \\\\, \\cr ou \\end attendu, '{got}' trouvé",
"Unknown column alignment: {alignment}" => "Alignement de colonne inconnu : {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "Trop de formules dans une ligne : {expected} attendues, {got} trouvées",
"Unknown CD directive: @{directive}" => "Directive CD inconnue : @{directive}",
"Expected argument for {command}" => "Argument attendu pour {command}",
"{command} needs {count} premise(s), but only {available} available" => {
"{command} nécessite {count} prémisse(s), mais seulement {available} disponible(s)"
}
"{command} valid only as a supported bussproofs command within prooftree" => {
"{command} n'est valide dans prooftree que comme commande bussproofs prise en charge"
}
"prooftree ended with {count} proof stack item(s), expected 1" => {
"prooftree s'est terminé avec {count} élément(s) sur la pile de preuve, 1 attendu"
}
"\\@char has non-numeric argument {argument}" => "\\@char a un argument non numérique {argument}",
"\\@char with invalid code point {code}" => "\\@char avec un point de code non valide {code}",
"Invalid environment name character: {character}" => "Caractère non valide dans le nom d'environnement : {character}",
_ => return None,
})
}
+119 -1
View File
@@ -770,7 +770,21 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Cell Color" => "Colore cella",
"A to Z" => "Dalla A alla Z",
"Z to A" => "Dalla Z alla A",
"+ Add Level" => "+ Aggiungi livello",
"Add Level" => "Aggiungi livello",
"Delete Level" => "Elimina livello",
"Copy Level" => "Copia livello",
"Move Up" => "Sposta su",
"Move Down" => "Sposta giù",
"Order" => "Ordine",
"Sort On" => "Ordina in base a",
"Sort|Column" => "Colonna",
"Column {letters}" => "Colonna {letters}",
"Smallest to Largest" => "Dal più piccolo al più grande",
"Largest to Smallest" => "Dal più grande al più piccolo",
"Close the Sort dialog before switching or changing worksheets." => {
"Chiudi la finestra di dialogo Ordina prima di cambiare o modificare i fogli di lavoro."
}
"Return to the original worksheet to sort, or cancel." => "Torna al foglio di lavoro originale per ordinare oppure annulla.",
"New…" => "Nuovo…",
"Edit…" => "Modifica…",
"Name" => "Nome",
@@ -1021,6 +1035,110 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "Mostra",
"Collapse dialog" => "Comprimi finestra di dialogo",
"Expand dialog" => "Espandi finestra di dialogo",
"Numerical Count" => "Conteggio numeri",
"Minimum" => "Minimo",
"Maximum" => "Massimo",
"Circular References: {cell}" => "Riferimenti circolari: {cell}",
"Width: {chars} ({pixels} pixels)" => "Larghezza: {chars} ({pixels} pixel)",
"Height: {points} ({pixels} pixels)" => "Altezza: {points} ({pixels} pixel)",
"Picture in cell" => "Immagine nella cella",
"Picture: {alt}" => "Immagine: {alt}",
"Format Control: {name}" => "Formato controllo: {name}",
"Error at character {position}: {message}" => "Errore al carattere {position}: {message}",
"Macro definitions are not supported in equations." => "Le definizioni di macro non sono supportate nelle equazioni.",
"A % can't be combined with a link in an equation." => "Un % non può essere combinato con un collegamento in un'equazione.",
"Equations can nest at most 32 levels deep." => "Le equazioni possono essere annidate al massimo su 32 livelli.",
"An equation can be at most 4096 bytes long." => "Un'equazione può essere lunga al massimo 4096 byte.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"Un'equazione può avere al massimo 2500 celle di matrice (righe per la riga più larga)."
}
"This equation is too large to draw." => "Questa equazione è troppo grande per essere disegnata.",
"This equation could not be laid out." => "Impossibile impaginare questa equazione.",
"Saved macro “{name}” ({steps} step)" => "Macro “{name}” salvata ({steps} passaggio)",
"Saved macro “{name}” ({steps} steps)" => "Macro “{name}” salvata ({steps} passaggi)",
"without {key}: another macro took it while recording" => "senza {key}: un’altra macro l’ha preso durante la registrazione",
"Recording stopped" => "Registrazione interrotta",
"Macro “{name}” stopped: {message}" => "Macro “{name}” interrotta: {message}",
"Ran macro “{name}” ({steps} step)" => "Macro “{name}” eseguita ({steps} passaggio)",
"Ran macro “{name}” ({steps} steps)" => "Macro “{name}” eseguita ({steps} passaggi)",
"Double superscript" => "Apice doppio",
"Double subscript" => "Pedice doppio",
"Extra }" => "} in eccesso",
"Unexpected end of input in a macro argument" => "Fine imprevista dell'input in un argomento di macro",
"Expected \\right after \\left" => "Previsto \\right dopo \\left",
"\\middle must be within \\left and \\right" => "\\middle deve trovarsi tra \\left e \\right",
"Invalid environment name" => "Nome di ambiente non valido",
"Expected \\end after environment body" => "Previsto \\end dopo il corpo dell'ambiente",
"Expected URL" => "Previsto un URL",
"\\tag requires an argument" => "\\tag richiede un argomento",
"only one infix operator per group" => "Un solo operatore infisso per gruppo",
"Expected color token" => "Previsto un colore",
"Expected size for \\raisebox" => "Prevista una dimensione per \\raisebox",
"Expected size for \\rule width" => "Prevista una dimensione per la larghezza di \\rule",
"Expected size for \\rule height" => "Prevista una dimensione per l'altezza di \\rule",
"Cannot use both \\tag and \\nonumber in the same row" => "Non si possono usare \\tag e \\nonumber nella stessa riga",
"Multiple \\tag in a row" => "Più \\tag in una riga",
"\\tag must appear at the end of the row after the equation body" => "\\tag deve trovarsi alla fine della riga, dopo il corpo dell'equazione",
"Multiple \\nonumber in a row" => "Più \\nonumber in una riga",
"\\nonumber must appear at the end of the row" => "\\nonumber deve trovarsi alla fine della riga",
"Too many tab characters: &" => "Troppi caratteri di tabulazione: &",
"Invalid column alignment for array" => "Allineamento di colonna non valido per array",
"Expected column alignment character" => "Previsto un carattere di allineamento di colonna",
"Expected l or c or r" => "Previsto l, c o r",
"Expected ]" => "Prevista ]",
"Unexpected end of CD row after @" => "Fine imprevista della riga CD dopo @",
"Invalid column alignment for subarray" => "Allineamento di colonna non valido per subarray",
"{subarray} can contain only one column" => "{subarray} può contenere una sola colonna",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"prooftree ha un \\LeftLabel o \\RightLabel senza un comando di inferenza successivo"
}
"Recursion limit exceeded" => "Limite di ricorsione superato",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"Troppe espansioni di macro: ciclo infinito o impostazione maxExpand troppo bassa"
}
"Expected raw style for \\htmlStyle" => "Previsto uno stile grezzo per \\htmlStyle",
"\\verb assertion failed" => "Verifica di \\verb non riuscita",
"Undefined control sequence: {name}" => "Sequenza di controllo non definita: {name}",
"Expected '{expected}', got '{got}'" => "Previsto '{expected}', trovato '{got}'",
"Expected group after '{symbol}'" => "Previsto un gruppo dopo '{symbol}'",
"Expected delimiter as argument to '{function}'" => "Previsto un delimitatore come argomento di '{function}'",
"Expected group as argument to '{function}'" => "Previsto un gruppo come argomento di '{function}'",
"Got function '{function}' with no arguments as superscript" => "Funzione '{function}' senza argomenti usata come apice",
"Got function '{function}' with no arguments as subscript" => "Funzione '{function}' senza argomenti usata come pedice",
"Got function '{function}' with no arguments as argument to '{parent}'" => {
"Funzione '{function}' senza argomenti usata come argomento di '{parent}'"
}
"Got function '{function}' with no arguments as \\tag" => "Funzione '{function}' senza argomenti usata come \\tag",
"Can't use function '{function}' in text mode" => "La funzione '{function}' non si può usare in modalità testo",
"Can't use function '{function}' in math mode" => "La funzione '{function}' non si può usare in modalità matematica",
"Invalid color: '{color}'" => "Colore non valido: '{color}'",
"Invalid size: '{size}'" => "Dimensione non valida: '{size}'",
"Invalid unit: '{unit}'" => "Unità non valida: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "Delimitatore '{delimiter}' non valido dopo '{function}'",
"Invalid delimiter type '{type}' after '{function}'" => "Tipo di delimitatore '{type}' non valido dopo '{function}'",
"Invalid delimiter type '{type}'" => "Tipo di delimitatore '{type}' non valido",
"No such environment: {name}" => "Ambiente sconosciuto: {name}",
"Expected argument to \\begin{{name}}" => "Previsto un argomento per \\begin{{name}}",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "Mancata corrispondenza: \\begin{{begin}} chiuso da \\end{{end}}",
"{command} valid only within array environment" => "{command} è valido solo in un ambiente array",
"Mismatched {command}" => "{command} senza corrispondenza",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "Previsto &, \\\\, \\cr o \\end, trovato '{got}'",
"Unknown column alignment: {alignment}" => "Allineamento di colonna sconosciuto: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "Troppe formule in una riga: previste {expected}, trovate {got}",
"Unknown CD directive: @{directive}" => "Direttiva CD sconosciuta: @{directive}",
"Expected argument for {command}" => "Previsto un argomento per {command}",
"{command} needs {count} premise(s), but only {available} available" => {
"{command} richiede {count} premessa/e, ma ne sono disponibili solo {available}"
}
"{command} valid only as a supported bussproofs command within prooftree" => {
"{command} è valido solo come comando bussproofs supportato in prooftree"
}
"prooftree ended with {count} proof stack item(s), expected 1" => {
"prooftree è terminato con {count} elemento/i nella pila di dimostrazione, previsto 1"
}
"\\@char has non-numeric argument {argument}" => "\\@char ha un argomento non numerico {argument}",
"\\@char with invalid code point {code}" => "\\@char con punto di codice non valido {code}",
"Invalid environment name character: {character}" => "Carattere non valido nel nome dell'ambiente: {character}",
_ => return None,
})
}
+115 -1
View File
@@ -786,7 +786,22 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
("Cell Color", "セルの色"),
("A to Z", "昇順"),
("Z to A", "降順"),
("+ Add Level", "+ レベルの追加"),
("Add Level", "レベルの追加"),
("Delete Level", "レベルの削除"),
("Copy Level", "レベルのコピー"),
("Move Up", "上へ移動"),
("Move Down", "下へ移動"),
("Order", "順序"),
("Sort On", "並べ替えのキー"),
("Sort|Column", "列"),
("Column {letters}", "列 {letters}"),
("Smallest to Largest", "小さい順"),
("Largest to Smallest", "大きい順"),
(
"Close the Sort dialog before switching or changing worksheets.",
"シートを切り替えたり変更したりする前に、並べ替えダイアログを閉じてください。",
),
("Return to the original worksheet to sort, or cancel.", "並べ替えるには元のシートに戻るか、キャンセルしてください。"),
("New…", "新規作成…"),
("Edit…", "編集…"),
("Name", "名前"),
@@ -1021,6 +1036,105 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
("Unprotect Sheet…", "シート保護の解除…"),
("Collapse dialog", "ダイアログを折りたたむ"),
("Expand dialog", "ダイアログを展開する"),
("Numerical Count", "数値の個数"),
("Minimum", "最小値"),
("Maximum", "最大値"),
("Circular References: {cell}", "循環参照: {cell}"),
("Width: {chars} ({pixels} pixels)", "幅: {chars} ({pixels} ピクセル)"),
("Height: {points} ({pixels} pixels)", "高さ: {points} ({pixels} ピクセル)"),
("Picture in cell", "セル内の画像"),
("Picture: {alt}", "画像: {alt}"),
("Format Control: {name}", "コントロールの書式設定: {name}"),
("Error at character {position}: {message}", "{position} 文字目でエラー: {message}"),
("Macro definitions are not supported in equations.", "数式ではマクロ定義はサポートされていません。"),
("A % can't be combined with a link in an equation.", "数式では % とリンクを組み合わせることはできません。"),
("Equations can nest at most 32 levels deep.", "数式の入れ子は 32 レベルまでです。"),
("An equation can be at most 4096 bytes long.", "数式の長さは 4096 バイトまでです。"),
("An equation can have at most 2500 matrix cells (rows times the widest row).", "数式の行列セルは 2500 個まで (行数 × 最も長い行) です。"),
("This equation is too large to draw.", "この数式は大きすぎて描画できません。"),
("This equation could not be laid out.", "この数式をレイアウトできませんでした。"),
("Saved macro “{name}” ({steps} step)", "マクロ「{name}」を保存しました ({steps} ステップ)"),
("Saved macro “{name}” ({steps} steps)", "マクロ「{name}」を保存しました ({steps} ステップ)"),
("without {key}: another macro took it while recording", "{key} なし: 記録中に別のマクロに割り当てられました"),
("Recording stopped", "記録を終了しました"),
("Macro “{name}” stopped: {message}", "マクロ「{name}」が停止しました: {message}"),
("Ran macro “{name}” ({steps} step)", "マクロ「{name}」を実行しました ({steps} ステップ)"),
("Ran macro “{name}” ({steps} steps)", "マクロ「{name}」を実行しました ({steps} ステップ)"),
("Double superscript", "上付き文字が重複しています"),
("Double subscript", "下付き文字が重複しています"),
("Extra }", "余分な } があります"),
("Unexpected end of input in a macro argument", "マクロ引数の途中で入力が終了しました"),
("Expected \\right after \\left", "\\left の後に \\right が必要です"),
("\\middle must be within \\left and \\right", "\\middle は \\left と \\right の間に置く必要があります"),
("Invalid environment name", "環境名が無効です"),
("Expected \\end after environment body", "環境の本体の後に \\end が必要です"),
("Expected URL", "URL が必要です"),
("\\tag requires an argument", "\\tag には引数が必要です"),
("only one infix operator per group", "中置演算子はグループごとに 1 つだけです"),
("Expected color token", "色の指定が必要です"),
("Expected size for \\raisebox", "\\raisebox にはサイズが必要です"),
("Expected size for \\rule width", "\\rule の幅にはサイズが必要です"),
("Expected size for \\rule height", "\\rule の高さにはサイズが必要です"),
("Cannot use both \\tag and \\nonumber in the same row", "同じ行で \\tag と \\nonumber は併用できません"),
("Multiple \\tag in a row", "1 行に \\tag が複数あります"),
("\\tag must appear at the end of the row after the equation body", "\\tag は行の末尾、数式の本体の後に置く必要があります"),
("Multiple \\nonumber in a row", "1 行に \\nonumber が複数あります"),
("\\nonumber must appear at the end of the row", "\\nonumber は行の末尾に置く必要があります"),
("Too many tab characters: &", "タブ文字が多すぎます: &"),
("Invalid column alignment for array", "array の列の配置が無効です"),
("Expected column alignment character", "列の配置文字が必要です"),
("Expected l or c or r", "l、c、r のいずれかが必要です"),
("Expected ]", "] が必要です"),
("Unexpected end of CD row after @", "@ の後で CD の行が終了しました"),
("Invalid column alignment for subarray", "subarray の列の配置が無効です"),
("{subarray} can contain only one column", "{subarray} に含められる列は 1 つだけです"),
(
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command",
"prooftree に、後に推論コマンドのない \\LeftLabel または \\RightLabel があります",
),
("Recursion limit exceeded", "再帰の上限を超えました"),
(
"Too many expansions: infinite loop or need to increase maxExpand setting",
"マクロの展開が多すぎます: 無限ループか、maxExpand の設定が小さすぎます",
),
("Expected raw style for \\htmlStyle", "\\htmlStyle には生のスタイルが必要です"),
("\\verb assertion failed", "\\verb のチェックに失敗しました"),
("Undefined control sequence: {name}", "未定義の制御シーケンス: {name}"),
("Expected '{expected}', got '{got}'", "'{expected}' が必要ですが、'{got}' がありました"),
("Expected group after '{symbol}'", "'{symbol}' の後にグループが必要です"),
("Expected delimiter as argument to '{function}'", "'{function}' の引数として区切り記号が必要です"),
("Expected group as argument to '{function}'", "'{function}' の引数としてグループが必要です"),
("Got function '{function}' with no arguments as superscript", "引数のない関数 '{function}' が上付き文字として使われています"),
("Got function '{function}' with no arguments as subscript", "引数のない関数 '{function}' が下付き文字として使われています"),
("Got function '{function}' with no arguments as argument to '{parent}'", "引数のない関数 '{function}' が '{parent}' の引数として使われています"),
("Got function '{function}' with no arguments as \\tag", "引数のない関数 '{function}' が \\tag として使われています"),
("Can't use function '{function}' in text mode", "関数 '{function}' はテキスト モードでは使用できません"),
("Can't use function '{function}' in math mode", "関数 '{function}' は数式モードでは使用できません"),
("Invalid color: '{color}'", "無効な色: '{color}'"),
("Invalid size: '{size}'", "無効なサイズ: '{size}'"),
("Invalid unit: '{unit}'", "無効な単位: '{unit}'"),
("Invalid delimiter '{delimiter}' after '{function}'", "'{function}' の後の区切り記号 '{delimiter}' が無効です"),
("Invalid delimiter type '{type}' after '{function}'", "'{function}' の後の区切り記号の種類 '{type}' が無効です"),
("Invalid delimiter type '{type}'", "区切り記号の種類 '{type}' が無効です"),
("No such environment: {name}", "不明な環境: {name}"),
("Expected argument to \\begin{{name}}", "\\begin{{name}} には引数が必要です"),
("Mismatch: \\begin{{begin}} matched by \\end{{end}}", "対応していません: \\begin{{begin}} が \\end{{end}} で閉じられています"),
("{command} valid only within array environment", "{command} は array 環境の中でのみ有効です"),
("Mismatched {command}", "{command} に対応するものがありません"),
("Expected & or \\\\ or \\cr or \\end, got '{got}'", "&、\\\\、\\cr、\\end のいずれかが必要ですが、'{got}' がありました"),
("Unknown column alignment: {alignment}", "不明な列の配置: {alignment}"),
("Too many math in a row: expected {expected}, but got {got}", "1 行の数式が多すぎます: {expected} 個のはずが {got} 個あります"),
("Unknown CD directive: @{directive}", "不明な CD ディレクティブ: @{directive}"),
("Expected argument for {command}", "{command} には引数が必要です"),
("{command} needs {count} premise(s), but only {available} available", "{command} には前提が {count} 個必要ですが、{available} 個しかありません"),
(
"{command} valid only as a supported bussproofs command within prooftree",
"{command} は prooftree の中でサポートされている bussproofs コマンドとしてのみ有効です",
),
("prooftree ended with {count} proof stack item(s), expected 1", "prooftree が証明スタックに {count} 個の項目を残して終了しました (1 個のはず)"),
("\\@char has non-numeric argument {argument}", "\\@char の引数 {argument} が数値ではありません"),
("\\@char with invalid code point {code}", "\\@char のコード ポイント {code} が無効です"),
("Invalid environment name character: {character}", "環境名に無効な文字があります: {character}"),
];
/// Labels of the ribbon menus, pop-ups and palettes that the reference catalog does not cover (the
+126
View File
@@ -490,6 +490,132 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "표시",
"Collapse dialog" => "대화 상자 축소",
"Expand dialog" => "대화 상자 확장",
"My list has headers" => "내 데이터에 머리글 표시",
"Sort by" => "정렬 기준",
"Then by" => "다음 기준",
"Cell Values" => "셀 값",
"Cell Color" => "셀 색",
"A to Z" => "A에서 Z",
"Z to A" => "Z에서 A",
"Add Level" => "기준 추가",
"Delete Level" => "기준 삭제",
"Copy Level" => "기준 복사",
"Move Up" => "위로 이동",
"Move Down" => "아래로 이동",
"Order" => "정렬",
"Sort On" => "정렬 기준",
"Sort|Column" => "열",
"Column {letters}" => "{letters} 열",
"Smallest to Largest" => "가장 작은 값에서 가장 큰 값으로",
"Largest to Smallest" => "가장 큰 값에서 가장 작은 값으로",
"Close the Sort dialog before switching or changing worksheets." => "시트를 전환하거나 변경하기 전에 정렬 대화 상자를 닫으세요.",
"Return to the original worksheet to sort, or cancel." => "정렬하려면 원래 시트로 돌아가거나 취소하세요.",
"Numerical Count" => "숫자 셀 수",
"Minimum" => "최소값",
"Maximum" => "최대값",
"Circular References: {cell}" => "순환 참조: {cell}",
"Width: {chars} ({pixels} pixels)" => "너비: {chars} ({pixels} 픽셀)",
"Height: {points} ({pixels} pixels)" => "높이: {points} ({pixels} 픽셀)",
"Picture in cell" => "셀 안의 그림",
"Picture: {alt}" => "그림: {alt}",
"Format Control: {name}" => "컨트롤 서식: {name}",
"Error at character {position}: {message}" => "{position}번째 문자에서 오류: {message}",
"Macro definitions are not supported in equations." => "수식에서는 매크로 정의가 지원되지 않습니다.",
"A % can't be combined with a link in an equation." => "수식에서 %를 링크와 함께 사용할 수 없습니다.",
"Equations can nest at most 32 levels deep." => "수식은 최대 32단계까지 중첩할 수 있습니다.",
"An equation can be at most 4096 bytes long." => "수식은 최대 4096바이트까지 입력할 수 있습니다.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"수식에는 최대 2500개의 행렬 셀(행 수 × 가장 넓은 행)을 넣을 수 있습니다."
}
"This equation is too large to draw." => "이 수식은 너무 커서 그릴 수 없습니다.",
"This equation could not be laid out." => "이 수식을 배치할 수 없습니다.",
"Saved macro “{name}” ({steps} step)" => "매크로 '{name}'을(를) 저장했습니다({steps}단계)",
"Saved macro “{name}” ({steps} steps)" => "매크로 '{name}'을(를) 저장했습니다({steps}단계)",
"without {key}: another macro took it while recording" => "{key} 없음: 기록 중에 다른 매크로가 사용했습니다",
"Recording stopped" => "기록이 중지되었습니다",
"Macro “{name}” stopped: {message}" => "매크로 '{name}'이(가) 중지되었습니다: {message}",
"Ran macro “{name}” ({steps} step)" => "매크로 '{name}'을(를) 실행했습니다({steps}단계)",
"Ran macro “{name}” ({steps} steps)" => "매크로 '{name}'을(를) 실행했습니다({steps}단계)",
"Average" => "평균",
"Count" => "개수",
"Sum" => "합계",
"Goal Seeking found a solution: {value}" => "목표값 찾기에서 해를 찾았습니다: {value}",
"Sheets: {sheets}" => "시트: {sheets}",
"Hidden: {sheets}" => "숨김: {sheets}",
"Double superscript" => "위 첨자가 중복되었습니다",
"Double subscript" => "아래 첨자가 중복되었습니다",
"Extra }" => "불필요한 } 이(가) 있습니다",
"Unexpected end of input in a macro argument" => "매크로 인수 안에서 입력이 끝났습니다",
"Expected \\right after \\left" => "\\left 뒤에 \\right 가 필요합니다",
"\\middle must be within \\left and \\right" => "\\middle 은 \\left 와 \\right 사이에 있어야 합니다",
"Invalid environment name" => "환경 이름이 잘못되었습니다",
"Expected \\end after environment body" => "환경 본문 뒤에 \\end 가 필요합니다",
"Expected URL" => "URL이 필요합니다",
"\\tag requires an argument" => "\\tag 에는 인수가 필요합니다",
"only one infix operator per group" => "그룹당 중위 연산자는 하나만 사용할 수 있습니다",
"Expected color token" => "색이 필요합니다",
"Expected size for \\raisebox" => "\\raisebox 에는 크기가 필요합니다",
"Expected size for \\rule width" => "\\rule 너비에는 크기가 필요합니다",
"Expected size for \\rule height" => "\\rule 높이에는 크기가 필요합니다",
"Cannot use both \\tag and \\nonumber in the same row" => "같은 행에서 \\tag 와 \\nonumber 를 함께 사용할 수 없습니다",
"Multiple \\tag in a row" => "한 행에 \\tag 가 여러 개 있습니다",
"\\tag must appear at the end of the row after the equation body" => "\\tag 는 행 끝, 수식 본문 뒤에 있어야 합니다",
"Multiple \\nonumber in a row" => "한 행에 \\nonumber 가 여러 개 있습니다",
"\\nonumber must appear at the end of the row" => "\\nonumber 는 행 끝에 있어야 합니다",
"Too many tab characters: &" => "탭 문자가 너무 많습니다: &",
"Invalid column alignment for array" => "array 의 열 맞춤이 잘못되었습니다",
"Expected column alignment character" => "열 맞춤 문자가 필요합니다",
"Expected l or c or r" => "l, c 또는 r 이 필요합니다",
"Expected ]" => "] 이(가) 필요합니다",
"Unexpected end of CD row after @" => "@ 뒤에서 CD 행이 끝났습니다",
"Invalid column alignment for subarray" => "subarray 의 열 맞춤이 잘못되었습니다",
"{subarray} can contain only one column" => "{subarray} 에는 열을 하나만 넣을 수 있습니다",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"prooftree 에 뒤따르는 추론 명령이 없는 \\LeftLabel 또는 \\RightLabel 이 있습니다"
}
"Recursion limit exceeded" => "재귀 한도를 초과했습니다",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"매크로 확장이 너무 많습니다: 무한 루프이거나 maxExpand 설정이 너무 작습니다"
}
"Expected raw style for \\htmlStyle" => "\\htmlStyle 에는 원시 스타일이 필요합니다",
"\\verb assertion failed" => "\\verb 검사에 실패했습니다",
"Undefined control sequence: {name}" => "정의되지 않은 제어 시퀀스: {name}",
"Expected '{expected}', got '{got}'" => "'{expected}' 이(가) 필요하지만 '{got}' 이(가) 있습니다",
"Expected group after '{symbol}'" => "'{symbol}' 뒤에 그룹이 필요합니다",
"Expected delimiter as argument to '{function}'" => "'{function}' 의 인수로 구분 기호가 필요합니다",
"Expected group as argument to '{function}'" => "'{function}' 의 인수로 그룹이 필요합니다",
"Got function '{function}' with no arguments as superscript" => "인수 없는 함수 '{function}' 이(가) 위 첨자로 사용되었습니다",
"Got function '{function}' with no arguments as subscript" => "인수 없는 함수 '{function}' 이(가) 아래 첨자로 사용되었습니다",
"Got function '{function}' with no arguments as argument to '{parent}'" => {
"인수 없는 함수 '{function}' 이(가) '{parent}' 의 인수로 사용되었습니다"
}
"Got function '{function}' with no arguments as \\tag" => "인수 없는 함수 '{function}' 이(가) \\tag 로 사용되었습니다",
"Can't use function '{function}' in text mode" => "함수 '{function}' 은(는) 텍스트 모드에서 사용할 수 없습니다",
"Can't use function '{function}' in math mode" => "함수 '{function}' 은(는) 수식 모드에서 사용할 수 없습니다",
"Invalid color: '{color}'" => "잘못된 색: '{color}'",
"Invalid size: '{size}'" => "잘못된 크기: '{size}'",
"Invalid unit: '{unit}'" => "잘못된 단위: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "'{function}' 뒤의 구분 기호 '{delimiter}' 이(가) 잘못되었습니다",
"Invalid delimiter type '{type}' after '{function}'" => "'{function}' 뒤의 구분 기호 유형 '{type}' 이(가) 잘못되었습니다",
"Invalid delimiter type '{type}'" => "구분 기호 유형 '{type}' 이(가) 잘못되었습니다",
"No such environment: {name}" => "알 수 없는 환경: {name}",
"Expected argument to \\begin{{name}}" => "\\begin{{name}} 에는 인수가 필요합니다",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "일치하지 않음: \\begin{{begin}} 이(가) \\end{{end}} 로 닫혔습니다",
"{command} valid only within array environment" => "{command} 은(는) array 환경 안에서만 사용할 수 있습니다",
"Mismatched {command}" => "짝이 없는 {command}",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "&, \\\\, \\cr 또는 \\end 이(가) 필요하지만 '{got}' 이(가) 있습니다",
"Unknown column alignment: {alignment}" => "알 수 없는 열 맞춤: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "한 행의 수식이 너무 많습니다: {expected}개여야 하지만 {got}개입니다",
"Unknown CD directive: @{directive}" => "알 수 없는 CD 지시문: @{directive}",
"Expected argument for {command}" => "{command} 에는 인수가 필요합니다",
"{command} needs {count} premise(s), but only {available} available" => "{command} 에는 전제가 {count}개 필요하지만 {available}개만 있습니다",
"{command} valid only as a supported bussproofs command within prooftree" => {
"{command} 은(는) prooftree 안에서 지원되는 bussproofs 명령으로만 사용할 수 있습니다"
}
"prooftree ended with {count} proof stack item(s), expected 1" => "prooftree 가 증명 스택에 항목 {count}개를 남기고 끝났습니다 (1개여야 함)",
"\\@char has non-numeric argument {argument}" => "\\@char 의 인수 {argument} 이(가) 숫자가 아닙니다",
"\\@char with invalid code point {code}" => "\\@char 의 코드 포인트 {code} 이(가) 잘못되었습니다",
"Invalid environment name character: {character}" => "환경 이름에 잘못된 문자가 있습니다: {character}",
_ => return None,
})
}
+130
View File
@@ -561,6 +561,136 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "Weergeven",
"Collapse dialog" => "Dialoogvenster samenvouwen",
"Expand dialog" => "Dialoogvenster uitvouwen",
"My list has headers" => "Mijn gegevens bevatten kopteksten",
"Sort by" => "Sorteren op",
"Then by" => "Vervolgens op",
"Cell Values" => "Celwaarden",
"Cell Color" => "Celkleur",
"A to Z" => "A tot Z",
"Z to A" => "Z tot A",
"Add Level" => "Niveau toevoegen",
"Delete Level" => "Niveau verwijderen",
"Copy Level" => "Niveau kopiëren",
"Move Up" => "Omhoog",
"Move Down" => "Omlaag",
"Order" => "Volgorde",
"Sort On" => "Sorteren op",
"Sort|Column" => "Kolom",
"Column {letters}" => "Kolom {letters}",
"Smallest to Largest" => "Van klein naar groot",
"Largest to Smallest" => "Van groot naar klein",
"Close the Sort dialog before switching or changing worksheets." => {
"Sluit het dialoogvenster Sorteren voordat u van blad wisselt of bladen wijzigt."
}
"Return to the original worksheet to sort, or cancel." => "Ga terug naar het oorspronkelijke blad om te sorteren, of annuleer.",
"Numerical Count" => "Numerieke telling",
"Minimum" => "Minimum",
"Maximum" => "Maximum",
"Circular References: {cell}" => "Kringverwijzingen: {cell}",
"Width: {chars} ({pixels} pixels)" => "Breedte: {chars} ({pixels} pixels)",
"Height: {points} ({pixels} pixels)" => "Hoogte: {points} ({pixels} pixels)",
"Picture in cell" => "Afbeelding in cel",
"Picture: {alt}" => "Afbeelding: {alt}",
"Format Control: {name}" => "Besturingselement opmaken: {name}",
"Error at character {position}: {message}" => "Fout bij teken {position}: {message}",
"Macro definitions are not supported in equations." => "Macrodefinities worden niet ondersteund in vergelijkingen.",
"A % can't be combined with a link in an equation." => "Een % kan niet worden gecombineerd met een koppeling in een vergelijking.",
"Equations can nest at most 32 levels deep." => "Vergelijkingen kunnen maximaal 32 niveaus diep worden genest.",
"An equation can be at most 4096 bytes long." => "Een vergelijking kan maximaal 4096 bytes lang zijn.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"Een vergelijking kan maximaal 2500 matrixcellen hebben (rijen maal de breedste rij)."
}
"This equation is too large to draw." => "Deze vergelijking is te groot om te tekenen.",
"This equation could not be laid out." => "Deze vergelijking kan niet worden opgemaakt.",
"Saved macro “{name}” ({steps} step)" => "Macro ‘{name}’ opgeslagen ({steps} stap)",
"Saved macro “{name}” ({steps} steps)" => "Macro ‘{name}’ opgeslagen ({steps} stappen)",
"without {key}: another macro took it while recording" => "zonder {key}: een andere macro heeft deze tijdens het opnemen overgenomen",
"Recording stopped" => "Opname gestopt",
"Macro “{name}” stopped: {message}" => "Macro ‘{name}’ gestopt: {message}",
"Ran macro “{name}” ({steps} step)" => "Macro ‘{name}’ uitgevoerd ({steps} stap)",
"Ran macro “{name}” ({steps} steps)" => "Macro ‘{name}’ uitgevoerd ({steps} stappen)",
"Average" => "Gemiddelde",
"Count" => "Aantal",
"Sum" => "Som",
"Goal Seeking found a solution: {value}" => "Doelzoeken heeft een oplossing gevonden: {value}",
"Sheets: {sheets}" => "Bladen: {sheets}",
"Hidden: {sheets}" => "Verborgen: {sheets}",
"Double superscript" => "Dubbele superscript",
"Double subscript" => "Dubbele subscript",
"Extra }" => "Overbodige }",
"Unexpected end of input in a macro argument" => "Onverwacht einde van de invoer in een macroargument",
"Expected \\right after \\left" => "\\right verwacht na \\left",
"\\middle must be within \\left and \\right" => "\\middle moet tussen \\left en \\right staan",
"Invalid environment name" => "Ongeldige omgevingsnaam",
"Expected \\end after environment body" => "\\end verwacht na de inhoud van de omgeving",
"Expected URL" => "URL verwacht",
"\\tag requires an argument" => "\\tag vereist een argument",
"only one infix operator per group" => "Slechts één infix-operator per groep",
"Expected color token" => "Kleur verwacht",
"Expected size for \\raisebox" => "Grootte verwacht voor \\raisebox",
"Expected size for \\rule width" => "Grootte verwacht voor de breedte van \\rule",
"Expected size for \\rule height" => "Grootte verwacht voor de hoogte van \\rule",
"Cannot use both \\tag and \\nonumber in the same row" => "\\tag en \\nonumber kunnen niet in dezelfde rij staan",
"Multiple \\tag in a row" => "Meerdere \\tag in een rij",
"\\tag must appear at the end of the row after the equation body" => "\\tag moet aan het einde van de rij na de vergelijking staan",
"Multiple \\nonumber in a row" => "Meerdere \\nonumber in een rij",
"\\nonumber must appear at the end of the row" => "\\nonumber moet aan het einde van de rij staan",
"Too many tab characters: &" => "Te veel tabtekens: &",
"Invalid column alignment for array" => "Ongeldige kolomuitlijning voor array",
"Expected column alignment character" => "Teken voor kolomuitlijning verwacht",
"Expected l or c or r" => "l, c of r verwacht",
"Expected ]" => "] verwacht",
"Unexpected end of CD row after @" => "Onverwacht einde van de CD-rij na @",
"Invalid column alignment for subarray" => "Ongeldige kolomuitlijning voor subarray",
"{subarray} can contain only one column" => "{subarray} kan maar één kolom bevatten",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"prooftree heeft een \\LeftLabel of \\RightLabel zonder volgende afleidingsopdracht"
}
"Recursion limit exceeded" => "Recursielimiet overschreden",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"Te veel macro-uitbreidingen: oneindige lus of maxExpand-instelling te laag"
}
"Expected raw style for \\htmlStyle" => "Onbewerkte stijl verwacht voor \\htmlStyle",
"\\verb assertion failed" => "Controle van \\verb mislukt",
"Undefined control sequence: {name}" => "Onbekende besturingsreeks: {name}",
"Expected '{expected}', got '{got}'" => "'{expected}' verwacht, '{got}' gevonden",
"Expected group after '{symbol}'" => "Groep verwacht na '{symbol}'",
"Expected delimiter as argument to '{function}'" => "Scheidingsteken verwacht als argument van '{function}'",
"Expected group as argument to '{function}'" => "Groep verwacht als argument van '{function}'",
"Got function '{function}' with no arguments as superscript" => "Functie '{function}' zonder argumenten gebruikt als superscript",
"Got function '{function}' with no arguments as subscript" => "Functie '{function}' zonder argumenten gebruikt als subscript",
"Got function '{function}' with no arguments as argument to '{parent}'" => {
"Functie '{function}' zonder argumenten gebruikt als argument van '{parent}'"
}
"Got function '{function}' with no arguments as \\tag" => "Functie '{function}' zonder argumenten gebruikt als \\tag",
"Can't use function '{function}' in text mode" => "Functie '{function}' kan niet in tekstmodus worden gebruikt",
"Can't use function '{function}' in math mode" => "Functie '{function}' kan niet in wiskundemodus worden gebruikt",
"Invalid color: '{color}'" => "Ongeldige kleur: '{color}'",
"Invalid size: '{size}'" => "Ongeldige grootte: '{size}'",
"Invalid unit: '{unit}'" => "Ongeldige eenheid: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "Ongeldig scheidingsteken '{delimiter}' na '{function}'",
"Invalid delimiter type '{type}' after '{function}'" => "Ongeldig type scheidingsteken '{type}' na '{function}'",
"Invalid delimiter type '{type}'" => "Ongeldig type scheidingsteken '{type}'",
"No such environment: {name}" => "Onbekende omgeving: {name}",
"Expected argument to \\begin{{name}}" => "Argument verwacht voor \\begin{{name}}",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "Komt niet overeen: \\begin{{begin}} afgesloten met \\end{{end}}",
"{command} valid only within array environment" => "{command} is alleen geldig binnen een array-omgeving",
"Mismatched {command}" => "{command} zonder tegenhanger",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "&, \\\\, \\cr of \\end verwacht, '{got}' gevonden",
"Unknown column alignment: {alignment}" => "Onbekende kolomuitlijning: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "Te veel formules in een rij: {expected} verwacht, {got} gevonden",
"Unknown CD directive: @{directive}" => "Onbekende CD-opdracht: @{directive}",
"Expected argument for {command}" => "Argument verwacht voor {command}",
"{command} needs {count} premise(s), but only {available} available" => {
"{command} heeft {count} premisse(s) nodig, maar er zijn er maar {available}"
}
"{command} valid only as a supported bussproofs command within prooftree" => {
"{command} is in prooftree alleen geldig als ondersteunde bussproofs-opdracht"
}
"prooftree ended with {count} proof stack item(s), expected 1" => "prooftree eindigde met {count} item(s) op de bewijsstapel, 1 verwacht",
"\\@char has non-numeric argument {argument}" => "\\@char heeft een niet-numeriek argument {argument}",
"\\@char with invalid code point {code}" => "\\@char met ongeldig codepunt {code}",
"Invalid environment name character: {character}" => "Ongeldig teken in de omgevingsnaam: {character}",
_ => return None,
})
}
+119 -1
View File
@@ -761,7 +761,21 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Cell Color" => "Kolor komórki",
"A to Z" => "Od A do Z",
"Z to A" => "Od Z do A",
"+ Add Level" => "+ Dodaj poziom",
"Add Level" => "Dodaj poziom",
"Delete Level" => "Usuń poziom",
"Copy Level" => "Kopiuj poziom",
"Move Up" => "Przesuń w górę",
"Move Down" => "Przesuń w dół",
"Order" => "Kolejność",
"Sort On" => "Sortuj na podstawie",
"Sort|Column" => "Kolumna",
"Column {letters}" => "Kolumna {letters}",
"Smallest to Largest" => "Od najmniejszych do największych",
"Largest to Smallest" => "Od największych do najmniejszych",
"Close the Sort dialog before switching or changing worksheets." => {
"Zamknij okno dialogowe Sortowanie przed przełączeniem lub zmianą arkuszy."
}
"Return to the original worksheet to sort, or cancel." => "Wróć do oryginalnego arkusza, aby posortować, lub anuluj.",
"New…" => "Nowy…",
"Edit…" => "Edytuj…",
"Name" => "Nazwa",
@@ -1009,6 +1023,110 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "Pokaż",
"Collapse dialog" => "Zwiń okno dialogowe",
"Expand dialog" => "Rozwiń okno dialogowe",
"Numerical Count" => "Liczba wartości liczbowych",
"Minimum" => "Minimum",
"Maximum" => "Maksimum",
"Circular References: {cell}" => "Odwołania cykliczne: {cell}",
"Width: {chars} ({pixels} pixels)" => "Szerokość: {chars} (pikseli: {pixels})",
"Height: {points} ({pixels} pixels)" => "Wysokość: {points} (pikseli: {pixels})",
"Picture in cell" => "Obraz w komórce",
"Picture: {alt}" => "Obraz: {alt}",
"Format Control: {name}" => "Formatuj formant: {name}",
"Error at character {position}: {message}" => "Błąd przy znaku {position}: {message}",
"Macro definitions are not supported in equations." => "Definicje makr nie są obsługiwane w równaniach.",
"A % can't be combined with a link in an equation." => "Znaku % nie można łączyć z linkiem w równaniu.",
"Equations can nest at most 32 levels deep." => "Równania mogą być zagnieżdżone na co najwyżej 32 poziomach.",
"An equation can be at most 4096 bytes long." => "Równanie może mieć co najwyżej 4096 bajtów.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"Równanie może mieć co najwyżej 2500 komórek macierzy (wiersze razy najszerszy wiersz)."
}
"This equation is too large to draw." => "To równanie jest za duże, aby je narysować.",
"This equation could not be laid out." => "Nie można złożyć tego równania.",
"Saved macro “{name}” ({steps} step)" => "Zapisano makro „{name}” ({steps} krok)",
"Saved macro “{name}” ({steps} steps)" => "Zapisano makro „{name}” (liczba kroków: {steps})",
"without {key}: another macro took it while recording" => "bez {key}: inne makro zajęło go podczas nagrywania",
"Recording stopped" => "Nagrywanie zatrzymane",
"Macro “{name}” stopped: {message}" => "Makro „{name}” zatrzymane: {message}",
"Ran macro “{name}” ({steps} step)" => "Uruchomiono makro „{name}” ({steps} krok)",
"Ran macro “{name}” ({steps} steps)" => "Uruchomiono makro „{name}” (liczba kroków: {steps})",
"Double superscript" => "Podwójny indeks górny",
"Double subscript" => "Podwójny indeks dolny",
"Extra }" => "Nadmiarowy }",
"Unexpected end of input in a macro argument" => "Nieoczekiwany koniec danych w argumencie makra",
"Expected \\right after \\left" => "Oczekiwano \\right po \\left",
"\\middle must be within \\left and \\right" => "\\middle musi być między \\left a \\right",
"Invalid environment name" => "Nieprawidłowa nazwa środowiska",
"Expected \\end after environment body" => "Oczekiwano \\end po treści środowiska",
"Expected URL" => "Oczekiwano adresu URL",
"\\tag requires an argument" => "\\tag wymaga argumentu",
"only one infix operator per group" => "Tylko jeden operator wrostkowy na grupę",
"Expected color token" => "Oczekiwano koloru",
"Expected size for \\raisebox" => "Oczekiwano rozmiaru dla \\raisebox",
"Expected size for \\rule width" => "Oczekiwano rozmiaru dla szerokości \\rule",
"Expected size for \\rule height" => "Oczekiwano rozmiaru dla wysokości \\rule",
"Cannot use both \\tag and \\nonumber in the same row" => "Nie można użyć \\tag i \\nonumber w tym samym wierszu",
"Multiple \\tag in a row" => "Wiele \\tag w jednym wierszu",
"\\tag must appear at the end of the row after the equation body" => "\\tag musi stać na końcu wiersza, po treści równania",
"Multiple \\nonumber in a row" => "Wiele \\nonumber w jednym wierszu",
"\\nonumber must appear at the end of the row" => "\\nonumber musi stać na końcu wiersza",
"Too many tab characters: &" => "Za dużo znaków tabulacji: &",
"Invalid column alignment for array" => "Nieprawidłowe wyrównanie kolumn dla array",
"Expected column alignment character" => "Oczekiwano znaku wyrównania kolumny",
"Expected l or c or r" => "Oczekiwano l, c lub r",
"Expected ]" => "Oczekiwano ]",
"Unexpected end of CD row after @" => "Nieoczekiwany koniec wiersza CD po @",
"Invalid column alignment for subarray" => "Nieprawidłowe wyrównanie kolumn dla subarray",
"{subarray} can contain only one column" => "{subarray} może zawierać tylko jedną kolumnę",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"prooftree zawiera \\LeftLabel lub \\RightLabel bez następującego polecenia wnioskowania"
}
"Recursion limit exceeded" => "Przekroczono limit rekurencji",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"Za dużo rozwinięć makr: nieskończona pętla lub zbyt niskie ustawienie maxExpand"
}
"Expected raw style for \\htmlStyle" => "Oczekiwano surowego stylu dla \\htmlStyle",
"\\verb assertion failed" => "Sprawdzenie \\verb nie powiodło się",
"Undefined control sequence: {name}" => "Niezdefiniowana sekwencja sterująca: {name}",
"Expected '{expected}', got '{got}'" => "Oczekiwano '{expected}', napotkano '{got}'",
"Expected group after '{symbol}'" => "Oczekiwano grupy po '{symbol}'",
"Expected delimiter as argument to '{function}'" => "Oczekiwano ogranicznika jako argumentu '{function}'",
"Expected group as argument to '{function}'" => "Oczekiwano grupy jako argumentu '{function}'",
"Got function '{function}' with no arguments as superscript" => "Funkcja '{function}' bez argumentów użyta jako indeks górny",
"Got function '{function}' with no arguments as subscript" => "Funkcja '{function}' bez argumentów użyta jako indeks dolny",
"Got function '{function}' with no arguments as argument to '{parent}'" => {
"Funkcja '{function}' bez argumentów użyta jako argument '{parent}'"
}
"Got function '{function}' with no arguments as \\tag" => "Funkcja '{function}' bez argumentów użyta jako \\tag",
"Can't use function '{function}' in text mode" => "Funkcji '{function}' nie można użyć w trybie tekstowym",
"Can't use function '{function}' in math mode" => "Funkcji '{function}' nie można użyć w trybie matematycznym",
"Invalid color: '{color}'" => "Nieprawidłowy kolor: '{color}'",
"Invalid size: '{size}'" => "Nieprawidłowy rozmiar: '{size}'",
"Invalid unit: '{unit}'" => "Nieprawidłowa jednostka: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "Nieprawidłowy ogranicznik '{delimiter}' po '{function}'",
"Invalid delimiter type '{type}' after '{function}'" => "Nieprawidłowy typ ogranicznika '{type}' po '{function}'",
"Invalid delimiter type '{type}'" => "Nieprawidłowy typ ogranicznika '{type}'",
"No such environment: {name}" => "Nieznane środowisko: {name}",
"Expected argument to \\begin{{name}}" => "Oczekiwano argumentu dla \\begin{{name}}",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "Niezgodność: \\begin{{begin}} zamknięte przez \\end{{end}}",
"{command} valid only within array environment" => "{command} jest dozwolone tylko w środowisku array",
"Mismatched {command}" => "{command} bez pary",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "Oczekiwano &, \\\\, \\cr lub \\end, napotkano '{got}'",
"Unknown column alignment: {alignment}" => "Nieznane wyrównanie kolumny: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "Za dużo formuł w wierszu: oczekiwano {expected}, jest {got}",
"Unknown CD directive: @{directive}" => "Nieznana dyrektywa CD: @{directive}",
"Expected argument for {command}" => "Oczekiwano argumentu dla {command}",
"{command} needs {count} premise(s), but only {available} available" => {
"{command} wymaga {count} przesłanek, ale dostępnych jest tylko {available}"
}
"{command} valid only as a supported bussproofs command within prooftree" => {
"{command} jest dozwolone w prooftree tylko jako obsługiwane polecenie bussproofs"
}
"prooftree ended with {count} proof stack item(s), expected 1" => {
"prooftree zakończyło się z {count} elementami na stosie dowodu, oczekiwano 1"
}
"\\@char has non-numeric argument {argument}" => "\\@char ma nienumeryczny argument {argument}",
"\\@char with invalid code point {code}" => "\\@char z nieprawidłowym punktem kodowym {code}",
"Invalid environment name character: {character}" => "Nieprawidłowy znak w nazwie środowiska: {character}",
_ => return None,
})
}
+117 -1
View File
@@ -795,7 +795,21 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Cell Color" => "Cor da Célula",
"A to Z" => "De A a Z",
"Z to A" => "De Z a A",
"+ Add Level" => "+ Adicionar Nível",
"Add Level" => "Adicionar Nível",
"Delete Level" => "Excluir Nível",
"Copy Level" => "Copiar Nível",
"Move Up" => "Mover para Cima",
"Move Down" => "Mover para Baixo",
"Order" => "Ordem",
"Sort On" => "Classificar em",
"Sort|Column" => "Coluna",
"Column {letters}" => "Coluna {letters}",
"Smallest to Largest" => "Do Menor para o Maior",
"Largest to Smallest" => "Do Maior para o Menor",
"Close the Sort dialog before switching or changing worksheets." => {
"Feche a caixa de diálogo Classificar antes de alternar ou alterar planilhas."
}
"Return to the original worksheet to sort, or cancel." => "Volte para a planilha original para classificar ou cancele.",
"New…" => "Novo…",
"Edit…" => "Editar…",
"Name" => "Nome",
@@ -1027,6 +1041,108 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "Mostrar",
"Collapse dialog" => "Recolher caixa de diálogo",
"Expand dialog" => "Expandir caixa de diálogo",
"Numerical Count" => "Contagem Numérica",
"Minimum" => "Mínimo",
"Maximum" => "Máximo",
"Circular References: {cell}" => "Referências Circulares: {cell}",
"Width: {chars} ({pixels} pixels)" => "Largura: {chars} ({pixels} pixels)",
"Height: {points} ({pixels} pixels)" => "Altura: {points} ({pixels} pixels)",
"Picture in cell" => "Imagem na célula",
"Picture: {alt}" => "Imagem: {alt}",
"Format Control: {name}" => "Formatar Controle: {name}",
"Error at character {position}: {message}" => "Erro no caractere {position}: {message}",
"Macro definitions are not supported in equations." => "Definições de macro não são compatíveis com equações.",
"A % can't be combined with a link in an equation." => "Um % não pode ser combinado com um link em uma equação.",
"Equations can nest at most 32 levels deep." => "As equações podem ter no máximo 32 níveis de aninhamento.",
"An equation can be at most 4096 bytes long." => "Uma equação pode ter no máximo 4096 bytes.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"Uma equação pode ter no máximo 2500 células de matriz (linhas vezes a linha mais larga)."
}
"This equation is too large to draw." => "Esta equação é grande demais para ser desenhada.",
"This equation could not be laid out." => "Não foi possível diagramar esta equação.",
"Saved macro “{name}” ({steps} step)" => "Macro “{name}” salva ({steps} etapa)",
"Saved macro “{name}” ({steps} steps)" => "Macro “{name}” salva ({steps} etapas)",
"without {key}: another macro took it while recording" => "sem {key}: outra macro o usou durante a gravação",
"Recording stopped" => "Gravação interrompida",
"Macro “{name}” stopped: {message}" => "Macro “{name}” interrompida: {message}",
"Ran macro “{name}” ({steps} step)" => "Macro “{name}” executada ({steps} etapa)",
"Ran macro “{name}” ({steps} steps)" => "Macro “{name}” executada ({steps} etapas)",
"Double superscript" => "Sobrescrito duplo",
"Double subscript" => "Subscrito duplo",
"Extra }" => "} a mais",
"Unexpected end of input in a macro argument" => "Fim inesperado da entrada em um argumento de macro",
"Expected \\right after \\left" => "\\right esperado após \\left",
"\\middle must be within \\left and \\right" => "\\middle deve estar entre \\left e \\right",
"Invalid environment name" => "Nome de ambiente inválido",
"Expected \\end after environment body" => "\\end esperado após o corpo do ambiente",
"Expected URL" => "URL esperada",
"\\tag requires an argument" => "\\tag requer um argumento",
"only one infix operator per group" => "Apenas um operador infixo por grupo",
"Expected color token" => "Cor esperada",
"Expected size for \\raisebox" => "Tamanho esperado para \\raisebox",
"Expected size for \\rule width" => "Tamanho esperado para a largura de \\rule",
"Expected size for \\rule height" => "Tamanho esperado para a altura de \\rule",
"Cannot use both \\tag and \\nonumber in the same row" => "Não é possível usar \\tag e \\nonumber na mesma linha",
"Multiple \\tag in a row" => "Vários \\tag em uma linha",
"\\tag must appear at the end of the row after the equation body" => "\\tag deve aparecer no fim da linha, após o corpo da equação",
"Multiple \\nonumber in a row" => "Vários \\nonumber em uma linha",
"\\nonumber must appear at the end of the row" => "\\nonumber deve aparecer no fim da linha",
"Too many tab characters: &" => "Caracteres de tabulação demais: &",
"Invalid column alignment for array" => "Alinhamento de coluna inválido para array",
"Expected column alignment character" => "Caractere de alinhamento de coluna esperado",
"Expected l or c or r" => "l, c ou r esperado",
"Expected ]" => "] esperado",
"Unexpected end of CD row after @" => "Fim inesperado da linha CD após @",
"Invalid column alignment for subarray" => "Alinhamento de coluna inválido para subarray",
"{subarray} can contain only one column" => "{subarray} pode conter apenas uma coluna",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"prooftree tem um \\LeftLabel ou \\RightLabel sem um comando de inferência a seguir"
}
"Recursion limit exceeded" => "Limite de recursão excedido",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"Expansões de macro demais: laço infinito ou configuração maxExpand baixa demais"
}
"Expected raw style for \\htmlStyle" => "Estilo bruto esperado para \\htmlStyle",
"\\verb assertion failed" => "Falha na verificação de \\verb",
"Undefined control sequence: {name}" => "Sequência de controle não definida: {name}",
"Expected '{expected}', got '{got}'" => "'{expected}' esperado, '{got}' encontrado",
"Expected group after '{symbol}'" => "Grupo esperado após '{symbol}'",
"Expected delimiter as argument to '{function}'" => "Delimitador esperado como argumento de '{function}'",
"Expected group as argument to '{function}'" => "Grupo esperado como argumento de '{function}'",
"Got function '{function}' with no arguments as superscript" => "Função '{function}' sem argumentos usada como sobrescrito",
"Got function '{function}' with no arguments as subscript" => "Função '{function}' sem argumentos usada como subscrito",
"Got function '{function}' with no arguments as argument to '{parent}'" => {
"Função '{function}' sem argumentos usada como argumento de '{parent}'"
}
"Got function '{function}' with no arguments as \\tag" => "Função '{function}' sem argumentos usada como \\tag",
"Can't use function '{function}' in text mode" => "A função '{function}' não pode ser usada no modo de texto",
"Can't use function '{function}' in math mode" => "A função '{function}' não pode ser usada no modo matemático",
"Invalid color: '{color}'" => "Cor inválida: '{color}'",
"Invalid size: '{size}'" => "Tamanho inválido: '{size}'",
"Invalid unit: '{unit}'" => "Unidade inválida: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "Delimitador '{delimiter}' inválido após '{function}'",
"Invalid delimiter type '{type}' after '{function}'" => "Tipo de delimitador '{type}' inválido após '{function}'",
"Invalid delimiter type '{type}'" => "Tipo de delimitador '{type}' inválido",
"No such environment: {name}" => "Ambiente desconhecido: {name}",
"Expected argument to \\begin{{name}}" => "Argumento esperado para \\begin{{name}}",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "Não correspondem: \\begin{{begin}} fechado por \\end{{end}}",
"{command} valid only within array environment" => "{command} só é válido dentro de um ambiente array",
"Mismatched {command}" => "{command} sem correspondência",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "&, \\\\, \\cr ou \\end esperado, '{got}' encontrado",
"Unknown column alignment: {alignment}" => "Alinhamento de coluna desconhecido: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "Fórmulas demais em uma linha: {expected} esperadas, {got} encontradas",
"Unknown CD directive: @{directive}" => "Diretiva CD desconhecida: @{directive}",
"Expected argument for {command}" => "Argumento esperado para {command}",
"{command} needs {count} premise(s), but only {available} available" => {
"{command} precisa de {count} premissa(s), mas só há {available} disponível(is)"
}
"{command} valid only as a supported bussproofs command within prooftree" => {
"{command} só é válido como comando bussproofs compatível dentro de prooftree"
}
"prooftree ended with {count} proof stack item(s), expected 1" => "prooftree terminou com {count} item(ns) na pilha de prova; esperado 1",
"\\@char has non-numeric argument {argument}" => "\\@char tem um argumento não numérico {argument}",
"\\@char with invalid code point {code}" => "\\@char com ponto de código inválido {code}",
"Invalid environment name character: {character}" => "Caractere inválido no nome do ambiente: {character}",
_ => return None,
})
}
File diff suppressed because it is too large Load Diff
+119 -1
View File
@@ -767,7 +767,21 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Cell Color" => "Culoare celulă",
"A to Z" => "De la A la Z",
"Z to A" => "De la Z la A",
"+ Add Level" => "+ Adăugare nivel",
"Add Level" => "Adăugare nivel",
"Delete Level" => "Ștergere nivel",
"Copy Level" => "Copiere nivel",
"Move Up" => "Mutare în sus",
"Move Down" => "Mutare în jos",
"Order" => "Ordine",
"Sort On" => "Sortare pe baza",
"Sort|Column" => "Coloană",
"Column {letters}" => "Coloană {letters}",
"Smallest to Largest" => "De la cel mai mic la cel mai mare",
"Largest to Smallest" => "De la cel mai mare la cel mai mic",
"Close the Sort dialog before switching or changing worksheets." => {
"Închideți caseta de dialog Sortare înainte de a comuta sau a modifica foile de lucru."
}
"Return to the original worksheet to sort, or cancel." => "Reveniți la foaia de lucru inițială pentru a sorta sau anulați.",
"New…" => "Nou…",
"Edit…" => "Editare…",
"Name" => "Nume",
@@ -1071,6 +1085,110 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "Afișare",
"Collapse dialog" => "Restrângere casetă de dialog",
"Expand dialog" => "Extindere casetă de dialog",
"Numerical Count" => "Numărare numerică",
"Minimum" => "Minim",
"Maximum" => "Maxim",
"Circular References: {cell}" => "Referințe circulare: {cell}",
"Width: {chars} ({pixels} pixels)" => "Lățime: {chars} ({pixels} pixeli)",
"Height: {points} ({pixels} pixels)" => "Înălțime: {points} ({pixels} pixeli)",
"Picture in cell" => "Imagine în celulă",
"Picture: {alt}" => "Imagine: {alt}",
"Format Control: {name}" => "Formatare control: {name}",
"Error at character {position}: {message}" => "Eroare la caracterul {position}: {message}",
"Macro definitions are not supported in equations." => "Definițiile de macrocomenzi nu sunt acceptate în ecuații.",
"A % can't be combined with a link in an equation." => "Un % nu poate fi combinat cu un link într-o ecuație.",
"Equations can nest at most 32 levels deep." => "Ecuațiile pot fi imbricate pe cel mult 32 de niveluri.",
"An equation can be at most 4096 bytes long." => "O ecuație poate avea cel mult 4096 de octeți.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"O ecuație poate avea cel mult 2500 de celule de matrice (rânduri înmulțite cu cel mai lat rând)."
}
"This equation is too large to draw." => "Această ecuație este prea mare pentru a fi desenată.",
"This equation could not be laid out." => "Această ecuație nu a putut fi așezată în pagină.",
"Saved macro “{name}” ({steps} step)" => "Macrocomanda „{name}” a fost salvată ({steps} pas)",
"Saved macro “{name}” ({steps} steps)" => "Macrocomanda „{name}” a fost salvată (pași: {steps})",
"without {key}: another macro took it while recording" => "fără {key}: altă macrocomandă l-a preluat în timpul înregistrării",
"Recording stopped" => "Înregistrare oprită",
"Macro “{name}” stopped: {message}" => "Macrocomanda „{name}” s-a oprit: {message}",
"Ran macro “{name}” ({steps} step)" => "Macrocomanda „{name}” a rulat ({steps} pas)",
"Ran macro “{name}” ({steps} steps)" => "Macrocomanda „{name}” a rulat (pași: {steps})",
"Double superscript" => "Exponent dublu",
"Double subscript" => "Indice dublu",
"Extra }" => "} în plus",
"Unexpected end of input in a macro argument" => "Sfârșit neașteptat al intrării într-un argument de macro",
"Expected \\right after \\left" => "Se aștepta \\right după \\left",
"\\middle must be within \\left and \\right" => "\\middle trebuie să fie între \\left și \\right",
"Invalid environment name" => "Nume de mediu nevalid",
"Expected \\end after environment body" => "Se aștepta \\end după conținutul mediului",
"Expected URL" => "Se aștepta un URL",
"\\tag requires an argument" => "\\tag necesită un argument",
"only one infix operator per group" => "Un singur operator infix per grup",
"Expected color token" => "Se aștepta o culoare",
"Expected size for \\raisebox" => "Se aștepta o dimensiune pentru \\raisebox",
"Expected size for \\rule width" => "Se aștepta o dimensiune pentru lățimea \\rule",
"Expected size for \\rule height" => "Se aștepta o dimensiune pentru înălțimea \\rule",
"Cannot use both \\tag and \\nonumber in the same row" => "\\tag și \\nonumber nu pot fi folosite pe același rând",
"Multiple \\tag in a row" => "Mai multe \\tag pe un rând",
"\\tag must appear at the end of the row after the equation body" => "\\tag trebuie să fie la sfârșitul rândului, după corpul ecuației",
"Multiple \\nonumber in a row" => "Mai multe \\nonumber pe un rând",
"\\nonumber must appear at the end of the row" => "\\nonumber trebuie să fie la sfârșitul rândului",
"Too many tab characters: &" => "Prea multe caractere de tabulare: &",
"Invalid column alignment for array" => "Aliniere de coloană nevalidă pentru array",
"Expected column alignment character" => "Se aștepta un caracter de aliniere a coloanei",
"Expected l or c or r" => "Se aștepta l, c sau r",
"Expected ]" => "Se aștepta ]",
"Unexpected end of CD row after @" => "Sfârșit neașteptat al rândului CD după @",
"Invalid column alignment for subarray" => "Aliniere de coloană nevalidă pentru subarray",
"{subarray} can contain only one column" => "{subarray} poate conține o singură coloană",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"prooftree are un \\LeftLabel sau \\RightLabel fără o comandă de inferență după el"
}
"Recursion limit exceeded" => "Limita de recursivitate a fost depășită",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"Prea multe expandări de macro: buclă infinită sau setarea maxExpand prea mică"
}
"Expected raw style for \\htmlStyle" => "Se aștepta un stil brut pentru \\htmlStyle",
"\\verb assertion failed" => "Verificarea \\verb a eșuat",
"Undefined control sequence: {name}" => "Secvență de control nedefinită: {name}",
"Expected '{expected}', got '{got}'" => "Se aștepta '{expected}', s-a găsit '{got}'",
"Expected group after '{symbol}'" => "Se aștepta un grup după '{symbol}'",
"Expected delimiter as argument to '{function}'" => "Se aștepta un delimitator ca argument pentru '{function}'",
"Expected group as argument to '{function}'" => "Se aștepta un grup ca argument pentru '{function}'",
"Got function '{function}' with no arguments as superscript" => "Funcția '{function}' fără argumente folosită ca exponent",
"Got function '{function}' with no arguments as subscript" => "Funcția '{function}' fără argumente folosită ca indice",
"Got function '{function}' with no arguments as argument to '{parent}'" => {
"Funcția '{function}' fără argumente folosită ca argument pentru '{parent}'"
}
"Got function '{function}' with no arguments as \\tag" => "Funcția '{function}' fără argumente folosită ca \\tag",
"Can't use function '{function}' in text mode" => "Funcția '{function}' nu poate fi folosită în modul text",
"Can't use function '{function}' in math mode" => "Funcția '{function}' nu poate fi folosită în modul matematic",
"Invalid color: '{color}'" => "Culoare nevalidă: '{color}'",
"Invalid size: '{size}'" => "Dimensiune nevalidă: '{size}'",
"Invalid unit: '{unit}'" => "Unitate nevalidă: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "Delimitator '{delimiter}' nevalid după '{function}'",
"Invalid delimiter type '{type}' after '{function}'" => "Tip de delimitator '{type}' nevalid după '{function}'",
"Invalid delimiter type '{type}'" => "Tip de delimitator '{type}' nevalid",
"No such environment: {name}" => "Mediu necunoscut: {name}",
"Expected argument to \\begin{{name}}" => "Se aștepta un argument pentru \\begin{{name}}",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "Nepotrivire: \\begin{{begin}} închis de \\end{{end}}",
"{command} valid only within array environment" => "{command} este valid doar într-un mediu array",
"Mismatched {command}" => "{command} fără pereche",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "Se aștepta &, \\\\, \\cr sau \\end, s-a găsit '{got}'",
"Unknown column alignment: {alignment}" => "Aliniere de coloană necunoscută: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "Prea multe formule pe un rând: se așteptau {expected}, s-au găsit {got}",
"Unknown CD directive: @{directive}" => "Directivă CD necunoscută: @{directive}",
"Expected argument for {command}" => "Se aștepta un argument pentru {command}",
"{command} needs {count} premise(s), but only {available} available" => {
"{command} necesită {count} premisă(e), dar sunt disponibile doar {available}"
}
"{command} valid only as a supported bussproofs command within prooftree" => {
"{command} este valid doar ca o comandă bussproofs acceptată în prooftree"
}
"prooftree ended with {count} proof stack item(s), expected 1" => {
"prooftree s-a încheiat cu {count} element(e) în stiva de demonstrație, se aștepta 1"
}
"\\@char has non-numeric argument {argument}" => "\\@char are un argument nenumeric {argument}",
"\\@char with invalid code point {code}" => "\\@char cu punct de cod nevalid {code}",
"Invalid environment name character: {character}" => "Caracter nevalid în numele mediului: {character}",
_ => return None,
})
}
+132
View File
@@ -494,6 +494,138 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "Показать",
"Collapse dialog" => "Свернуть диалоговое окно",
"Expand dialog" => "Развернуть диалоговое окно",
"My list has headers" => "Мои данные содержат заголовки",
"Sort by" => "Сортировать по",
"Then by" => "Затем по",
"Cell Values" => "Значения ячеек",
"Cell Color" => "Цвет ячейки",
"A to Z" => "От А до Я",
"Z to A" => "От Я до А",
"Add Level" => "Добавить уровень",
"Delete Level" => "Удалить уровень",
"Copy Level" => "Копировать уровень",
"Move Up" => "Вверх",
"Move Down" => "Вниз",
"Order" => "Порядок",
"Sort On" => "Сортировка",
"Sort|Column" => "Столбец",
"Column {letters}" => "Столбец {letters}",
"Smallest to Largest" => "От наименьшего к наибольшему",
"Largest to Smallest" => "От наибольшего к наименьшему",
"Close the Sort dialog before switching or changing worksheets." => {
"Закройте диалоговое окно «Сортировка», прежде чем переключать или изменять листы."
}
"Return to the original worksheet to sort, or cancel." => "Вернитесь на исходный лист, чтобы выполнить сортировку, или отмените действие.",
"Numerical Count" => "Количество чисел",
"Minimum" => "Минимум",
"Maximum" => "Максимум",
"Circular References: {cell}" => "Циклические ссылки: {cell}",
"Width: {chars} ({pixels} pixels)" => "Ширина: {chars} (пикселей: {pixels})",
"Height: {points} ({pixels} pixels)" => "Высота: {points} (пикселей: {pixels})",
"Picture in cell" => "Изображение в ячейке",
"Picture: {alt}" => "Изображение: {alt}",
"Format Control: {name}" => "Формат элемента управления: {name}",
"Error at character {position}: {message}" => "Ошибка в символе {position}: {message}",
"Macro definitions are not supported in equations." => "Определения макросов в формулах не поддерживаются.",
"A % can't be combined with a link in an equation." => "Знак % нельзя сочетать со ссылкой в формуле.",
"Equations can nest at most 32 levels deep." => "Формулы могут иметь не более 32 уровней вложенности.",
"An equation can be at most 4096 bytes long." => "Длина формулы не может превышать 4096 байт.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"Формула может содержать не более 2500 ячеек матрицы (строки, умноженные на самую широкую строку)."
}
"This equation is too large to draw." => "Эта формула слишком велика для отрисовки.",
"This equation could not be laid out." => "Не удалось построить эту формулу.",
"Saved macro “{name}” ({steps} step)" => "Макрос «{name}» сохранён ({steps} шаг)",
"Saved macro “{name}” ({steps} steps)" => "Макрос «{name}» сохранён (шагов: {steps})",
"without {key}: another macro took it while recording" => "без {key}: во время записи его занял другой макрос",
"Recording stopped" => "Запись остановлена",
"Macro “{name}” stopped: {message}" => "Макрос «{name}» остановлен: {message}",
"Ran macro “{name}” ({steps} step)" => "Макрос «{name}» выполнен ({steps} шаг)",
"Ran macro “{name}” ({steps} steps)" => "Макрос «{name}» выполнен (шагов: {steps})",
"Average" => "Среднее",
"Count" => "Количество",
"Sum" => "Сумма",
"Goal Seeking found a solution: {value}" => "Подбор параметра нашёл решение: {value}",
"Sheets: {sheets}" => "Листы: {sheets}",
"Hidden: {sheets}" => "Скрытые: {sheets}",
"Double superscript" => "Двойной верхний индекс",
"Double subscript" => "Двойной нижний индекс",
"Extra }" => "Лишняя }",
"Unexpected end of input in a macro argument" => "Неожиданный конец ввода в аргументе макроса",
"Expected \\right after \\left" => "После \\left ожидается \\right",
"\\middle must be within \\left and \\right" => "\\middle должен стоять между \\left и \\right",
"Invalid environment name" => "Недопустимое имя окружения",
"Expected \\end after environment body" => "После содержимого окружения ожидается \\end",
"Expected URL" => "Ожидается URL-адрес",
"\\tag requires an argument" => "Для \\tag требуется аргумент",
"only one infix operator per group" => "В группе допускается только один инфиксный оператор",
"Expected color token" => "Ожидается цвет",
"Expected size for \\raisebox" => "Для \\raisebox ожидается размер",
"Expected size for \\rule width" => "Для ширины \\rule ожидается размер",
"Expected size for \\rule height" => "Для высоты \\rule ожидается размер",
"Cannot use both \\tag and \\nonumber in the same row" => "Нельзя использовать \\tag и \\nonumber в одной строке",
"Multiple \\tag in a row" => "Несколько \\tag в одной строке",
"\\tag must appear at the end of the row after the equation body" => "\\tag должен стоять в конце строки после формулы",
"Multiple \\nonumber in a row" => "Несколько \\nonumber в одной строке",
"\\nonumber must appear at the end of the row" => "\\nonumber должен стоять в конце строки",
"Too many tab characters: &" => "Слишком много символов табуляции: &",
"Invalid column alignment for array" => "Недопустимое выравнивание столбцов для array",
"Expected column alignment character" => "Ожидается символ выравнивания столбца",
"Expected l or c or r" => "Ожидается l, c или r",
"Expected ]" => "Ожидается ]",
"Unexpected end of CD row after @" => "Неожиданный конец строки CD после @",
"Invalid column alignment for subarray" => "Недопустимое выравнивание столбцов для subarray",
"{subarray} can contain only one column" => "{subarray} может содержать только один столбец",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"В prooftree есть \\LeftLabel или \\RightLabel без последующей команды вывода"
}
"Recursion limit exceeded" => "Превышен предел рекурсии",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"Слишком много раскрытий макросов: бесконечный цикл или слишком малое значение maxExpand"
}
"Expected raw style for \\htmlStyle" => "Для \\htmlStyle ожидается необработанный стиль",
"\\verb assertion failed" => "Проверка \\verb не пройдена",
"Undefined control sequence: {name}" => "Неопределённая управляющая последовательность: {name}",
"Expected '{expected}', got '{got}'" => "Ожидается '{expected}', получено '{got}'",
"Expected group after '{symbol}'" => "После '{symbol}' ожидается группа",
"Expected delimiter as argument to '{function}'" => "В качестве аргумента '{function}' ожидается разделитель",
"Expected group as argument to '{function}'" => "В качестве аргумента '{function}' ожидается группа",
"Got function '{function}' with no arguments as superscript" => "Функция '{function}' без аргументов использована как верхний индекс",
"Got function '{function}' with no arguments as subscript" => "Функция '{function}' без аргументов использована как нижний индекс",
"Got function '{function}' with no arguments as argument to '{parent}'" => {
"Функция '{function}' без аргументов использована как аргумент '{parent}'"
}
"Got function '{function}' with no arguments as \\tag" => "Функция '{function}' без аргументов использована как \\tag",
"Can't use function '{function}' in text mode" => "Функцию '{function}' нельзя использовать в текстовом режиме",
"Can't use function '{function}' in math mode" => "Функцию '{function}' нельзя использовать в математическом режиме",
"Invalid color: '{color}'" => "Недопустимый цвет: '{color}'",
"Invalid size: '{size}'" => "Недопустимый размер: '{size}'",
"Invalid unit: '{unit}'" => "Недопустимая единица: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "Недопустимый разделитель '{delimiter}' после '{function}'",
"Invalid delimiter type '{type}' after '{function}'" => "Недопустимый тип разделителя '{type}' после '{function}'",
"Invalid delimiter type '{type}'" => "Недопустимый тип разделителя '{type}'",
"No such environment: {name}" => "Неизвестное окружение: {name}",
"Expected argument to \\begin{{name}}" => "Для \\begin{{name}} ожидается аргумент",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "Несоответствие: \\begin{{begin}} закрыт \\end{{end}}",
"{command} valid only within array environment" => "{command} допускается только в окружении array",
"Mismatched {command}" => "{command} без пары",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "Ожидается &, \\\\, \\cr или \\end, получено '{got}'",
"Unknown column alignment: {alignment}" => "Неизвестное выравнивание столбца: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "Слишком много формул в строке: ожидалось {expected}, получено {got}",
"Unknown CD directive: @{directive}" => "Неизвестная директива CD: @{directive}",
"Expected argument for {command}" => "Для {command} ожидается аргумент",
"{command} needs {count} premise(s), but only {available} available" => {
"Для {command} нужно посылок: {count}, но доступно только {available}"
}
"{command} valid only as a supported bussproofs command within prooftree" => {
"{command} допускается в prooftree только как поддерживаемая команда bussproofs"
}
"prooftree ended with {count} proof stack item(s), expected 1" => {
"prooftree завершился с элементами в стеке доказательства: {count}, ожидался 1"
}
"\\@char has non-numeric argument {argument}" => "У \\@char нечисловой аргумент {argument}",
"\\@char with invalid code point {code}" => "\\@char с недопустимой кодовой точкой {code}",
"Invalid environment name character: {character}" => "Недопустимый символ в имени окружения: {character}",
_ => return None,
})
}
+128
View File
@@ -481,6 +481,134 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "Prikaži",
"Collapse dialog" => "Skupi dijalog",
"Expand dialog" => "Proširi dijalog",
"My list has headers" => "Moji podaci imaju zaglavlja",
"Sort by" => "Sortiraj po",
"Then by" => "Zatim po",
"Cell Values" => "Vrednosti ćelija",
"Cell Color" => "Boja ćelije",
"A to Z" => "Od A do Z",
"Z to A" => "Od Z do A",
"Add Level" => "Dodaj nivo",
"Delete Level" => "Izbriši nivo",
"Copy Level" => "Kopiraj nivo",
"Move Up" => "Pomeri nagore",
"Move Down" => "Pomeri nadole",
"Order" => "Redosled",
"Sort On" => "Sortiraj po",
"Sort|Column" => "Kolona",
"Column {letters}" => "Kolona {letters}",
"Smallest to Largest" => "Od najmanjeg do najvećeg",
"Largest to Smallest" => "Od najvećeg do najmanjeg",
"Close the Sort dialog before switching or changing worksheets." => {
"Zatvorite dijalog Sortiranje pre nego što promenite ili izmenite radne listove."
}
"Return to the original worksheet to sort, or cancel." => "Vratite se na prvobitni radni list da biste sortirali, ili otkažite.",
"Numerical Count" => "Broj numeričkih vrednosti",
"Minimum" => "Minimum",
"Maximum" => "Maksimum",
"Circular References: {cell}" => "Kružne reference: {cell}",
"Width: {chars} ({pixels} pixels)" => "Širina: {chars} (piksela: {pixels})",
"Height: {points} ({pixels} pixels)" => "Visina: {points} (piksela: {pixels})",
"Picture in cell" => "Slika u ćeliji",
"Picture: {alt}" => "Slika: {alt}",
"Format Control: {name}" => "Oblikuj kontrolu: {name}",
"Error at character {position}: {message}" => "Greška kod znaka {position}: {message}",
"Macro definitions are not supported in equations." => "Definicije makroa nisu podržane u jednačinama.",
"A % can't be combined with a link in an equation." => "Znak % ne može da se kombinuje sa vezom u jednačini.",
"Equations can nest at most 32 levels deep." => "Jednačine mogu da budu ugnežđene najviše 32 nivoa.",
"An equation can be at most 4096 bytes long." => "Jednačina može da ima najviše 4096 bajtova.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"Jednačina može da ima najviše 2500 ćelija matrice (redovi puta najširi red)."
}
"This equation is too large to draw." => "Ova jednačina je prevelika za crtanje.",
"This equation could not be laid out." => "Ova jednačina nije mogla da se složi.",
"Saved macro “{name}” ({steps} step)" => "Makro „{name}“ je sačuvan ({steps} korak)",
"Saved macro “{name}” ({steps} steps)" => "Makro „{name}“ je sačuvan (broj koraka: {steps})",
"without {key}: another macro took it while recording" => "bez {key}: drugi makro ga je zauzeo tokom snimanja",
"Recording stopped" => "Snimanje je zaustavljeno",
"Macro “{name}” stopped: {message}" => "Makro „{name}“ je zaustavljen: {message}",
"Ran macro “{name}” ({steps} step)" => "Makro „{name}“ je pokrenut ({steps} korak)",
"Ran macro “{name}” ({steps} steps)" => "Makro „{name}“ je pokrenut (broj koraka: {steps})",
"Average" => "Prosek",
"Count" => "Broj",
"Sum" => "Zbir",
"Goal Seeking found a solution: {value}" => "Traženje cilja je pronašlo rešenje: {value}",
"Sheets: {sheets}" => "Listovi: {sheets}",
"Hidden: {sheets}" => "Skriveni: {sheets}",
"Double superscript" => "Dvostruki eksponent",
"Double subscript" => "Dvostruki indeks",
"Extra }" => "Višak }",
"Unexpected end of input in a macro argument" => "Neočekivan kraj unosa u argumentu makroa",
"Expected \\right after \\left" => "Posle \\left se očekuje \\right",
"\\middle must be within \\left and \\right" => "\\middle mora biti između \\left i \\right",
"Invalid environment name" => "Nevažeći naziv okruženja",
"Expected \\end after environment body" => "Posle sadržaja okruženja se očekuje \\end",
"Expected URL" => "Očekuje se URL adresa",
"\\tag requires an argument" => "\\tag zahteva argument",
"only one infix operator per group" => "Samo jedan infiksni operator po grupi",
"Expected color token" => "Očekuje se boja",
"Expected size for \\raisebox" => "Za \\raisebox se očekuje veličina",
"Expected size for \\rule width" => "Za širinu \\rule se očekuje veličina",
"Expected size for \\rule height" => "Za visinu \\rule se očekuje veličina",
"Cannot use both \\tag and \\nonumber in the same row" => "\\tag i \\nonumber ne mogu biti u istom redu",
"Multiple \\tag in a row" => "Više \\tag u jednom redu",
"\\tag must appear at the end of the row after the equation body" => "\\tag mora biti na kraju reda, posle sadržaja jednačine",
"Multiple \\nonumber in a row" => "Više \\nonumber u jednom redu",
"\\nonumber must appear at the end of the row" => "\\nonumber mora biti na kraju reda",
"Too many tab characters: &" => "Previše znakova tabulatora: &",
"Invalid column alignment for array" => "Nevažeće poravnanje kolona za array",
"Expected column alignment character" => "Očekuje se znak za poravnanje kolone",
"Expected l or c or r" => "Očekuje se l, c ili r",
"Expected ]" => "Očekuje se ]",
"Unexpected end of CD row after @" => "Neočekivan kraj CD reda posle @",
"Invalid column alignment for subarray" => "Nevažeće poravnanje kolona za subarray",
"{subarray} can contain only one column" => "{subarray} može da sadrži samo jednu kolonu",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"prooftree sadrži \\LeftLabel ili \\RightLabel bez naredne komande zaključivanja"
}
"Recursion limit exceeded" => "Prekoračeno ograničenje rekurzije",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"Previše proširenja makroa: beskonačna petlja ili premala vrednost postavke maxExpand"
}
"Expected raw style for \\htmlStyle" => "Za \\htmlStyle se očekuje neobrađeni stil",
"\\verb assertion failed" => "Provera za \\verb nije uspela",
"Undefined control sequence: {name}" => "Nedefinisana kontrolna sekvenca: {name}",
"Expected '{expected}', got '{got}'" => "Očekuje se '{expected}', pronađeno '{got}'",
"Expected group after '{symbol}'" => "Posle '{symbol}' se očekuje grupa",
"Expected delimiter as argument to '{function}'" => "Kao argument za '{function}' se očekuje graničnik",
"Expected group as argument to '{function}'" => "Kao argument za '{function}' se očekuje grupa",
"Got function '{function}' with no arguments as superscript" => "Funkcija '{function}' bez argumenata upotrebljena kao eksponent",
"Got function '{function}' with no arguments as subscript" => "Funkcija '{function}' bez argumenata upotrebljena kao indeks",
"Got function '{function}' with no arguments as argument to '{parent}'" => {
"Funkcija '{function}' bez argumenata upotrebljena kao argument za '{parent}'"
}
"Got function '{function}' with no arguments as \\tag" => "Funkcija '{function}' bez argumenata upotrebljena kao \\tag",
"Can't use function '{function}' in text mode" => "Funkcija '{function}' ne može da se koristi u tekstualnom režimu",
"Can't use function '{function}' in math mode" => "Funkcija '{function}' ne može da se koristi u matematičkom režimu",
"Invalid color: '{color}'" => "Nevažeća boja: '{color}'",
"Invalid size: '{size}'" => "Nevažeća veličina: '{size}'",
"Invalid unit: '{unit}'" => "Nevažeća jedinica: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "Nevažeći graničnik '{delimiter}' posle '{function}'",
"Invalid delimiter type '{type}' after '{function}'" => "Nevažeći tip graničnika '{type}' posle '{function}'",
"Invalid delimiter type '{type}'" => "Nevažeći tip graničnika '{type}'",
"No such environment: {name}" => "Nepoznato okruženje: {name}",
"Expected argument to \\begin{{name}}" => "Za \\begin{{name}} se očekuje argument",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "Neslaganje: \\begin{{begin}} zatvoreno sa \\end{{end}}",
"{command} valid only within array environment" => "{command} važi samo unutar okruženja array",
"Mismatched {command}" => "{command} bez para",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "Očekuje se &, \\\\, \\cr ili \\end, pronađeno '{got}'",
"Unknown column alignment: {alignment}" => "Nepoznato poravnanje kolone: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "Previše formula u redu: očekivano {expected}, pronađeno {got}",
"Unknown CD directive: @{directive}" => "Nepoznata CD direktiva: @{directive}",
"Expected argument for {command}" => "Za {command} se očekuje argument",
"{command} needs {count} premise(s), but only {available} available" => "{command} zahteva {count} premisa, ali je dostupno samo {available}",
"{command} valid only as a supported bussproofs command within prooftree" => {
"{command} u prooftree važi samo kao podržana bussproofs komanda"
}
"prooftree ended with {count} proof stack item(s), expected 1" => "prooftree se završio sa {count} stavki na steku dokaza, očekivana 1",
"\\@char has non-numeric argument {argument}" => "\\@char ima nenumerički argument {argument}",
"\\@char with invalid code point {code}" => "\\@char sa nevažećom kodnom tačkom {code}",
"Invalid environment name character: {character}" => "Nevažeći znak u nazivu okruženja: {character}",
_ => return None,
})
}
+130
View File
@@ -451,6 +451,136 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "Göster",
"Collapse dialog" => "İletişim kutusunu daralt",
"Expand dialog" => "İletişim kutusunu genişlet",
"My list has headers" => "Verilerimde üst bilgi var",
"Sort by" => "Sıralama ölçütü",
"Then by" => "Sonra",
"Cell Values" => "Hücre Değerleri",
"Cell Color" => "Hücre Rengi",
"A to Z" => "A'dan Z'ye",
"Z to A" => "Z'den A'ya",
"Add Level" => "Düzey Ekle",
"Delete Level" => "Düzeyi Sil",
"Copy Level" => "Düzeyi Kopyala",
"Move Up" => "Yukarı Taşı",
"Move Down" => "Aşağı Taşı",
"Order" => "Sıra",
"Sort On" => "Sıralama Ölçütü",
"Sort|Column" => "Sütun",
"Column {letters}" => "Sütun {letters}",
"Smallest to Largest" => "En Küçükten En Büyüğe",
"Largest to Smallest" => "En Büyükten En Küçüğe",
"Close the Sort dialog before switching or changing worksheets." => {
"Çalışma sayfaları arasında geçiş yapmadan veya sayfaları değiştirmeden önce Sırala iletişim kutusunu kapatın."
}
"Return to the original worksheet to sort, or cancel." => "Sıralamak için özgün çalışma sayfasına dönün veya iptal edin.",
"Numerical Count" => "Sayısal Sayım",
"Minimum" => "En Küçük",
"Maximum" => "En Büyük",
"Circular References: {cell}" => "Döngüsel Başvurular: {cell}",
"Width: {chars} ({pixels} pixels)" => "Genişlik: {chars} ({pixels} piksel)",
"Height: {points} ({pixels} pixels)" => "Yükseklik: {points} ({pixels} piksel)",
"Picture in cell" => "Hücredeki resim",
"Picture: {alt}" => "Resim: {alt}",
"Format Control: {name}" => "Denetimi Biçimlendir: {name}",
"Error at character {position}: {message}" => "{position}. karakterde hata: {message}",
"Macro definitions are not supported in equations." => "Denklemlerde makro tanımları desteklenmez.",
"A % can't be combined with a link in an equation." => "Bir denklemde % bir bağlantıyla birlikte kullanılamaz.",
"Equations can nest at most 32 levels deep." => "Denklemler en fazla 32 düzey iç içe olabilir.",
"An equation can be at most 4096 bytes long." => "Bir denklem en fazla 4096 bayt uzunluğunda olabilir.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"Bir denklemde en fazla 2500 matris hücresi olabilir (satır sayısı çarpı en geniş satır)."
}
"This equation is too large to draw." => "Bu denklem çizilemeyecek kadar büyük.",
"This equation could not be laid out." => "Bu denklem dizilemedi.",
"Saved macro “{name}” ({steps} step)" => "“{name}” makrosu kaydedildi ({steps} adım)",
"Saved macro “{name}” ({steps} steps)" => "“{name}” makrosu kaydedildi ({steps} adım)",
"without {key}: another macro took it while recording" => "{key} olmadan: kayıt sırasında başka bir makro aldı",
"Recording stopped" => "Kayıt durduruldu",
"Macro “{name}” stopped: {message}" => "“{name}” makrosu durdu: {message}",
"Ran macro “{name}” ({steps} step)" => "“{name}” makrosu çalıştırıldı ({steps} adım)",
"Ran macro “{name}” ({steps} steps)" => "“{name}” makrosu çalıştırıldı ({steps} adım)",
"Average" => "Ortalama",
"Count" => "Sayı",
"Sum" => "Toplam",
"Goal Seeking found a solution: {value}" => "Hedef Ara bir çözüm buldu: {value}",
"Sheets: {sheets}" => "Sayfalar: {sheets}",
"Hidden: {sheets}" => "Gizli: {sheets}",
"Double superscript" => "Çift üst simge",
"Double subscript" => "Çift alt simge",
"Extra }" => "Fazladan }",
"Unexpected end of input in a macro argument" => "Makro bağımsız değişkeninde beklenmeyen giriş sonu",
"Expected \\right after \\left" => "\\left sonrasında \\right bekleniyordu",
"\\middle must be within \\left and \\right" => "\\middle, \\left ile \\right arasında olmalıdır",
"Invalid environment name" => "Geçersiz ortam adı",
"Expected \\end after environment body" => "Ortam gövdesinden sonra \\end bekleniyordu",
"Expected URL" => "URL bekleniyordu",
"\\tag requires an argument" => "\\tag bir bağımsız değişken gerektirir",
"only one infix operator per group" => "Grup başına yalnızca bir ara işleç",
"Expected color token" => "Renk bekleniyordu",
"Expected size for \\raisebox" => "\\raisebox için boyut bekleniyordu",
"Expected size for \\rule width" => "\\rule genişliği için boyut bekleniyordu",
"Expected size for \\rule height" => "\\rule yüksekliği için boyut bekleniyordu",
"Cannot use both \\tag and \\nonumber in the same row" => "\\tag ve \\nonumber aynı satırda birlikte kullanılamaz",
"Multiple \\tag in a row" => "Bir satırda birden çok \\tag",
"\\tag must appear at the end of the row after the equation body" => "\\tag satırın sonunda, denklem gövdesinden sonra yer almalıdır",
"Multiple \\nonumber in a row" => "Bir satırda birden çok \\nonumber",
"\\nonumber must appear at the end of the row" => "\\nonumber satırın sonunda yer almalıdır",
"Too many tab characters: &" => "Çok fazla sekme karakteri: &",
"Invalid column alignment for array" => "array için geçersiz sütun hizalaması",
"Expected column alignment character" => "Sütun hizalama karakteri bekleniyordu",
"Expected l or c or r" => "l, c veya r bekleniyordu",
"Expected ]" => "] bekleniyordu",
"Unexpected end of CD row after @" => "@ sonrasında beklenmeyen CD satırı sonu",
"Invalid column alignment for subarray" => "subarray için geçersiz sütun hizalaması",
"{subarray} can contain only one column" => "{subarray} yalnızca bir sütun içerebilir",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"prooftree, ardından çıkarım komutu gelmeyen bir \\LeftLabel veya \\RightLabel içeriyor"
}
"Recursion limit exceeded" => "Özyineleme sınırı aşıldı",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"Çok fazla makro genişletmesi: sonsuz döngü veya maxExpand ayarı çok düşük"
}
"Expected raw style for \\htmlStyle" => "\\htmlStyle için ham stil bekleniyordu",
"\\verb assertion failed" => "\\verb denetimi başarısız oldu",
"Undefined control sequence: {name}" => "Tanımsız denetim dizisi: {name}",
"Expected '{expected}', got '{got}'" => "'{expected}' bekleniyordu, '{got}' bulundu",
"Expected group after '{symbol}'" => "'{symbol}' sonrasında grup bekleniyordu",
"Expected delimiter as argument to '{function}'" => "'{function}' bağımsız değişkeni olarak sınırlayıcı bekleniyordu",
"Expected group as argument to '{function}'" => "'{function}' bağımsız değişkeni olarak grup bekleniyordu",
"Got function '{function}' with no arguments as superscript" => "Bağımsız değişkensiz '{function}' işlevi üst simge olarak kullanıldı",
"Got function '{function}' with no arguments as subscript" => "Bağımsız değişkensiz '{function}' işlevi alt simge olarak kullanıldı",
"Got function '{function}' with no arguments as argument to '{parent}'" => {
"Bağımsız değişkensiz '{function}' işlevi '{parent}' bağımsız değişkeni olarak kullanıldı"
}
"Got function '{function}' with no arguments as \\tag" => "Bağımsız değişkensiz '{function}' işlevi \\tag olarak kullanıldı",
"Can't use function '{function}' in text mode" => "'{function}' işlevi metin modunda kullanılamaz",
"Can't use function '{function}' in math mode" => "'{function}' işlevi matematik modunda kullanılamaz",
"Invalid color: '{color}'" => "Geçersiz renk: '{color}'",
"Invalid size: '{size}'" => "Geçersiz boyut: '{size}'",
"Invalid unit: '{unit}'" => "Geçersiz birim: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "'{function}' sonrasında geçersiz sınırlayıcı '{delimiter}'",
"Invalid delimiter type '{type}' after '{function}'" => "'{function}' sonrasında geçersiz sınırlayıcı türü '{type}'",
"Invalid delimiter type '{type}'" => "Geçersiz sınırlayıcı türü '{type}'",
"No such environment: {name}" => "Bilinmeyen ortam: {name}",
"Expected argument to \\begin{{name}}" => "\\begin{{name}} için bağımsız değişken bekleniyordu",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "Uyuşmazlık: \\begin{{begin}}, \\end{{end}} ile kapatılmış",
"{command} valid only within array environment" => "{command} yalnızca array ortamında geçerlidir",
"Mismatched {command}" => "Eşi olmayan {command}",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "&, \\\\, \\cr veya \\end bekleniyordu, '{got}' bulundu",
"Unknown column alignment: {alignment}" => "Bilinmeyen sütun hizalaması: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "Bir satırda çok fazla formül: {expected} bekleniyordu, {got} bulundu",
"Unknown CD directive: @{directive}" => "Bilinmeyen CD yönergesi: @{directive}",
"Expected argument for {command}" => "{command} için bağımsız değişken bekleniyordu",
"{command} needs {count} premise(s), but only {available} available" => {
"{command} {count} öncül gerektirir, ancak yalnızca {available} mevcut"
}
"{command} valid only as a supported bussproofs command within prooftree" => {
"{command} prooftree içinde yalnızca desteklenen bir bussproofs komutu olarak geçerlidir"
}
"prooftree ended with {count} proof stack item(s), expected 1" => "prooftree, ispat yığınında {count} öğeyle bitti, 1 bekleniyordu",
"\\@char has non-numeric argument {argument}" => "\\@char sayısal olmayan bir bağımsız değişkene sahip: {argument}",
"\\@char with invalid code point {code}" => "\\@char geçersiz bir kod noktası içeriyor: {code}",
"Invalid environment name character: {character}" => "Ortam adında geçersiz karakter: {character}",
_ => return None,
})
}
+132 -14
View File
@@ -507,7 +507,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Name:" => "Name:",
"Before sheet (position, 0 = first):" => "Before sheet (position, 0 = first):",
"Create a copy" => "Create a copy",
"Sheets: {sheets}" => "Sheets: {sheets}",
"Sheets: {sheets}" => "Аркуші: {sheets}",
"Password (optional):" => "Password (optional):",
"Password:" => "Password:",
"Allow all users of this sheet to:" => "Allow all users of this sheet to:",
@@ -531,7 +531,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Remove the password (Modify)" => "Remove the password (Modify)",
"'{file}' is protected." => "'{file}' is protected.",
"Unhide sheet:" => "Unhide sheet:",
"Hidden: {sheets}" => "Hidden: {sheets}",
"Hidden: {sheets}" => "Приховані: {sheets}",
"All" => "All",
"Formulas (F)" => "Formulas (F)",
"Values (V)" => "Values (V)",
@@ -598,13 +598,13 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Interpolation" => "Interpolation",
"Zeros" => "Zeros",
"Aggregate duplicates using" => "Aggregate duplicates using",
"Average" => "Average",
"Count" => "Count",
"Average" => "Середнє",
"Count" => "Кількість",
"CountA" => "CountA",
"Max" => "Max",
"Median" => "Median",
"Min" => "Min",
"Sum" => "Sum",
"Sum" => "Сума",
"Product" => "Product",
"Include forecast statistics" => "Include forecast statistics",
"Chart" => "Діаграма",
@@ -757,14 +757,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"{count} cell(s) found" => "{count} cell(s) found",
"Reference:" => "Reference:",
"Special…" => "Special…",
"My list has headers" => "My list has headers",
"Sort by" => "Sort by",
"Then by" => "Then by",
"Cell Values" => "Cell Values",
"Cell Color" => "Cell Color",
"A to Z" => "A to Z",
"Z to A" => "Z to A",
"+ Add Level" => "+ Add Level",
"My list has headers" => "Мої дані містять заголовки",
"Sort by" => "Сортувати за",
"Then by" => "Потім за",
"Cell Values" => "Значення клітинок",
"Cell Color" => "Колір клітинки",
"A to Z" => "Від А до Я",
"Z to A" => "Від Я до А",
"Add Level" => "Додати рівень",
"Delete Level" => "Видалити рівень",
"Copy Level" => "Копіювати рівень",
"Move Up" => "Вгору",
"Move Down" => "Вниз",
"Order" => "Порядок",
"Sort On" => "Сортування",
"Sort|Column" => "Стовпець",
"Column {letters}" => "Стовпець {letters}",
"Smallest to Largest" => "Від найменшого до найбільшого",
"Largest to Smallest" => "Від найбільшого до найменшого",
"Close the Sort dialog before switching or changing worksheets." => {
"Закрийте діалогове вікно «Сортування», перш ніж перемикати або змінювати аркуші."
}
"Return to the original worksheet to sort, or cancel." => "Поверніться на вихідний аркуш, щоб виконати сортування, або скасуйте дію.",
"New…" => "New…",
"Edit…" => "Edit…",
"Name" => "Name",
@@ -808,7 +822,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Set cell:" => "Set cell:",
"To value:" => "To value:",
"By changing cell:" => "By changing cell:",
"Goal Seeking found a solution: {value}" => "Goal Seeking found a solution: {value}",
"Goal Seeking found a solution: {value}" => "Підбір параметра знайшов розв’язок: {value}",
"Analysis Tools" => "Analysis Tools",
"Anova: Single Factor" => "Anova: Single Factor",
"Correlation" => "Correlation",
@@ -1013,6 +1027,110 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "Показати",
"Collapse dialog" => "Згорнути діалогове вікно",
"Expand dialog" => "Розгорнути діалогове вікно",
"Numerical Count" => "Кількість чисел",
"Minimum" => "Мінімум",
"Maximum" => "Максимум",
"Circular References: {cell}" => "Циклічні посилання: {cell}",
"Width: {chars} ({pixels} pixels)" => "Ширина: {chars} (пікселів: {pixels})",
"Height: {points} ({pixels} pixels)" => "Висота: {points} (пікселів: {pixels})",
"Picture in cell" => "Зображення в клітинці",
"Picture: {alt}" => "Зображення: {alt}",
"Format Control: {name}" => "Формат елемента керування: {name}",
"Error at character {position}: {message}" => "Помилка в символі {position}: {message}",
"Macro definitions are not supported in equations." => "Визначення макросів у формулах не підтримуються.",
"A % can't be combined with a link in an equation." => "Знак % не можна поєднувати з посиланням у формулі.",
"Equations can nest at most 32 levels deep." => "Формули можуть мати не більше 32 рівнів вкладеності.",
"An equation can be at most 4096 bytes long." => "Довжина формули не може перевищувати 4096 байт.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"Формула може містити не більше 2500 клітинок матриці (рядки, помножені на найширший рядок)."
}
"This equation is too large to draw." => "Ця формула завелика для відображення.",
"This equation could not be laid out." => "Не вдалося побудувати цю формулу.",
"Saved macro “{name}” ({steps} step)" => "Макрос «{name}» збережено ({steps} крок)",
"Saved macro “{name}” ({steps} steps)" => "Макрос «{name}» збережено (кроків: {steps})",
"without {key}: another macro took it while recording" => "без {key}: під час запису його зайняв інший макрос",
"Recording stopped" => "Запис зупинено",
"Macro “{name}” stopped: {message}" => "Макрос «{name}» зупинено: {message}",
"Ran macro “{name}” ({steps} step)" => "Макрос «{name}» виконано ({steps} крок)",
"Ran macro “{name}” ({steps} steps)" => "Макрос «{name}» виконано (кроків: {steps})",
"Double superscript" => "Подвійний верхній індекс",
"Double subscript" => "Подвійний нижній індекс",
"Extra }" => "Зайва }",
"Unexpected end of input in a macro argument" => "Неочікуваний кінець введення в аргументі макросу",
"Expected \\right after \\left" => "Після \\left очікується \\right",
"\\middle must be within \\left and \\right" => "\\middle має стояти між \\left і \\right",
"Invalid environment name" => "Неприпустима назва середовища",
"Expected \\end after environment body" => "Після вмісту середовища очікується \\end",
"Expected URL" => "Очікується URL-адреса",
"\\tag requires an argument" => "Для \\tag потрібен аргумент",
"only one infix operator per group" => "У групі допускається лише один інфіксний оператор",
"Expected color token" => "Очікується колір",
"Expected size for \\raisebox" => "Для \\raisebox очікується розмір",
"Expected size for \\rule width" => "Для ширини \\rule очікується розмір",
"Expected size for \\rule height" => "Для висоти \\rule очікується розмір",
"Cannot use both \\tag and \\nonumber in the same row" => "Не можна використовувати \\tag і \\nonumber в одному рядку",
"Multiple \\tag in a row" => "Кілька \\tag в одному рядку",
"\\tag must appear at the end of the row after the equation body" => "\\tag має стояти в кінці рядка після формули",
"Multiple \\nonumber in a row" => "Кілька \\nonumber в одному рядку",
"\\nonumber must appear at the end of the row" => "\\nonumber має стояти в кінці рядка",
"Too many tab characters: &" => "Забагато символів табуляції: &",
"Invalid column alignment for array" => "Неприпустиме вирівнювання стовпців для array",
"Expected column alignment character" => "Очікується символ вирівнювання стовпця",
"Expected l or c or r" => "Очікується l, c або r",
"Expected ]" => "Очікується ]",
"Unexpected end of CD row after @" => "Неочікуваний кінець рядка CD після @",
"Invalid column alignment for subarray" => "Неприпустиме вирівнювання стовпців для subarray",
"{subarray} can contain only one column" => "{subarray} може містити лише один стовпець",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"У prooftree є \\LeftLabel або \\RightLabel без наступної команди виведення"
}
"Recursion limit exceeded" => "Перевищено межу рекурсії",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"Забагато розгортань макросів: нескінченний цикл або замале значення maxExpand"
}
"Expected raw style for \\htmlStyle" => "Для \\htmlStyle очікується необроблений стиль",
"\\verb assertion failed" => "Перевірку \\verb не пройдено",
"Undefined control sequence: {name}" => "Невизначена керівна послідовність: {name}",
"Expected '{expected}', got '{got}'" => "Очікується '{expected}', отримано '{got}'",
"Expected group after '{symbol}'" => "Після '{symbol}' очікується група",
"Expected delimiter as argument to '{function}'" => "Як аргумент '{function}' очікується роздільник",
"Expected group as argument to '{function}'" => "Як аргумент '{function}' очікується група",
"Got function '{function}' with no arguments as superscript" => "Функцію '{function}' без аргументів використано як верхній індекс",
"Got function '{function}' with no arguments as subscript" => "Функцію '{function}' без аргументів використано як нижній індекс",
"Got function '{function}' with no arguments as argument to '{parent}'" => {
"Функцію '{function}' без аргументів використано як аргумент '{parent}'"
}
"Got function '{function}' with no arguments as \\tag" => "Функцію '{function}' без аргументів використано як \\tag",
"Can't use function '{function}' in text mode" => "Функцію '{function}' не можна використовувати в текстовому режимі",
"Can't use function '{function}' in math mode" => "Функцію '{function}' не можна використовувати в математичному режимі",
"Invalid color: '{color}'" => "Неприпустимий колір: '{color}'",
"Invalid size: '{size}'" => "Неприпустимий розмір: '{size}'",
"Invalid unit: '{unit}'" => "Неприпустима одиниця: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "Неприпустимий роздільник '{delimiter}' після '{function}'",
"Invalid delimiter type '{type}' after '{function}'" => "Неприпустимий тип роздільника '{type}' після '{function}'",
"Invalid delimiter type '{type}'" => "Неприпустимий тип роздільника '{type}'",
"No such environment: {name}" => "Невідоме середовище: {name}",
"Expected argument to \\begin{{name}}" => "Для \\begin{{name}} очікується аргумент",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "Невідповідність: \\begin{{begin}} закрито \\end{{end}}",
"{command} valid only within array environment" => "{command} допускається лише в середовищі array",
"Mismatched {command}" => "{command} без пари",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "Очікується &, \\\\, \\cr або \\end, отримано '{got}'",
"Unknown column alignment: {alignment}" => "Невідоме вирівнювання стовпця: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "Забагато формул у рядку: очікувалося {expected}, отримано {got}",
"Unknown CD directive: @{directive}" => "Невідома директива CD: @{directive}",
"Expected argument for {command}" => "Для {command} очікується аргумент",
"{command} needs {count} premise(s), but only {available} available" => {
"Для {command} потрібно засновків: {count}, але доступно лише {available}"
}
"{command} valid only as a supported bussproofs command within prooftree" => {
"{command} допускається в prooftree лише як підтримувана команда bussproofs"
}
"prooftree ended with {count} proof stack item(s), expected 1" => {
"prooftree завершився з елементами в стеку доведення: {count}, очікувався 1"
}
"\\@char has non-numeric argument {argument}" => "\\@char має нечисловий аргумент {argument}",
"\\@char with invalid code point {code}" => "\\@char з неприпустимою кодовою точкою {code}",
"Invalid environment name character: {character}" => "Неприпустимий символ у назві середовища: {character}",
_ => return None,
})
}
+126
View File
@@ -451,6 +451,132 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "Hiện",
"Collapse dialog" => "Thu gọn hộp thoại",
"Expand dialog" => "Mở rộng hộp thoại",
"My list has headers" => "Dữ liệu của tôi có tiêu đề",
"Sort by" => "Sắp xếp theo",
"Then by" => "Sau đó theo",
"Cell Values" => "Giá trị ô",
"Cell Color" => "Màu ô",
"A to Z" => "A đến Z",
"Z to A" => "Z đến A",
"Add Level" => "Thêm cấp",
"Delete Level" => "Xóa cấp",
"Copy Level" => "Sao chép cấp",
"Move Up" => "Di chuyển lên",
"Move Down" => "Di chuyển xuống",
"Order" => "Thứ tự",
"Sort On" => "Sắp xếp theo",
"Sort|Column" => "Cột",
"Column {letters}" => "Cột {letters}",
"Smallest to Largest" => "Nhỏ nhất đến lớn nhất",
"Largest to Smallest" => "Lớn nhất đến nhỏ nhất",
"Close the Sort dialog before switching or changing worksheets." => "Hãy đóng hộp thoại Sắp xếp trước khi chuyển hoặc thay đổi trang tính.",
"Return to the original worksheet to sort, or cancel." => "Hãy quay lại trang tính ban đầu để sắp xếp, hoặc hủy.",
"Numerical Count" => "Số đếm số",
"Minimum" => "Tối thiểu",
"Maximum" => "Tối đa",
"Circular References: {cell}" => "Tham chiếu vòng: {cell}",
"Width: {chars} ({pixels} pixels)" => "Độ rộng: {chars} ({pixels} điểm ảnh)",
"Height: {points} ({pixels} pixels)" => "Chiều cao: {points} ({pixels} điểm ảnh)",
"Picture in cell" => "Ảnh trong ô",
"Picture: {alt}" => "Ảnh: {alt}",
"Format Control: {name}" => "Định dạng điều khiển: {name}",
"Error at character {position}: {message}" => "Lỗi tại ký tự {position}: {message}",
"Macro definitions are not supported in equations." => "Định nghĩa macro không được hỗ trợ trong phương trình.",
"A % can't be combined with a link in an equation." => "Không thể kết hợp % với liên kết trong phương trình.",
"Equations can nest at most 32 levels deep." => "Phương trình chỉ có thể lồng nhau tối đa 32 cấp.",
"An equation can be at most 4096 bytes long." => "Phương trình chỉ có thể dài tối đa 4096 byte.",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => {
"Phương trình chỉ có thể có tối đa 2500 ô ma trận (số hàng nhân với hàng rộng nhất)."
}
"This equation is too large to draw." => "Phương trình này quá lớn để vẽ.",
"This equation could not be laid out." => "Không thể dàn trang phương trình này.",
"Saved macro “{name}” ({steps} step)" => "Đã lưu macro “{name}” ({steps} bước)",
"Saved macro “{name}” ({steps} steps)" => "Đã lưu macro “{name}” ({steps} bước)",
"without {key}: another macro took it while recording" => "không có {key}: một macro khác đã dùng phím này khi đang ghi",
"Recording stopped" => "Đã dừng ghi",
"Macro “{name}” stopped: {message}" => "Macro “{name}” đã dừng: {message}",
"Ran macro “{name}” ({steps} step)" => "Đã chạy macro “{name}” ({steps} bước)",
"Ran macro “{name}” ({steps} steps)" => "Đã chạy macro “{name}” ({steps} bước)",
"Average" => "Trung bình",
"Count" => "Số đếm",
"Sum" => "Tổng",
"Goal Seeking found a solution: {value}" => "Tìm mục tiêu đã tìm thấy nghiệm: {value}",
"Sheets: {sheets}" => "Trang tính: {sheets}",
"Hidden: {sheets}" => "Đang ẩn: {sheets}",
"Double superscript" => "Chỉ số trên bị lặp",
"Double subscript" => "Chỉ số dưới bị lặp",
"Extra }" => "Thừa }",
"Unexpected end of input in a macro argument" => "Dữ liệu nhập kết thúc bất ngờ trong đối số macro",
"Expected \\right after \\left" => "Cần \\right sau \\left",
"\\middle must be within \\left and \\right" => "\\middle phải nằm giữa \\left và \\right",
"Invalid environment name" => "Tên môi trường không hợp lệ",
"Expected \\end after environment body" => "Cần \\end sau phần thân môi trường",
"Expected URL" => "Cần URL",
"\\tag requires an argument" => "\\tag cần một đối số",
"only one infix operator per group" => "Mỗi nhóm chỉ được có một toán tử trung tố",
"Expected color token" => "Cần màu",
"Expected size for \\raisebox" => "Cần kích thước cho \\raisebox",
"Expected size for \\rule width" => "Cần kích thước cho chiều rộng \\rule",
"Expected size for \\rule height" => "Cần kích thước cho chiều cao \\rule",
"Cannot use both \\tag and \\nonumber in the same row" => "Không thể dùng cả \\tag và \\nonumber trong cùng một hàng",
"Multiple \\tag in a row" => "Nhiều \\tag trong một hàng",
"\\tag must appear at the end of the row after the equation body" => "\\tag phải nằm ở cuối hàng, sau phần thân phương trình",
"Multiple \\nonumber in a row" => "Nhiều \\nonumber trong một hàng",
"\\nonumber must appear at the end of the row" => "\\nonumber phải nằm ở cuối hàng",
"Too many tab characters: &" => "Quá nhiều ký tự tab: &",
"Invalid column alignment for array" => "Căn chỉnh cột không hợp lệ cho array",
"Expected column alignment character" => "Cần ký tự căn chỉnh cột",
"Expected l or c or r" => "Cần l, c hoặc r",
"Expected ]" => "Cần ]",
"Unexpected end of CD row after @" => "Hàng CD kết thúc bất ngờ sau @",
"Invalid column alignment for subarray" => "Căn chỉnh cột không hợp lệ cho subarray",
"{subarray} can contain only one column" => "{subarray} chỉ có thể chứa một cột",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"prooftree có \\LeftLabel hoặc \\RightLabel mà không có lệnh suy luận theo sau"
}
"Recursion limit exceeded" => "Vượt quá giới hạn đệ quy",
"Too many expansions: infinite loop or need to increase maxExpand setting" => {
"Quá nhiều lần mở rộng macro: vòng lặp vô hạn hoặc thiết lập maxExpand quá thấp"
}
"Expected raw style for \\htmlStyle" => "Cần kiểu thô cho \\htmlStyle",
"\\verb assertion failed" => "Kiểm tra \\verb không thành công",
"Undefined control sequence: {name}" => "Chuỗi điều khiển chưa định nghĩa: {name}",
"Expected '{expected}', got '{got}'" => "Cần '{expected}', nhận được '{got}'",
"Expected group after '{symbol}'" => "Cần nhóm sau '{symbol}'",
"Expected delimiter as argument to '{function}'" => "Cần dấu phân cách làm đối số cho '{function}'",
"Expected group as argument to '{function}'" => "Cần nhóm làm đối số cho '{function}'",
"Got function '{function}' with no arguments as superscript" => "Hàm '{function}' không có đối số được dùng làm chỉ số trên",
"Got function '{function}' with no arguments as subscript" => "Hàm '{function}' không có đối số được dùng làm chỉ số dưới",
"Got function '{function}' with no arguments as argument to '{parent}'" => {
"Hàm '{function}' không có đối số được dùng làm đối số cho '{parent}'"
}
"Got function '{function}' with no arguments as \\tag" => "Hàm '{function}' không có đối số được dùng làm \\tag",
"Can't use function '{function}' in text mode" => "Không thể dùng hàm '{function}' trong chế độ văn bản",
"Can't use function '{function}' in math mode" => "Không thể dùng hàm '{function}' trong chế độ toán",
"Invalid color: '{color}'" => "Màu không hợp lệ: '{color}'",
"Invalid size: '{size}'" => "Kích thước không hợp lệ: '{size}'",
"Invalid unit: '{unit}'" => "Đơn vị không hợp lệ: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "Dấu phân cách '{delimiter}' không hợp lệ sau '{function}'",
"Invalid delimiter type '{type}' after '{function}'" => "Loại dấu phân cách '{type}' không hợp lệ sau '{function}'",
"Invalid delimiter type '{type}'" => "Loại dấu phân cách '{type}' không hợp lệ",
"No such environment: {name}" => "Môi trường không xác định: {name}",
"Expected argument to \\begin{{name}}" => "Cần đối số cho \\begin{{name}}",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "Không khớp: \\begin{{begin}} được đóng bằng \\end{{end}}",
"{command} valid only within array environment" => "{command} chỉ hợp lệ bên trong môi trường array",
"Mismatched {command}" => "{command} không có cặp",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "Cần &, \\\\, \\cr hoặc \\end, nhận được '{got}'",
"Unknown column alignment: {alignment}" => "Căn chỉnh cột không xác định: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "Quá nhiều công thức trong một hàng: cần {expected}, có {got}",
"Unknown CD directive: @{directive}" => "Chỉ thị CD không xác định: @{directive}",
"Expected argument for {command}" => "Cần đối số cho {command}",
"{command} needs {count} premise(s), but only {available} available" => "{command} cần {count} tiền đề, nhưng chỉ có {available}",
"{command} valid only as a supported bussproofs command within prooftree" => {
"{command} chỉ hợp lệ như một lệnh bussproofs được hỗ trợ bên trong prooftree"
}
"prooftree ended with {count} proof stack item(s), expected 1" => "prooftree kết thúc với {count} mục trên ngăn xếp chứng minh, cần 1",
"\\@char has non-numeric argument {argument}" => "\\@char có đối số không phải số {argument}",
"\\@char with invalid code point {code}" => "\\@char có điểm mã không hợp lệ {code}",
"Invalid environment name character: {character}" => "Ký tự không hợp lệ trong tên môi trường: {character}",
_ => return None,
})
}
+118
View File
@@ -482,6 +482,124 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Show" => "显示",
"Collapse dialog" => "折叠对话框",
"Expand dialog" => "展开对话框",
"My list has headers" => "数据包含标题",
"Sort by" => "主要关键字",
"Then by" => "次要关键字",
"Cell Values" => "单元格值",
"Cell Color" => "单元格颜色",
"A to Z" => "A 到 Z",
"Z to A" => "Z 到 A",
"Add Level" => "添加条件",
"Delete Level" => "删除条件",
"Copy Level" => "复制条件",
"Move Up" => "上移",
"Move Down" => "下移",
"Order" => "次序",
"Sort On" => "排序依据",
"Sort|Column" => "列",
"Column {letters}" => "列 {letters}",
"Smallest to Largest" => "从小到大",
"Largest to Smallest" => "从大到小",
"Close the Sort dialog before switching or changing worksheets." => "切换或更改工作表之前,请先关闭“排序”对话框。",
"Return to the original worksheet to sort, or cancel." => "请返回原工作表后再排序,或取消。",
"Numerical Count" => "数值计数",
"Minimum" => "最小值",
"Maximum" => "最大值",
"Circular References: {cell}" => "循环引用: {cell}",
"Width: {chars} ({pixels} pixels)" => "宽度: {chars} ({pixels} 像素)",
"Height: {points} ({pixels} pixels)" => "高度: {points} ({pixels} 像素)",
"Picture in cell" => "单元格中的图片",
"Picture: {alt}" => "图片: {alt}",
"Format Control: {name}" => "设置控件格式: {name}",
"Error at character {position}: {message}" => "第 {position} 个字符处出错: {message}",
"Macro definitions are not supported in equations." => "公式中不支持宏定义。",
"A % can't be combined with a link in an equation." => "公式中的 % 不能与链接同时使用。",
"Equations can nest at most 32 levels deep." => "公式最多只能嵌套 32 层。",
"An equation can be at most 4096 bytes long." => "公式最长为 4096 字节。",
"An equation can have at most 2500 matrix cells (rows times the widest row)." => "公式最多只能有 2500 个矩阵单元格(行数乘以最宽的行)。",
"This equation is too large to draw." => "此公式太大,无法绘制。",
"This equation could not be laid out." => "无法排版此公式。",
"Saved macro “{name}” ({steps} step)" => "已保存宏“{name}”({steps} 步)",
"Saved macro “{name}” ({steps} steps)" => "已保存宏“{name}”({steps} 步)",
"without {key}: another macro took it while recording" => "未使用 {key}: 录制时已被另一个宏占用",
"Recording stopped" => "已停止录制",
"Macro “{name}” stopped: {message}" => "宏“{name}”已停止: {message}",
"Ran macro “{name}” ({steps} step)" => "已运行宏“{name}”({steps} 步)",
"Ran macro “{name}” ({steps} steps)" => "已运行宏“{name}”({steps} 步)",
"Average" => "平均值",
"Count" => "计数",
"Sum" => "求和",
"Goal Seeking found a solution: {value}" => "单变量求解找到一个解: {value}",
"Sheets: {sheets}" => "工作表: {sheets}",
"Hidden: {sheets}" => "隐藏: {sheets}",
"Double superscript" => "上标重复",
"Double subscript" => "下标重复",
"Extra }" => "多余的 }",
"Unexpected end of input in a macro argument" => "宏参数中输入意外结束",
"Expected \\right after \\left" => "\\left 之后应有 \\right",
"\\middle must be within \\left and \\right" => "\\middle 必须位于 \\left 和 \\right 之间",
"Invalid environment name" => "环境名称无效",
"Expected \\end after environment body" => "环境主体之后应有 \\end",
"Expected URL" => "应为 URL",
"\\tag requires an argument" => "\\tag 需要一个参数",
"only one infix operator per group" => "每个组只能有一个中缀运算符",
"Expected color token" => "应为颜色",
"Expected size for \\raisebox" => "\\raisebox 需要尺寸",
"Expected size for \\rule width" => "\\rule 的宽度需要尺寸",
"Expected size for \\rule height" => "\\rule 的高度需要尺寸",
"Cannot use both \\tag and \\nonumber in the same row" => "同一行中不能同时使用 \\tag 和 \\nonumber",
"Multiple \\tag in a row" => "一行中有多个 \\tag",
"\\tag must appear at the end of the row after the equation body" => "\\tag 必须位于行尾、公式主体之后",
"Multiple \\nonumber in a row" => "一行中有多个 \\nonumber",
"\\nonumber must appear at the end of the row" => "\\nonumber 必须位于行尾",
"Too many tab characters: &" => "制表符过多: &",
"Invalid column alignment for array" => "array 的列对齐方式无效",
"Expected column alignment character" => "应为列对齐字符",
"Expected l or c or r" => "应为 l、c 或 r",
"Expected ]" => "应为 ]",
"Unexpected end of CD row after @" => "CD 行在 @ 之后意外结束",
"Invalid column alignment for subarray" => "subarray 的列对齐方式无效",
"{subarray} can contain only one column" => "{subarray} 只能包含一列",
"prooftree has a \\LeftLabel or \\RightLabel without a following inference command" => {
"prooftree 中的 \\LeftLabel 或 \\RightLabel 之后没有推理命令"
}
"Recursion limit exceeded" => "超出递归限制",
"Too many expansions: infinite loop or need to increase maxExpand setting" => "宏展开次数过多: 无限循环或 maxExpand 设置过小",
"Expected raw style for \\htmlStyle" => "\\htmlStyle 需要原始样式",
"\\verb assertion failed" => "\\verb 检查失败",
"Undefined control sequence: {name}" => "未定义的控制序列: {name}",
"Expected '{expected}', got '{got}'" => "应为 '{expected}',实际为 '{got}'",
"Expected group after '{symbol}'" => "'{symbol}' 之后应有组",
"Expected delimiter as argument to '{function}'" => "'{function}' 的参数应为分隔符",
"Expected group as argument to '{function}'" => "'{function}' 的参数应为组",
"Got function '{function}' with no arguments as superscript" => "无参数的函数 '{function}' 被用作上标",
"Got function '{function}' with no arguments as subscript" => "无参数的函数 '{function}' 被用作下标",
"Got function '{function}' with no arguments as argument to '{parent}'" => "无参数的函数 '{function}' 被用作 '{parent}' 的参数",
"Got function '{function}' with no arguments as \\tag" => "无参数的函数 '{function}' 被用作 \\tag",
"Can't use function '{function}' in text mode" => "函数 '{function}' 不能在文本模式中使用",
"Can't use function '{function}' in math mode" => "函数 '{function}' 不能在数学模式中使用",
"Invalid color: '{color}'" => "颜色无效: '{color}'",
"Invalid size: '{size}'" => "尺寸无效: '{size}'",
"Invalid unit: '{unit}'" => "单位无效: '{unit}'",
"Invalid delimiter '{delimiter}' after '{function}'" => "'{function}' 之后的分隔符 '{delimiter}' 无效",
"Invalid delimiter type '{type}' after '{function}'" => "'{function}' 之后的分隔符类型 '{type}' 无效",
"Invalid delimiter type '{type}'" => "分隔符类型 '{type}' 无效",
"No such environment: {name}" => "未知环境: {name}",
"Expected argument to \\begin{{name}}" => "\\begin{{name}} 需要参数",
"Mismatch: \\begin{{begin}} matched by \\end{{end}}" => "不匹配: \\begin{{begin}} 由 \\end{{end}} 结束",
"{command} valid only within array environment" => "{command} 仅在 array 环境中有效",
"Mismatched {command}" => "{command} 没有配对",
"Expected & or \\\\ or \\cr or \\end, got '{got}'" => "应为 &、\\\\、\\cr 或 \\end,实际为 '{got}'",
"Unknown column alignment: {alignment}" => "未知的列对齐方式: {alignment}",
"Too many math in a row: expected {expected}, but got {got}" => "一行中的公式过多: 应为 {expected} 个,实际为 {got} 个",
"Unknown CD directive: @{directive}" => "未知的 CD 指令: @{directive}",
"Expected argument for {command}" => "{command} 需要参数",
"{command} needs {count} premise(s), but only {available} available" => "{command} 需要 {count} 个前提,但只有 {available} 个",
"{command} valid only as a supported bussproofs command within prooftree" => "{command} 在 prooftree 中只能作为受支持的 bussproofs 命令使用",
"prooftree ended with {count} proof stack item(s), expected 1" => "prooftree 结束时证明栈中有 {count} 项,应为 1 项",
"\\@char has non-numeric argument {argument}" => "\\@char 的参数 {argument} 不是数字",
"\\@char with invalid code point {code}" => "\\@char 的码位 {code} 无效",
"Invalid environment name character: {character}" => "环境名称中有无效字符: {character}",
_ => return None,
})
}
+48 -8
View File
@@ -55,14 +55,54 @@ fn borders(preset: &str) -> Shortcut {
Shortcut::Run("home.borders", json!({"preset": preset}))
}
/// The shortcut for a key press in the grid, if any. `physical` is the key's position on a US
/// layout (as Excel matches Ctrl+Shift+4 rather than the `$` character); `mac` selects the Excel
/// for Mac variants where they differ. Navigation keys go by the logical key: with Num Lock off
/// the numpad's arrows and Page Down report the digit keys (Num6, Num3) as their physical keys.
pub fn lookup(key: Key, physical: Option<Key>, m: Modifiers, mac: bool) -> Option<Shortcut> {
/// Navigation keys go by the logical key: with Num Lock off the numpad's arrows and Page Down
/// report the digit keys (Num6, Num3) as their physical keys.
fn is_navigation(key: Key) -> bool {
use Key::*;
let navigation = matches!(key, ArrowLeft | ArrowRight | ArrowUp | ArrowDown | PageUp | PageDown | Home | End | Insert | Delete);
let key = if navigation { key } else { physical.unwrap_or(key) };
matches!(key, ArrowLeft | ArrowRight | ArrowUp | ArrowDown | PageUp | PageDown | Home | End | Insert | Delete)
}
/// The US key and Shift state a symbol or digit key press stands for in the English shortcuts.
/// Digits go by position (Ctrl+Shift+4 is the currency format wherever `$` is). Punctuation keys
/// go by the character the layout types, as Excel does: Shift+, types `;` on a Croatian or German
/// keyboard, so Ctrl+Shift+, is Ctrl+; (today's date) there, and a lone `+` is the US Shift+=.
/// A character egui has no key for (`č`, `ö`, `<`) arrives as the key's position, which stands
/// in. `None` for every other key (letters, navigation, function keys).
pub fn us_key(key: Key, physical: Option<Key>, shift: bool) -> Option<(Key, bool)> {
use Key::*;
if is_navigation(key) {
return None;
}
let at = physical?;
let symbol =
|k: Key| matches!(k, Backtick | Minus | Equals | OpenBracket | CloseBracket | Backslash | Semicolon | Quote | Comma | Period | Slash);
match at {
Num0 | Num1 | Num2 | Num3 | Num4 | Num5 | Num6 | Num7 | Num8 | Num9 => Some((at, shift)),
_ if symbol(at) => Some(match key {
// Characters a US keyboard types with Shift.
Colon => (Semicolon, true),
Plus => (Equals, true),
Questionmark => (Slash, true),
Pipe => (Backslash, true),
OpenCurlyBracket => (OpenBracket, true),
CloseCurlyBracket => (CloseBracket, true),
// An unshifted US character, typed here with or without Shift.
_ if key != at && symbol(key) => (key, false),
_ => (key, shift),
}),
_ => None,
}
}
/// The shortcut for a key press in the grid, if any. `physical` is the key's position on a US
/// layout: digits and letters go by it, punctuation by the character typed ([`us_key`]). `mac`
/// selects the Excel for Mac variants where they differ. Navigation keys go by the logical key.
pub fn lookup(key: Key, physical: Option<Key>, m: Modifiers, mac: bool) -> Option<Shortcut> {
let (key, shift) = match us_key(key, physical, m.shift) {
Some(us) => us,
None if is_navigation(key) => (key, m.shift),
None => (physical.unwrap_or(key), m.shift),
};
let ctx = LookupContext {
key,
modifiers: m,
@@ -71,7 +111,7 @@ pub fn lookup(key: Key, physical: Option<Key>, m: Modifiers, mac: bool) -> Optio
alt: m.alt && !m.ctrl && !m.command,
ctrl_alt: m.alt && (m.ctrl || m.command),
plain: !m.ctrl && !m.command && !m.alt,
shift: m.shift,
shift,
mac,
};
lookup_number_formats(ctx)
+60 -5
View File
@@ -89,13 +89,16 @@ pub fn stop_recording(app: &mut SheetApp) {
Some(name) => {
let steps = v["steps"].as_u64().unwrap_or(0);
app.macros.note_recent(name);
let mut text = format!("Saved macro “{name}” ({steps} step{})", if steps == 1 { "" } else { "s" });
let lang = app.ui.language;
let saved = if steps == 1 { "Saved macro “{name}” ({steps} step)" } else { "Saved macro “{name}” ({steps} steps)" };
let mut text = lang.tr_fill(saved, &[("name", name), ("steps", &steps.to_string())]);
if let Some(k) = v["shortcutDropped"].as_str() {
text.push_str(&format!(" without {k}: another macro took it while recording"));
text.push(' ');
text.push_str(&lang.tr_fill("without {key}: another macro took it while recording", &[("key", k)]));
}
app.toast = Some((text, crate::now_ms()));
}
None => app.toast = Some(("Recording stopped".into(), crate::now_ms())),
None => app.toast = Some((app.ui.language.tr("Recording stopped").into(), crate::now_ms())),
},
Err(e) => app.message = Some(("Record Macro".into(), crate::clean_error(&e))),
}
@@ -174,9 +177,13 @@ pub fn note_result(app: &mut SheetApp, id: &str, params: &Json, v: &Json) {
}
app.macros.note_recent(&name);
let ran = v["ran"].as_u64().unwrap_or(0);
let lang = app.ui.language;
let text = match v["stopped"].as_str() {
Some(msg) => format!("Macro “{name}” stopped: {msg}"),
None => format!("Ran macro “{name}” ({ran} step{})", if ran == 1 { "" } else { "s" }),
Some(msg) => lang.tr_fill("Macro “{name}” stopped: {message}", &[("name", &name), ("message", msg)]),
None => {
let ran_text = if ran == 1 { "Ran macro “{name}” ({steps} step)" } else { "Ran macro “{name}” ({steps} steps)" };
lang.tr_fill(ran_text, &[("name", &name), ("steps", &ran.to_string())])
}
};
app.toast = Some((text, crate::now_ms()));
}
@@ -673,6 +680,54 @@ pub fn record_dialog(app: &mut SheetApp, ui: &mut Ui, d: &mut Dialog, open: &mut
mod tests {
use super::*;
#[test]
fn macro_toasts_follow_the_interface_language() {
use crate::i18n::Language;
use gridcraft_engine::Session;
let mut session = Session::new();
session.new_workbook();
let mut app = SheetApp::new(session, Default::default());
let ran = |app: &mut SheetApp, v: Json| {
note_result(app, "macro.run", &json!({}), &v);
app.toast.take().map(|t| t.0).unwrap_or_default()
};
assert_eq!(ran(&mut app, json!({"macro": "M", "ran": 1})), "Ran macro “M” (1 step)");
assert_eq!(ran(&mut app, json!({"macro": "M", "ran": 2})), "Ran macro “M” (2 steps)");
assert_eq!(ran(&mut app, json!({"macro": "M", "stopped": "Oops"})), "Macro “M” stopped: Oops");
let it = Language::It;
app.ui.language = it;
// A name holding a placeholder is shown as it is.
let want = it.tr("Ran macro “{name}” ({steps} steps)").replace("{steps}", "2").replace("{name}", "{steps}");
assert_eq!(ran(&mut app, json!({"macro": "{steps}", "ran": 2})), want);
assert_ne!(want, "Ran macro “{steps}” (2 steps)");
let want = it.tr("Ran macro “{name}” ({steps} step)").replace("{name}", "M").replace("{steps}", "1");
assert_eq!(ran(&mut app, json!({"macro": "M", "ran": 1})), want);
let want = it.tr("Macro “{name}” stopped: {message}").replace("{name}", "M").replace("{message}", "Oops");
assert_eq!(ran(&mut app, json!({"macro": "M", "stopped": "Oops"})), want);
}
#[test]
fn recording_toasts_follow_the_interface_language() {
use crate::i18n::Language;
use gridcraft_engine::Session;
let mut session = Session::new();
session.new_workbook();
let mut app = SheetApp::new(session, Default::default());
app.run("macro.record", json!({"name": "Two"})).unwrap();
app.run("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
app.run("cell.set", json!({"cell": "A2", "input": "2"})).unwrap();
stop_recording(&mut app);
assert_eq!(app.toast.take().map(|t| t.0).as_deref(), Some("Saved macro “Two” (2 steps)"));
let it = Language::It;
app.ui.language = it;
app.run("macro.record", json!({"name": "Rec"})).unwrap();
app.run("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
stop_recording(&mut app);
let want = it.tr("Saved macro “{name}” ({steps} step)").replace("{name}", "Rec").replace("{steps}", "1");
assert_eq!(app.toast.take().map(|t| t.0).as_deref(), Some(want.as_str()));
assert!(!want.starts_with("Saved macro"));
}
#[test]
fn questions_are_read_from_the_error() {
let e = "approve: Run macro 'M'? It came with a workbook you opened. (run again with `approve: true`)";
+43 -24
View File
@@ -27,36 +27,55 @@ pub(super) fn table_gallery(app: &mut SheetApp, ui: &mut Ui, cmd: &str) {
}
}
/// A style's gallery thumbnail: a 5x5 table (header row, banded rows) painted cell by cell from
/// the same look the grid uses.
pub(super) fn paint_table_swatch(ui: &Ui, r: Rect, wb: &gridcraft_engine::model::Workbook, style: &str) {
let lk = gridcraft_engine::tables::look(style);
let res = |c: Option<gridcraft_engine::model::Color>| c.and_then(|c| c.resolve(&wb.theme)).map(theme::color32);
use egui::emath::GuiRounding;
use gridcraft_engine::tables::{TableParts, cell_look, look};
let lk = look(style);
let parts = TableParts { header_row: true, totals_row: false, banded_rows: true, banded_cols: false, first_col: false, last_col: false };
let res = |c: gridcraft_engine::model::Color| c.resolve(&wb.theme).map(theme::color32);
let p = ui.painter();
let t = Tokens::get(ui.ctx());
p.rect_filled(r, 0.0, t.grid_bg);
let rows = 5;
let rh = r.height() / rows as f32;
for i in 0..rows {
let rr = Rect::from_min_size(pos2(r.left(), r.top() + i as f32 * rh), vec2(r.width(), rh));
let fill = if i == 0 {
res(lk.header_fill)
} else if i % 2 == 1 {
res(lk.band_fill)
} else {
res(lk.body_fill)
};
if let Some(f) = fill {
p.rect_filled(rr, 0.0, f);
}
if let Some(l) = res(lk.line) {
p.line_segment([rr.left_bottom(), rr.right_bottom()], Stroke::new(1.0, l));
}
for k in 0..3 {
let x = rr.left() + 4.0 + k as f32 * (r.width() - 8.0) / 3.0;
let col = if i == 0 { res(Some(lk.header_font)).unwrap_or(t.cell_text) } else { t.sheet_control_border };
p.line_segment([pos2(x, rr.center().y), pos2(x + 10.0, rr.center().y)], Stroke::new(1.0, col));
let line = |l: gridcraft_engine::model::BorderLine| if l.is_none() { None } else { Some(res(l.color).unwrap_or(t.cell_text)) };
let n = 5u32;
let (cw, rh) = (r.width() / n as f32, r.height() / n as f32);
// Cell edges on whole pixels keep the lines crisp and the rows evenly spaced.
let ppp = ui.pixels_per_point();
let at = |start: f32, size: f32, k: u32| (start + size * k as f32).round_to_pixels(ppp);
for row in 0..n {
for col in 0..n {
let (x0, x1) = (at(r.left(), cw, col), at(r.left(), cw, col + 1));
let cr = Rect::from_min_max(pos2(x0, at(r.top(), rh, row)), pos2(x1, at(r.top(), rh, row + 1)));
let cl = cell_look(&lk, parts, row, col, n, n);
if let Some(f) = cl.fill.and_then(res) {
p.rect_filled(cr, 0.0, f);
}
let b = cl.borders;
// Excel centres the dash in the space inside the cell's own lines, across about half of it.
let inset = |l: gridcraft_engine::model::BorderLine| if l.is_none() { 0.0 } else { 1.0 };
let inner = Rect::from_min_max(
pos2(cr.left() + inset(b.left), cr.top() + inset(b.top)),
pos2(cr.right() - inset(b.right), cr.bottom() - inset(b.bottom)),
);
// When the gap can't split evenly, Excel puts the spare pixel below the dash.
let top = ((inner.center().y - 0.5) * ppp).floor() / ppp;
let (mid, half) = (inner.center().x, cw * 0.26);
let dash = Rect::from_min_max(pos2((mid - half).round_to_pixels(ppp), top), pos2((mid + half).round_to_pixels(ppp), top + 1.0));
p.rect_filled(dash, 0.0, res(cl.font).unwrap_or(t.cell_text));
for (side, edge) in [
(b.top, Rect::from_min_max(cr.left_top(), pos2(cr.right(), cr.top() + 1.0))),
(b.bottom, Rect::from_min_max(pos2(cr.left(), cr.bottom() - 1.0), cr.right_bottom())),
(b.left, Rect::from_min_max(cr.left_top(), pos2(cr.left() + 1.0, cr.bottom()))),
(b.right, Rect::from_min_max(pos2(cr.right() - 1.0, cr.top()), cr.right_bottom())),
] {
if let Some(c) = line(side) {
p.rect_filled(edge, 0.0, c);
}
}
}
}
p.rect_stroke(r, 0.0, Stroke::new(1.0, t.separator), StrokeKind::Inside);
}
pub(super) fn cell_style_gallery(app: &mut SheetApp, ui: &mut Ui) {
+2 -1
View File
@@ -70,7 +70,8 @@ pub fn shortcut(app: &mut SheetApp, key: Key, m: Modifiers) {
None
}
},
Key::Semicolon => {
// Ctrl+Shift+; (the time) is in `keymap::lookup`; Cmd+Shift+; on a Mac does nothing.
Key::Semicolon if !shift => {
// Insert today's date.
let text = app
.session
+32 -8
View File
@@ -417,8 +417,8 @@ pub fn status_bar(app: &mut SheetApp, ui: &mut Ui) {
ui.add_space(12.0);
// Only a loop on the active sheet is named, so the address needs no sheet.
let label = match d.calc.circular.iter().find(|(si, _)| *si == d.wb.active_sheet()) {
Some((_, c)) => format!("Circular References: {}", c.a1()),
None => "Circular References".to_owned(),
Some((_, c)) => app.ui.language.tr_fill("Circular References: {cell}", &[("cell", &c.a1())]),
None => app.ui.language.tr("Circular References").to_owned(),
};
text(ui, egui::RichText::new(label).font(theme::ui_font(12.5)).color(t.danger));
}
@@ -516,26 +516,30 @@ pub(crate) fn selection_statistics(app: &SheetApp) -> Vec<String> {
let code = if code == "General" { "#,##0.##########".to_string() } else { code };
gridcraft_engine::display::format(&gridcraft_engine::core::Value::Number(v), &code, &d.wb).text.trim_end_matches('.').to_string()
};
// The label the right-click menu shows, then the value: clicking a statistic copies the part
// after `": "`.
let lang = app.ui.language;
let part = |label: &str, value: String| format!("{}: {value}", lang.tr(label));
let mut parts = Vec::new();
if on.average
&& let Some(a) = st.average
{
parts.push(format!("Average: {}", fmt(a)));
parts.push(part("Average", fmt(a)));
}
if on.count && st.count > 0 {
parts.push(format!("Count: {}", st.count));
parts.push(part("Count", st.count.to_string()));
}
if on.numerical_count && st.count > 0 {
parts.push(format!("Numerical Count: {}", st.numeric));
parts.push(part("Numerical Count", st.numeric.to_string()));
}
if on.minimum && st.numeric > 0 {
parts.push(format!("Minimum: {}", fmt(st.min)));
parts.push(part("Minimum", fmt(st.min)));
}
if on.maximum && st.numeric > 0 {
parts.push(format!("Maximum: {}", fmt(st.max)));
parts.push(part("Maximum", fmt(st.max)));
}
if on.sum && st.numeric > 0 {
parts.push(format!("Sum: {}", fmt(st.sum)));
parts.push(part("Sum", fmt(st.sum)));
}
parts
}
@@ -586,6 +590,26 @@ mod tests {
app.session.active().unwrap().wb.sheets.iter().map(|s| s.name.clone()).collect()
}
#[test]
fn status_bar_statistics_follow_the_interface_language() {
use crate::i18n::Language;
let mut session = gridcraft_engine::Session::default();
session.new_workbook();
let mut app = SheetApp::new(session, Default::default());
for (cell, input) in [("A1", "1"), ("A2", "2"), ("A3", "3")] {
app.run("cell.set", json!({"cell": cell, "input": input})).unwrap();
}
app.run("selection.set", json!({"range": "A1:A3"})).unwrap();
app.run("view.statusBar", json!({"numericalCount": true, "minimum": true, "maximum": true})).unwrap();
let parts = [("Average", "2"), ("Count", "3"), ("Numerical Count", "3"), ("Minimum", "1"), ("Maximum", "3"), ("Sum", "6")];
let english: Vec<String> = parts.iter().map(|(label, value)| format!("{label}: {value}")).collect();
assert_eq!(super::selection_statistics(&app), english);
app.ui.language = Language::It;
let italian: Vec<String> = parts.iter().map(|(label, value)| format!("{}: {value}", Language::It.tr(label))).collect();
assert_eq!(super::selection_statistics(&app), italian, "each label as the right-click menu shows it");
assert!(italian.iter().zip(&english).all(|(it, en)| it != en), "the Italian catalog translates every label: {italian:?}");
}
#[test]
fn status_bar_shows_the_statistics_that_are_turned_on_in_order() {
let mut session = gridcraft_engine::Session::default();
+111
View File
@@ -0,0 +1,111 @@
//! Space on a checkbox cell toggles it and nothing else (#1951).
use egui::{Event, Key, Modifiers, PointerButton};
use gridcraft_engine::Session;
use gridcraft_engine::core::CellRef;
use gridcraft_engine::core::Value;
use gridcraft_ui_egui::{SheetApp, grid::Geo};
use serde_json::json;
type Harness = egui_kittest::Harness<'static, SheetApp>;
fn harness(session: Session) -> Harness {
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
SheetApp::new(session, Default::default()),
);
h.run_steps(4);
h
}
/// A space, as a keyboard reports it: the key press, the text it produces, then the release.
fn space(h: &mut Harness) {
let k = |pressed| Event::Key { key: Key::Space, physical_key: Some(Key::Space), pressed, repeat: false, modifiers: Modifiers::NONE };
h.input_mut().events.push(k(true));
h.input_mut().events.push(Event::Text(" ".into()));
h.input_mut().events.push(k(false));
h.run_steps(2);
}
fn press(h: &mut Harness, key: Key) {
let k = |pressed| Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: Modifiers::NONE };
h.input_mut().events.push(k(true));
h.input_mut().events.push(k(false));
h.run_steps(2);
}
fn value(h: &Harness, a1: &str) -> Option<Value> {
let d = h.state().session.active().unwrap();
d.wb.active().unwrap().cell(CellRef::parse(a1).unwrap()).map(|c| c.value.clone())
}
#[test]
fn space_toggles_a_checkbox_cell_without_editing_it() {
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "B2", "input": "FALSE"})).unwrap();
s.execute("insert.checkbox", json!({"range": "B2"})).unwrap();
s.execute("selection.set", json!({"range": "B2"})).unwrap();
let mut h = harness(s);
assert_eq!(value(&h, "B2"), Some(Value::Bool(false)));
// The key press toggles the box; the text it also produces must not start editing, or Enter
// commits that space over the checkbox and leaves the cell blank.
space(&mut h);
assert_eq!(value(&h, "B2"), Some(Value::Bool(true)));
assert!(h.state().editor.is_none(), "no editor opened");
press(&mut h, Key::Enter);
assert_eq!(value(&h, "B2"), Some(Value::Bool(true)), "Enter moved on and left the checkbox");
// And again, back to unchecked. Reached without clicking the box, since a click on the box
// toggles it in its own right (below): an ordinary cell, then across to it.
click_cell(&mut h, "D2");
press(&mut h, Key::ArrowLeft);
press(&mut h, Key::ArrowLeft);
assert_eq!(active(&h), "B2", "the arrows walked back to the checkbox");
space(&mut h);
assert_eq!(value(&h, "B2"), Some(Value::Bool(false)));
assert!(h.state().editor.is_none());
// A click on the box toggles it too, which is what the pointer path does with a checkbox
// cell and the reason the walk above avoids it.
click_cell(&mut h, "B2");
assert_eq!(value(&h, "B2"), Some(Value::Bool(true)), "the click toggled the box");
assert!(h.state().editor.is_none(), "no editor opened");
// A space still types on an ordinary cell.
click_cell(&mut h, "C3");
space(&mut h);
assert!(h.state().editor.is_some(), "an ordinary cell starts editing");
press(&mut h, Key::Escape);
}
/// Click a cell, as a person selects one: the grid's own geometry gives where it is, so the
/// click goes through hit-testing and whatever the grid does with focus, rather than the
/// selection being set behind the app's back once it is running (#1960 review).
fn click_cell(h: &mut Harness, cell: &str) {
let pos = {
let app = h.state();
let sheet = app.session.active().unwrap().wb.active().unwrap();
let geo = Geo::new(sheet, app.grid.rect.unwrap(), app.view().scroll);
geo.cell_rect(sheet, CellRef::parse(cell).unwrap()).center()
};
h.input_mut().events.extend([
Event::PointerMoved(pos),
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 click has to have landed: a selection that did not move would leave each assertion
// after it testing the cell before it instead.
assert_eq!(active(h), cell, "the click selected {cell}");
}
/// The active cell, in A1 form.
fn active(h: &Harness) -> String {
h.state().session.active().unwrap().selection.active.to_string()
}
+265
View File
@@ -0,0 +1,265 @@
//! #4389 and #4390: a selected chart outlines its data in the sheet (series names red, category
//! labels purple, values blue), and dragging a corner of the values outline changes what the
//! chart plots, through real pointer input.
use egui::{Event, Key, Modifiers, PointerButton, Pos2, Shape, vec2};
use gridcraft_engine::core::RangeRef;
use gridcraft_ui_egui::theme::Tokens;
use serde_json::json;
type Harness = egui_kittest::Harness<'static, gridcraft_ui_egui::SheetApp>;
/// 10..50 down A1:A5 and 5s below them, charted from A1:A5, which stays the cell selection as
/// after Insert › Chart, so the fill handle sits on the outline's bottom-right corner.
fn fixture() -> (Harness, u32) {
let mut session = crate::support::blank_session();
let values: Vec<_> = [10, 20, 30, 40, 50, 5, 5, 5].iter().map(|v| json!([v])).collect();
session.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap();
session.execute("selection.set", json!({"range": "A1:A5"})).unwrap();
let chart = session.execute("insert.chart", json!({"type": "column", "at": "D3", "width": 300, "height": 200})).unwrap();
let id = chart["chart"].as_u64().unwrap() as u32;
let mut h = crate::support::stepped_harness(session);
h.state_mut().select_object_id(Some(id));
h.run_steps(2);
(h, id)
}
fn values(h: &Harness) -> String {
h.state().session.doc().unwrap().wb.active().unwrap().charts[0].series[0].values.clone()
}
/// On-screen rect of `range`.
fn rect(h: &Harness, range: &str) -> egui::Rect {
let app = h.state();
let sh = app.session.doc().unwrap().wb.active().unwrap();
app.grid.geo.as_ref().unwrap().range_rect(sh, RangeRef::parse(range).unwrap())
}
fn hover(h: &mut Harness, at: Pos2) {
h.input_mut().events.push(Event::PointerMoved(at));
h.run_steps(2);
}
fn button(h: &mut Harness, at: Pos2, pressed: bool) {
h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(2);
}
/// Presses at `from` and moves to `to` in small steps, leaving the button down.
fn press_and_move(h: &mut Harness, from: Pos2, to: Pos2) {
hover(h, from);
button(h, from, true);
press_and_move_on(h, from, to);
}
/// With the button already down, moves from `from` to `to` in small steps.
fn press_and_move_on(h: &mut Harness, from: Pos2, to: Pos2) {
for i in 1..=8 {
h.input_mut().events.push(Event::PointerMoved(from + (to - from) * (i as f32 / 8.0)));
h.run_steps(1);
}
}
#[test]
fn dragging_the_values_corner_extends_the_chart_data() {
let (mut h, id) = fixture();
assert_eq!(values(&h), "Sheet1!$A$1:$A$5");
let corner = rect(&h, "A1:A5").right_bottom();
hover(&mut h, corner);
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeNwSe, "the corner shows a resize cursor, not the fill cross");
// Three rows down from the corner, as the hand moves it.
let target = rect(&h, "A8").right_bottom();
press_and_move(&mut h, corner, target);
// The outline previews the new block while the button is held; the chart is unchanged.
let blue = Tokens::get(&h.ctx).ref_color(0, true);
let preview = rect(&h, "A1:A8");
let previewed = h.output().shapes.iter().any(|s| matches!(&s.shape, Shape::Rect(r) if r.rect == preview && r.stroke.color == blue));
assert!(previewed, "the outline follows the pointer");
assert_eq!(values(&h), "Sheet1!$A$1:$A$5");
button(&mut h, target, false);
assert_eq!(values(&h), "Sheet1!$A$1:$A$8", "the chart plots the dragged block");
assert_eq!(h.state().selected_chart(), Some(id), "the chart stays selected");
let a6 = h.state().session.doc().unwrap().wb.active().unwrap().value(gridcraft_engine::core::CellRef::parse("A6").unwrap());
assert_eq!(a6, gridcraft_engine::core::Value::number(5.0), "the press did not drag the fill handle");
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(values(&h), "Sheet1!$A$1:$A$5", "one undo step puts the block back");
}
#[test]
fn dragging_the_top_corner_down_shrinks_the_chart_data() {
let (mut h, _) = fixture();
let corner = rect(&h, "A1:A5").left_top() + vec2(1.0, 1.0);
let target = rect(&h, "A3").left_top() + vec2(1.0, 1.0);
press_and_move(&mut h, corner, target);
button(&mut h, target, false);
assert_eq!(values(&h), "Sheet1!$A$3:$A$5");
}
/// #4391 review: a corner lies on the boundary of the next row and column, so reading the pointer
/// as is put a press on the bottom-right corner of A1:A5 in B6.
#[test]
fn a_drag_back_to_the_grabbed_corner_or_along_its_edge_keeps_the_other_axis() {
// Away and back to the very point pressed: nothing changes.
let (mut h, _) = fixture();
let corner = rect(&h, "A1:A5").right_bottom();
press_and_move(&mut h, corner, corner + vec2(40.0, 30.0));
press_and_move_on(&mut h, corner + vec2(40.0, 30.0), corner);
button(&mut h, corner, false);
assert_eq!(values(&h), "Sheet1!$A$1:$A$5", "a release where the press was leaves the data alone");
// Straight down the right edge of column A: rows only, no column B.
let (mut h, _) = fixture();
let corner = rect(&h, "A1:A5").right_bottom();
let target = rect(&h, "A6").right_bottom();
press_and_move(&mut h, corner, target);
button(&mut h, target, false);
assert_eq!(values(&h), "Sheet1!$A$1:$A$6");
}
/// #4391 review: the drag read the pointer from the middle of the grabbed row, so with a tall
/// row 5 the pointer could reach the bottom of a short row 6 and the block stayed at A1:A5.
#[test]
fn a_drag_past_rows_of_unequal_height_follows_the_rows_under_the_pointer() {
let (mut h, _) = fixture();
h.state_mut().run("home.rowHeight", json!({"rows": "5:5", "height": 120})).unwrap();
h.run_steps(2);
let corner = rect(&h, "A1:A5").right_bottom();
let row6 = rect(&h, "A6");
assert!(rect(&h, "A5").height() > 3.0 * row6.height(), "row 5 is much taller than row 6");
// Short of the middle of row 6 the edge stays on row 5's bottom gridline.
let short = corner + vec2(0.0, row6.height() * 0.4);
press_and_move(&mut h, corner, short);
assert!(values_outline_at(&h, "A1:A5"));
// At the bottom of row 6 the block takes row 6, in the preview and on release.
let target = row6.right_bottom();
press_and_move_on(&mut h, short, target);
assert!(values_outline_at(&h, "A1:A6"), "the preview takes row 6");
button(&mut h, target, false);
assert_eq!(values(&h), "Sheet1!$A$1:$A$6");
}
#[test]
fn escape_cancels_a_values_drag() {
let (mut h, _) = fixture();
let corner = rect(&h, "A1:A5").right_bottom();
let target = rect(&h, "A8").right_bottom();
press_and_move(&mut h, corner, target);
h.key_press(Key::Escape);
h.run_steps(2);
button(&mut h, target, false);
assert_eq!(values(&h), "Sheet1!$A$1:$A$5");
}
/// Whether the last frame stroked `range` in the values blue.
fn values_outline_at(h: &Harness, range: &str) -> bool {
let blue = Tokens::get(&h.ctx).ref_color(0, true);
let want = rect(h, range);
h.output().shapes.iter().any(|s| matches!(&s.shape, Shape::Rect(r) if r.rect == want && r.stroke.color == blue))
}
#[test]
fn a_release_in_the_same_frame_as_the_last_move_takes_the_release_position() {
let (mut h, _) = fixture();
let (corner, a6, end) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A6").right_bottom(), rect(&h, "A8").right_bottom());
press_and_move(&mut h, corner, a6);
// The pointer reaches A8 and the button goes up within one frame.
h.input_mut().events.push(Event::PointerMoved(end));
h.input_mut().events.push(Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(2);
assert_eq!(values(&h), "Sheet1!$A$1:$A$8");
}
/// A command that changes the chart's data while the button is held (the control channel runs
/// between frames) makes the drag stale: releasing must not put the dragged block over it,
/// whether the pointer moves on first or is released straight away.
#[test]
fn a_chart_data_change_during_the_drag_is_not_overwritten_by_the_release() {
for move_on in [true, false] {
let (mut h, id) = fixture();
let (corner, a7, a8) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A7").right_bottom(), rect(&h, "A8").right_bottom());
press_and_move(&mut h, corner, a7);
h.state_mut().session.execute("chart.setValuesRange", json!({"chart": id, "range": "A2:A4"})).unwrap();
if move_on {
press_and_move_on(&mut h, a7, a8);
}
button(&mut h, if move_on { a8 } else { a7 }, false);
assert_eq!(values(&h), "Sheet1!$A$2:$A$4", "the newer data stays (pointer moved on: {move_on})");
assert!(!values_outline_at(&h, "A1:A8") && !values_outline_at(&h, "A1:A7"), "no stale preview is left (pointer moved on: {move_on})");
}
}
#[test]
fn escape_with_ctrl_held_still_cancels_a_values_drag() {
let (mut h, _) = fixture();
let (corner, target) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A8").right_bottom());
press_and_move(&mut h, corner, target);
h.input_mut().events.push(Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::CTRL });
h.run_steps(2);
button(&mut h, target, false);
assert_eq!(values(&h), "Sheet1!$A$1:$A$5");
}
#[test]
fn the_preview_stays_while_the_drag_scrolls_the_chart_away() {
let (mut h, _) = fixture();
// Column A stays in a frozen pane while the chart in D:H scrolls off to the left.
h.state_mut().run("view.freezePanes", json!({"cell": "B1"})).unwrap();
h.run_steps(2);
let (corner, target) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A8").right_bottom());
press_and_move(&mut h, corner, target);
assert!(values_outline_at(&h, "A1:A8"));
h.state_mut().view_mut().unwrap().scroll.x = 3000.0;
h.run_steps(2);
assert!(values_outline_at(&h, "A1:A8"), "the dragged block is still previewed");
button(&mut h, target, false);
assert_eq!(values(&h), "Sheet1!$A$1:$A$8");
}
#[test]
fn a_corner_hidden_under_frozen_rows_cannot_be_grabbed() {
let mut session = crate::support::blank_session();
let values: Vec<_> = (1..=12).map(|v| json!([v])).collect();
session.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap();
session.execute("selection.set", json!({"range": "A5:A8"})).unwrap();
let chart = session.execute("insert.chart", json!({"type": "column", "at": "D2", "width": 300, "height": 200})).unwrap();
session.execute("view.freezePanes", json!({"cell": "A4"})).unwrap();
let mut h = crate::support::stepped_harness(session);
h.state_mut().select_object_id(Some(chart["chart"].as_u64().unwrap() as u32));
// Scroll two rows, so the top of row 5 lies under the frozen rows 1-3.
let two_rows = {
let sh = h.state().session.doc().unwrap().wb.active().unwrap().clone();
(sh.row_top(5) - sh.row_top(3)) as f32
};
h.state_mut().view_mut().unwrap().scroll.y = two_rows;
h.run_steps(2);
let app = h.state();
let sh = app.session.doc().unwrap().wb.active().unwrap();
let geo = app.grid.geo.as_ref().unwrap();
let block = geo.range_rect(sh, RangeRef::parse("A5:A8").unwrap());
let hidden = block.left_top();
let frozen_bottom = geo.y(sh, 2) + sh.row_height(2) as f32 * geo.z;
assert!(geo.cells.contains(hidden) && hidden.y + 4.0 < frozen_bottom, "the top corner lies over the frozen rows: {hidden:?} {frozen_bottom}");
assert!(gridcraft_ui_egui::chartview::chart_data_handle(app, geo, sh, hidden).is_none(), "a hidden corner is not a handle");
assert!(gridcraft_ui_egui::chartview::chart_data_handle(app, geo, sh, block.right_bottom()).is_some(), "a visible corner still is");
}
#[test]
fn a_selected_chart_outlines_names_categories_and_values_in_their_colours() {
let mut session = crate::support::blank_session();
session
.execute("range.setValues", json!({"range": "A1", "values": [["", "North", "South"], ["Q1", 10, 15], ["Q2", 20, 25], ["Q3", 30, 35]]}))
.unwrap();
session.execute("selection.set", json!({"range": "A1:C4"})).unwrap();
let chart = session.execute("insert.chart", json!({"type": "column", "at": "F2", "width": 300, "height": 200})).unwrap();
let mut h = crate::support::stepped_harness(session);
h.state_mut().select_object_id(Some(chart["chart"].as_u64().unwrap() as u32));
h.run_steps(2);
let t = Tokens::get(&h.ctx);
let stroked = |h: &Harness, range: &str, color: egui::Color32| {
let want = rect(h, range);
h.output().shapes.iter().any(|s| matches!(&s.shape, Shape::Rect(r) if r.rect == want && r.stroke.color == color && r.stroke.width == 1.5))
};
assert!(stroked(&h, "B1:C1", t.ref_color(1, true)), "series names in red");
assert!(stroked(&h, "A2:A4", t.ref_color(2, true)), "category labels in purple");
assert!(stroked(&h, "B2:C4", t.ref_color(0, true)), "the values as one blue block");
assert!(!stroked(&h, "B2:B4", t.ref_color(0, true)), "not one outline per series");
}
+50
View File
@@ -166,6 +166,56 @@ fn save_actions_include_the_cell_draft_and_close_keeps_the_unsaved_prompt() {
assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().value(CellRef::new(0, 0)), Value::Number(123.0));
}
/// Where the title bar's icon button for `name` is. Its icon has no text, so it is found by
/// hovering along the title bar until its tooltip ("Save (⌘S)") shows.
fn title_bar_button(h: &mut egui_kittest::Harness<'static, SheetApp>, name: &str) -> egui::Pos2 {
let autosave = h.get_by_label("AutoSave").rect();
let tip = format!("{name} (");
let mut x = autosave.right();
while x < autosave.right() + 300.0 {
let at = egui::pos2(x, autosave.center().y);
h.hover_at(at);
h.run_steps(3);
// The button's accessible label carries its tooltip, so the node found may be the button
// itself rather than a tooltip at the pointer: aim at the node.
if let Some(node) = h.query_by_label_contains(&tip) {
return node.rect().center();
}
x += 6.0;
}
panic!("no title bar button shows a {tip:?} tooltip");
}
#[test]
fn the_title_bar_save_button_saves_the_cell_being_typed() {
// Regression test for #223: the title bar's Save button saved the file without the cell the
// user was still typing in.
let dir = std::env::temp_dir().join(format!("gridcraft-title-bar-save-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("Book.xlsx").to_string_lossy().into_owned();
let mut h = harness(Services::default());
h.state_mut().run("file.save", serde_json::json!({"path": &path})).unwrap();
h.run_steps(2);
h.input_mut().events.push(egui::Event::Text("123".into()));
h.run_steps(2);
assert!(h.state().editor.is_some());
let save = title_bar_button(&mut h, "Save");
for pressed in [true, false] {
h.input_mut().events.push(egui::Event::PointerButton {
pos: save,
button: egui::PointerButton::Primary,
pressed,
modifiers: egui::Modifiers::NONE,
});
h.run_steps(1);
}
h.run_steps(2);
assert!(h.state().editor.is_none(), "Save commits the cell draft");
let (wb, _) = gridcraft_engine::io::open_bytes("Book.xlsx", &std::fs::read(&path).unwrap()).unwrap();
assert_eq!(wb.active().unwrap().value(CellRef::new(0, 0)), Value::Number(123.0), "the saved file has the typed value");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
/// Options opens, named Backstage pages are reachable and accessible, an invalid page errors, and both close and Back leave Backstage.
fn file_options_opens_the_options_page_and_pages_are_reachable_by_command() {
+6 -1
View File
@@ -287,7 +287,12 @@ fn table_filter_autofit_works_through_command_and_header_double_click() {
let rect = geo.cell_rect(sheet, cell);
let button = gridcraft_ui_egui::grid::filter_button_rect(&geo, sheet, cell);
let style = app.session.active().unwrap().wb.styles.get(sheet.style_id(cell));
let text_width = gridcraft_engine::cmd::format::approx_text_width("Quarterly Revenue", style.font.size, style.font.bold) * geo.z;
// Measured as AutoFit measured it, with the app's fonts (they differ from machine to
// machine). The app installs them before AutoFit runs; AutoFit without them, on the
// engine's estimate, is `autofit_filter_buttons` in the engine's tests.
let measure = app.session.text_width.as_ref().expect("the app measures text with its fonts");
let measured = measure("Quarterly Revenue", &style.font, true);
let text_width = measured * geo.z;
assert!(rect.left() + text_width + 2.5 * geo.z < button.left(), "heading overlaps filter: zoom={zoom}, double_click={double_click}");
assert_eq!(app.session.active().unwrap().undo.len(), 1);
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
+143
View File
@@ -0,0 +1,143 @@
//! IME composition at the grid level.
//!
//! With a CJK input method, the first keystroke of a composition must reach the input method,
//! not be written straight into the cell as raw text. The grid publishes `PlatformOutput::ime`
//! on every frame it owns keyboard input, so the OS delivers `ImeEvent`s; a `Commit` opens the
//! in-cell editor with the finished text. Plain ASCII keeps using `Event::Text` (no regression).
use egui::{Event, ImeEvent};
use gridcraft_engine::Session;
use gridcraft_engine::core::CellRef;
use gridcraft_ui_egui::SheetApp;
use serde_json::json;
type Harness = egui_kittest::Harness<'static, SheetApp>;
/// A warmed harness over `session`, with the grid holding keyboard input on the active cell.
///
/// The suite pins a font set with no Han face, so the harness draws tofu for the CJK commit
/// text: these tests check input routing, not glyph coverage.
fn fixture_with(session: Session) -> Harness {
let builder = crate::common::builder().allow_missing_glyphs().with_size(egui::vec2(1200.0, 800.0));
crate::common::harness_with(builder, crate::common::app(session), 4)
}
/// A warmed harness over a blank workbook, with the grid holding keyboard input on `A1`.
fn fixture() -> Harness {
fixture_with(crate::support::blank_session())
}
/// A protected sheet with `active` selected, optionally unlocking one cell first.
fn protected_session(active: &str, unlock: Option<&str>) -> Session {
let mut s = Session::new();
s.new_workbook();
if let Some(cell) = unlock {
s.execute("home.formatCells", json!({"range": cell, "style": {"protection": {"locked": false}}})).unwrap();
}
s.execute("review.protectSheet", json!({})).unwrap();
s.execute("selection.set", json!({"cell": active})).unwrap();
s
}
/// The text the in-cell editor currently holds, or `None` when no editor is open.
fn editor_text(h: &Harness) -> Option<String> {
h.state().editor.as_ref().map(|ed| ed.text.clone())
}
/// The grid must request IME on every frame it owns keyboard input: winit applies
/// `set_ime_allowed` at the end of the frame, so requesting it in response to the first key is
/// already too late. The commit tests below only exercise the event handler and would still
/// pass with `request_grid_ime` removed, so this asserts the actual fix.
#[test]
fn grid_publishes_ime_request_before_the_first_keystroke() {
let mut h = fixture();
h.run_steps(1);
let ime = h.output().platform_output.ime.as_ref().expect("the focused grid must request IME");
assert!(matches!(ime.purpose, egui::IMEPurpose::Normal), "cell text is ordinary input");
assert!(ime.rect.width() > 0.0 && ime.rect.height() > 0.0, "the IME rect must cover the active cell");
assert_eq!(ime.cursor_rect.min, ime.rect.min, "the caret sits at the cell's start");
assert!(ime.context_generation > 0, "egui 0.37 needs a non-zero IME context generation");
}
/// When a dialog takes the keyboard, `PlatformOutput` must stop advertising a grid IME owner.
/// The output is rebuilt each frame, so an early return is what turns IME off.
#[test]
fn grid_withholds_ime_request_when_it_does_not_own_keyboard_input() {
let mut h = fixture();
h.state_mut().message = Some(("GridCraft".into(), "busy".into()));
h.run_steps(1);
assert!(h.output().platform_output.ime.is_none(), "a message dialog must take IME ownership away from the grid");
}
/// A locked cell on a protected sheet cannot be edited, so inviting a composition there would
/// only produce text that `SheetApp::begin_edit` discards.
#[test]
fn locked_cell_on_a_protected_sheet_does_not_request_ime() {
let mut h = fixture_with(protected_session("A1", None));
h.run_steps(1);
assert!(h.output().platform_output.ime.is_none(), "a composition on a locked cell is always refused");
}
/// The protection guard must not disable IME for cells that are still editable.
#[test]
fn unlocked_cell_on_a_protected_sheet_still_requests_ime() {
let mut h = fixture_with(protected_session("C2", Some("C2")));
h.run_steps(1);
assert!(h.output().platform_output.ime.is_some(), "unlocked cells stay editable on a protected sheet");
}
/// `IMEOutput::rect` is in screen coordinates, while `Geo::cell_rect` is in logical ones; on a
/// right-to-left sheet the two differ, and the candidate window must follow the drawn cell.
#[test]
fn right_to_left_sheet_publishes_mirrored_ime_rects() {
let mut s = Session::new();
s.new_workbook();
s.execute("view.rightToLeft", json!({"on": true})).unwrap();
s.execute("selection.set", json!({"cell": "B2"})).unwrap();
let mut h = fixture_with(s);
h.run_steps(1);
let geo = h.state().grid.geo.clone().expect("the grid has been drawn");
let sheet = h.state().session.active().unwrap().wb.active().unwrap();
let logical = geo.cell_rect(sheet, CellRef::parse("B2").unwrap());
let expected = geo.mirror_rect(logical);
assert!(geo.rtl, "the fixture must be right-to-left");
assert!((expected.min.x - logical.min.x).abs() > 1.0, "the fixture must distinguish mirrored from logical x");
let ime = h.output().platform_output.ime.as_ref().expect("the focused grid must request IME");
assert!((ime.rect.min.x - expected.min.x).abs() < 0.01, "IME rect must use screen coordinates: got {:?}, expected {:?}", ime.rect, expected);
assert!((ime.rect.max.x - expected.max.x).abs() < 0.01, "IME rect must use screen coordinates: got {:?}, expected {:?}", ime.rect, expected);
assert!((ime.cursor_rect.min.x - ime.rect.min.x).abs() < 0.01, "the caret must sit at the mirrored cell's start");
}
/// A committed composition opens the editor with its text and leaves the caret after it.
#[test]
fn ime_commit_opens_editor_with_committed_text() {
let mut h = fixture();
h.input_mut().events.push(Event::Ime(ImeEvent::Commit("张".into())));
h.run_steps(2);
let ed = h.state().editor.as_ref().expect("an IME commit must open the in-cell editor");
assert_eq!(ed.text, "张", "the committed text should seed the editor");
assert_eq!(ed.caret, ed.text.chars().count(), "the caret should sit after the committed text");
}
/// A preedit is not text yet: it must not open the editor on its own, only the commit does.
#[test]
fn ime_preedit_does_not_seed_editor() {
let mut h = fixture();
h.input_mut().events.push(Event::Ime(ImeEvent::Preedit { text: "zh".into(), active_range_chars: Some(0..2) }));
h.run_steps(2);
assert!(h.state().editor.is_none(), "a preedit must not seed the editor on its own");
h.input_mut().events.push(Event::Ime(ImeEvent::Commit("张".into())));
h.run_steps(2);
assert_eq!(editor_text(&h).as_deref(), Some("张"), "the commit after a preedit opens the editor");
}
/// Plain ASCII never composes, so `Event::Text` still seeds the editor exactly as before.
#[test]
fn ascii_text_still_seeds_editor_no_regression() {
let mut h = fixture();
h.input_mut().events.push(Event::Text("abc".into()));
h.run_steps(2);
assert_eq!(editor_text(&h).as_deref(), Some("abc"), "ASCII typing must still seed the editor");
}
+24
View File
@@ -19,6 +19,30 @@ fn blank() -> Session {
s
}
#[test]
fn the_formulas_ribbon_keeps_watch_window_inside_the_ribbon() {
// Regression test for #360 (#342): Watch Window was a fourth small button in a column of
// three, so it hung below the ribbon and was cut off.
fn texts(shape: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
match shape {
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| texts(s, out)),
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.galley.rect.translate(t.pos.to_vec2()))),
_ => {}
}
}
let mut h = harness(blank());
h.state_mut().ui.ribbon_tab = "Formulas".into();
h.run_steps(3);
// Ribbon button labels are painted text: find them among the frame's shapes.
let mut painted = Vec::new();
h.output().shapes.iter().for_each(|c| texts(&c.shape, &mut painted));
let bottom_of = |word: &str| painted.iter().filter(|(s, _)| s.contains(word)).map(|(_, r)| r.bottom()).fold(f32::NEG_INFINITY, f32::max);
// "Calculation Options" is a big button whose second line sits at the foot of the ribbon.
let (watch, foot) = (bottom_of("Window"), bottom_of("Options"));
assert!(watch.is_finite() && foot.is_finite(), "the Formulas ribbon paints Watch Window and Calculation Options");
assert!(watch <= foot + 0.5, "Watch Window's label ends at y={watch}, below the ribbon's last label row (y={foot})");
}
#[test]
fn vertical_scrollbar_pages_and_drags_without_changing_selection() {
let mut h = harness(blank());
@@ -212,6 +212,144 @@ fn alt_down_only_opens_enabled_table_filter_buttons() {
}
}
/// A key press as a non-US layout reports it: `typed` is the character the layout types (egui's
/// logical key), `at` the key's position named after a US keyboard.
fn key_on_layout(h: &mut Harness, typed: Key, at: Key, m: Modifiers) {
h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: true, repeat: false, modifiers: m });
h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: false, repeat: false, modifiers: m });
h.run_steps(2);
}
fn editor_text(h: &Harness) -> Option<String> {
h.state().editor.as_ref().map(|e| e.text.clone())
}
fn today(h: &Harness) -> String {
let d = h.state().session.active().unwrap();
let now = gridcraft_engine::core::date::serial_in_system(d.wb.date_system, gridcraft_engine::calc::now_serial());
gridcraft_engine::display::format(&gridcraft_engine::core::Value::Number(now.floor()), "m/d/yyyy", &d.wb).text
}
#[test]
fn symbol_shortcuts_follow_the_character_the_layout_types() {
// Croatian and German keyboards type `;` with Shift+, and `:` with Shift+. (US positions).
// `+` is unshifted, on the US `=` key (Croatian) or `]` key (German); `'` is the US `-` key
// (Croatian) or Shift+# on the US `\` key (German); Shift+0 types `=` on both.
for (layout, plus_at, quote_at, quote_shift) in [("hr", Key::Equals, Key::Minus, false), ("de", Key::CloseBracket, Key::Backslash, true)] {
let mut h = harness(book("C2"));
let size = style(&h, "C2").font.size;
// Ctrl+; (Ctrl+Shift+,): today's date, not Decrease Font Size.
key_on_layout(&mut h, Key::Semicolon, Key::Comma, CTRL_SHIFT);
assert_eq!(editor_text(&h), Some(today(&h)), "{layout}: Ctrl+;");
assert_eq!(style(&h, "C2").font.size, size, "{layout}: Ctrl+; changed the font size");
key(&mut h, Key::Escape, Modifiers::NONE);
// Ctrl+: (Ctrl+Shift+.): the time, not Increase Font Size.
key_on_layout(&mut h, Key::Colon, Key::Period, CTRL_SHIFT);
let time = editor_text(&h).unwrap_or_default();
assert!(time.contains(':') && (time.ends_with("AM") || time.ends_with("PM")), "{layout}: Ctrl+: gave {time:?}");
assert_eq!(style(&h, "C2").font.size, size, "{layout}: Ctrl+: changed the font size");
key(&mut h, Key::Escape, Modifiers::NONE);
// Ctrl+': the formula of the cell above.
key_on_layout(&mut h, Key::Quote, quote_at, if quote_shift { CTRL_SHIFT } else { CTRL });
assert_eq!(editor_text(&h).as_deref(), Some("=A1*2"), "{layout}: Ctrl+'");
key(&mut h, Key::Escape, Modifiers::NONE);
// Ctrl++: Insert, as Ctrl+Shift+= on a US keyboard.
key_on_layout(&mut h, Key::Plus, plus_at, CTRL);
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("insertCells"), "{layout}: Ctrl++");
h.state_mut().dialog = None;
// Digits go by position: Ctrl+Shift+0 unhides columns although it types `=`.
h.state_mut().session.run("selection.set", json!({"range": "B:B"})).unwrap();
h.state_mut().session.run("home.hideColumns", json!({})).unwrap();
h.state_mut().session.run("selection.set", json!({"range": "A1:C1"})).unwrap();
key_on_layout(&mut h, Key::Equals, Key::Num0, CTRL_SHIFT);
assert!(h.state().dialog.is_none(), "{layout}: Ctrl+Shift+0 opened {:?}", h.state().dialog.as_ref().map(|d| d.name()));
let d = h.state().session.active().unwrap();
assert!(!d.wb.active().unwrap().is_col_hidden(1), "{layout}: Ctrl+Shift+0 didn't unhide column B");
}
}
#[test]
fn date_and_time_shortcuts_on_azerty_and_czech_keyboards() {
// French AZERTY types `;` and `:` unshifted on the US `,` and `.` keys; Czech QWERTZ types `;`
// unshifted on the US backtick key and `:` with Shift+. (US positions).
for (layout, semi_at, semi_m, colon_m) in [("fr", Key::Comma, CTRL, CTRL), ("cs", Key::Backtick, CTRL, CTRL_SHIFT)] {
let mut h = harness(book("C2"));
let size = style(&h, "C2").font.size;
key_on_layout(&mut h, Key::Semicolon, semi_at, semi_m);
assert_eq!(editor_text(&h), Some(today(&h)), "{layout}: Ctrl+;");
key(&mut h, Key::Escape, Modifiers::NONE);
key_on_layout(&mut h, Key::Colon, Key::Period, colon_m);
let time = editor_text(&h).unwrap_or_default();
assert!(time.contains(':') && (time.ends_with("AM") || time.ends_with("PM")), "{layout}: Ctrl+: gave {time:?}");
assert_eq!(style(&h, "C2").font.size, size, "{layout}: the font size changed");
}
}
#[test]
fn layout_keys_type_their_character_in_a_cell_being_edited() {
// While a cell is edited the grid reads no shortcuts, so `;` and `:` (Shift+, and Shift+. on
// Croatian and German keyboards) are typed, and nothing changes the font size.
let mut h = harness(book("C2"));
let size = style(&h, "C2").font.size;
h.input_mut().events.push(Event::Text("x".into()));
h.run_steps(2);
for (typed, at, text) in [(Key::Semicolon, Key::Comma, ";"), (Key::Colon, Key::Period, ":")] {
let m = Modifiers::SHIFT;
h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: true, repeat: false, modifiers: m });
h.input_mut().events.push(Event::Text(text.into()));
h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: false, repeat: false, modifiers: m });
h.run_steps(2);
}
assert_eq!(editor_text(&h).as_deref(), Some("x;:"));
assert_eq!(style(&h, "C2").font.size, size);
}
#[test]
fn us_symbol_shortcuts_keep_their_keys() {
let mut h = harness(book("C2"));
// Ctrl+;: the date. Ctrl+Shift+; arrives as `:` on Windows and as `;` with Shift elsewhere.
key(&mut h, Key::Semicolon, CTRL);
assert_eq!(editor_text(&h), Some(today(&h)));
key(&mut h, Key::Escape, Modifiers::NONE);
for typed in [Key::Colon, Key::Semicolon] {
key_on_layout(&mut h, typed, Key::Semicolon, CTRL_SHIFT);
assert!(editor_text(&h).is_some_and(|t| t.ends_with("AM") || t.ends_with("PM")), "Ctrl+Shift+; as {typed:?}");
key(&mut h, Key::Escape, Modifiers::NONE);
}
// Ctrl+Shift+, and Ctrl+Shift+. (`<` and `>` have no egui key) change the font size.
let size = style(&h, "C2").font.size;
key(&mut h, Key::Period, CTRL_SHIFT);
assert!(style(&h, "C2").font.size > size);
key(&mut h, Key::Comma, CTRL_SHIFT);
assert_eq!(style(&h, "C2").font.size, size);
// Ctrl+Shift+= arrives as `+`: Insert.
key_on_layout(&mut h, Key::Plus, Key::Equals, CTRL_SHIFT);
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("insertCells"));
let run = |id: &'static str| Some(Shortcut::Run(id, json!({})));
// The lookup itself: `;` typed with Shift is Ctrl+; (handled with the Ctrl letters), not the
// key's position (Decrease Font Size).
assert_eq!(lookup(Key::Semicolon, Some(Key::Comma), CTRL_SHIFT, false), None);
assert_eq!(lookup(Key::Colon, Some(Key::Period), CTRL_SHIFT, false), Some(Shortcut::Time));
assert_eq!(lookup(Key::Comma, Some(Key::Comma), CTRL_SHIFT, false), run("home.decreaseFontSize"));
// A character egui has no key for (`č` on the US `;` key) leaves the position.
assert_eq!(lookup(Key::Semicolon, Some(Key::Semicolon), CTRL_SHIFT, false), Some(Shortcut::Time));
}
#[test]
fn cmd_shift_semicolon_on_a_mac_does_not_insert_the_date() {
// The Mac table has Cmd+; (the time) and Control+; (the date), and nothing for Cmd+Shift+;. It
// arrives as `:` on the US `;` key, or on the US `.` key of a Croatian or German keyboard.
let mut h = harness(book("C2"));
h.ctx.set_os(egui::os::OperatingSystem::Mac);
let cmd_shift = Modifiers { shift: true, mac_cmd: true, command: true, ..Modifiers::NONE };
for at in [Key::Semicolon, Key::Period] {
key_on_layout(&mut h, Key::Colon, at, cmd_shift);
assert_eq!(editor_text(&h), None, "Cmd+Shift+; at {at:?}");
}
key(&mut h, Key::Semicolon, Modifiers { mac_cmd: true, command: true, ..Modifiers::NONE });
assert!(editor_text(&h).is_some_and(|t| t.ends_with("AM") || t.ends_with("PM")), "Cmd+; is still the time");
}
/// #1443: Ctrl+Q (also with Shift or Alt, which is what AltGr+Q reports on Windows) must not
/// close the window and lose unsaved input; macOS keeps Cmd+Q as the app's Quit.
#[test]

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