Compare commits

..
Author SHA1 Message Date
FredApps 0bcc39e0ba Keep workbook print settings available when the browser refuses the PDF 2026-12-02 23:39:20 +01:00
FredApps 71ec2b9aa0 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 20:15:48 +01:00
13 changed files with 57 additions and 300 deletions
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",
+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",
-5
View File
@@ -141,11 +141,6 @@ pub trait Host {
fn range_values(&mut self, sheet: usize, range: RangeRef) -> Vec<Value> {
range.iter().map(|c| self.cell_value(sheet, c)).collect()
}
/// Finds the smallest rectangle covering the non-empty cells of a block without reading its
/// full grid. The outer `None` leaves the read to `range_values`. `Some(None)` means all blank.
fn range_nonempty_bounds(&mut self, _sheet: usize, _range: RangeRef) -> Option<Option<RangeRef>> {
None
}
/// The sheet's used range (`Sheet::used_range`, which walks every stored row). Hosts that
/// keep the workbook unchanged while evaluating can remember it.
fn used_range(&mut self, sheet: usize) -> Option<RangeRef> {
-64
View File
@@ -915,70 +915,6 @@ pub(crate) mod tests {
assert!(!index_spills(5_000, 5_000, [].iter()));
}
#[test]
fn trim_references_skip_the_dense_grid_for_sparse_stored_values() {
use crate::eval::{Area, Ev, Evaluator};
use gridcraft_core::CellError;
use gridcraft_model::StyleId;
let mut wb = Workbook::new();
let sh = wb.sheet_mut(0).unwrap();
let at = |s: &str| CellRef::parse(s).unwrap();
sh.set_cell(at("C3"), Cell::value(Value::Number(0.0)));
let mut cached = Cell::formula(Formula::new("\"\""));
cached.value = Value::text("");
sh.set_cell(at("N39999"), cached);
sh.set_cell(at("Q40001"), Cell::styled(Value::Empty, StyleId(1)));
// These cells keep the sheet's used extent wide and tall without being in the trim range.
sh.set_cell(at("Q1"), Cell::value(Value::Number(1.0)));
sh.set_cell(at("A40001"), Cell::value(Value::Number(1.0)));
let exprs = HashMap::default();
let mut rng = 1u64;
let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0);
let mut ev = Evaluator::new(&mut host, 0, at("S1"));
for (src, expected) in [("B2.:.Q40001", "C3:N39999"), ("TRIMRANGE(B2:Q40001,1,2)", "B3:N40001")] {
let expr = gridcraft_formula::parse(src).unwrap();
let result = ev.eval(&expr);
let area = Area { sheet: 0, range: RangeRef::parse(expected).unwrap() };
assert!(matches!(&result, Ev::R(areas) if areas.as_slice() == [area]), "{src}: {result:?}");
}
let blank = gridcraft_formula::parse("TRIMRANGE(O2:Q40001)").unwrap();
assert!(matches!(ev.eval(&blank), Ev::V(Value::Error(CellError::Calc))));
assert_eq!(host.materialized_range_cells, 0, "bounds reads must not allocate a dense grid");
}
#[test]
fn trim_range_includes_a_spill_from_outside_the_block() {
use crate::eval::Evaluator;
let mut wb = Workbook::new();
let sh = wb.sheet_mut(0).unwrap();
let at = |s: &str| CellRef::parse(s).unwrap();
let anchor = (0, at("C1"));
let target = at("I1");
let source = Formula::new("SEQUENCE(2,5)");
let consumer = Formula::new("COLUMNS(TRIMRANGE(C2:G4))");
let exprs = [(anchor, source.expr_arc().unwrap()), ((0, target), consumer.expr_arc().unwrap())].into_iter().collect();
sh.set_cell(anchor.1, Cell::formula(source));
sh.set_cell(target, Cell::formula(consumer));
// Extend the read area before the new spill has been committed to the sheet.
sh.set_cell(at("H5"), Cell::value(Value::Number(1.0)));
let mut rng = 1u64;
let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0);
host.calculate(anchor);
host.calculate((0, target));
assert_eq!(host.results.get(&(0, target)), Some(&Value::Number(5.0)), "new spill in the current pass");
Calc::new().recalc_all(&mut wb);
let exprs = HashMap::default();
let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0);
let consumer = gridcraft_formula::parse("COLUMNS(TRIMRANGE(C2:G4))").unwrap();
let result = Evaluator::new(&mut host, 0, target).value(&consumer);
assert_eq!(result, Value::Number(5.0), "stored spill from a completed recalculation");
}
/// A 1,000 x 1,000 Python result laid out from A1 in a pass, with the same values already
/// spilled on the sheet from the last calculation, as a full recalculation finds them.
fn big_python_spill() -> (Workbook, HashMap<Key, Value>) {
+12 -55
View File
@@ -57,9 +57,6 @@ pub(super) struct PassHost<'a> {
/// looks at none of it).
#[cfg(test)]
pub(super) spill_visits: usize,
/// Number of value slots allocated by dense range reads.
#[cfg(test)]
pub(super) materialized_range_cells: usize,
/// The formulas in `cycles`.
cycle_seen: HashSet<Key>,
/// Iterative calculation: a circular reference reads the cell's previous value instead of
@@ -117,8 +114,6 @@ impl<'a> PassHost<'a> {
suspensions: 0,
#[cfg(test)]
spill_visits: 0,
#[cfg(test)]
materialized_range_cells: 0,
cycle_seen: HashSet::default(),
iterate: false,
prev: HashMap::default(),
@@ -243,25 +238,6 @@ fn stored_spill_in<'s>(sheet: &'s gridcraft_model::Sheet, range: RangeRef, f: &m
}
impl PassHost<'_> {
fn range_has_spill(&mut self, sheet: usize, range: RangeRef) -> bool {
let mut arrays = Vec::new();
self.spill_index.meeting(sheet, range, &mut arrays);
if !arrays.is_empty() {
return true;
}
let Some(sh) = self.wb.sheet(sheet) else { return false };
let mut stored = false;
let _seen = stored_spill_in(sh, range, &mut |_, _| {
stored = true;
false
});
#[cfg(test)]
{
self.spill_visits += _seen;
}
stored
}
/// Calculates `k` (and the formulas it reads) with bounded stack: when [`Self::compute`] would
/// go deeper than [`MAX_NESTED`], it suspends what is in progress, the formula it needed is
/// calculated from here, then the suspended ones again (reading the results kept so far).
@@ -633,10 +609,6 @@ impl Host for PassHost<'_> {
}
fn range_values(&mut self, sheet: usize, range: RangeRef) -> Vec<Value> {
let (h, w) = (range.height() as usize, range.width() as usize);
#[cfg(test)]
{
self.materialized_range_cells += h * w;
}
let mut out = vec![Value::Empty; h * w];
let Some(sh) = self.wb.sheet(sheet) else { return out };
// Sparse walk: only stored cells; formula and Python cells that are (or were) dirty go
@@ -726,7 +698,18 @@ impl Host for PassHost<'_> {
}
// Spilled values sit between the stored cells (and the formulas just calculated may have
// produced some): leave such blocks to `range_values`.
if self.range_has_spill(sheet, range) {
let mut arrays = Vec::new();
self.spill_index.meeting(sheet, range, &mut arrays);
let mut stored = false;
let _seen = stored_spill_in(sh, range, &mut |_, _| {
stored = true;
false
});
#[cfg(test)]
{
self.spill_visits += _seen;
}
if !arrays.is_empty() || stored {
return false;
}
for (c, cell) in sh.cells.iter_range(range) {
@@ -737,32 +720,6 @@ impl Host for PassHost<'_> {
}
true
}
fn range_nonempty_bounds(&mut self, sheet: usize, range: RangeRef) -> Option<Option<RangeRef>> {
if self.iterate || self.range_has_spill(sheet, range) {
return None;
}
let sh = self.wb.sheet(sheet)?;
// When fewer calculations are in play than cells to inspect, check their coordinates
// first. A formula near the bottom of a dense range would otherwise cost two walks.
let pass_cells = self.pending.len() + self.results.len();
let checked_pass = (pass_cells as u64) < range.count() && pass_cells < sh.cells.len();
if checked_pass && self.pending.iter().chain(self.results.keys()).any(|&(s, c)| s == sheet && range.contains(c)) {
return None;
}
let mut bounds: Option<RangeRef> = None;
for (c, cell) in sh.cells.iter_range(range) {
// With no pending or computed results in the block, formula and Python readers
// see the stored values as well. Otherwise leave their evaluation to range_values.
if !checked_pass && (cell.formula.is_some() || cell.py.is_some()) {
return None;
}
if !cell.value.is_empty() {
let cell_range = RangeRef::cell(c);
bounds = Some(bounds.map_or(cell_range, |b| b.union(&cell_range)));
}
}
Some(bounds)
}
fn range_sum(&mut self, sheet: usize, range: RangeRef) -> Option<(f64, u64)> {
// Constants can't change during a pass, so a block's result stays valid for it. Spills
// found in this pass (and iteration, which tracks what a read depends on) go the long way.
-15
View File
@@ -2497,21 +2497,6 @@ fn blank_lookup_values_match_excel_windows_observation() {
}
}
#[test]
fn written_blank_lookup_argument_is_numeric_zero() {
// #4044: `XMATCH(, array)` writes a blank argument, which Excel reads as numeric zero. Only a
// reference to a blank cell (B1 here) is a blank lookup value.
let mut t = T::new();
t.set("A1", "=XMATCH(,{0,1,3})");
t.set("A2", "=XMATCH(B1,{0,1,3})");
t.set("A3", "=XLOOKUP(,{0,1,3},{10,20,30})");
t.set("A4", "=XLOOKUP(B1,{0,1,3},{10,20,30},\"none\")");
assert_eq!(t.get("A1"), Value::Number(1.0));
assert_eq!(t.get("A2"), Value::Error(CellError::NA));
assert_eq!(t.get("A3"), Value::Number(10.0));
assert_eq!(t.get("A4"), Value::from("none"));
}
#[test]
fn cell_width_is_the_column_width_dialog_value_rounded() {
// #735: Excel 365 values. Widths in px as `home.columnWidth {"chars"}` sets them
+2 -9
View File
@@ -95,15 +95,8 @@ impl Evaluator<'_> {
if (h as u64) * (w as u64) > MAX_CELLS {
return Err(CellError::Num);
}
let ((r0, r1), (c0, c1)) = if let Some(nonempty) = self.host.range_nonempty_bounds(a.sheet, part) {
let nonempty = nonempty.ok_or(CellError::Calc)?;
let row = |c: CellRef| (c.row - part.start.row) as usize;
let col = |c: CellRef| (c.col - part.start.col) as usize;
((row(nonempty.start), row(nonempty.end)), (col(nonempty.start), col(nonempty.end)))
} else {
let values = self.host.range_values(a.sheet, part);
bounds(&values, w).ok_or(CellError::Calc)?
};
let values = self.host.range_values(a.sheet, part);
let ((r0, r1), (c0, c1)) = bounds(&values, w).ok_or(CellError::Calc)?;
let (h_all, w_all) = (a.range.height() as usize, a.range.width() as usize);
let (kr0, kr1) = keep(h_all, (r0, r1), rows);
let (kc0, kc1) = keep(w_all, (c0, c1), cols);
+2 -72
View File
@@ -23,19 +23,6 @@ fn needle(args: &[Arg], i: usize) -> R<Value> {
}
}
/// The lookup value of XLOOKUP and XMATCH. Unlike the older lookups, a reference to a blank cell is
/// blank rather than numeric zero: it matches a blank entry and nothing else (#4044). A written
/// blank argument (`XMATCH(, array)`) still becomes zero, as MATCH does.
fn xneedle(args: &[Arg], i: usize) -> R<Value> {
let a = arg(args, i)?;
match a.value.scalar() {
Value::Error(e) => Err(e),
Value::Empty if a.from_ref || a.blank_value => Ok(Value::Empty),
Value::Empty => Ok(Value::Number(0.0)),
v => Ok(v),
}
}
/// Order of two values for the approximate and binary searches: [`compare`], except that numbers
/// compare exactly. Excel's `=` treats numbers equal to 15 significant digits as equal, but its
/// lookups don't. Observed in Excel 365 with A1 holding
@@ -246,12 +233,6 @@ fn xsearch(x: &Value, hay: &[Value], match_mode: i64, search_mode: i64) -> R<Opt
}
if search_mode.abs() == 2 {
let desc = search_mode == -2;
// A blank needle only matches a blank entry. The coercing comparison would read it as
// numeric zero, so the exact result stands even when it finds nothing: the approximate
// probes must not fall through to a zero (#4044).
if matches!(x, Value::Empty) {
return Ok(bsearch_exact(x, hay, desc));
}
if match_mode == 2 {
// Wildcards are not supported with binary search: Excel falls back to exact.
return Ok(bsearch_exact(x, hay, desc));
@@ -311,20 +292,13 @@ fn xsearch(x: &Value, hay: &[Value], match_mode: i64, search_mode: i64) -> R<Opt
}
fn bsearch_exact(x: &Value, hay: &[Value], desc: bool) -> Option<usize> {
if matches!(x, Value::Empty) {
// A blank needle only matches a blank entry. The coercing comparison below would read it
// as numeric zero, so handle it here: blanks sort last in both directions, so the first
// blank entry is the only possible exact match.
let p = hay.partition_point(|v| !matches!(v, Value::Empty));
return matches!(hay.get(p)?, Value::Empty).then_some(p);
}
let p = bsearch_first(x, hay, desc)?;
let v = hay.get(p)?;
if binary_order(v, x, desc) == Ordering::Equal { Some(p) } else { None }
}
fn xlookup(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
let x = xneedle(args, 0)?;
let x = needle(args, 0)?;
let lv = &arg(args, 1)?.value;
if let Value::Error(e) = lv {
return Err(*e);
@@ -370,7 +344,7 @@ fn xlookup(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
}
fn xmatch(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
let x = xneedle(args, 0)?;
let x = needle(args, 0)?;
let lv = &arg(args, 1)?.value;
if let Value::Error(e) = lv {
return Err(*e);
@@ -593,7 +567,6 @@ pub(crate) fn specs() -> Vec<FnSpec> {
mod tests {
use gridcraft_core::{CellError, Value};
use crate::Arg;
use crate::util::testutil::*;
fn table() -> Value {
@@ -786,49 +759,6 @@ mod tests {
assert_eq!(rows_of(&r), vec![vec![nv(3.0), nv(1.0)]]);
}
/// A reference to a blank cell is a blank lookup value, not numeric zero, for XMATCH and
/// XLOOKUP: it finds a blank entry and misses numbers. MATCH keeps Excel's zero coercion (#4044).
#[test]
fn xmatch_and_xlookup_treat_a_blank_reference_as_blank() {
let numbers = || av(row(&[0.0, 1.0, 3.0]));
let blank = || Arg::reference(Value::Empty);
is_err(ev("XMATCH", vec![blank(), numbers()]), CellError::NA);
close(ev("XMATCH", vec![blank(), rf(arr(vec![vec![Value::Empty], vec![nv(2.0)]]))]), 1.0);
let keys = || rf(col(&[0.0, 1.0, 3.0]));
let values = || av(col(&[10.0, 20.0, 30.0]));
close(ev("XLOOKUP", vec![blank(), keys(), values(), n(999.0), n(0.0)]), 999.0);
// Binary exact search (search mode 2 ascending, -2 descending) does not coerce the blank
// needle to zero either: {0} has no blank entry, {0;blank} has one last.
let zero = || rf(col(&[0.0]));
let zero_then_blank = || rf(arr(vec![vec![nv(0.0)], vec![Value::Empty]]));
let just_blank = || rf(arr(vec![vec![Value::Empty]]));
for mode in [2.0, -2.0] {
is_err(ev("XMATCH", vec![blank(), zero(), n(0.0), n(mode)]), CellError::NA);
close(ev("XMATCH", vec![blank(), zero_then_blank(), n(0.0), n(mode)]), 2.0);
close(ev("XMATCH", vec![blank(), just_blank(), n(0.0), n(mode)]), 1.0);
close(ev("XLOOKUP", vec![blank(), zero(), av(col(&[10.0])), n(999.0), n(0.0), n(mode)]), 999.0);
close(ev("XLOOKUP", vec![blank(), just_blank(), av(col(&[10.0])), n(999.0), n(0.0), n(mode)]), 10.0);
// The approximate binary modes (-1 next smaller, 1 next larger) still take a present
// exact blank before their fallback, in both search directions.
for mm in [-1.0, 1.0] {
close(ev("XMATCH", vec![blank(), just_blank(), n(mm), n(mode)]), 1.0);
close(ev("XMATCH", vec![blank(), zero_then_blank(), n(mm), n(mode)]), 2.0);
close(ev("XLOOKUP", vec![blank(), just_blank(), av(col(&[10.0])), n(999.0), n(mm), n(mode)]), 10.0);
close(ev("XLOOKUP", vec![blank(), zero_then_blank(), av(col(&[10.0, 20.0])), n(999.0), n(mm), n(mode)]), 20.0);
// Without a blank entry the approximate probes must not read the blank as zero.
is_err(ev("XMATCH", vec![blank(), zero(), n(mm), n(mode)]), CellError::NA);
close(ev("XLOOKUP", vec![blank(), zero(), av(col(&[10.0])), n(999.0), n(mm), n(mode)]), 999.0);
}
}
// Controls: numeric zero is still a key, and a written blank stays zero.
close(ev("XMATCH", vec![n(0.0), numbers()]), 1.0);
close(ev("XLOOKUP", vec![n(0.0), keys(), values(), n(999.0), n(0.0)]), 10.0);
is_err(ev("XMATCH", vec![n(0.0), just_blank(), n(0.0), n(2.0)]), CellError::NA);
close(ev("XMATCH", vec![empty(), zero(), n(0.0), n(2.0)]), 1.0);
close(ev("MATCH", vec![blank(), numbers(), n(0.0)]), 1.0);
close(ev("XMATCH", vec![empty(), numbers()]), 1.0);
}
/// Lookups compare numbers exactly, unlike `=` (15 significant digits). Observed in Excel 365.
#[test]
fn lookups_compare_numbers_exactly() {
+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());
}
+4 -2
View File
@@ -39,8 +39,10 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
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")
+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)]
+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"));
}