mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-03 02:57:01 -06:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f7d293566 | ||
|
|
a60cbc0ec2 | ||
|
|
2629818ee5 |
@@ -231,6 +231,7 @@ 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, Duplex, Printer, Settings, Submit};
|
||||
use gridcraft_ui_egui::printing::{Destination, Discover, DiscoverPapers, Duplex, Paper, 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,6 +13,56 @@ 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());
|
||||
@@ -27,9 +77,11 @@ pub fn finish_pending_jobs() {
|
||||
}
|
||||
|
||||
pub fn submit() -> Submit {
|
||||
Box::new(|bytes, settings: Settings| {
|
||||
Box::new(|bytes, settings: Settings, paper| {
|
||||
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),
|
||||
@@ -44,11 +96,16 @@ pub fn submit() -> Submit {
|
||||
_ => None,
|
||||
}),
|
||||
grayscale: settings.grayscale,
|
||||
scaling: craft_print::Scaling::ShrinkToFit,
|
||||
scaling: if explicit_paper { craft_print::Scaling::Exact } else { craft_print::Scaling::ShrinkToFit },
|
||||
options: cups_media.into_iter().map(|key| ("media".into(), key)).collect(),
|
||||
title: "GridCraft document".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let _ = sender.send(craft_print::submit(&bytes, &job).map_err(|error| error.to_string()));
|
||||
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()));
|
||||
});
|
||||
if let Ok(worker) = worker {
|
||||
let mut jobs = JOBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
|
||||
@@ -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::{PrintOptions, SheetLayout, layout_sheet, layouts, paper_size, print_range};
|
||||
pub use layout::{PaperOverride, 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} → {pages, bytes, base64} — the PDF the UI hands to the system print dialog",
|
||||
"{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",
|
||||
has_doc,
|
||||
print
|
||||
),
|
||||
@@ -87,7 +87,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?, paperOverride?: {name,width,height} (points)} → {pages, pageList: [{page, sheet, range, rows, columns, scale, paper, orientation, pageOrder, width, height}]} in print order",
|
||||
has_doc,
|
||||
print_preview
|
||||
),
|
||||
|
||||
@@ -75,6 +75,15 @@ 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 {
|
||||
@@ -90,7 +99,18 @@ 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 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 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,8 +269,13 @@ 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 st = sh.print.clone();
|
||||
let (mut pw, mut ph) = paper_size(&st.paper);
|
||||
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)
|
||||
};
|
||||
if st.orientation == Orientation::Landscape {
|
||||
std::mem::swap(&mut pw, &mut ph);
|
||||
}
|
||||
|
||||
@@ -1011,6 +1011,26 @@ 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() {
|
||||
|
||||
@@ -42,6 +42,7 @@ impl SheetApp {
|
||||
notice: None,
|
||||
services,
|
||||
printing: Default::default(),
|
||||
print_paper: Default::default(),
|
||||
print_feedback_seen: None,
|
||||
synthetic: Default::default(),
|
||||
ctrl_wheel: false,
|
||||
@@ -579,7 +580,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,7 +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.printSettings" => printing::settings(
|
||||
&mut self.printing,
|
||||
&mut self.print_paper,
|
||||
p,
|
||||
self.services.printers.as_ref(),
|
||||
self.services.printer_papers.is_some(),
|
||||
),
|
||||
"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,16 +46,28 @@ impl SheetApp {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn submit_print(&mut self, params: Json) -> Result<Json, String> {
|
||||
pub(super) fn submit_print(&mut self, mut 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())).map_err(|_| "A print job is already being submitted.".to_owned())?;
|
||||
self.printing
|
||||
.begin(submit(bytes, self.printing.settings.clone(), paper))
|
||||
.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);
|
||||
@@ -70,6 +82,9 @@ 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);
|
||||
type PreviewKey = (u64, u64, PrintScope, String, bool, Option<crate::printing::Paper>);
|
||||
|
||||
/// 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 (document, revision, scope, the selection when it is the scope, fit to page).
|
||||
/// Print: the preview for the workbook, job selection and paper.
|
||||
preview: Option<(PreviewKey, Json)>,
|
||||
/// Save As: the chosen file type (an extension from [`SAVE_TYPES`]).
|
||||
pub save_format: &'static str,
|
||||
|
||||
@@ -23,8 +23,16 @@ 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);
|
||||
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);
|
||||
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));
|
||||
}
|
||||
@@ -35,6 +43,11 @@ 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, 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, 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",
|
||||
),
|
||||
(
|
||||
"ui.printSubmit",
|
||||
|
||||
@@ -261,6 +261,7 @@ 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,6 +1,12 @@
|
||||
//! The print page's printer controls (craft-print's `PrintPanel` over its `State`) and their
|
||||
//! localized feedback. The panel's own words come from the framework host.
|
||||
pub use craft_print::ui::{Destination, Discover, Duplex, Feedback, Printer, Settings, State, Submit};
|
||||
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>>>;
|
||||
|
||||
/// Draws the shared print controls and the feedback of the last discovery or job.
|
||||
///
|
||||
@@ -15,7 +21,7 @@ pub fn show(state: &mut State, ui: &mut egui::Ui, discover: &Discover, translate
|
||||
}
|
||||
|
||||
/// The printer queue the settings name; empty for none.
|
||||
fn printer_name(settings: &Settings) -> &str {
|
||||
pub(crate) fn printer_name(settings: &Settings) -> &str {
|
||||
match &settings.destination {
|
||||
Destination::Printer(name) => name,
|
||||
_ => "",
|
||||
@@ -24,11 +30,17 @@ 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 fn settings(state: &mut State, params: &serde_json::Value, discover: Option<&Discover>) -> Result<serde_json::Value, String> {
|
||||
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> {
|
||||
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", "paper", "copies", "duplex", "grayscale", "refresh"].contains(&key.as_str())) {
|
||||
return Err("unknown print setting; use printer, paper, copies, duplex, grayscale or refresh".into());
|
||||
}
|
||||
if state.busy() && !object.is_empty() {
|
||||
return Err("wait for the active print submission before changing settings".into());
|
||||
@@ -58,6 +70,18 @@ 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 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")?;
|
||||
@@ -65,7 +89,12 @@ pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<
|
||||
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", ""),
|
||||
@@ -81,6 +110,9 @@ pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<
|
||||
"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,
|
||||
}))
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
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,6 +11,8 @@ 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, 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,7 @@ 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>,
|
||||
@@ -61,6 +62,7 @@ impl SheetApp {
|
||||
text_box_editor,
|
||||
dialog,
|
||||
backstage,
|
||||
print_paper,
|
||||
message,
|
||||
toast,
|
||||
notice,
|
||||
@@ -78,6 +80,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_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, Printer};
|
||||
use gridcraft_ui_egui::printing::{Destination, Duplex, Feedback, Paper, 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,3 +129,70 @@ 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