mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-03 22:41:38 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
623061303f | ||
|
|
c05683be93 |
@@ -231,7 +231,6 @@ fn services() -> Services {
|
||||
})),
|
||||
open_url: Some(Box::new(|url: &str| open_with_system(url))),
|
||||
printers: Some(print::discover()),
|
||||
printer_papers: Some(print::discover_papers()),
|
||||
print_native: Some(print::submit()),
|
||||
..Default::default()
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Desktop spooler adapter. Discovery and submission never run on the UI thread.
|
||||
use gridcraft_ui_egui::printing::{Destination, Discover, DiscoverPapers, Duplex, Paper, Printer, Settings, Submit};
|
||||
use gridcraft_ui_egui::printing::{Destination, Discover, Duplex, Printer, Settings, Submit};
|
||||
|
||||
/// Returns a printer-discovery closure that enumerates `craft_print::printers()` on a named background thread and sends the mapped list through a channel.
|
||||
pub fn discover() -> Discover {
|
||||
@@ -13,56 +13,6 @@ pub fn discover() -> Discover {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn discover_papers() -> DiscoverPapers {
|
||||
Box::new(|queue| {
|
||||
let queue = queue.to_owned();
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let _ = std::thread::Builder::new().name("print-paper-discovery".into()).spawn(move || {
|
||||
let _ = sender.send(papers(&queue));
|
||||
});
|
||||
receiver
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn papers(queue: &str) -> Vec<Paper> {
|
||||
craft_print::windows_paper_choices(queue)
|
||||
.into_iter()
|
||||
.map(|choice| Paper {
|
||||
id: choice.form.as_ref().map_or_else(
|
||||
|| format!("size:{}x{}:{}", choice.paper.width, choice.paper.height, choice.paper.name),
|
||||
|form| format!("form:{}", form.id()),
|
||||
),
|
||||
name: choice.paper.name,
|
||||
width: choice.paper.width,
|
||||
height: choice.paper.height,
|
||||
cups_media: None,
|
||||
windows_form: choice.form,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn papers(queue: &str) -> Vec<Paper> {
|
||||
craft_print::cups::media_catalog(queue)
|
||||
.sizes
|
||||
.into_iter()
|
||||
.map(|size| Paper {
|
||||
id: size.key.clone(),
|
||||
name: size.label,
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
cups_media: Some(size.key),
|
||||
windows_form: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(not(any(windows, unix)))]
|
||||
fn papers(_queue: &str) -> Vec<Paper> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
// Keep submission workers reachable until normal app shutdown; dropping a JoinHandle would
|
||||
// let process exit kill PowerShell/CUPS before it hands the job to the spooler.
|
||||
static JOBS: std::sync::Mutex<Vec<std::thread::JoinHandle<()>>> = std::sync::Mutex::new(Vec::new());
|
||||
@@ -77,11 +27,9 @@ pub fn finish_pending_jobs() {
|
||||
}
|
||||
|
||||
pub fn submit() -> Submit {
|
||||
Box::new(|bytes, settings: Settings, paper| {
|
||||
Box::new(|bytes, settings: Settings| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let worker = std::thread::Builder::new().name("print-submit".into()).spawn(move || {
|
||||
let explicit_paper = paper.is_some();
|
||||
let (windows_form, cups_media) = paper.map(|choice| (choice.windows_form, choice.cups_media)).unwrap_or_default();
|
||||
let job = craft_print::Job {
|
||||
printer: match settings.destination {
|
||||
Destination::Printer(name) => Some(name),
|
||||
@@ -96,16 +44,11 @@ pub fn submit() -> Submit {
|
||||
_ => None,
|
||||
}),
|
||||
grayscale: settings.grayscale,
|
||||
scaling: if explicit_paper { craft_print::Scaling::Exact } else { craft_print::Scaling::ShrinkToFit },
|
||||
options: cups_media.into_iter().map(|key| ("media".into(), key)).collect(),
|
||||
scaling: craft_print::Scaling::ShrinkToFit,
|
||||
title: "GridCraft document".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let result = match windows_form {
|
||||
Some(form) => craft_print::submit_to_windows_form(&bytes, &job, &form),
|
||||
None => craft_print::submit(&bytes, &job),
|
||||
};
|
||||
let _ = sender.send(result.map_err(|error| error.to_string()));
|
||||
let _ = sender.send(craft_print::submit(&bytes, &job).map_err(|error| error.to_string()));
|
||||
});
|
||||
if let Ok(worker) = worker {
|
||||
let mut jobs = JOBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
|
||||
@@ -141,6 +141,11 @@ 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> {
|
||||
|
||||
@@ -915,6 +915,70 @@ 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>) {
|
||||
|
||||
@@ -57,6 +57,9 @@ 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
|
||||
@@ -114,6 +117,8 @@ 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(),
|
||||
@@ -238,6 +243,25 @@ 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).
|
||||
@@ -609,6 +633,10 @@ 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
|
||||
@@ -698,18 +726,7 @@ 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`.
|
||||
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 {
|
||||
if self.range_has_spill(sheet, range) {
|
||||
return false;
|
||||
}
|
||||
for (c, cell) in sh.cells.iter_range(range) {
|
||||
@@ -720,6 +737,32 @@ 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.
|
||||
|
||||
@@ -2497,6 +2497,21 @@ 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
|
||||
|
||||
@@ -95,8 +95,15 @@ impl Evaluator<'_> {
|
||||
if (h as u64) * (w as u64) > MAX_CELLS {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let values = self.host.range_values(a.sheet, part);
|
||||
let ((r0, r1), (c0, c1)) = bounds(&values, w).ok_or(CellError::Calc)?;
|
||||
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 (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);
|
||||
|
||||
@@ -56,7 +56,7 @@ const MAX_CHART_PRIMS: usize = 4_000_000;
|
||||
#[cfg(test)]
|
||||
use layout::bands;
|
||||
pub(crate) use layout::split_bands;
|
||||
pub use layout::{PaperOverride, PrintOptions, SheetLayout, layout_sheet, layouts, paper_size, print_range};
|
||||
pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, paper_size, print_range};
|
||||
use layout::{seg_size, segments};
|
||||
use objects::{PicCache, draw_objects};
|
||||
#[cfg(test)]
|
||||
@@ -78,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print…",
|
||||
["File"],
|
||||
Some("Cmd+P"),
|
||||
"{path?, sheets?: active|all, range?, fitToPage?: bool, paperOverride?: {name,width,height} (points)} → {pages, bytes, base64} — the PDF the UI hands to the system print dialog",
|
||||
"{path?, sheets?: active|all, range?, fitToPage?: bool} → {pages, bytes, base64} — the PDF the UI hands to the system print dialog",
|
||||
has_doc,
|
||||
print
|
||||
),
|
||||
@@ -87,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Preview",
|
||||
["File"],
|
||||
None,
|
||||
"{page? (1-based), sheets?: active|all, range?, fitToPage?, paperOverride?: {name,width,height} (points)} → {pages, pageList: [{page, sheet, range, rows, columns, scale, paper, orientation, pageOrder, width, height}]} in print order",
|
||||
"{page? (1-based), sheets?: active|all, range?, fitToPage?} → {pages, pageList: [{page, sheet, range, rows, columns, scale, paper, orientation, pageOrder, width, height}]} in print order",
|
||||
has_doc,
|
||||
print_preview
|
||||
),
|
||||
|
||||
@@ -75,15 +75,6 @@ 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>,
|
||||
/// One physical paper size for this print job, without editing any worksheet's Page Setup.
|
||||
pub paper_override: Option<PaperOverride>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PaperOverride {
|
||||
pub name: String,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
}
|
||||
|
||||
impl PrintOptions {
|
||||
@@ -99,18 +90,7 @@ impl PrintOptions {
|
||||
ranges.push(RangeRef::parse(split_sheet(part.trim()).1.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?);
|
||||
}
|
||||
}
|
||||
let paper_override = p
|
||||
.get("paperOverride")
|
||||
.map(|paper| {
|
||||
let size = |key| paper.get(key).and_then(Json::as_f64).filter(|value| (36.0..=14_400.0).contains(value)).map(|v| v as f32);
|
||||
let name = paper.get("name").and_then(Json::as_str).filter(|name| !name.trim().is_empty());
|
||||
match (name, size("width"), size("height")) {
|
||||
(Some(name), Some(width), Some(height)) => Ok(PaperOverride { name: name.into(), width, height }),
|
||||
_ => Err(bad(cmd, "`paperOverride` needs a name and a width and height from 36 to 14400 points")),
|
||||
}
|
||||
})
|
||||
.transpose()?;
|
||||
Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage"), paper_override })
|
||||
Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage") })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -269,13 +249,8 @@ fn title_span(t: Option<(u32, u32)>, max: u32) -> Option<(u32, u32)> {
|
||||
/// Paginates one sheet.
|
||||
pub fn layout_sheet(wb: &Workbook, si: usize, opts: &PrintOptions, range_override: Option<RangeRef>) -> Option<SheetLayout> {
|
||||
let sh = wb.sheet(si)?;
|
||||
let mut st = sh.print.clone();
|
||||
let (mut pw, mut ph) = if let Some(paper) = &opts.paper_override {
|
||||
st.paper.clone_from(&paper.name);
|
||||
(paper.width.min(paper.height), paper.width.max(paper.height))
|
||||
} else {
|
||||
paper_size(&st.paper)
|
||||
};
|
||||
let st = sh.print.clone();
|
||||
let (mut pw, mut ph) = paper_size(&st.paper);
|
||||
if st.orientation == Orientation::Landscape {
|
||||
std::mem::swap(&mut pw, &mut ph);
|
||||
}
|
||||
|
||||
@@ -1011,26 +1011,6 @@ fn page_setup_paper_sizes_reach_the_pdf_page() {
|
||||
assert!(s.execute("pageLayout.pageSetup", json!({"paper": "Napkin"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn job_paper_override_reflows_the_preview_and_keeps_saved_orientation() {
|
||||
let mut s = s();
|
||||
let rows: Vec<_> = (0..60).map(|row| [row]).collect();
|
||||
s.execute("range.setValues", json!({"range":"A1:A60","values":rows})).unwrap();
|
||||
s.execute("pageLayout.pageSetup", json!({"paper":"A4","orientation":"landscape"})).unwrap();
|
||||
let original = s.execute("file.printPreview", json!({})).unwrap();
|
||||
let params = json!({"paperOverride":{"name":"Short Form","width":288.0,"height":432.0}});
|
||||
let show = s.execute("file.printPreview", params.clone()).unwrap();
|
||||
assert_eq!(show["pageList"][0]["paper"], "Short Form");
|
||||
assert_eq!(show["pageList"][0]["width"], 432.0);
|
||||
assert_eq!(show["pageList"][0]["height"], 288.0);
|
||||
assert!(show["pages"].as_u64().unwrap() > original["pages"].as_u64().unwrap());
|
||||
let (pdf, pages) = pdf_of(&mut s, params);
|
||||
assert_eq!(pages as u64, show["pages"].as_u64().unwrap());
|
||||
assert!(contains(&pdf, "/MediaBox [0 0 432 288]"));
|
||||
assert_eq!(s.execute("file.printPreview", json!({})).unwrap(), original);
|
||||
assert!(s.execute("file.print", json!({"paperOverride":{"name":"Bad","width":0,"height":432}})).is_err());
|
||||
}
|
||||
|
||||
/// An empty paper name means no paper is stated; it prints on Letter.
|
||||
#[test]
|
||||
fn an_unstated_paper_prints_on_letter() {
|
||||
|
||||
@@ -23,6 +23,19 @@ 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
|
||||
@@ -233,6 +246,12 @@ 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));
|
||||
@@ -292,13 +311,20 @@ 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 = needle(args, 0)?;
|
||||
let x = xneedle(args, 0)?;
|
||||
let lv = &arg(args, 1)?.value;
|
||||
if let Value::Error(e) = lv {
|
||||
return Err(*e);
|
||||
@@ -344,7 +370,7 @@ fn xlookup(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
}
|
||||
|
||||
fn xmatch(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let x = needle(args, 0)?;
|
||||
let x = xneedle(args, 0)?;
|
||||
let lv = &arg(args, 1)?.value;
|
||||
if let Value::Error(e) = lv {
|
||||
return Err(*e);
|
||||
@@ -567,6 +593,7 @@ pub(crate) fn specs() -> Vec<FnSpec> {
|
||||
mod tests {
|
||||
use gridcraft_core::{CellError, Value};
|
||||
|
||||
use crate::Arg;
|
||||
use crate::util::testutil::*;
|
||||
|
||||
fn table() -> Value {
|
||||
@@ -759,6 +786,49 @@ 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() {
|
||||
|
||||
@@ -42,7 +42,6 @@ impl SheetApp {
|
||||
notice: None,
|
||||
services,
|
||||
printing: Default::default(),
|
||||
print_paper: Default::default(),
|
||||
print_feedback_seen: None,
|
||||
synthetic: Default::default(),
|
||||
ctrl_wheel: false,
|
||||
@@ -580,7 +579,7 @@ mod lifecycle_tests {
|
||||
let mut app = app();
|
||||
app.printing.printers.push(crate::printing::Printer::new("Queue").is_default(true));
|
||||
app.run("ui.printSettings", serde_json::json!({"printer": "Queue"})).unwrap();
|
||||
app.services.print_native = Some(Box::new(|_, _, _| {
|
||||
app.services.print_native = Some(Box::new(|_, _| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
sender.send(Err("printer is offline".into())).unwrap();
|
||||
receiver
|
||||
|
||||
@@ -223,13 +223,7 @@ impl SheetApp {
|
||||
Ok(Json::Null)
|
||||
}
|
||||
"data.fromClipboard" => self.import_clipboard_text(p),
|
||||
"ui.printSettings" => printing::settings(
|
||||
&mut self.printing,
|
||||
&mut self.print_paper,
|
||||
p,
|
||||
self.services.printers.as_ref(),
|
||||
self.services.printer_papers.is_some(),
|
||||
),
|
||||
"ui.printSettings" => printing::settings(&mut self.printing, p, self.services.printers.as_ref()),
|
||||
"ui.printSubmit" => self.submit_print(p.clone()),
|
||||
"ui.ribbonTab" => {
|
||||
self.ui.ribbon_tab = p.get("tab").and_then(Json::as_str).unwrap_or("Home").to_string();
|
||||
|
||||
@@ -46,28 +46,16 @@ impl SheetApp {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn submit_print(&mut self, mut params: Json) -> Result<Json, String> {
|
||||
pub(super) fn submit_print(&mut self, params: Json) -> Result<Json, String> {
|
||||
if self.services.print_native.is_some() && !self.printing.ready() {
|
||||
return Err("Select an available printer in File > Print before submitting.".into());
|
||||
}
|
||||
let paper = self.print_paper.selected(printing::printer_name(&self.printing.settings)).cloned();
|
||||
if self.services.print_native.is_some() {
|
||||
// A native request may choose only a paper from the selected queue.
|
||||
if let Some(fields) = params.as_object_mut() {
|
||||
fields.remove("paperOverride");
|
||||
}
|
||||
if let Some(paper) = &paper {
|
||||
paper.apply(&mut params);
|
||||
}
|
||||
}
|
||||
let pdf = self.run("file.print", params)?;
|
||||
let encoded = pdf.get("base64").and_then(Json::as_str).ok_or("The print command did not produce a PDF.")?;
|
||||
let bytes = gridcraft_engine::io::base64_decode(encoded).ok_or("Couldn't decode the generated PDF.")?;
|
||||
let len = bytes.len();
|
||||
if let Some(submit) = &self.services.print_native {
|
||||
self.printing
|
||||
.begin(submit(bytes, self.printing.settings.clone(), paper))
|
||||
.map_err(|_| "A print job is already being submitted.".to_owned())?;
|
||||
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);
|
||||
@@ -82,9 +70,6 @@ impl SheetApp {
|
||||
/// `tests/native_print.rs` deliberately bypass the lifecycle to test this helper alone.
|
||||
pub fn poll_printing(&mut self, ctx: &egui::Context) {
|
||||
self.printing.poll(ctx);
|
||||
if let Some(discover) = &self.services.printer_papers {
|
||||
self.print_paper.poll(printing::printer_name(&self.printing.settings), discover, ctx);
|
||||
}
|
||||
if self.printing.message == self.print_feedback_seen {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ 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, Option<crate::printing::Paper>);
|
||||
type PreviewKey = (u64, u64, PrintScope, String, bool);
|
||||
|
||||
/// What File › Print › Settings prints.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -147,7 +147,7 @@ pub struct Backstage {
|
||||
pub fit_to_page: bool,
|
||||
/// Print: the previewed page (0-based).
|
||||
preview_page: usize,
|
||||
/// Print: the preview for the workbook, job selection and paper.
|
||||
/// Print: the preview for (document, revision, scope, the selection when it is the scope, fit to page).
|
||||
preview: Option<(PreviewKey, Json)>,
|
||||
/// Save As: the chosen file type (an extension from [`SAVE_TYPES`]).
|
||||
pub save_format: &'static str,
|
||||
|
||||
@@ -23,16 +23,8 @@ 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 queue = crate::printing::printer_name(&app.printing.settings);
|
||||
let paper = app.print_paper.selected(queue).cloned();
|
||||
if let Some(paper) = &paper {
|
||||
paper.apply(&mut params);
|
||||
}
|
||||
let key = (uid, revision, bs.print_scope, selection, bs.fit_to_page, paper);
|
||||
let key = (uid, revision, bs.print_scope, selection, bs.fit_to_page);
|
||||
if bs.preview.as_ref().is_none_or(|(k, _)| *k != key) {
|
||||
if bs.preview.as_ref().is_some_and(|(previous, _)| previous.5 != key.5) {
|
||||
bs.preview_page = 0;
|
||||
}
|
||||
let preview = app.session.run("file.printPreview", params.clone()).unwrap_or(Json::Null);
|
||||
bs.preview = Some((key, preview));
|
||||
}
|
||||
@@ -43,11 +35,6 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
|
||||
if let Some(discover) = &app.services.printers {
|
||||
crate::printing::show(&mut app.printing, ui, discover, |label| lang.tr(label).to_owned());
|
||||
}
|
||||
if let Some(discover) = &app.services.printer_papers {
|
||||
let queue = crate::printing::printer_name(&app.printing.settings);
|
||||
app.print_paper.poll(queue, discover, ui.ctx());
|
||||
app.print_paper.show(ui, queue, lang, !app.printing.busy());
|
||||
}
|
||||
let can_print = app.services.print_native.is_none() || app.printing.ready();
|
||||
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)
|
||||
|
||||
@@ -294,7 +294,7 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
|
||||
(
|
||||
"ui.printSettings",
|
||||
"Print Settings",
|
||||
"{printer?: discovered name, paper?: discovered paper id|null for workbook paper, copies?: 1..999, duplex?: printerDefault|off|longEdge|shortEdge|null, grayscale?: bool, refresh?: bool} → {printer,paper,papers,papersLoading,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, refresh?: bool} → {printer,copies,duplex,grayscale,printers,ready,busy,discovering,status,detail}; {} inspects without submitting",
|
||||
),
|
||||
(
|
||||
"ui.printSubmit",
|
||||
|
||||
@@ -261,7 +261,6 @@ pub struct SheetApp {
|
||||
pub notice: Option<Notice>,
|
||||
pub services: Services,
|
||||
pub printing: printing::State,
|
||||
print_paper: printing::PaperSelection,
|
||||
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>>,
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
//! The print page's printer controls (craft-print's `PrintPanel` over its `State`) and their
|
||||
//! localized feedback. The panel's own words come from the framework host.
|
||||
pub use craft_print::ui::{Destination, Discover, Duplex, Feedback, Printer, Settings, State};
|
||||
|
||||
mod paper;
|
||||
pub(crate) use paper::PaperSelection;
|
||||
pub use paper::{DiscoverPapers, Paper};
|
||||
|
||||
pub type Submit = Box<dyn Fn(Vec<u8>, Settings, Option<Paper>) -> std::sync::mpsc::Receiver<Result<String, String>>>;
|
||||
pub use craft_print::ui::{Destination, Discover, Duplex, Feedback, Printer, Settings, State, Submit};
|
||||
|
||||
/// Draws the shared print controls and the feedback of the last discovery or job.
|
||||
///
|
||||
@@ -21,7 +15,7 @@ pub fn show(state: &mut State, ui: &mut egui::Ui, discover: &Discover, translate
|
||||
}
|
||||
|
||||
/// The printer queue the settings name; empty for none.
|
||||
pub(crate) fn printer_name(settings: &Settings) -> &str {
|
||||
fn printer_name(settings: &Settings) -> &str {
|
||||
match &settings.destination {
|
||||
Destination::Printer(name) => name,
|
||||
_ => "",
|
||||
@@ -30,17 +24,11 @@ pub(crate) fn printer_name(settings: &Settings) -> &str {
|
||||
|
||||
/// 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(crate) fn settings(
|
||||
state: &mut State,
|
||||
paper: &mut PaperSelection,
|
||||
params: &serde_json::Value,
|
||||
discover: Option<&Discover>,
|
||||
has_catalog: bool,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
pub fn settings(state: &mut State, 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", "paper", "copies", "duplex", "grayscale", "refresh"].contains(&key.as_str())) {
|
||||
return Err("unknown print setting; use printer, paper, copies, duplex, grayscale or refresh".into());
|
||||
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 state.busy() && !object.is_empty() {
|
||||
return Err("wait for the active print submission before changing settings".into());
|
||||
@@ -70,18 +58,6 @@ pub(crate) fn settings(
|
||||
if let Some(value) = object.get("grayscale") {
|
||||
next.grayscale = value.as_bool().ok_or("grayscale must be a boolean")?;
|
||||
}
|
||||
let queue = printer_name(&next);
|
||||
let requested_paper = match object.get("paper") {
|
||||
None => None,
|
||||
Some(Value::Null) => Some(None),
|
||||
Some(value) => {
|
||||
let id = value.as_str().ok_or("paper must be an id from the selected printer or null for workbook paper")?;
|
||||
if !paper.offered(queue).iter().any(|size| size.id == id) {
|
||||
return Err("paper must be an id from the selected printer's available papers".into());
|
||||
}
|
||||
Some(Some(id.to_owned()))
|
||||
}
|
||||
};
|
||||
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")?;
|
||||
@@ -89,12 +65,7 @@ pub(crate) fn settings(
|
||||
return Err("printer discovery or submission is already active".into());
|
||||
}
|
||||
}
|
||||
paper.set_queue(queue);
|
||||
if let Some(requested) = requested_paper {
|
||||
paper.selected = requested;
|
||||
}
|
||||
state.settings = next;
|
||||
let queue = printer_name(&state.settings);
|
||||
let (status, detail) = match state.message.as_ref() {
|
||||
None => ("idle", ""),
|
||||
Some(Feedback::FindingPrinters) => ("findingPrinters", ""),
|
||||
@@ -110,9 +81,6 @@ pub(crate) fn settings(
|
||||
"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,
|
||||
"paper": paper.selected(queue).map(|size| size.id.as_str()),
|
||||
"papers": paper.offered(queue).iter().map(|size| json!({"id":size.id,"name":size.name,"width":size.width,"height":size.height})).collect::<Vec<_>>(),
|
||||
"papersLoading": has_catalog && paper.loading(queue),
|
||||
"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,117 +0,0 @@
|
||||
use std::sync::mpsc::{Receiver, TryRecvError};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A paper offered by a system printer. Dimensions are in points.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Paper {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub width: f64,
|
||||
pub height: f64,
|
||||
/// The exact CUPS choice, where the spooler takes one independently of the PDF geometry.
|
||||
pub cups_media: Option<String>,
|
||||
/// The exact form that the selected Windows driver offered.
|
||||
pub windows_form: Option<craft_print::WindowsPaperForm>,
|
||||
}
|
||||
|
||||
impl Paper {
|
||||
pub(crate) fn apply(&self, params: &mut Value) {
|
||||
if !params.is_object() {
|
||||
*params = json!({});
|
||||
}
|
||||
if let Some(fields) = params.as_object_mut() {
|
||||
fields.insert("paperOverride".into(), json!({"name":self.name,"width":self.width,"height":self.height}));
|
||||
}
|
||||
}
|
||||
|
||||
fn usable(&self) -> bool {
|
||||
!self.name.trim().is_empty() && [self.width, self.height].iter().all(|side| (36.0..=14_400.0).contains(side))
|
||||
}
|
||||
}
|
||||
|
||||
pub type DiscoverPapers = Box<dyn Fn(&str) -> Receiver<Vec<Paper>>>;
|
||||
|
||||
/// Paper choices belong to the selected queue and window, never the workbook.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct PaperSelection {
|
||||
queue: String,
|
||||
offered: Option<Vec<Paper>>,
|
||||
pub(super) selected: Option<String>,
|
||||
pending: Vec<(String, Receiver<Vec<Paper>>)>,
|
||||
}
|
||||
|
||||
impl PaperSelection {
|
||||
pub(super) fn set_queue(&mut self, queue: &str) {
|
||||
if self.queue != queue {
|
||||
self.queue = queue.into();
|
||||
self.offered = None;
|
||||
self.selected = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn poll(&mut self, queue: &str, discover: &DiscoverPapers, ctx: &egui::Context) {
|
||||
self.set_queue(queue);
|
||||
self.pending.retain(|(requested, answer)| {
|
||||
match answer.try_recv() {
|
||||
Err(TryRecvError::Empty) => return true,
|
||||
Ok(mut papers) if *requested == self.queue => {
|
||||
papers.retain(Paper::usable);
|
||||
self.offered = Some(papers);
|
||||
}
|
||||
Err(TryRecvError::Disconnected) if *requested == self.queue => self.offered = Some(Vec::new()),
|
||||
_ => {}
|
||||
}
|
||||
false
|
||||
});
|
||||
if !queue.is_empty() && self.offered.is_none() && self.pending.len() < 2 && !self.pending.iter().any(|(requested, _)| requested == queue) {
|
||||
self.pending.push((queue.into(), discover(queue)));
|
||||
}
|
||||
if !self.pending.is_empty() {
|
||||
ctx.request_repaint_after(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn offered(&self, queue: &str) -> &[Paper] {
|
||||
if self.queue == queue { self.offered.as_deref().unwrap_or_default() } else { &[] }
|
||||
}
|
||||
|
||||
pub(super) fn loading(&self, queue: &str) -> bool {
|
||||
!queue.is_empty() && (self.queue != queue || self.offered.is_none())
|
||||
}
|
||||
|
||||
pub(crate) fn selected(&self, queue: &str) -> Option<&Paper> {
|
||||
self.offered(queue).iter().find(|paper| self.selected.as_deref() == Some(paper.id.as_str()))
|
||||
}
|
||||
|
||||
pub(crate) fn show(&mut self, ui: &mut egui::Ui, queue: &str, language: crate::i18n::Language, enabled: bool) {
|
||||
use egui::accesskit::Role;
|
||||
let papers = self.offered(queue);
|
||||
let default = language.tr("Use workbook paper");
|
||||
let label = language.tr("Paper");
|
||||
let value = self.selected(queue).map_or(default, |paper| paper.name.as_str());
|
||||
let mut selected = self.selected.clone();
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(label);
|
||||
ui.add_enabled_ui(enabled && !papers.is_empty(), |ui| {
|
||||
let response = egui::ComboBox::from_id_salt("gridcraft_queue_paper")
|
||||
.width(200.0)
|
||||
.selected_text(value)
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut selected, None, default);
|
||||
for paper in papers {
|
||||
ui.selectable_value(&mut selected, Some(paper.id.clone()), &paper.name);
|
||||
}
|
||||
})
|
||||
.response;
|
||||
ui.ctx().accesskit_node_builder(response.id, |node| node.set_label(label));
|
||||
});
|
||||
});
|
||||
self.selected = selected;
|
||||
if self.loading(queue) {
|
||||
let response = ui.label(language.tr("Looking for printer paper sizes…"));
|
||||
response.ctx.accesskit_node_builder(response.id, |node| node.set_role(Role::Status));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,6 @@ type PrintPdf = Box<dyn Fn(&[u8])>;
|
||||
pub struct Services {
|
||||
/// Desktop: discover configured printers on a worker.
|
||||
pub printers: Option<printing::Discover>,
|
||||
/// Desktop: discover the selected queue's physical paper dimensions on a worker.
|
||||
pub printer_papers: Option<printing::DiscoverPapers>,
|
||||
/// Desktop: submit the PDF with the chosen settings on a worker.
|
||||
pub print_native: Option<printing::Submit>,
|
||||
pub pick_open: Option<Box<dyn Fn() -> Option<String>>>,
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
use gridcraft_engine::core::CellRef;
|
||||
|
||||
use crate::{Notice, SheetApp, backstage, dialogs, editor, grid, keytips, printing, text_box};
|
||||
use crate::{Notice, SheetApp, backstage, dialogs, editor, grid, keytips, text_box};
|
||||
|
||||
/// One window's parked interface state (see the module docs).
|
||||
#[derive(Default)]
|
||||
@@ -17,7 +17,6 @@ pub struct WindowUi {
|
||||
text_box_editor: Option<text_box::EditState>,
|
||||
dialog: Option<dialogs::Dialog>,
|
||||
backstage: Option<backstage::Backstage>,
|
||||
print_paper: printing::PaperSelection,
|
||||
message: Option<(String, String)>,
|
||||
toast: Option<(String, f64)>,
|
||||
notice: Option<Notice>,
|
||||
@@ -62,7 +61,6 @@ impl SheetApp {
|
||||
text_box_editor,
|
||||
dialog,
|
||||
backstage,
|
||||
print_paper,
|
||||
message,
|
||||
toast,
|
||||
notice,
|
||||
@@ -80,7 +78,6 @@ 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_paper, print_paper);
|
||||
std::mem::swap(&mut self.message, message);
|
||||
std::mem::swap(&mut self.toast, toast);
|
||||
std::mem::swap(&mut self.notice, notice);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Native print onboarding preserves engine PDF generation and submits the selected settings.
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_ui_egui::printing::{Destination, Duplex, Feedback, Paper, Printer};
|
||||
use gridcraft_ui_egui::printing::{Destination, Duplex, Feedback, Printer};
|
||||
use gridcraft_ui_egui::{Services, SheetApp};
|
||||
use serde_json::json;
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
@@ -14,7 +14,7 @@ fn native_print_uses_selected_settings_and_reports_spool_errors() {
|
||||
app.run("cell.set", json!({"cell":"A1", "input":"A sheet to print"})).unwrap();
|
||||
let jobs = Rc::new(RefCell::new(Vec::new()));
|
||||
let observed = jobs.clone();
|
||||
app.services.print_native = Some(Box::new(move |bytes, settings, _| {
|
||||
app.services.print_native = Some(Box::new(move |bytes, settings| {
|
||||
observed.borrow_mut().push((bytes, settings));
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
sender.send(Err("printer is offline".into())).unwrap();
|
||||
@@ -56,7 +56,7 @@ fn print_settings_are_visible_in_a_narrow_window() {
|
||||
sender.send(vec![Printer::new("Test queue").is_default(true)]).unwrap();
|
||||
receiver
|
||||
}));
|
||||
app.services.print_native = Some(Box::new(|_, _, _| {
|
||||
app.services.print_native = Some(Box::new(|_, _| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
sender.send(Ok("queued".into())).unwrap();
|
||||
receiver
|
||||
@@ -112,7 +112,7 @@ fn repeated_fast_jobs_each_surface_an_identical_receipt() {
|
||||
let mut app = SheetApp::new(session, Services::default());
|
||||
app.printing.printers.push(Printer::new("Queue").is_default(true));
|
||||
app.run("ui.printSettings", json!({"printer":"Queue"})).unwrap();
|
||||
app.services.print_native = Some(Box::new(|_, _, _| {
|
||||
app.services.print_native = Some(Box::new(|_, _| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
sender.send(Ok("same receipt".into())).unwrap();
|
||||
receiver
|
||||
@@ -129,70 +129,3 @@ fn repeated_fast_jobs_each_surface_an_identical_receipt() {
|
||||
assert!(app.toast.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queue_papers_ignore_late_answers_and_are_used_only_for_the_selected_queue() {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
let mut app = SheetApp::new(session, Services::default());
|
||||
app.run("cell.set", json!({"cell":"A1", "input":"Paper choice fixture"})).unwrap();
|
||||
app.printing.printers = vec![Printer::new("Label queue"), Printer::new("Office queue")];
|
||||
|
||||
let (label_send, label_receive) = std::sync::mpsc::channel();
|
||||
let (office_send, office_receive) = std::sync::mpsc::channel();
|
||||
let replies = RefCell::new(std::collections::HashMap::from([("Label queue", label_receive), ("Office queue", office_receive)]));
|
||||
app.services.printer_papers = Some(Box::new(move |queue| replies.borrow_mut().remove(queue).unwrap()));
|
||||
let jobs = Rc::new(RefCell::new(Vec::new()));
|
||||
let observed = jobs.clone();
|
||||
app.services.print_native = Some(Box::new(move |bytes, settings, paper| {
|
||||
observed.borrow_mut().push((bytes, settings, paper));
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
sender.send(Ok("queued".into())).unwrap();
|
||||
receiver
|
||||
}));
|
||||
|
||||
let ctx = egui::Context::default();
|
||||
app.run("ui.printSettings", json!({"printer":"Label queue"})).unwrap();
|
||||
app.poll_printing(&ctx);
|
||||
app.run("ui.printSettings", json!({"printer":"Office queue"})).unwrap();
|
||||
app.poll_printing(&ctx);
|
||||
let office =
|
||||
Paper { id: "Legal".into(), name: "Office Legal".into(), width: 612.0, height: 1008.0, cups_media: Some("Legal".into()), windows_form: None };
|
||||
let side_feed =
|
||||
Paper { id: "LegalSideFeed".into(), name: "Office Legal Side Feed".into(), cups_media: Some("LegalSideFeed".into()), ..office.clone() };
|
||||
office_send.send(vec![office.clone(), side_feed.clone()]).unwrap();
|
||||
label_send
|
||||
.send(vec![Paper { id: "Label".into(), name: "Label".into(), width: 144.0, height: 216.0, cups_media: None, windows_form: None }])
|
||||
.unwrap();
|
||||
app.poll_printing(&ctx);
|
||||
assert!(app.run("ui.printSettings", json!({"paper":"Label"})).is_err());
|
||||
let configured = app.run("ui.printSettings", json!({"paper":"Legal"})).unwrap();
|
||||
assert_eq!(configured["papers"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(configured["paper"], "Legal");
|
||||
|
||||
app.run("ui.printSubmit", json!({})).unwrap();
|
||||
app.poll_printing(&ctx);
|
||||
let configured = app.run("ui.printSettings", json!({"paper":"LegalSideFeed"})).unwrap();
|
||||
assert_eq!(configured["paper"], "LegalSideFeed");
|
||||
app.run("ui.printSubmit", json!({})).unwrap();
|
||||
app.poll_printing(&ctx);
|
||||
let preview = app.run("file.printPreview", json!({})).unwrap();
|
||||
assert_eq!(preview["pageList"][0]["height"], 792.0, "workbook Page Setup stays Letter");
|
||||
assert!(app.run("ui.printSettings", json!({"printer":"Label queue","paper":"Legal"})).is_err());
|
||||
assert_eq!(app.run("ui.printSettings", json!({})).unwrap()["printer"], "Office queue");
|
||||
let switched = app.run("ui.printSettings", json!({"printer":"Label queue"})).unwrap();
|
||||
assert_eq!(switched["paper"], serde_json::Value::Null);
|
||||
app.run("ui.printSubmit", json!({})).unwrap();
|
||||
|
||||
let jobs = jobs.borrow();
|
||||
assert_eq!(jobs.len(), 3);
|
||||
assert_eq!(jobs[0].1.destination, Destination::Printer("Office queue".into()));
|
||||
assert_eq!(jobs[0].2.as_ref(), Some(&office));
|
||||
assert!(String::from_utf8_lossy(&jobs[0].0).contains("/MediaBox [0 0 612 1008]"));
|
||||
assert_eq!(jobs[1].1.destination, Destination::Printer("Office queue".into()));
|
||||
assert_eq!(jobs[1].2.as_ref(), Some(&side_feed));
|
||||
assert!(String::from_utf8_lossy(&jobs[1].0).contains("/MediaBox [0 0 612 1008]"));
|
||||
assert_eq!(jobs[2].1.destination, Destination::Printer("Label queue".into()));
|
||||
assert!(jobs[2].2.is_none());
|
||||
assert!(String::from_utf8_lossy(&jobs[2].0).contains("/MediaBox [0 0 612 792]"));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user