Compare commits

..
Author SHA1 Message Date
FredApps 7065d3d36f Resume workbook validation at the range preview regression [workbook only] 2026-12-03 00:08:13 +01:00
FredApps 7f6a69b126 Return the workbook preview to the first sheet when its page range changes 2026-12-03 00:05:11 +01:00
FredApps 475dc6c43a Restore PrintScope in the ranged Print view and resume at the UI tests [workbook only] 2026-12-02 23:53:24 +01:00
FredApps 0e73f559d4 Verify changed selection, browser refusal and native print window together [workbook only] 2026-12-02 23:40:12 +01:00
FredApps b5d3ab97dd Keep workbook print settings available when the browser refuses the PDF 2026-12-02 23:39:41 +01:00
FredApps 3db0857bc9 Use craft-print for GridCraft web printing
Stage this switch until the shared browser lifecycle patch is included in the unified craft-libs pin and verified with browser PDF viewers.
2026-12-02 23:39:41 +01:00
FredApps a52182d431 Use current queue fixtures and inspect the selected worksheet PDF page 2026-12-02 23:34:26 +01:00
FredApps f6f2648962 Check the app print graph independently from the desktop nightly updater [workbook only] 2026-12-02 23:31:06 +01:00
FredApps d68512302f Verify combined workbook print ranges on shared and native app paths 2026-12-02 23:27:20 +01:00
FredApps 79c0836f34 Use shared page bounds for workbook print, preview and PDF output 2026-12-02 23:25:58 +01:00
FredApps 894bb14be2 Integrate the contributor page-range controls with current GridCraft printing 2026-12-02 23:21:15 +01:00
Ingmar Lübbe c50fa8d3e1 Merge remote-tracking branch 'origin/main' into feat/print-page-range 2026-11-13 14:08:55 +01:00
Ingmar Lübbe 30bfcac0d1 Merge remote-tracking branch 'origin/main' into feat/print-page-range
# Conflicts:
#	docs/file-format-parity.md
#	docs/ui-parity.md
2026-11-05 09:47:47 +01:00
Ingmar Lübbe 078ef5f7cc Merge remote-tracking branch 'origin/main' into feat/print-page-range 2026-11-04 07:44:45 +01:00
Ingmar LübbeandClaude Opus 5.5 1bfd0f0cf0 Print: a call to another window uses that window's page range (#3016)
`engine.execute` with `window` or `doc` made the target window active in the engine, but a UI
command such as `ui.printSettings` or `ui.printSubmit` still read and changed the interface state
of the window that was active: it set that window's page range, and printed the target workbook
with it. `run_in` now brings in the target window's interface state before the command and the
active window's after it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj
2026-11-04 00:12:27 +01:00
Ingmar LübbeandClaude Opus 5.5 6376c5ddb2 Print: each window keeps its own page range (#3016)
File › Print's page range was one for the whole app: with two workbooks in their Print views, a
range set in one applied to the other, and one starting after its last page disabled its Print
button. `print_pages` is now part of the interface state each window parks and swaps in, like its
Backstage view; a new window starts with every page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj
2026-11-03 20:21:36 +01:00
Ingmar Lübbe 3f935e0461 Merge remote-tracking branch 'origin/main' into feat/print-page-range
# Conflicts:
#	docs/file-format-parity.md
#	docs/ui-parity.md
2026-11-03 19:59:49 +01:00
Ingmar Lübbe 455d11bd5a Merge remote-tracking branch 'origin/main' into feat/print-page-range
# Conflicts:
#	docs/file-format-parity.md
#	docs/ui-parity.md
2026-11-02 17:51:54 +01:00
Ingmar Lübbe 9f5919dd87 Merge remote-tracking branch 'origin/main' into feat/print-page-range
# Conflicts:
#	crates/engine/src/cmd/print/tests.rs
#	docs/file-format-parity.md
#	docs/gaps.md
#	docs/ui-parity.md
2026-11-02 16:11:26 +01:00
Ingmar Lübbe b1ecd718af Merge remote-tracking branch 'origin/main' into feat/print-page-range
# Conflicts:
#	docs/gaps.md
#	docs/ui-parity.md
2026-11-02 15:41:14 +01:00
Ingmar Lübbe 0ba908412c Merge remote-tracking branch 'origin/main' into feat/print-page-range
# Conflicts:
#	docs/gaps.md
2026-11-02 07:34:17 +01:00
Ingmar LübbeandClaude Opus 5.5 adbcd14233 Print: a page range counts the pages in the sheet's page order (#3016)
With main's page order merged in, a test holds `from`/`to` to the pages as they print: over,
then down, page 2 of a 2×2 sheet is the top right one and page 3 the bottom left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj
2026-11-02 07:26:37 +01:00
Ingmar Lübbe 145c253a60 Merge remote-tracking branch 'origin/main' into feat/print-page-range
# Conflicts:
#	crates/engine/src/cmd/print.rs
#	docs/file-format-parity.md
#	docs/gaps.md
#	docs/ui-parity.md
2026-11-02 07:08:41 +01:00
Ingmar LübbeandClaude Opus 5.5 4f7f73cd4b Print: a page range (Pages … to …) in File › Print and Export as PDF (#3016)
file.print, file.exportPdf and file.printPreview take `from` and `to`,
page numbers counted over the whole job in sheet order. Only those pages
print, and their headers and footers keep the job's &P and &N. As Excel
measures it, a range after the last page is an error, `to` past the last
page stops there and `from` greater than `to` prints the pages between.
The preview lists only the pages that print, under their own numbers.

File › Print has Pages … to … below the scope, set through
ui.printSettings, which takes `from`/`to` (null clears one);
ui.printSubmit prints that range. Export › Create PDF has the same
fields. Labels in all interface languages; docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj
2026-10-31 10:15:30 +01:00
43 changed files with 850 additions and 138 deletions
+76
View File
@@ -0,0 +1,76 @@
name: Workbook print range verification
on:
push:
branches: [verify/gridcraft-print-range-4859]
permissions:
contents: read
env:
CARGO_PROFILE_TEST_DEBUG: 0
CARGO_PROFILE_DEV_DEBUG: 0
CARGO_INCREMENTAL: 0
jobs:
shared:
if: "!contains(github.event.head_commit.message, '[workbook only]')"
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
repository: storytold/craft-libs
ref: 2ed780c05a40870fe0487b04d74aa0d4d89a18c8
persist-credentials: false
- run: |
set -euo pipefail
cargo test --locked -p craft-pages --lib | tee "$RUNNER_TEMP/shared.txt"
grep -E 'print_page_spans_follow_whole_job_bounds.*ok' "$RUNNER_TEMP/shared.txt"
workbook:
runs-on: ubuntu-24.04
timeout-minutes: 115
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: 1
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/install-apt-packages@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
packages: >-
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev
libgtk-3-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers libgl1-mesa-dev libasound2-dev xvfb xauth
- name: Check framework dependencies used by the engine and print UI
run: |
set -euo pipefail
old=8fa4db64a9bb943520259ea95331a303ba788f21
new=2ed780c05a40870fe0487b04d74aa0d4d89a18c8
git grep -lz -F "$old" -- Cargo.toml Cargo.lock ':(glob)**/Cargo.toml' | xargs -0 sed -i "s/$old/$new/g"
cargo metadata --format-version 1 > "$RUNNER_TEMP/graph.json"
python3 - "$RUNNER_TEMP/graph.json" "$new" <<'PY'
import json, sys
graph = json.load(open(sys.argv[1]))
packages = {p["id"]: p for p in graph["packages"]}
nodes = {n["id"]: n for n in graph["resolve"]["nodes"]}
expected = {"gridcraft-engine": "craft-pages", "gridcraft-ui-egui": "craft-print"}
for name, required in expected.items():
app, = [p for p in packages.values() if p["name"] == name]
deps = [packages[d["pkg"]] for d in nodes[app["id"]]["deps"]]
libs = [p for p in deps if "github.com/storytold/craft-libs" in (p["source"] or "")]
assert required in {p["name"] for p in libs}, (name, required)
for lib in libs:
assert lib["source"].endswith("#" + sys.argv[2]), (name, lib["name"], lib["source"])
# The desktop nightly updater has an intentional, independent baseline pin.
PY
- name: Native print window and browser selection retry
run: |
set -euo pipefail
xvfb-run -a cargo test --locked -p gridcraft-ui-egui --test it --test print_selection -- the_print_views_page_fields_set_the_range_and_the_preview_follows print_selection_previews the_preview_follows refused_browser_handoff --test-threads=1 | tee "$RUNNER_TEMP/ui.txt"
for test in the_print_views_page_fields_set_the_range_and_the_preview_follows refused_browser_handoff_keeps_the_print_selection_available_for_retry; do
grep -E "test .*${test}.*ok" "$RUNNER_TEMP/ui.txt"
done
- name: Compile the real browser print hook
run: |
rustup target add wasm32-unknown-unknown
cargo check --locked --target wasm32-unknown-unknown -p gridcraft-web
Generated
+1
View File
@@ -3078,6 +3078,7 @@ dependencies = [
name = "gridcraft-web"
version = "0.20.0"
dependencies = [
"craft-print",
"craft-web-api",
"craft-web-host",
"eframe",
+1
View File
@@ -44,6 +44,7 @@ craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9
# Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs`
# turn them into workbooks.
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-pages = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
# The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back.
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
+2 -1
View File
@@ -25,9 +25,10 @@ log = { workspace = true }
serde_json = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
craft-print = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
rfd = { workspace = true }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "AddEventListenerOptions", "Storage", "CustomEvent", "CustomEventInit"] }
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "Storage", "CustomEvent", "CustomEventInit"] }
+1 -74
View File
@@ -227,11 +227,7 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
log::error!("download of {name} failed: {e}");
}
})),
print: Some(Box::new(|bytes: &[u8]| {
if let Err(e) = print_pdf(bytes) {
log::error!("print failed: {e}");
}
})),
print: Some(Box::new(craft_print::browser::print_pdf)),
open_url: Some(Box::new(|url: &str| {
if let Some(w) = web_sys::window()
&& let gridcraft_engine::links::LinkKind::External(url) = gridcraft_engine::links::classify(url)
@@ -280,75 +276,6 @@ fn copy_html(html: &str, text: &str) -> Result<(), String> {
Ok(())
}
/// Opens `bytes` (a PDF) as an object URL in a hidden iframe and calls the iframe's own
/// `print()` once it has finished loading — the standard way to drive the browser's native print
/// dialog on a PDF without a download or a popup window the browser might block. The blob URL and
/// the iframe are both cleaned up once the print dialog closes, so repeated prints don't leak
/// them.
fn print_pdf(bytes: &[u8]) -> Result<(), String> {
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
let window = web_sys::window().ok_or("no window")?;
let document = window.document().ok_or("no document")?;
let iframe: web_sys::HtmlIFrameElement = document.create_element("iframe").map_err(js)?.dyn_into().map_err(|_| "not an iframe")?;
iframe.style().set_property("display", "none").map_err(js)?;
let body = document.body().ok_or("no body")?;
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
let opts = web_sys::BlobPropertyBag::new();
opts.set_type("application/pdf");
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
if let Err(e) = body.append_child(&iframe) {
cleanup_print(&iframe, &url);
return Err(js(e));
}
// `onload` fires once the PDF has actually rendered inside the iframe;
// printing before that would show a blank page. Set the handler BEFORE
// `src` so a fast/cached load can't fire before we're listening.
let iframe_for_load = iframe.clone();
let url_for_cleanup = url.clone();
let on_load = wasm_bindgen::closure::Closure::once_into_js(move || {
iframe_for_load.set_onload(None);
if let Err(e) = print_loaded_pdf(&iframe_for_load, &url_for_cleanup) {
cleanup_print(&iframe_for_load, &url_for_cleanup);
log::error!("print failed: {e:?}");
}
});
iframe.set_onload(Some(on_load.unchecked_ref()));
iframe.set_src(&url);
Ok(())
}
fn cleanup_print(iframe: &web_sys::HtmlIFrameElement, url: &str) {
// Both operations are idempotent: print can fail after dispatching `afterprint`.
web_sys::Url::revoke_object_url(url).ok();
iframe.remove();
}
fn print_loaded_pdf(iframe: &web_sys::HtmlIFrameElement, url: &str) -> Result<(), JsValue> {
let content_window = iframe.content_window().ok_or_else(|| JsValue::from_str("no print content window"))?;
let iframe_for_cleanup = iframe.clone();
let url_for_cleanup = url.to_owned();
let on_after_print = wasm_bindgen::closure::Closure::once(move || {
cleanup_print(&iframe_for_cleanup, &url_for_cleanup);
});
// Listen before `print()`, which can dispatch `afterprint` before it returns.
// A one-shot listener also releases the callback when the dialog closes or is cancelled.
let options = web_sys::AddEventListenerOptions::new();
options.set_once(true);
let callback = on_after_print.as_ref().unchecked_ref();
content_window.add_event_listener_with_callback_and_add_event_listener_options("afterprint", callback, &options)?;
if let Err(e) = content_window.print() {
let _ = content_window.remove_event_listener_with_callback("afterprint", callback);
return Err(e);
}
let _ = on_after_print.into_js_value();
Ok(())
}
fn mime_for(name: &str) -> &'static str {
match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() {
Some("xlsx") => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+1
View File
@@ -22,6 +22,7 @@ thiserror = { workspace = true }
log = { workspace = true }
gridcraft-xlsx = { workspace = true }
craft-csv = { workspace = true }
craft-pages = { workspace = true }
craft-gridcraft-format = { workspace = true }
gridcraft-chart = { workspace = true }
gridcraft-pdf = { workspace = true }
+40 -12
View File
@@ -7,7 +7,9 @@
//! drawn into a PDF with `gridcraft-pdf`: fills, gridlines, borders, formatted text (fonts mapped
//! to the standard 14 PDF fonts), merged cells, wrapping, overflow into empty neighbours,
//! conditional formats, table styles, charts, images, shapes and sparklines. Headers and footers
//! support `&L`/`&C`/`&R` sections and the `&P &N &D &T &A &F &Z` codes.
//! support `&L`/`&C`/`&R` sections and the `&P &N &D &T &A &F &Z` codes. A page range
//! (`from`/`to`, File › Print's Pages … to …) prints some of the job's pages, each still numbered
//! as in the whole job.
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value};
#[cfg(test)]
@@ -69,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export as PDF",
["File", "Export"],
None,
"{path?, sheets?: active|all, range?: \"A1:F40\" or several areas \"A1:B5,D1:E5\", one run of pages each (active sheet), fitToPage?: bool} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup.",
"{path?, sheets?: active|all, range?: \"A1:F40\" or several areas \"A1:B5,D1:E5\" (active sheet), fitToPage?: bool, from?: page (1-based, counted over the whole job in sheet order), to?: page} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup. A page range prints only its pages, and their headers and footers keep the whole job's &P and &N; `from` after the last page is an error, `to` past it stops at the last page, and `from` greater than `to` prints the pages between them.",
has_doc,
export_pdf
),
@@ -78,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print…",
["File"],
Some("Cmd+P"),
"{path?, sheets?: active|all, range?, fitToPage?: bool} → {pages, bytes, base64} — the PDF the UI hands to the system print dialog",
"{path?, sheets?: active|all, range?, fitToPage?: bool, from?: page (1-based, over the whole job), to?: page} → {pages, bytes, base64} — the PDF the UI hands to the system print dialog; a page range works as in file.exportPdf",
has_doc,
print
),
@@ -87,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Preview",
["File"],
None,
"{page? (1-based), sheets?: active|all, range?, fitToPage?} → {pages, pageList: [{page, sheet, range, rows, columns, scale, paper, orientation, pageOrder, width, height}]} in print order",
"{page? (1-based), sheets?: active|all, range?, fitToPage?, from?: page, to?: page} → {pages, total, pageList: [{page, sheet, range, rows, columns, scale, paper, orientation, pageOrder, width, height}]} in print order; with a page range, pageList holds only the pages that print, under their numbers in the whole job of `total` pages",
has_doc,
print_preview
),
@@ -119,12 +121,19 @@ const MISSING_ARABIC_FONT: &str = "Some Arabic text could not be drawn in this P
/// Renders laid-out sheets to a PDF.
pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str) -> Result<RenderedPdf> {
render_pdf_with_image_budget(wb, layouts, file, path, gridcraft_pdf::MAX_DOC_IMAGE_BYTES)
render_pdf_with_image_budget(wb, layouts, file, path, gridcraft_pdf::MAX_DOC_IMAGE_BYTES, 1..=usize::MAX)
}
/// [`render_pdf`] keeping at most `image_bytes` of picture data in the document (tests lower it
/// to exercise the cap without building gigabytes of pictures).
fn render_pdf_with_image_budget(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str, image_bytes: u64) -> Result<RenderedPdf> {
fn render_pdf_with_image_budget(
wb: &Workbook,
layouts: &[SheetLayout],
file: &str,
path: &str,
image_bytes: u64,
pages: std::ops::RangeInclusive<usize>,
) -> Result<RenderedPdf> {
let mut doc = PdfDoc::new();
doc.set_image_budget(image_bytes);
doc.info.title = if wb.props.title.is_empty() { file.to_string() } else { wb.props.title.clone() };
@@ -145,6 +154,9 @@ fn render_pdf_with_image_budget(wb: &Workbook, layouts: &[SheetLayout], file: &s
let (aw, ah) = lay.avail();
for (pi, (ri, ci)) in lay.pages.iter().enumerate() {
page_no += 1;
if !pages.contains(&page_no) {
continue;
}
let (Some(rband), Some(cband)) = (lay.row_bands.get(*ri).copied(), lay.col_bands.get(*ci).copied()) else { continue };
let rsegs = segments(lay.title_rows, rband);
let csegs = segments(lay.title_cols, cband);
@@ -223,8 +235,9 @@ fn build_pdf(s: &mut Session, p: &Json, cmd: &str) -> Result<(Vec<u8>, usize)> {
let opts = PrintOptions::from_params(p, cmd)?;
let d = s.doc()?;
let lays = layouts(&d.wb, &opts);
let (first, last) = opts.page_span(lays.iter().map(|l| l.pages.len()).sum(), cmd)?;
let path = d.path.clone().unwrap_or_default();
let pdf = render_pdf(&d.wb, &lays, &d.display_title(), &path)?;
let pdf = render_pdf_with_image_budget(&d.wb, &lays, &d.display_title(), &path, gridcraft_pdf::MAX_DOC_IMAGE_BYTES, first..=last)?;
if pdf.missing_arabic_font {
s.ui_requests.push(crate::UiRequest::Message(MISSING_ARABIC_FONT.into()));
}
@@ -252,16 +265,24 @@ fn print(s: &mut Session, p: &Json) -> Result<Json> {
Ok(out)
}
/// The pages a print would print, each with its number in the whole job: a page range lists only
/// the pages in it, under their own numbers.
fn print_preview(s: &mut Session, p: &Json) -> Result<Json> {
let opts = PrintOptions::from_params(p, "file.printPreview")?;
const CMD: &str = "file.printPreview";
let opts = PrintOptions::from_params(p, CMD)?;
let d = s.doc()?;
let lays = layouts(&d.wb, &opts);
let total: usize = lays.iter().map(|l| l.pages.len()).sum();
let (first, last) = opts.page_span(total, CMD)?;
let mut list = Vec::new();
let mut n = 0usize;
for lay in &lays {
let name = d.wb.sheet(lay.sheet).map(|s| s.name.clone()).unwrap_or_default();
for (ri, ci) in &lay.pages {
n += 1;
if !(first..=last).contains(&n) {
continue;
}
let (Some(rb), Some(cb)) = (lay.row_bands.get(*ri), lay.col_bands.get(*ci)) else { continue };
let r = RangeRef::new(CellRef::new(rb.0, cb.0), CellRef::new(rb.1, cb.1));
list.push(json!({
@@ -280,11 +301,18 @@ fn print_preview(s: &mut Session, p: &Json) -> Result<Json> {
}
}
if let Some(page) = u32_param(p, "page") {
let one =
list.get((page as usize).saturating_sub(1)).cloned().ok_or_else(|| bad("file.printPreview", format!("there are only {n} pages")))?;
return Ok(json!({"pages": n, "page": one}));
let page = (page as usize).max(1);
if page > total {
return Err(bad(CMD, format!("there are only {total} pages")));
}
let one = list
.iter()
.find(|pg| pg["page"].as_u64() == Some(page as u64))
.cloned()
.ok_or_else(|| bad(CMD, format!("page {page} is outside the pages to print ({first} to {last})")))?;
return Ok(json!({"pages": list.len(), "total": total, "page": one}));
}
Ok(json!({"pages": n, "pageList": list}))
Ok(json!({"pages": list.len(), "total": total, "pageList": list}))
}
fn page_setup(s: &mut Session, p: &Json) -> Result<Json> {
+35 -1
View File
@@ -75,6 +75,10 @@ pub struct PrintOptions {
/// Areas of the active sheet to print instead of its print area, in order (Print Selection).
pub ranges: Vec<RangeRef>,
pub fit_to_page: Option<bool>,
/// The page range (File › Print's Pages … to …): 1-based page numbers counted over the
/// whole job in sheet order. `None` = from the first page, to the last.
pub from: Option<usize>,
pub to: Option<usize>,
}
impl PrintOptions {
@@ -90,7 +94,37 @@ impl PrintOptions {
ranges.push(RangeRef::parse(split_sheet(part.trim()).1.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?);
}
}
Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage") })
let (from, to) = (page_param(p, "from", cmd)?, page_param(p, "to", cmd)?);
Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage"), from, to })
}
/// The first and last page that print out of a job of `total` pages (1-based, inclusive),
/// as Excel measures them: `from` after the last page is an error (nothing to print), `to`
/// past the last page stops at the last page, and `from` greater than `to` prints the pages
/// between them (3 to 2 prints pages 2 and 3).
pub(super) fn page_span(&self, total: usize, cmd: &str) -> Result<(usize, usize)> {
let span = craft_pages::range::print_page_span(total, self.from, self.to).map_err(|first| {
let pages = if total == 1 { "1 page".to_string() } else { format!("{total} pages") };
bad(cmd, format!("nothing to print: the job has {pages} and the page range starts at page {first}"))
})?;
Ok((span.start + 1, span.end))
}
}
/// A page-number param (`from`, `to`): a whole number from 1, as a number or as text. Absent,
/// `null` or empty text means no bound.
fn page_param(p: &Json, key: &str, cmd: &str) -> Result<Option<usize>> {
let n = match p.get(key) {
None | Some(Json::Null) => return Ok(None),
Some(Json::String(t)) if t.trim().is_empty() => return Ok(None),
Some(Json::String(t)) => t.trim().parse::<u64>().ok(),
// 2.0 is a whole number; 2.5, -1 and 0 are not page numbers.
Some(Json::Number(n)) => n.as_u64().or_else(|| n.as_f64().filter(|v| v.fract() == 0.0 && *v >= 1.0).map(|v| v as u64)),
Some(_) => None,
};
match n {
Some(n) if n >= 1 => Ok(Some(usize::try_from(n).unwrap_or(usize::MAX))),
_ => Err(bad(cmd, format!("`{key}` must be a page number from 1, not {}", p.get(key).map(Json::to_string).unwrap_or_default()))),
}
}
+192 -1
View File
@@ -1,4 +1,6 @@
use gridcraft_model::{Sparkline, SparklineKind};
use std::collections::BTreeSet;
use serde_json::json;
use super::*;
@@ -899,7 +901,7 @@ fn picture_copies_across_pages_stay_within_the_image_budget() {
// 64×64 RGB is 12,288 bytes: a 64 KiB budget holds a handful of page copies, not one per page.
let budget = 64 * 1024;
let RenderedPdf { bytes: capped, pages: capped_pages, .. } = render_pdf_with_image_budget(&d.wb, &lays, "t", "", budget).unwrap();
let RenderedPdf { bytes: capped, pages: capped_pages, .. } = render_pdf_with_image_budget(&d.wb, &lays, "t", "", budget, 1..=usize::MAX).unwrap();
assert_eq!(capped_pages, pages, "pages past the budget still print, without the pictures");
let capped_draws = draws(&capped);
assert!((1..full_draws / 2).contains(&capped_draws), "{capped_draws} of {full_draws} picture draws kept with a {budget}-byte budget");
@@ -1288,6 +1290,186 @@ fn checkbox_cells_print_as_boxes_not_true_false() {
assert!(contains(&pdf, "0.431 0.431 0.431 RG"), "the unchecked box is not outlined");
}
/// #3016's workbook: Sheet1 holds A1:A50 with a page break every 10 rows (5 pages), sheet Two
/// A1:A30 (3 pages), both with the footer "Page &P of &N". Each cell names its sheet, page and
/// row (`S1P2R11`).
fn paged_book() -> Session {
let mut s = s();
let labels =
|sheet: u32, rows: u32| -> Vec<Vec<Json>> { (1..=rows).map(|r| vec![json!(format!("S{sheet}P{}R{r}", (r - 1) / 10 + 1))]).collect() };
s.execute("range.setValues", json!({"range": "A1", "values": labels(1, 50)})).unwrap();
s.execute("pageLayout.pageSetup", json!({"rowBreaks": [11, 21, 31, 41], "footer": "&CPage &P of &N"})).unwrap();
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
s.execute("sheet.activate", json!({"sheet": "Two"})).unwrap();
s.execute("range.setValues", json!({"range": "A1", "values": labels(2, 30)})).unwrap();
s.execute("pageLayout.pageSetup", json!({"rowBreaks": [11, 21], "footer": "&CPage &P of &N"})).unwrap();
s.execute("sheet.activate", json!({"sheet": 0})).unwrap();
s
}
/// Each page of a PDF as (the sheet and page its cells name, its footer): `("S1P2", "Page 2 of
/// 5")`. Pages are the content streams in order (one per page; the workbook has no pictures).
fn printed_pages(pdf: &[u8]) -> Vec<(String, String)> {
let text = String::from_utf8_lossy(pdf);
let chunks: Vec<&str> = text.split("endstream").collect();
let streams = chunks.get(..chunks.len().saturating_sub(1)).unwrap_or_default();
streams
.iter()
.map(|page| {
let shown: Vec<&str> = page.lines().filter_map(|l| l.strip_prefix('(')?.strip_suffix(") Tj")).collect();
let cells: BTreeSet<&str> = shown.iter().filter(|t| t.starts_with('S')).filter_map(|t| t.split_once('R').map(|(sp, _)| sp)).collect();
assert_eq!(cells.len(), 1, "a page shows the cells of one printed page: {shown:?}");
let footer = shown.iter().find(|t| t.starts_with("Page ")).copied().unwrap_or_default();
(cells.into_iter().next().unwrap_or_default().to_string(), footer.to_string())
})
.collect()
}
fn pages_of(s: &mut Session, cmd: &str, p: Json) -> Vec<(String, String)> {
let r = s.execute(cmd, p.clone()).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
let pdf = crate::io::base64_decode(r["base64"].as_str().unwrap()).unwrap();
let pages = printed_pages(&pdf);
assert_eq!(r["pages"].as_u64(), Some(pages.len() as u64), "{cmd} {p}: `pages` counts the printed pages");
pages
}
#[test]
fn a_page_range_prints_its_pages_under_the_whole_jobs_numbers() {
// #3016: the cases measured in Excel (ExportAsFixedFormat with From and To).
let mut s = paged_book();
let page = |sp: &str, n: u32, of: u32| (sp.to_string(), format!("Page {n} of {of}"));
let sheet1 = |pages: &[u32]| pages.iter().map(|n| page(&format!("S1P{n}"), *n, 5)).collect::<Vec<_>>();
for (params, want) in [
(json!({}), sheet1(&[1, 2, 3, 4, 5])),
(json!({"from": 2, "to": 3}), sheet1(&[2, 3])),
(json!({"from": 5, "to": 5}), sheet1(&[5])),
// `to` past the last page stops at the last page.
(json!({"from": 4, "to": 99}), sheet1(&[4, 5])),
// `from` greater than `to` prints the pages between them.
(json!({"from": 3, "to": 2}), sheet1(&[2, 3])),
// Only `from`: to the last page; only `to`: from the first.
(json!({"from": 4}), sheet1(&[4, 5])),
(json!({"to": 2}), sheet1(&[1, 2])),
// Whole numbers as text or as 3.0, and `null` or empty text for no bound.
(json!({"from": "2", "to": 3.0}), sheet1(&[2, 3])),
(json!({"from": null, "to": ""}), sheet1(&[1, 2, 3, 4, 5])),
// The whole workbook counts its pages in sheet order: Two's first page is page 6 of 8.
(json!({"sheets": "all", "from": 5, "to": 6}), vec![page("S1P5", 5, 8), page("S2P1", 6, 8)]),
(json!({"sheets": "all", "from": 6, "to": 8}), vec![page("S2P1", 6, 8), page("S2P2", 7, 8), page("S2P3", 8, 8)]),
] {
assert_eq!(pages_of(&mut s, "file.exportPdf", params.clone()), want, "file.exportPdf {params}");
// The printer gets the same pages.
assert_eq!(pages_of(&mut s, "file.print", params.clone()), want, "file.print {params}");
}
// A range that starts after the last page prints nothing: an error, not an empty PDF.
for cmd in ["file.exportPdf", "file.print", "file.printPreview"] {
for params in [json!({"from": 6, "to": 7}), json!({"from": 6}), json!({"from": 9, "to": 9, "sheets": "all"})] {
let e = s.execute(cmd, params.clone()).unwrap_err().to_string();
assert!(e.contains("nothing to print"), "{cmd} {params}: {e}");
}
}
// A written file holds the same pages.
let dir = std::env::temp_dir().join(format!("gridcraft-print-range-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("p.pdf");
let r = s.execute("file.exportPdf", json!({"path": path.to_str().unwrap(), "from": 2, "to": 3})).unwrap();
assert_eq!(r["pages"], 2);
assert_eq!(printed_pages(&std::fs::read(&path).unwrap()), sheet1(&[2, 3]));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn print_preview_lists_the_pages_of_a_range_under_their_numbers() {
let mut s = paged_book();
let pv = s.execute("file.printPreview", json!({"from": 2, "to": 3})).unwrap();
assert_eq!((pv["pages"].as_u64(), pv["total"].as_u64()), (Some(2), Some(5)));
let listed: Vec<(u64, &str)> =
pv["pageList"].as_array().unwrap().iter().map(|p| (p["page"].as_u64().unwrap(), p["rows"].as_str().unwrap())).collect();
assert_eq!(listed, [(2, "11:20"), (3, "21:30")]);
let pv = s.execute("file.printPreview", json!({"sheets": "all", "from": 5, "to": 6})).unwrap();
let listed: Vec<(u64, &str)> =
pv["pageList"].as_array().unwrap().iter().map(|p| (p["page"].as_u64().unwrap(), p["sheet"].as_str().unwrap())).collect();
assert_eq!(listed, [(5, "Sheet1"), (6, "Two")]);
assert_eq!(pv["total"], 8);
// `page` picks a page by its number in the job; one outside the range is an error.
assert_eq!(s.execute("file.printPreview", json!({"page": 3, "from": 2, "to": 3})).unwrap()["page"]["rows"], "21:30");
assert!(s.execute("file.printPreview", json!({"page": 1, "from": 2, "to": 3})).is_err());
assert!(s.execute("file.printPreview", json!({"page": 6})).is_err());
// Without a range nothing changes: every page, `pages` and `total` alike.
let pv = s.execute("file.printPreview", json!({})).unwrap();
assert_eq!((pv["pages"].as_u64(), pv["total"].as_u64(), pv["pageList"].as_array().map(Vec::len)), (Some(5), Some(5), Some(5)));
}
#[test]
fn a_page_range_counts_the_pages_in_the_sheets_page_order() {
let mut s = s();
let rows: Vec<Vec<Json>> = (0..60).map(|r| (0..15).map(|c| json!(r * 100 + c)).collect()).collect();
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
s.execute("pageLayout.pageSetup", json!({"pageOrder": "overThenDown"})).unwrap();
let pv = s.execute("file.printPreview", json!({"from": 2, "to": 3})).unwrap();
let listed: Vec<(u64, &str)> =
pv["pageList"].as_array().unwrap().iter().map(|p| (p["page"].as_u64().unwrap(), p["range"].as_str().unwrap())).collect();
// Over, then down: page 2 is the top right of the four, page 3 the bottom left.
assert_eq!(listed, [(2, "K1:O45"), (3, "A46:J60")]);
assert_eq!(pv["total"], 4);
}
#[test]
fn page_range_params_that_are_not_page_numbers_are_clear_errors() {
let mut s = paged_book();
for cmd in ["file.exportPdf", "file.print", "file.printPreview"] {
for bad_value in [json!(0), json!(-1), json!(2.5), json!("x"), json!("-2"), json!("1.5"), json!(true), json!([2]), json!({"page": 2})] {
for key in ["from", "to"] {
let params = json!({ key: bad_value.clone() });
let e = s.execute(cmd, params.clone()).unwrap_err();
assert!(matches!(e, crate::EngineError::BadParams { .. }), "{cmd} {params}: {e:?}");
assert!(e.to_string().contains(&format!("`{key}` must be a page number from 1")), "{cmd} {params}: {e}");
}
}
}
}
#[test]
fn hostile_page_ranges_never_panic() {
// `every_command_survives_empty_params` for the page range: any value, alone or paired, on
// every print command gives a result or a clear error, never a caught panic.
let mut s = paged_book();
let values = [
json!(null),
json!(0),
json!(1),
json!(-1),
json!(2.5),
json!(1e300),
json!(-1e300),
json!(u64::MAX),
json!(i64::MIN),
json!(MAX_PAGES + 1),
json!(""),
json!(" 3 "),
json!("x"),
json!("99999999999999999999999999"),
json!(true),
json!([]),
json!({}),
];
for cmd in ["file.exportPdf", "file.print", "file.printPreview"] {
for from in &values {
for to in [json!(null), json!(2), json!(u64::MAX), json!("x")] {
for params in [json!({"from": from, "to": to}), json!({"to": from}), json!({"from": from, "to": to, "sheets": "all", "page": 7})] {
let r = s.execute(cmd, params.clone());
assert!(!matches!(r, Err(crate::EngineError::Internal(..))), "{cmd} {params}: {r:?}");
}
}
}
}
// Huge numbers are pages after the last one, not an overflow.
let e = s.execute("file.exportPdf", json!({"from": u64::MAX})).unwrap_err().to_string();
assert!(e.contains("nothing to print"), "{e}");
assert_eq!(pages_of(&mut s, "file.exportPdf", json!({"from": 5, "to": u64::MAX})).len(), 1);
assert_eq!(pages_of(&mut s, "file.exportPdf", json!({"from": 5, "to": 1e300})).len(), 1);
}
#[test]
fn an_equation_without_a_layout_prints_its_source_one_line_per_line() {
use super::objects::{MAX_FALLBACK_LINES, fallback_lines};
@@ -1567,6 +1749,15 @@ fn a_range_prints_instead_of_the_print_area_and_each_area_gets_its_own_pages() {
assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2"})), ["A1:B2"]);
// Several areas, like a multi-area selection: one run of pages each, in the order given.
assert_eq!(preview_ranges(&mut s, json!({"range": "D4:E5,A1:B2"})), ["D4:E5", "A1:B2"]);
let second_area = json!({"range": "D4:E5,A1:B2", "from": 2, "to": 2});
let preview = s.execute("file.printPreview", second_area.clone()).unwrap();
assert_eq!(preview["pageList"].as_array().unwrap().len(), 1);
assert_eq!(preview["pageList"][0]["range"], "A1:B2");
assert_eq!(preview["pageList"][0]["page"], 2);
let (pdf, count) = pdf_of(&mut s, second_area);
assert_eq!(count, 1);
assert!(contains(&pdf, "/Count 1 >>"));
assert!(contains(&pdf, "(x) Tj"));
assert_eq!(preview_ranges(&mut s, json!({"range": "Sheet1!A1:B2, D4:E5"})), ["A1:B2", "D4:E5"]);
let (_, pages) = pdf_of(&mut s, json!({"range": "A1:B2,D4:E5"}));
assert_eq!(pages, 2);
+1
View File
@@ -42,6 +42,7 @@ impl SheetApp {
notice: None,
services,
printing: Default::default(),
print_pages: Default::default(),
print_feedback_seen: None,
synthetic: Default::default(),
ctrl_wheel: false,
+7 -2
View File
@@ -223,8 +223,13 @@ impl SheetApp {
Ok(Json::Null)
}
"data.fromClipboard" => self.import_clipboard_text(p),
"ui.printSettings" => printing::settings(&mut self.printing, p, self.services.printers.as_ref()),
"ui.printSubmit" => self.submit_print(p.clone()),
"ui.printSettings" => printing::settings(&mut self.printing, &mut self.print_pages, p, self.services.printers.as_ref()),
"ui.printSubmit" => {
// The Print view's page range applies unless the call names its own.
let mut params = p.clone();
self.print_pages.apply(&mut params);
self.submit_print(params)
}
"ui.ribbonTab" => {
self.ui.ribbon_tab = p.get("tab").and_then(Json::as_str).unwrap_or("Home").to_string();
Ok(Json::Null)
+1 -1
View File
@@ -58,7 +58,7 @@ impl SheetApp {
self.printing.begin(submit(bytes, self.printing.settings.clone())).map_err(|_| "A print job is already being submitted.".to_owned())?;
self.print_feedback_seen = None;
} else if let Some(print) = &self.services.print {
print(&bytes);
print(&bytes)?;
} else {
return Err("Printing is unavailable here; export a PDF instead.".into());
}
+48 -17
View File
@@ -18,13 +18,14 @@ use serde_json::{Value as Json, json};
use crate::SheetApp;
use crate::i18n::{self, Language};
use crate::icons::{self, Icon};
use crate::printing::PageRange;
use crate::theme::{self, Tokens};
mod options;
mod print;
use options::{options, platform};
use print::print;
use print::{page_range_fields, print};
/// Width of the navigation column.
const NAV_W: f32 = 196.0;
@@ -99,8 +100,16 @@ impl Page {
}
/// What a print preview was built for: document, revision, scope, the selection when it is
/// the scope, and fit to page.
type PreviewKey = (u64, u64, PrintScope, String, bool);
/// the scope, fit to page, and the requested page range.
#[derive(Clone, Debug, PartialEq, Eq)]
struct PreviewKey {
document: u64,
revision: u64,
scope: PrintScope,
selection: String,
fit_to_page: bool,
pages: PageRange,
}
/// What File › Print › Settings prints.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -145,10 +154,15 @@ pub struct Backstage {
pub print_scope: PrintScope,
/// Print: fit each sheet on one page.
pub fit_to_page: bool,
/// Print: the previewed page (0-based).
/// Print: the previewed page (0-based, among the pages that print).
preview_page: usize,
/// Print: the preview for (document, revision, scope, the selection when it is the scope, fit to page).
/// Print: the preview and what it was made for.
preview: Option<(PreviewKey, Json)>,
/// Print: the Pages … to … fields as typed.
print_drafts: [String; 2],
/// Export: the page range of Create PDF, and its fields as typed.
pdf_pages: PageRange,
pdf_drafts: [String; 2],
/// Save As: the chosen file type (an extension from [`SAVE_TYPES`]).
pub save_format: &'static str,
/// Home and Open: when the recent workbooks were last changed.
@@ -170,6 +184,9 @@ impl Backstage {
fit_to_page: false,
preview_page: 0,
preview: None,
print_drafts: Default::default(),
pdf_pages: PageRange::default(),
pdf_drafts: Default::default(),
save_format: "xlsx",
recent: RecentFiles::default(),
}
@@ -250,7 +267,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) {
Page::Info => info(app, ui, &mut bs),
Page::SaveAs => save_as(app, ui, &mut bs, &mut out),
Page::Print => print(app, ui, &mut bs, &mut out),
Page::Export => export(app, ui, &mut out),
Page::Export => export(app, ui, &mut bs, &mut out),
Page::Options => options(app, ui),
Page::Account => account(app, ui),
}
@@ -728,7 +745,7 @@ fn save_as(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcom
if after != before || asking || app.services.pick_save.is_none() {
out.close = true;
}
} else if export_as(app, fmt) {
} else if export_as(app, fmt, json!({})) {
out.close = true;
}
}
@@ -736,12 +753,23 @@ fn save_as(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcom
dim(ui, lang.tr("A CSV file, web page or PDF is a copy: the workbook keeps its own file."));
}
fn export(app: &mut SheetApp, ui: &mut Ui, out: &mut Outcome) {
fn export(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcome) {
let lang = app.ui.language;
if action_row(ui, Icon::Paper, lang.tr("Create PDF"), lang.tr("Save the sheet as a PDF document that keeps its page layout.")).clicked()
&& export_as(app, "pdf")
{
out.close = true;
let create_pdf =
action_row(ui, Icon::Paper, lang.tr("Create PDF"), lang.tr("Save the sheet as a PDF document that keeps its page layout.")).clicked();
// Create PDF's page range, in line with its description; empty fields export every page.
ui.horizontal(|ui| {
ui.add_space(52.0);
if let Some(range) = page_range_fields(ui, lang, "backstage_pdf_pages", &mut bs.pdf_drafts, bs.pdf_pages) {
bs.pdf_pages = range;
}
});
if create_pdf {
let mut params = json!({});
bs.pdf_pages.apply(&mut params);
if export_as(app, "pdf", params) {
out.close = true;
}
}
ui.add_space(14.0);
section(ui, lang, "Change File Type");
@@ -749,15 +777,16 @@ fn export(app: &mut SheetApp, ui: &mut Ui, out: &mut Outcome) {
("csv", Icon::TextColumns, "CSV (Comma delimited)", "Save the active sheet as comma-separated text."),
("html", Icon::Link, "Web Page (.html)", "Save the workbook as a web page."),
] {
if action_row(ui, icon, lang.tr(title), lang.tr(detail)).clicked() && export_as(app, fmt) {
if action_row(ui, icon, lang.tr(title), lang.tr(detail)).clicked() && export_as(app, fmt, json!({})) {
out.close = true;
}
}
}
/// Exports the active workbook as `pdf`, `csv` or `html`: through the save picker on the desktop,
/// as a browser download on the web. Returns whether a file was written or handed over.
pub fn export_as(app: &mut SheetApp, fmt: &str) -> bool {
/// as a browser download on the web. `params` go to the export command with the path (a PDF's
/// page range). Returns whether a file was written or handed over.
pub fn export_as(app: &mut SheetApp, fmt: &str, params: Json) -> bool {
if !app.commit_edit(0, 0, false, false) {
return false;
}
@@ -767,13 +796,15 @@ pub fn export_as(app: &mut SheetApp, fmt: &str) -> bool {
"html" => "file.exportHtml",
_ => return false,
};
let mut params = if params.is_object() { params } else { json!({}) };
let title = app.session.active().map(|d| d.display_title()).unwrap_or_else(|| "Book1".into());
let stem = std::path::Path::new(&title).file_stem().and_then(std::ffi::OsStr::to_str).unwrap_or("Book1").to_string();
if let Some(pick) = &app.services.pick_save {
let Some(path) = pick(&format!("{stem}.{fmt}")) else { return false };
// The picker may suggest a workbook extension; the export writes the chosen format.
let path = std::path::Path::new(&path).with_extension(fmt).to_string_lossy().into_owned();
return match app.run(id, json!({"path": path})) {
params["path"] = json!(path);
return match app.run(id, params) {
Ok(_) => true,
Err(e) => {
app.message = Some(("GridCraft".into(), crate::clean_error(&e)));
@@ -787,7 +818,7 @@ pub fn export_as(app: &mut SheetApp, fmt: &str) -> bool {
}
if fmt == "pdf" {
// Without a path the PDF comes back as bytes, which `SheetApp::run` hands to the browser.
return match app.run(id, json!({})) {
return match app.run(id, params) {
Ok(_) => true,
Err(e) => {
app.message = Some(("GridCraft".into(), crate::clean_error(&e)));
+53 -12
View File
@@ -1,9 +1,9 @@
use super::{
Align2, Backstage, Icon, Json, Outcome, PrintScope, Rect, Sense, SheetApp, Stroke, StrokeKind, Tokens, Ui, dim, json, pos2, square_button, theme,
vec2,
Align2, Backstage, Icon, Json, Language, Outcome, PageRange, PreviewKey, PrintScope, Rect, Sense, SheetApp, Stroke, StrokeKind, Tokens, Ui, dim,
json, pos2, square_button, theme, vec2,
};
/// Builds the print scope and fit-to-page parameters, caches `file.printPreview` per document revision/options, and draws page thumbnails with navigation plus the print settings and Print action.
/// Builds the print scope, page range and fit-to-page parameters, caches `file.printPreview` per document revision/options, and draws page thumbnails with navigation plus the print settings and Print action.
pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcome) {
let t = Tokens::get(ui.ctx());
let lang = app.ui.language;
@@ -23,24 +23,34 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
if bs.fit_to_page {
params["fitToPage"] = json!(true);
}
let key = (uid, revision, bs.print_scope, selection, bs.fit_to_page);
app.print_pages.apply(&mut params);
let key = PreviewKey { document: uid, revision, scope: bs.print_scope, selection, fit_to_page: bs.fit_to_page, pages: app.print_pages };
if bs.preview.as_ref().is_none_or(|(k, _)| *k != key) {
if bs.preview.as_ref().is_some_and(|(k, _)| k.pages != key.pages) {
bs.preview_page = 0;
}
// A range that starts after the last page is an error: nothing to print.
let preview = app.session.run("file.printPreview", params.clone()).unwrap_or(Json::Null);
bs.preview = Some((key, preview));
}
let pages: Vec<Json> = bs.preview.as_ref().and_then(|(_, p)| p.get("pageList")).and_then(Json::as_array).cloned().unwrap_or_default();
let preview = bs.preview.as_ref().map(|(_, p)| p);
let pages: Vec<Json> = preview.and_then(|p| p.get("pageList")).and_then(Json::as_array).cloned().unwrap_or_default();
// The whole job's page count: a page range previews only its pages, under their numbers in the job.
let total = preview.and_then(|p| p.get("total")).and_then(Json::as_u64).unwrap_or(pages.len() as u64);
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(340.0);
if let Some(discover) = &app.services.printers {
crate::printing::show(&mut app.printing, ui, discover, |label| lang.tr(label).to_owned());
}
let can_print = app.services.print_native.is_none() || app.printing.ready();
let can_print = (app.services.print_native.is_none() || app.printing.ready()) && !pages.is_empty();
if ui.add_enabled_ui(can_print, |ui| square_button(ui, Icon::Print, lang.tr("Print"))).inner.clicked()
&& app.commit_edit(0, 0, false, false)
{
app.print_now(params.clone());
out.close = app.services.print_native.is_none();
match app.run("ui.printSubmit", params.clone()) {
Ok(_) => out.close = app.services.print_native.is_none(),
Err(error) => app.alert(error),
}
}
ui.add_space(16.0);
egui::ComboBox::from_id_salt("backstage_print_scope")
@@ -57,6 +67,16 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
.response
.accessible_name(lang.tr("Print What"));
ui.add_space(8.0);
// Pages … to …, counted over what the scope prints; empty fields print every page.
ui.horizontal(|ui| {
if let Some(range) = page_range_fields(ui, lang, "backstage_print_pages", &mut bs.print_drafts, app.print_pages) {
// Set through `ui.printSettings`, as a control client sets them. It refuses changes
// only while a job is being handed to the printer; a field left then shows the kept range.
let _ = app.run("ui.printSettings", json!({"from": range.from, "to": range.to}));
ui.ctx().request_repaint();
}
});
ui.add_space(8.0);
if ui.checkbox(&mut bs.fit_to_page, lang.tr("Fit Sheet on One Page")).changed() {
bs.preview_page = 0;
}
@@ -95,10 +115,9 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
if ui.add_enabled(bs.preview_page > 0, egui::Button::new("◀")).on_hover_text(lang.tr("Previous page")).clicked() {
bs.preview_page = bs.preview_page.saturating_sub(1);
}
let text = lang
.tr("Page {page} of {pages}")
.replace("{page}", &(bs.preview_page + 1).to_string())
.replace("{pages}", &pages.len().to_string());
// The page's own number in the job, as its header and footer print it.
let number = page.get("page").and_then(Json::as_u64).unwrap_or(bs.preview_page as u64 + 1);
let text = lang.tr("Page {page} of {pages}").replace("{page}", &number.to_string()).replace("{pages}", &total.to_string());
ui.label(text);
if ui.add_enabled(bs.preview_page < last, egui::Button::new("▶")).on_hover_text(lang.tr("Next page")).clicked() {
bs.preview_page = (bs.preview_page + 1).min(last);
@@ -108,6 +127,28 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
});
}
/// Pages [from] to [to]: a page range as two small number fields, in a horizontal layout. Empty
/// fields mean the first and the last page. `drafts` hold the text as typed (a field that isn't
/// being edited shows `range`); returns the new range when a field changed it.
pub(super) fn page_range_fields(ui: &mut Ui, lang: Language, id: &str, drafts: &mut [String; 2], range: PageRange) -> Option<PageRange> {
let mut next = range;
for (i, (label, bound)) in [("Pages", &mut next.from), ("Print pages|to", &mut next.to)].into_iter().enumerate() {
let Some(draft) = drafts.get_mut(i) else { continue };
let label = ui.label(lang.tr(label));
let field = ui.make_persistent_id((id, i));
if !ui.ctx().memory(|m| m.has_focus(field)) {
*draft = bound.map(|page| page.to_string()).unwrap_or_default();
}
let edit = egui::TextEdit::singleline(draft).id(field).desired_width(44.0).char_limit(5);
if ui.add(edit).labelled_by(label.id).changed() {
draft.retain(|c| c.is_ascii_digit());
// 0 is no page: like an empty field, it prints from the first or to the last page.
*bound = draft.parse::<u32>().ok().filter(|page| *page >= 1);
}
}
(next != range).then_some(next)
}
/// Most rows and columns one preview page draws (a page holds far fewer at any readable scale).
const PREVIEW_ROWS: u32 = 200;
+6 -2
View File
@@ -110,8 +110,12 @@ fn run(app: &mut SheetApp, id: &str, params: Json) -> Result<Json, String> {
/// window afterwards unless the command itself switched windows.
fn run_in(app: &mut SheetApp, target: gridcraft_engine::Target, id: &str, params: Json) -> Result<Json, String> {
let guard = app.session.enter_target(target).map_err(|e| e.to_string())?;
// A UI command reads and changes the target window's interface state (its page range…),
// and the active window's is back once the command is done.
app.follow_active_window();
let r = run(app, id, params);
app.session.leave_target(guard);
app.follow_active_window();
r
}
@@ -294,12 +298,12 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
(
"ui.printSettings",
"Print Settings",
"{printer?: discovered name, copies?: 1..999, duplex?: printerDefault|off|longEdge|shortEdge|null, grayscale?: bool, refresh?: bool} → {printer,copies,duplex,grayscale,printers,ready,busy,discovering,status,detail}; {} inspects without submitting",
"{printer?: discovered name, copies?: 1..999, duplex?: printerDefault|off|longEdge|shortEdge|null, grayscale?: bool, from?: page (1-based)|null, to?: page|null, refresh?: bool} → {printer,copies,duplex,grayscale,from,to,printers,ready,busy,discovering,status,detail}; from/to are the Print view's page range (null clears a bound); {} inspects without submitting",
),
(
"ui.printSubmit",
"Submit Print Job",
"existing file.print sheet/pagination params → {printing,bytes,pending}; submits without opening a dialog",
"existing file.print sheet/pagination params; without from/to, the page range of ui.printSettings → {printing,bytes,pending}; submits without opening a dialog",
),
("app.language.set", "Interface Language", language_params.as_str()),
("app.language.english", "Interface Language: English", ""),
+2
View File
@@ -339,6 +339,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Vytisknout celý sešit",
"Print Selection" => "Vytisknout výběr",
"Fit Sheet on One Page" => "Přizpůsobit list na jednu stránku",
"Pages" => "Stránky",
"Print pages|to" => "až",
"Page Setup…" => "Vzhled stránky…",
"Page {page} of {pages}" => "Stránka {page} z {pages}",
"Nothing to print." => "Není co tisknout.",
+2
View File
@@ -358,6 +358,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Gesamte Arbeitsmappe drucken",
"Print Selection" => "Auswahl drucken",
"Fit Sheet on One Page" => "Blatt auf einer Seite darstellen",
"Pages" => "Seiten",
"Print pages|to" => "bis",
"Page Setup…" => "Seite einrichten…",
"Page {page} of {pages}" => "Seite {page} von {pages}",
"Nothing to print." => "Nichts zu drucken.",
+2
View File
@@ -317,6 +317,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Εκτύπωση ολόκληρου βιβλίου εργασίας",
"Print Selection" => "Εκτύπωση επιλογής",
"Fit Sheet on One Page" => "Προσαρμογή φύλλου σε μία σελίδα",
"Pages" => "Σελίδες",
"Print pages|to" => "έως",
"Page Setup…" => "Διαμόρφωση σελίδας…",
"Page {page} of {pages}" => "Σελίδα {page} από {pages}",
"Nothing to print." => "Δεν υπάρχει περιεχόμενο για εκτύπωση.",
+2
View File
@@ -345,6 +345,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Imprimir todo el libro",
"Print Selection" => "Imprimir selección",
"Fit Sheet on One Page" => "Ajustar hoja en una página",
"Pages" => "Páginas",
"Print pages|to" => "a",
"Page Setup…" => "Configurar página…",
"Page {page} of {pages}" => "Página {page} de {pages}",
"Nothing to print." => "No hay nada que imprimir.",
+2
View File
@@ -434,6 +434,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Imprimer tout le classeur",
"Print Selection" => "Imprimer la sélection",
"Fit Sheet on One Page" => "Ajuster la feuille sur une page",
"Pages" => "Pages",
"Print pages|to" => "à",
"Page Setup…" => "Mise en page…",
"Page {page} of {pages}" => "Page {page} sur {pages}",
"Nothing to print." => "Rien à imprimer.",
+2
View File
@@ -419,6 +419,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Stampa intera cartella di lavoro",
"Print Selection" => "Stampa selezione",
"Fit Sheet on One Page" => "Adatta foglio a una pagina",
"Pages" => "Pagine",
"Print pages|to" => "a",
"Page Setup…" => "Imposta pagina…",
"Page {page} of {pages}" => "Pagina {page} di {pages}",
"Nothing to print." => "Niente da stampare.",
+2
View File
@@ -422,6 +422,8 @@ pub(super) const CORE: &[(&str, &str)] = &[
("Print Entire Workbook", "ブック全体を印刷"),
("Print Selection", "選択した部分を印刷"),
("Fit Sheet on One Page", "シートを 1 ページに印刷"),
("Pages", "ページ指定"),
("Print pages|to", "~"),
("Page Setup…", "ページ設定…"),
("Page {page} of {pages}", "{page} / {pages} ページ"),
("Nothing to print.", "印刷する内容がありません。"),
+2
View File
@@ -434,6 +434,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "전체 통합 문서 인쇄",
"Print Selection" => "선택 영역 인쇄",
"Fit Sheet on One Page" => "한 페이지에 시트 맞추기",
"Pages" => "페이지",
"Print pages|to" => "~",
"Page Setup…" => "페이지 설정…",
"Page {page} of {pages}" => "{page}/{pages} 페이지",
"Nothing to print." => "인쇄할 내용이 없습니다.",
+2
View File
@@ -421,6 +421,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Hele werkmap afdrukken",
"Print Selection" => "Selectie afdrukken",
"Fit Sheet on One Page" => "Blad op één pagina passen",
"Pages" => "Pagina's",
"Print pages|to" => "tot",
"Page Setup…" => "Pagina-instelling…",
"Page {page} of {pages}" => "Pagina {page} van {pages}",
"Nothing to print." => "Niets om af te drukken.",
+2
View File
@@ -411,6 +411,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Drukuj cały skoroszyt",
"Print Selection" => "Drukuj zaznaczenie",
"Fit Sheet on One Page" => "Dopasuj arkusz do jednej strony",
"Pages" => "Strony",
"Print pages|to" => "do",
"Page Setup…" => "Ustawienia strony…",
"Page {page} of {pages}" => "Strona {page} z {pages}",
"Nothing to print." => "Nie ma nic do wydrukowania.",
+2
View File
@@ -428,6 +428,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Imprimir toda a pasta de trabalho",
"Print Selection" => "Imprimir seleção",
"Fit Sheet on One Page" => "Ajustar planilha em uma página",
"Pages" => "Páginas",
"Print pages|to" => "até",
"Page Setup…" => "Configurar página…",
"Page {page} of {pages}" => "Página {page} de {pages}",
"Nothing to print." => "Nada para imprimir.",
+2
View File
@@ -418,6 +418,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Imprimare tot registrul",
"Print Selection" => "Imprimare selecție",
"Fit Sheet on One Page" => "Încadrare foaie pe o pagină",
"Pages" => "Pagini",
"Print pages|to" => "la",
"Page Setup…" => "Configurare pagină…",
"Page {page} of {pages}" => "Pagina {page} din {pages}",
"Nothing to print." => "Nimic de imprimat.",
+2
View File
@@ -433,6 +433,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Напечатать всю книгу",
"Print Selection" => "Напечатать выделенный диапазон",
"Fit Sheet on One Page" => "Вписать лист на одну страницу",
"Pages" => "Страницы",
"Print pages|to" => "по",
"Page Setup…" => "Параметры страницы…",
"Page {page} of {pages}" => "Страница {page} из {pages}",
"Nothing to print." => "Нечего печатать.",
+2
View File
@@ -427,6 +427,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Štampaj celu radnu svesku",
"Print Selection" => "Štampaj izbor",
"Fit Sheet on One Page" => "Uklopi list na jednu stranicu",
"Pages" => "Stranice",
"Print pages|to" => "do",
"Page Setup…" => "Podešavanje stranice…",
"Page {page} of {pages}" => "Stranica {page} od {pages}",
"Nothing to print." => "Nema ničega za štampu.",
+2
View File
@@ -332,6 +332,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Tüm Çalışma Kitabını Yazdır",
"Print Selection" => "Seçimi Yazdır",
"Fit Sheet on One Page" => "Sayfayı Bir Sayfaya Sığdır",
"Pages" => "Sayfalar",
"Print pages|to" => "-",
"Page Setup…" => "Sayfa Yapısı…",
"Page {page} of {pages}" => "Sayfa {page} / {pages}",
"Nothing to print." => "Yazdırılacak bir şey yok.",
+2
View File
@@ -416,6 +416,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Надрукувати всю книгу",
"Print Selection" => "Надрукувати виділений діапазон",
"Fit Sheet on One Page" => "Вмістити аркуш на одну сторінку",
"Pages" => "Сторінки",
"Print pages|to" => "по",
"Page Setup…" => "Параметри сторінки…",
"Page {page} of {pages}" => "Сторінка {page} з {pages}",
"Nothing to print." => "Немає що друкувати.",
+2
View File
@@ -421,6 +421,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "In toàn bộ sổ làm việc",
"Print Selection" => "In vùng chọn",
"Fit Sheet on One Page" => "Vừa trang tính trên một trang in",
"Pages" => "Trang",
"Print pages|to" => "đến",
"Page Setup…" => "Thiết lập trang…",
"Page {page} of {pages}" => "Trang {page} trên {pages}",
"Nothing to print." => "Không có nội dung để in.",
+2
View File
@@ -426,6 +426,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "打印整个工作簿",
"Print Selection" => "打印选定区域",
"Fit Sheet on One Page" => "将工作表调整为一页",
"Pages" => "页数",
"Print pages|to" => "至",
"Page Setup…" => "页面设置…",
"Page {page} of {pages}" => "第 {page} 页,共 {pages} 页",
"Nothing to print." => "没有可打印的内容。",
+3
View File
@@ -261,6 +261,9 @@ pub struct SheetApp {
pub notice: Option<Notice>,
pub services: Services,
pub printing: printing::State,
/// File › Print's page range (Pages … to …), set there or by `ui.printSettings`. Each window
/// has its own, parked with its other interface state while another window is active.
pub print_pages: printing::PageRange,
print_feedback_seen: Option<printing::Feedback>,
/// Synthetic input from agents, one batch per step (drags need several steps).
pub synthetic: std::collections::VecDeque<Vec<egui::Event>>,
+50 -4
View File
@@ -22,13 +22,43 @@ fn printer_name(settings: &Settings) -> &str {
}
}
/// File › Print's page range (Pages … to …): 1-based page numbers counted over the whole print
/// job. `None` prints from the first page or to the last.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PageRange {
pub from: Option<u32>,
pub to: Option<u32>,
}
impl PageRange {
/// Adds the range to print-command params as `from` and `to`, unless they name a range of
/// their own (either bound, `null` included).
pub fn apply(&self, params: &mut serde_json::Value) {
let Some(map) = params.as_object_mut() else { return };
if map.contains_key("from") || map.contains_key("to") {
return;
}
for (key, page) in [("from", self.from), ("to", self.to)] {
if let Some(page) = page {
map.insert(key.into(), page.into());
}
}
}
}
/// Read print settings/status, or validate an explicit update before changing anything.
/// `refresh: true` starts discovery only; this command never submits a job or opens a dialog.
pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<&Discover>) -> Result<serde_json::Value, String> {
/// `from` and `to` set the Print view's page range (`null` clears a bound).
pub fn settings(
state: &mut State,
pages: &mut PageRange,
params: &serde_json::Value,
discover: Option<&Discover>,
) -> Result<serde_json::Value, String> {
use serde_json::{Value, json};
let object = params.as_object().ok_or("print settings must be an object")?;
if object.keys().any(|key| !["printer", "copies", "duplex", "grayscale", "refresh"].contains(&key.as_str())) {
return Err("unknown print setting; use printer, copies, duplex, grayscale or refresh".into());
if object.keys().any(|key| !["printer", "copies", "duplex", "grayscale", "from", "to", "refresh"].contains(&key.as_str())) {
return Err("unknown print setting; use printer, copies, duplex, grayscale, from, to or refresh".into());
}
if state.busy() && !object.is_empty() {
return Err("wait for the active print submission before changing settings".into());
@@ -58,6 +88,21 @@ pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<
if let Some(value) = object.get("grayscale") {
next.grayscale = value.as_bool().ok_or("grayscale must be a boolean")?;
}
let mut range = *pages;
for (key, bound) in [("from", &mut range.from), ("to", &mut range.to)] {
if let Some(value) = object.get(key) {
*bound = match value {
Value::Null => None,
_ => Some(
value
.as_u64()
.and_then(|page| u32::try_from(page).ok())
.filter(|page| *page >= 1)
.ok_or_else(|| format!("{key} must be a page number from 1, or null for no limit"))?,
),
};
}
}
let refresh = object.get("refresh").map(|value| value.as_bool().ok_or("refresh must be a boolean")).transpose()?.unwrap_or(false);
if refresh {
let discover = discover.ok_or("native printer discovery is unavailable here")?;
@@ -66,6 +111,7 @@ pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<
}
}
state.settings = next;
*pages = range;
let (status, detail) = match state.message.as_ref() {
None => ("idle", ""),
Some(Feedback::FindingPrinters) => ("findingPrinters", ""),
@@ -80,7 +126,7 @@ pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<
Ok(json!({
"printer": printer_name(&state.settings), "copies": state.settings.copies,
"duplex": match state.settings.duplex { Some(Duplex::Off) => "off", Some(Duplex::LongEdge) => "longEdge", Some(Duplex::ShortEdge) => "shortEdge", _ => "printerDefault" },
"grayscale": state.settings.grayscale,
"grayscale": state.settings.grayscale, "from": pages.from, "to": pages.to,
"printers": state.printers.iter().map(|printer| json!({"name": printer.name, "default": printer.default})).collect::<Vec<Value>>(),
"busy": state.busy(), "discovering": state.discovering(), "ready": state.ready(), "status": status, "detail": detail,
}))
+1 -1
View File
@@ -4,7 +4,7 @@ type PickSave = Box<dyn Fn(&str) -> Option<String>>;
type OpenUrl = Box<dyn Fn(&str)>;
type CopyHtml = Box<dyn FnMut(&str, &str) -> Result<(), String>>;
type Download = Box<dyn Fn(&str, &[u8])>;
type PrintPdf = Box<dyn Fn(&[u8])>;
type PrintPdf = Box<dyn Fn(&[u8]) -> Result<(), String>>;
/// Host services the platform shell provides (file pickers, opening URLs).
#[derive(Default)]
+5 -1
View File
@@ -8,7 +8,7 @@
use gridcraft_engine::core::CellRef;
use crate::{Notice, SheetApp, backstage, dialogs, editor, grid, keytips, text_box};
use crate::{Notice, SheetApp, backstage, dialogs, editor, grid, keytips, printing, text_box};
/// One window's parked interface state (see the module docs).
#[derive(Default)]
@@ -17,6 +17,8 @@ pub struct WindowUi {
text_box_editor: Option<text_box::EditState>,
dialog: Option<dialogs::Dialog>,
backstage: Option<backstage::Backstage>,
/// File › Print's page range: each window prints its own workbook's pages.
print_pages: printing::PageRange,
message: Option<(String, String)>,
toast: Option<(String, f64)>,
notice: Option<Notice>,
@@ -61,6 +63,7 @@ impl SheetApp {
text_box_editor,
dialog,
backstage,
print_pages,
message,
toast,
notice,
@@ -78,6 +81,7 @@ impl SheetApp {
std::mem::swap(&mut self.text_box_editor, text_box_editor);
std::mem::swap(&mut self.dialog, dialog);
std::mem::swap(&mut self.backstage, backstage);
std::mem::swap(&mut self.print_pages, print_pages);
std::mem::swap(&mut self.message, message);
std::mem::swap(&mut self.toast, toast);
std::mem::swap(&mut self.notice, notice);
+237
View File
@@ -97,6 +97,15 @@ fn invalid_print_settings_are_rejected_without_partial_changes() {
json!({"grayscale":"yes"}),
json!({"refresh":"yes"}),
json!({"copies":3,"duplex":"invalid"}),
json!({"from":0}),
json!({"from":-1}),
json!({"from":2.5}),
json!({"from":"2"}),
json!({"to":"x"}),
json!({"to":true}),
json!({"to":u64::MAX}),
json!({"from":2,"to":0}),
json!({"pages":2}),
json!([]),
] {
assert!(app.run("ui.printSettings", params.clone()).is_err(), "{params}");
@@ -129,3 +138,231 @@ fn repeated_fast_jobs_each_surface_an_identical_receipt() {
assert!(app.toast.is_none());
}
}
/// A workbook of 5 pages (A1:A50, a page break every 10 rows) whose footer numbers its pages.
fn five_pages() -> Session {
let mut session = Session::new();
session.new_workbook();
let rows: Vec<Vec<serde_json::Value>> = (1..=50).map(|r| vec![json!(format!("R{r}"))]).collect();
session.run("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
session.run("pageLayout.pageSetup", json!({"rowBreaks": [11, 21, 31, 41], "footer": "&CPage &P of &N"})).unwrap();
session
}
/// Replaces the text of the field labelled `label` with `text` (empty clears it), as typed.
fn type_into(h: &mut egui_kittest::Harness<'_, SheetApp>, label: &str, text: &str) {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
let rect = h.get_by_role_and_label(Role::TextInput, label).rect();
h.input_mut().events.push(egui::Event::PointerMoved(rect.center()));
h.run_steps(1);
h.get_by_role_and_label(Role::TextInput, label).click();
h.run_steps(2);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.run_steps(1);
if text.is_empty() {
h.key_press(egui::Key::Backspace);
} else {
h.input_mut().events.push(egui::Event::Text(text.into()));
}
h.run_steps(3);
}
/// The footers a PDF prints, in page order.
fn footers(pdf: &[u8]) -> Vec<String> {
String::from_utf8_lossy(pdf).lines().filter_map(|l| l.strip_prefix("(Page ")?.strip_suffix(") Tj")).map(|f| format!("Page {f}")).collect()
}
#[test]
/// `ui.printSettings` holds the Print view's page range: `from` and `to` are set, read back and
/// cleared with `null`, and `ui.printSubmit` prints that range unless the call names its own.
fn print_settings_hold_the_page_range_that_print_submit_prints() {
let mut app = SheetApp::new(five_pages(), Services::default());
app.printing.printers.push(Printer::new("Queue").is_default(true));
let jobs = Rc::new(RefCell::new(Vec::new()));
let observed = jobs.clone();
app.services.print_native = Some(Box::new(move |bytes, _| {
observed.borrow_mut().push(bytes);
let (sender, receiver) = std::sync::mpsc::channel();
sender.send(Ok("queued".into())).unwrap();
receiver
}));
let unknown = app.run("ui.printSettings", json!({"pages": 2})).unwrap_err();
assert!(unknown.contains("from, to"), "the error lists the settings it takes: {unknown}");
let set = app.run("ui.printSettings", json!({"printer": "Queue", "from": 2, "to": 3})).unwrap();
assert_eq!((&set["from"], &set["to"]), (&json!(2), &json!(3)));
assert_eq!(app.run("ui.printSettings", json!({})).unwrap()["from"], 2, "the range stays until changed");
let submit = |app: &mut SheetApp, params: serde_json::Value| {
app.run("ui.printSubmit", params).unwrap();
app.printing.poll(&egui::Context::default());
app.poll_printing(&egui::Context::default());
footers(&jobs.borrow_mut().pop().unwrap())
};
assert_eq!(submit(&mut app, json!({})), ["Page 2 of 5", "Page 3 of 5"]);
// A call that names a range prints it instead: `from` alone runs to the last page.
assert_eq!(submit(&mut app, json!({"from": 4})), ["Page 4 of 5", "Page 5 of 5"]);
assert_eq!(submit(&mut app, json!({"from": null})).len(), 5, "an explicit null prints every page");
// `null` clears one bound, then the other.
let set = app.run("ui.printSettings", json!({"to": null})).unwrap();
assert_eq!((&set["from"], &set["to"]), (&json!(2), &json!(null)));
assert_eq!(submit(&mut app, json!({})), ["Page 2 of 5", "Page 3 of 5", "Page 4 of 5", "Page 5 of 5"]);
app.run("ui.printSettings", json!({"from": null})).unwrap();
assert_eq!(app.print_pages, gridcraft_ui_egui::printing::PageRange::default());
assert_eq!(submit(&mut app, json!({})).len(), 5);
// A range after the last page is refused when printing, with nothing sent to the printer.
app.run("ui.printSettings", json!({"from": 6})).unwrap();
let e = app.run("ui.printSubmit", json!({})).unwrap_err();
assert!(e.contains("nothing to print"), "{e}");
assert!(jobs.borrow().is_empty());
}
#[test]
/// Each window keeps its own page range: a range set in one window's Print view doesn't print
/// from another window, and comes back when its window is active again.
fn each_window_keeps_its_own_page_range() {
use gridcraft_ui_egui::printing::PageRange;
let mut app = SheetApp::new(five_pages(), Services::default());
// The first frame makes the window's interface state its own.
app.follow_active_window();
let first = app.session.active_window().unwrap();
app.run("ui.printSettings", json!({"from": 4})).unwrap();
app.run("view.newWindow", json!({})).unwrap();
let second = app.session.active_window().unwrap();
assert_ne!(first, second);
assert_eq!(app.print_pages, PageRange::default(), "a new window prints every page");
app.run("ui.printSettings", json!({"from": 2, "to": 3})).unwrap();
app.run("window.activate", json!({"window": first})).unwrap();
assert_eq!(app.print_pages, PageRange { from: Some(4), to: None });
assert_eq!(app.run("ui.printSettings", json!({})).unwrap()["from"], 4);
app.run("window.activate", json!({"window": second})).unwrap();
assert_eq!(app.print_pages, PageRange { from: Some(2), to: Some(3) });
}
#[test]
/// `ui.printSettings` and `ui.printSubmit` sent to another window through the control channel
/// read, change and print that window's page range, and leave the active window's alone.
fn print_calls_for_another_window_use_its_page_range() {
use gridcraft_ui_egui::control::{Outcome, handle};
use gridcraft_ui_egui::printing::PageRange;
let mut app = SheetApp::new(five_pages(), Services::default());
app.printing.printers.push(Printer::new("Queue").is_default(true));
let jobs = Rc::new(RefCell::new(Vec::new()));
let observed = jobs.clone();
app.services.print_native = Some(Box::new(move |bytes, _| {
observed.borrow_mut().push(bytes);
let (sender, receiver) = std::sync::mpsc::channel();
sender.send(Ok("queued".into())).unwrap();
receiver
}));
app.follow_active_window();
let first = app.session.active_window().unwrap();
app.run("ui.printSettings", json!({"printer": "Queue", "from": 4})).unwrap();
app.run("view.newWindow", json!({})).unwrap();
let second = app.session.active_window().unwrap();
let ctx = egui::Context::default();
let call = |app: &mut SheetApp, command: &str, params: serde_json::Value| match handle(
app,
&ctx,
"engine.execute",
&json!({"command": command, "params": params, "window": first}),
) {
Outcome::Done(v) => v,
Outcome::Screenshot { .. } => panic!("{command} took a screenshot"),
};
let read = call(&mut app, "ui.printSettings", json!({}));
assert_eq!(read["result"]["from"], 4, "{read}");
let set = call(&mut app, "ui.printSettings", json!({"to": 4}));
assert_eq!((&set["result"]["from"], &set["result"]["to"]), (&json!(4), &json!(4)), "{set}");
assert_eq!(app.session.active_window(), Some(second), "the active window stays active");
assert_eq!(app.print_pages, PageRange::default(), "the active window's range is untouched");
let printed = call(&mut app, "ui.printSubmit", json!({}));
assert_eq!(printed["ok"], true, "{printed}");
app.printing.poll(&ctx);
app.poll_printing(&ctx);
assert_eq!(footers(&jobs.borrow_mut().pop().unwrap()), ["Page 4 of 5"]);
app.run("window.activate", json!({"window": first})).unwrap();
assert_eq!(app.print_pages, PageRange { from: Some(4), to: Some(4) });
}
#[test]
/// File › Print's Pages … to … fields set the page range, the preview shows the pages that will
/// print under their own numbers, and the fields follow `ui.printSettings`. In German too.
fn the_print_views_page_fields_set_the_range_and_the_preview_follows() {
use egui::accesskit::Role;
use egui_kittest::kittest::{NodeT, Queryable};
let mut app = crate::common::prepare(SheetApp::new(five_pages(), Services::default()));
app.run("ui.backstage", json!({"page": "print"})).unwrap();
let mut h = crate::common::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(
|ui, app: &mut SheetApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(4);
assert!(h.query_by_label("Page 1 of 5").is_some());
type_into(&mut h, "Pages", "2");
type_into(&mut h, "to", "3x");
let range = h.state().print_pages;
assert_eq!((range.from, range.to), (Some(2), Some(3)), "digits only");
assert!(h.query_by_label("Page 2 of 5").is_some(), "the preview starts at the range's first page, under its own number");
h.get_by_label("▶").click();
h.run_steps(3);
assert!(h.query_by_label("Page 3 of 5").is_some());
assert!(h.get_by_label("▶").accesskit_node().is_disabled(), "page 3 is the last page that prints");
assert!(h.get_all_by_role_and_label(Role::Button, "Print").all(|b| !b.accesskit_node().is_disabled()));
// A range changed by automation also returns the preview to the start of the new range.
h.state_mut().run("ui.printSettings", json!({"from": 1, "to": 2})).unwrap();
h.run_steps(3);
assert!(h.query_by_label("Page 1 of 5").is_some());
// An emptied field has no bound; a range after the last page has nothing to print, and Print is off.
type_into(&mut h, "to", "");
assert_eq!(h.state().print_pages.to, None);
type_into(&mut h, "Pages", "9");
assert!(h.query_by_label("Nothing to print.").is_some());
// The square Print button, not the navigation entry of the same name.
assert!(h.get_all_by_role_and_label(Role::Button, "Print").any(|b| b.accesskit_node().is_disabled()));
// The fields show what `ui.printSettings` sets once they are left (Tab moves on to "to").
h.key_press(egui::Key::Tab);
h.run_steps(2);
h.state_mut().run("ui.printSettings", json!({"from": 4, "to": null})).unwrap();
h.run_steps(3);
assert_eq!(h.get_by_role_and_label(Role::TextInput, "Pages").value().as_deref(), Some("4"));
assert_eq!(h.get_by_role_and_label(Role::TextInput, "to").value().as_deref(), Some(""));
assert!(h.query_by_label("Page 4 of 5").is_some());
// German labels.
h.state_mut().run("app.language.set", json!({"language": "de"})).unwrap();
h.run_steps(3);
assert_eq!(h.get_by_role_and_label(Role::TextInput, "Seiten").value().as_deref(), Some("4"));
assert!(h.query_by_role_and_label(Role::TextInput, "bis").is_some());
assert!(h.query_by_label("Seite 4 von 5").is_some());
}
#[test]
/// Export › Create PDF exports the page range typed under it.
fn create_pdf_exports_the_page_range_under_it() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
let dir = std::env::temp_dir().join(format!("gridcraft-export-range-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let target = dir.join("Range.pdf");
let path = target.to_string_lossy().into_owned();
let services = Services { pick_save: Some(Box::new(move |_| Some(path.clone()))), ..Default::default() };
let mut app = crate::common::prepare(SheetApp::new(five_pages(), services));
app.run("ui.backstage", json!({"page": "export"})).unwrap();
let mut h = crate::common::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(
|ui, app: &mut SheetApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(4);
type_into(&mut h, "Pages", "4");
h.get_by_role_and_label(Role::Button, "Create PDF").click();
h.run_steps(3);
assert!(h.state().message.is_none(), "{:?}", h.state().message);
assert_eq!(footers(&std::fs::read(&target).unwrap()), ["Page 4 of 5", "Page 5 of 5"]);
assert_eq!(h.state().print_pages, gridcraft_ui_egui::printing::PageRange::default(), "File › Print keeps its own range");
let _ = std::fs::remove_dir_all(&dir);
}
+31 -1
View File
@@ -21,7 +21,10 @@ fn harness(jobs: Rc<RefCell<Vec<Vec<u8>>>>) -> egui_kittest::Harness<'static, Sh
app.run("cell.set", json!({"cell": "H20", "input": "Outside"})).unwrap();
app.run("pageLayout.pageSetup", json!({"printArea": "F10:H20"})).unwrap();
app.run("selection.set", json!({"range": "A1:B2"})).unwrap();
app.services.print = Some(Box::new(move |bytes| jobs.borrow_mut().push(bytes.to_vec())));
app.services.print = Some(Box::new(move |bytes| {
jobs.borrow_mut().push(bytes.to_vec());
Ok(())
}));
app.run("ui.backstage", json!({"page": "print"})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state(
|ui, app: &mut SheetApp| {
@@ -76,3 +79,30 @@ fn the_preview_follows_the_selection_and_each_area_gets_its_own_page() {
h.run_steps(4);
assert!(h.query_by_label("Page 1 of 2").is_some(), "two areas, two pages");
}
#[test]
fn refused_browser_handoff_keeps_the_print_selection_available_for_retry() {
let jobs = Rc::new(RefCell::new(Vec::new()));
let mut h = harness(jobs.clone());
choose_selection(&mut h);
let accepted = h.state_mut().services.print.take();
h.state_mut().services.print = Some(Box::new(|_| Err("The browser blocked the print window".into())));
let error = h.state_mut().run("ui.printSubmit", json!({})).unwrap_err();
assert!(error.contains("blocked the print window"));
h.get_all_by_role_and_label(egui::accesskit::Role::Button, "Print").last().expect("Print button").click();
h.run_steps(3);
assert!(h.state().backstage.is_some());
assert!(h.state().message.as_ref().unwrap().1.contains("blocked the print window"));
assert!(jobs.borrow().is_empty());
h.state_mut().message = None;
h.state_mut().services.print = accepted;
h.run_steps(3);
h.get_all_by_role_and_label(egui::accesskit::Role::Button, "Print").last().expect("Print button").click();
h.run_steps(3);
assert!(h.state().backstage.is_none());
let jobs = jobs.borrow();
assert_eq!(jobs.len(), 1);
assert!(contains(&jobs[0], "(Inside) Tj"));
assert!(!contains(&jobs[0], "(Outside) Tj"));
}
+16 -5
View File
@@ -154,8 +154,19 @@ lists `ui.printSettings` and `ui.printSubmit` with their parameter and result fi
printer, copies, duplex, grayscale, discovery/submission status and backend receipt/error.
`{"refresh":true}` starts background discovery; poll the same command until `discovering` is
false. Set `printer` to a discovered name, integer `copies` from 1 to 999, `duplex` to
`printerDefault`, `off`, `longEdge` or `shortEdge`, and boolean `grayscale`. Invalid updates are
rejected without changing earlier settings. `ui.printSubmit` explicitly submits the current
print-ready PDF without opening a dialog; inspect `ui.printSettings` until `busy` becomes false
and check `status`/`detail`. The browser keeps its own print hook. PDF export remains separate.
GridCraft accepts the existing `file.print` sheet/pagination params on `ui.printSubmit`; the engine `file.print` command returns the PDF without spooling.
`printerDefault`, `off`, `longEdge` or `shortEdge`, and boolean `grayscale`. `from` and `to`
are the Print view's page range (Pages … to …) of the active window, or of the window named by
`window` or `doc`, as each window keeps its own: whole page numbers from 1, counted over the
whole print job in sheet order, or `null` to clear a bound; the result reports both. Invalid updates are rejected without changing earlier
settings. `ui.printSubmit` explicitly submits the current print-ready PDF without opening a
dialog; inspect `ui.printSettings` until `busy` becomes false and check `status`/`detail`. The
browser keeps its own print hook. PDF export remains
separate. GridCraft accepts the existing `file.print` sheet/pagination params on
`ui.printSubmit`, and the page range of `ui.printSettings` when the call names neither `from` nor
`to`; the engine `file.print` command returns the PDF without spooling.
`file.print`, `file.exportPdf` and `file.printPreview` take the same `from` and `to`. Only those
pages print, and their headers and footers keep the whole job's `&P` and `&N`. A range that
starts after the last page is an error, `to` past the last page stops there, and `from` greater
than `to` prints the pages between them. `file.printPreview` then lists only the pages that
print, each under its number in the job, with the job's page count as `total`.
+2 -1
View File
@@ -123,7 +123,7 @@ past the parser's limit, and a wrapper inside the text. **Saving writes the real
| Format | Excel | GridCraft | Notes |
|---|---|---|---|
| PDF | Save As / Export | yes (own PDF 1.7 writer; CLI `convert` output) | Printed cell hyperlinks export as clickable HTTP(S)/mailto links or destinations within printed pages (#954); unsafe schemes and destinations outside the print range are omitted. Latin text uses the standard Helvetica, Times and Courier faces (13 base-14 entries with Symbol), not embedded; Arabic exports as shaped, embedded Noto Arabic glyphs; cell reading direction and RTL sheet geometry are kept; other characters outside WinAnsiEncoding are set in a predefined, non-embedded CID font (STSong-Light, Adobe-GB1, `UniGB-UTF16-H`, #1912), so **Simplified Chinese displays where the reader supplies that font, and scripts outside Adobe-GB1 (Devanagari, Thai) export as code points but show as the reader's missing-glyph box**; equations use Symbol for the Greek letters and operators it has, the Times faces for letters and digits, and a `[?]` box for the rest; web build exports without a file prompt (#141) |
| PDF | Save As / Export | yes (own PDF 1.7 writer; CLI `convert` output) | Pages … to … in File › Print and Export › Create PDF select whole-job page numbers (#3016). Printed cell hyperlinks export as clickable HTTP(S)/mailto links or destinations within printed pages (#954); unsafe schemes and destinations outside the print range are omitted. Latin text uses the standard Helvetica, Times and Courier faces (13 base-14 entries with Symbol), not embedded; Arabic exports as shaped, embedded Noto Arabic glyphs; cell reading direction and RTL sheet geometry are kept; other characters outside WinAnsiEncoding are set in a predefined, non-embedded CID font (STSong-Light, Adobe-GB1, `UniGB-UTF16-H`, #1912), so **Simplified Chinese displays where the reader supplies that font, and scripts outside Adobe-GB1 (Devanagari, Thai) export as code points but show as the reader's missing-glyph box**; equations use Symbol for the Greek letters and operators it has, the Times faces for letters and digits, and a `[?]` box for the rest; web build exports without a file prompt (#141) |
| XPS | Windows | no | Low priority |
| Print | yes | yes (via PDF, system dialog on desktop; PR #143 for web) | Pages print in the sheet's page order: down, then over (the default) or over, then down. A sheet marked `excluded` (Page Setup) is left out when the whole workbook prints or exports to PDF, unless every visible sheet is, as LibreOffice treats an OpenDocument sheet set not to print; Excel has no such flag, so it is not kept in XLSX: Save asks first and offers GridCraft JSON, AutoSave waits, and `file.save`, `file.saveAs` and `file.saveBytes` return `warnings` |
| Images of ranges/charts (Copy as Picture) | yes | chart raster in `crates/chart` | No range-to-image command |
@@ -194,6 +194,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
| 2026-11-01 | minor | Chart data tables preserve showKeys, showHorzBorder, showVertBorder and showOutline through native c:dTable XLSX import/export; synthetic tests cover all 16 flag combinations and boolean defaults. Excel-side verification remains outstanding. |
| 2026-11-01 | minor | XLSX reads and writes Page Setup's page order: `<pageSetup pageOrder="overThenDown">` for Over, then down, and no attribute for Down, then over (the default), as Excel writes them; PDF export and printing number and order the pages by it |
| 2026-11-01 | trivial | XLSX selects the first visible workbook view as one unit and bounds imported/exported tab ratios; isolated attributes and sheet-edit round trips covered, with firstSheet left to #2264 (#3057) |
| 2026-10-31 | minor | PDF export and printing take a page range (`from`/`to` on `file.exportPdf`, `file.print` and `file.printPreview`; Pages … to … in File › Print and Export › Create PDF, #3016). Only those pages print, counted over the whole job in sheet order, and their headers and footers keep the whole job's `&P` and `&N`. A range starting after the last page is an error, `to` past the last page stops there, and `from` greater than `to` prints the pages between them, as Excel's Export › PDF measured |
| 2026-10-31 | minor | CSV and text open detects each column's date order: a value that reads only day first (`31/05/2026`) makes the column day first, a value that reads only month first (`12/31/2026`) makes it month first, an all-ambiguous column keeps month first with a warning, and a column with both kinds stays text with a warning (#2765) |
| 2026-10-31 | minor | XLSX open reads Google Sheets' `IFERROR(__xludf.DUMMYFUNCTION("…"),cached)` export wrapper as the formula inside when GridCraft calculates every function in it (plain, shared and array formulas, whole or nested; Google-only functions and unparseable, over-long or over-deep inner text keep the wrapper and the cached value) and keeps the cached value; saving writes the real formula with Excel's `_xlfn.` prefixes (#2871) |
| 2026-10-26 | minor | PDF honors cell Context/LTR/RTL, preserves paragraph direction across wrapping, and mirrors RTL sheet geometry without reversing glyphs |
+2 -1
View File
@@ -149,7 +149,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
### 14. Page Layout view and print polish (U, F)
- Page Layout view landed (#329): paper view with rulers and in-place header/footer editing.
Margins are dragged on the rulers (#792). Remaining: pictures in headers/footers, Different First Page / Odd & Even pages. Desktop now submits directly through craft-print with printer choice, copies, duplex and grayscale; browser printing stays available. Print Selection landed (File › Print › Settings); Set Print Area is in Page Layout. Driver tray/options UI remains. **Estimate:** 5–10 h.
Margins are dragged on the rulers (#792). Remaining: pictures in headers/footers, Different First Page / Odd & Even pages. Desktop now submits directly through craft-print with printer choice, copies, duplex and grayscale; browser printing stays available. Print Selection landed (File › Print › Settings); Set Print Area is in Page Layout. Page ranges (Pages … to …) are in File › Print and Export › Create PDF (#3016). Driver tray/options UI remains. **Estimate:** 5–10 h.
### 15. Remaining functions and an oracle suite (F)
- 9 missing, 9 stubs; no Excel-computed oracle corpus; #137, #138. **Estimate:** 15–25 h.
@@ -205,6 +205,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
| 2026-11-02 | minor | §4: charts, like every floating object, move and resize from eight handles (#190), so resizing is no longer listed as missing; the evidence is one paragraph again, without the stale "PRs #158, #161 open" |
| 2026-11-01 | minor | §13: the Analysis ToolPak has all 19 of Excel's tools (two-factor Anova with and without replication, z-Test, Fourier Analysis, Random Number Generation, Sampling); its chart output remains. The stale "`data.solver`, `data.analysisToolPak` missing" and "no Forecast Start" sentences removed |
| 2026-11-01 | minor | §4: chart data tables implemented for column, bar, line, area and compatible combo charts, with legend keys and border settings, live source values, XLSX round-trip and print/PDF; other chart gaps remain. |
| 2026-10-31 | minor | §14: page ranges (Pages … to …) in File › Print and Export › Create PDF, and `from`/`to` on `file.print`, `file.exportPdf` and `file.printPreview` (#3016) |
| 2026-10-31 | minor | §13: Solver Options (Max Evaluations, Integer Optimality and the Evolutionary options), saved with the model |
| 2026-10-31 | minor | §13: Solver Load/Save Model (`data.solverSaveModel`, `data.solverLoadModel`) and Reset All (`data.solverReset`), with buttons in the Solver Parameters dialog |
| 2026-10-26 | minor | §1: `packaging/windows/excel-open-check` opens saved workbooks in real Excel and records pass or the exact failure; first run: 24 of 25 open cleanly |
+2 -1
View File
@@ -43,7 +43,7 @@ desktops is not guaranteed. FreeBSD has not been tested locally.
| Task panes (Format Chart, Comments, Watch, Selection, PivotTable fields) | yes | yes; PivotTable source-field list scrollbar sits at the right edge of its pane | element-level Format pane for shapes and pictures missing |
| Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | partial | template gallery missing |
| Dark mode, system appearance | yes | yes | done (10-09); follows the system on first run, title-bar switch and File › Display theme (#194, #239); icons, reference colours, primary buttons and the comments pane follow the theme, and a unit test holds every token pair to WCAG 2 contrast in both themes |
| Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | yes (#174, 10-11): the File tab opens a full-window view (Esc or the back arrow return; Esc in a text field first cancels editing and leaves the field, #3035) with Home, New (blank + the three samples), Open (recent + Browse; the recent list tells when each workbook was last changed, 10-12), Info (location, properties, Protect Workbook), Save, Save As, Print (page preview, active sheet, workbook or selection, fit to page, Page Setup), Export (PDF, CSV, web page), Close and Options (`file.options`: theme, language, formula bar, AutoSave, calculation mode and iterative calculation with Maximum Iterations and Maximum Change, 10-15) | no Account, Share or template gallery beyond the samples; Options applies at once (no OK/Cancel dialog) and holds only the settings GridCraft has |
| Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | yes (#174, 10-11): the File tab opens a full-window view (Esc or the back arrow return; Esc in a text field first cancels editing and leaves the field, #3035) with Home, New (blank + the three samples), Open (recent + Browse; the recent list tells when each workbook was last changed, 10-12), Info (location, properties, Protect Workbook), Save, Save As, Print (page preview, active sheet, workbook or selection, fit to page, Pages … to …, Page Setup), Export (PDF with a page range, CSV, web page), Close and Options (`file.options`: theme, language, formula bar, AutoSave, calculation mode and iterative calculation with Maximum Iterations and Maximum Change, 10-15) | no Account, Share or template gallery beyond the samples; Options applies at once (no OK/Cancel dialog) and holds only the settings GridCraft has |
| Dark mode, system appearance | yes | yes | done (10-09) |
| Page Layout view (paper view with rulers and header editing) | yes | yes (#329, 10-11): per-sheet view saved in XLSX, pages with margins and gaps on the print pagination, "Click to add data" pages, rulers (inches or centimetres), headers and footers drawn and edited in place with a Header & Footer tab, whose Different First Page and Different Odd & Even Pages give the first page and the even pages their own header and footer (#344), and whose Scale with Document and Align with Page Margins set whether header and footer text follows the print scale and the side margins, on paper and in the view | margins drag on the rulers (#792, with header and footer margins); header/footer pictures missing (1–3 h). Unverified: with Align with Page Margins off, header and footer text sits 0.7 in from the paper edge, a value not yet measured in the target app |
| Multiple windows per workbook | yes | yes (10-22, desktop): each workbook window is a native window of its own (New, Open and New Window open one; titles "Book1", or "Book1:1" / "Book1:2" for a workbook's second window, with " — Edited" while unsaved). Each window keeps its own cell draft, dialog, Backstage view, message and grid state, and its ribbon acts on it; on macOS the menu bar acts on the window focused last. Leaving a window enters its draft as Enter would. A window's close button closes that window: one of several on a workbook closes without asking, a workbook's last asks Save / Don't Save / Cancel when unsaved. Quit asks about each unsaved workbook in its window, and Cancel stops it. The last window closed quits on Windows and Linux; macOS keeps running with the menu bar until New or Open. View › Arrange All (dialog: Tiled, Horizontal, Vertical, Cascade, Windows of active workbook; `view.arrangeAll` tiles by default) lays the visible windows out over the main window's monitor, the active one first. Web: one window | Arrange All uses one monitor; a hidden window (View › Hide) has no native window; every window repaints when one does; see [hardware-parity.md](hardware-parity.md) |
@@ -346,6 +346,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
| 2026-11-01 | minor | Formulas › Error Checking › Trace Error (`formulas.traceError`): red arrows from the cell an error starts in to the selected cell, through the first reference showing the same error at each step, and blue arrows from that cell's own references, as measured in Excel; the command returns the source and the arrows |
| 2026-11-01 | minor | Trace arrows stay when the sheet is zoomed (View › Zoom, the status bar, Ctrl+wheel), as in Excel; every zoom used to remove them (#3097) |
| 2026-11-01 | minor | Assert shared baselines in the actual title layout and record manual visual-size validation of a compiled macOS build |
| 2026-10-31 | minor | File › Print has Pages … to … below Print Active Sheets / Print Entire Workbook, and Export › Create PDF has the same two fields (#3016). Empty fields print every page, and each window keeps its own range. Pages are counted over the whole job in sheet order, and the printed pages keep the job's numbers in their headers and footers (`&P` of `&N`: page 2 of a 5-page sheet prints "Page 2 of 5"), as in Excel. The preview shows only the pages that print, under their own numbers. `ui.printSettings` takes `from` and `to` (`null` clears one), and `ui.printSubmit` prints that range |
| 2026-10-31 | minor | Esc in a File-page text field leaves the field and cancels editing; the next Esc returns to the sheet (#3035) |
| 2026-10-31 | minor | Recently Used lists the functions most recently entered in a formula from any source, kept with the preferences; the Insert Function dialog is titled as in Excel, its category list (Most Recently Used, All, each category) works, and its category column follows the widest name shown |
| 2026-10-31 | minor | Formulas › Function Library: Insert Function, the AutoSum split button and three columns of labelled small buttons with category colours; category menus end with Insert Function…; More Functions cascades; Home › Editing shares the AutoSum menu; MR key tip for Recently Used |