Compare commits

..
Author SHA1 Message Date
FredApps 609105b401 Verify DeckCraft print through a private CUPS queue 2026-12-03 00:08:25 +01:00
FredApps f17e0582dc Keep DeckCraft print job feedback after leaving the printer settings 2026-12-03 00:03:06 +01:00
FredApps 16cb262983 Install desktop printing through an explicit host capability
Keep PDF viewer fallback for other hosts even when they can pick files, and exercise an unsuccessful printer job with the test spool.
2026-12-02 20:47:24 +01:00
FredApps cf091013e6 Use shared desktop print jobs and the Windows helper
Keep DeckCraft job options and viewer fallback. Discover queues on host jobs, report lost results as uncertain, and shut down the spool on exit.
2026-12-02 20:43:04 +01:00
Dejan Kocić c29124a389 Web: use the shared browser print dialog
Adapt the browser intent from DeckCraft #66 to the existing Print page and its PDF composition. Retain the explicit PDF export and stage adoption until craft-libs includes the browser lifecycle update.

(cherry picked from commit 68ad9af8e3)
2026-12-02 20:38:49 +01:00
Larry e4c99e2d6f Print: list queues without the driver query; report the printer the job went to
Review: printer_queues() avoids a PrintCapabilities wait on Windows when the
Print page opens, and the status names the printer captured at submission,
not the current selection.

(cherry picked from commit b81c420308)
2026-12-02 20:34:37 +01:00
Larry c33deedb94 Print: send to a printer directly on the desktop
File › Print now has a printer list and copies, and the Print button sends the
job straight to the chosen printer through craft-print, as PowerPoint does,
instead of opening a PDF in the system viewer. On macOS craft-print goes
through the system print path (storytold/craft-libs#4624), so sign-in queues
such as PaperCut use the keychain. "Open as PDF instead" keeps the old route;
the web build is unchanged.

(cherry picked from commit 6ad54311b3)
2026-12-02 20:34:35 +01:00
18 changed files with 432 additions and 21 deletions
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
set -euo pipefail
# Reuse the shared scheduler setup through validation of its private file queue.
shared=shared-print/crates/print/examples/print_acceptance/cups_capture.sh
anchor='timeout 20s "$harness" list | tee "$results/discovery.log"'
grep -Fxq "$anchor" "$shared"
awk -v anchor="$anchor" '$0 == anchor { exit } { print }' "$shared" >"$RUNNER_TEMP/deckcraft-cups-setup.sh"
source "$RUNNER_TEMP/deckcraft-cups-setup.sh" "$1" "$PWD/deckcraft-print-output"
timeout 20s lpadmin -h "$CUPS_SERVER" -d "$queue"
test -z "$(timeout 10s lpstat -W all -o "$queue")"
sudo -n test ! -e "$capture"
sudo -n install -m 0600 /dev/null "$capture"
DECKCRAFT_PRIVATE_CUPS=1 timeout 90s "$harness" --test-threads=1 --nocapture print 2>&1 | tee "$results/ui-tests.log"
for test in \
print_from_quick_access_opens_settings_and_job_feedback_survives_leaving \
print_previews_pages_and_prints_a_pdf \
direct_print_reports_the_spooler_failure_and_keeps_the_viewer \
direct_print_to_private_cups_from_quick_access; do
grep -Eq "^test .*::${test} \\.\\.\\. (ok|DECKCRAFT_RECEIPT=)" "$results/ui-tests.log"
done
mapfile -t receipts < <(sed -nE 's/^.*DECKCRAFT_RECEIPT=(craft-print-capture-[0-9]+)$/\1/p' "$results/ui-tests.log")
[[ ${#receipts[@]} == 1 ]]
job_id=${receipts[0]}
for elapsed in {1..60}; do
timeout 10s lpstat -W completed -o "$queue" >"$results/completed-jobs.log"
if awk -v id="$job_id" '$1 == id { seen=1 } END { exit !seen }' "$results/completed-jobs.log" && sudo -n test -s "$capture"; then
sudo -n cat -- "$capture" >"$results/captured.pdf"
break
fi
sleep 1
done
timeout 10s lpstat -W all -o "$queue" >"$results/all-jobs.log"
[[ $(awk '{print $1}' "$results/all-jobs.log") == "$job_id" ]]
pdfinfo "$results/captured.pdf" >"$results/captured.pdfinfo"
grep -Eq '^Pages: +2$' "$results/captured.pdfinfo"
pdftoppm -r 36 "$results/captured.pdf" "$results/page"
python3 - "$results" <<'PY' | tee "$results/page-order.log"
import pathlib
import sys
root = pathlib.Path(sys.argv[1])
for n, expected in enumerate(((224, 32, 32), (32, 64, 224)), 1):
magic, width, height, maximum, pixels = (root / f"page-{n}.ppm").read_bytes().split(maxsplit=4)
w, h = int(width), int(height)
assert magic == b"P6" and maximum == b"255" and len(pixels) == 3*w*h
offset = 3 * ((h//2) * w + w//2)
actual = tuple(pixels[offset:offset+3])
assert all(abs(a-e) <= 25 for a, e in zip(actual, expected)), (n, actual, expected)
print(f"Page {n}: center RGB {actual}, expected {expected}")
PY
(cd "$results" && sha256sum captured.pdf) | tee "$results/sha256.txt"
@@ -0,0 +1,46 @@
name: DeckCraft Linux print queue output
on:
push:
branches: [verify/deckcraft-print-queue-output-4859]
permissions:
contents: read
jobs:
print:
runs-on: ubuntu-24.04
timeout-minutes: 60
env:
CARGO_PROFILE_DEV_DEBUG: '0'
CARGO_PROFILE_TEST_DEBUG: '0'
CARGO_INCREMENTAL: '0'
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
repository: storytold/craft-libs
ref: fa63a22393bb03f40e33accbffa67c51465ee327
path: shared-print
persist-credentials: false
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
- uses: storytold/craft-common-actions/actions/install-apt-packages@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
packages: >-
libasound2-dev libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev
libgl1-mesa-dev cups-daemon cups-client cups-filters poppler-utils
- name: Build the native UI tests
run: |
set -euo pipefail
cargo test --locked -p deckcraft-ui-egui --lib --no-run --message-format json > "$RUNNER_TEMP/deckcraft-build.jsonl"
binary=$(jq -er 'select(.reason == "compiler-artifact" and .profile.test and .target.name == "deckcraft_ui_egui" and .executable) | .executable' "$RUNNER_TEMP/deckcraft-build.jsonl")
echo "DECKCRAFT_TEST_BINARY=$binary" >> "$GITHUB_ENV"
- name: Exercise Print and check the captured pages
run: bash .github/qa/measure-print-queue-output.sh "$DECKCRAFT_TEST_BINARY"
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
if: always()
with:
name: deckcraft-print-output
path: deckcraft-print-output/
if-no-files-found: warn
+1 -1
View File
@@ -22,7 +22,7 @@ log = { workspace = true }
serde_json = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
craft = { workspace = true, features = ["web-api", "web-host", "platform-browser"] }
craft = { workspace = true, features = ["web-api", "web-host", "platform-browser", "print"] }
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
wasm-bindgen = "0.2"
+1
View File
@@ -90,6 +90,7 @@ pub fn start() {
}
let mut app = SlideApp::new(&cc.egui_ctx, platform).map_err(|error| std::io::Error::other(error.to_string()))?;
app.services.presenter = crate::presenter::opener(&cc.egui_ctx);
app.services.browser_print = Some(Box::new(craft::print::browser::print_pdf));
// In host mode the parent sends the presentation to edit; no sample meanwhile.
if app_bridge.is_some() {
if let Err(e) = app.start_for_host() {
+1 -1
View File
@@ -15,7 +15,7 @@ craft-nightly = { workspace = true }
deckcraft-engine = { workspace = true }
deckcraft-ui-egui = { workspace = true }
deckcraft-media = { workspace = true }
craft = { workspace = true, features = ["ui-app", "window", "gpu-startup", "quit", "dialogs", "platform", "platform-clipboard-system", "automation", "settings", "font-catalog"] }
craft = { workspace = true, features = ["ui-app", "window", "gpu-startup", "quit", "dialogs", "platform", "platform-clipboard-system", "automation", "settings", "font-catalog", "print"] }
# `clipboard` is the OS clipboard (Ctrl+C/X/V with other apps). Without it egui simulates one inside
# the app; the egui 0.37 migration (#1350) dropped it from this list.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "links", "wayland", "x11"] }
+5
View File
@@ -268,6 +268,10 @@ fn report_launch_profile_error(error: &str) {
pub(crate) const LOG_DIR: &str = "logs";
fn main() -> eframe::Result {
#[cfg(windows)]
if let Some(code) = craft::print::spool::isolated::helper_main() {
std::process::exit(code);
}
let Some(arguments) = prepare_launch() else { return Ok(()) };
let nightly = launch_profile::current().is_nightly();
// Nightly session health: the record names this window's owner and survives an abnormal end.
@@ -433,6 +437,7 @@ fn main() -> eframe::Result {
}
}
let mut app = SlideApp::new(ctx, platform)?;
app.enable_direct_print();
if !nightly {
// Nightly is managed by ArtCraft Launcher: no self-update prompt or stable feed.
app.enable_update_checks();
+1 -1
View File
@@ -28,7 +28,7 @@ log = { workspace = true }
web-time = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft = { workspace = true, features = ["update"] }
craft = { workspace = true, features = ["update", "print"] }
craft-update = { workspace = true }
[dev-dependencies]
+33
View File
@@ -195,6 +195,10 @@ impl SlideApp {
#[cfg(not(target_arch = "wasm32"))]
print_previews: Default::default(),
#[cfg(not(target_arch = "wasm32"))]
print_spool: None,
#[cfg(not(target_arch = "wasm32"))]
print_receipt: None,
#[cfg(not(target_arch = "wasm32"))]
updates_rt: Default::default(),
selpane: Default::default(),
align_to: None,
@@ -220,6 +224,12 @@ impl SlideApp {
self.print_previews.cleanup();
}
/// Installs the system print spool for the native desktop shell.
#[cfg(not(target_arch = "wasm32"))]
pub fn enable_direct_print(&mut self) {
self.print_spool = Some(craft::print::spool::Spool::new(self.host.jobs_shared().clone()));
}
/// Holds the close request until dirty presentations have passed the closing guard.
pub fn close_decision(&mut self) -> embed::CloseDecision {
let dirty: Vec<_> = self.session.documents().iter().filter(|doc| doc.is_dirty()).map(|doc| doc.uid).collect();
@@ -248,11 +258,32 @@ impl SlideApp {
}
#[cfg(not(target_arch = "wasm32"))]
{
if let Some(spool) = self.print_spool.take() {
spool.shutdown();
}
self.start_pending_update();
self.cleanup_print_previews();
}
}
#[cfg(not(target_arch = "wasm32"))]
fn poll_print_receipt(&mut self, ctx: &egui::Context) {
use std::sync::mpsc::TryRecvError;
let Some((printer, receipt)) = &self.print_receipt else { return };
let status = match receipt.try_recv() {
Ok(Ok(message)) => format!("Sent to {printer}: {message}"),
Ok(Err(error)) => format!("Couldn't print: {error}"),
Err(TryRecvError::Disconnected) => "Couldn't confirm whether the print job reached the printer".into(),
Err(TryRecvError::Empty) => {
ctx.request_repaint_after(std::time::Duration::from_millis(200));
return;
}
};
self.print_receipt = None;
self.set_status(status);
}
/// Displays a transient message in the status bar.
pub fn set_status(&mut self, msg: impl Into<String>) {
self.status = Some((msg.into(), self.clock.now() * 1000.0));
@@ -375,6 +406,8 @@ impl SlideApp {
if !Self::root_viewport_admitted(ctx) {
return;
}
#[cfg(not(target_arch = "wasm32"))]
self.poll_print_receipt(ctx);
self.tick_hidden_show(ctx, web_time::Instant::now());
if WindowHost::of(ctx).injected_idle() {
self.drain_intake(ctx);
+1 -1
View File
@@ -58,7 +58,7 @@ pub static UI_COMMANDS: &[UiCommand] = &[
UiCommand {
id: "app.print",
label: "Print",
params: "{layout?, perPage?, slides?, includeHidden?, frame?, paper?: letter|a4|legal|a3, orientation?: portrait|landscape}",
params: "{layout?, perPage?, slides?, includeHidden?, frame?, paper?: letter|a4|legal|a3, orientation?: portrait|landscape} (no options opens desktop print settings when a system spooler is installed)",
},
UiCommand { id: "app.about", label: "About DeckCraft", params: "{}" },
UiCommand { id: "app.checkUpdates", label: "Check for Updates…", params: "{}" },
+5
View File
@@ -275,6 +275,11 @@ impl SlideApp {
if self.session.active().is_none() {
return Err("nothing to print: no presentation is open".into());
}
#[cfg(not(target_arch = "wasm32"))]
if self.print_spool.is_some() && (p.is_null() || p.as_object().is_some_and(|args| args.is_empty())) {
self.open_backstage(backstage::Page::Print);
return Ok(json!({"printed": false, "page": "print"}));
}
return Ok(json!({"printed": self.print_pdf(p.clone())}));
}
"app.about" => self.open_dialog("about", p.clone()),
+23 -6
View File
@@ -257,14 +257,24 @@ impl SlideApp {
self.submit_save(uid, None, files, &suggested, false, instance)
}
/// File › Print: DeckCraft prints through a PDF. On the desktop the PDF (with the Print page's
/// layout, slides and options) is written to the temporary folder and opened in the system's
/// PDF viewer, which has the printers; on the web it downloads.
/// File › Print: use the same PDF layout, slides and options with the host's available route.
/// The browser opens its print dialog when installed. Other hosts open their viewer or export.
pub fn print_pdf(&mut self, params: Value) -> bool {
if self.session.active().is_none() {
return false;
}
let Some(active) = self.session.active() else { return false };
let params = if params.is_object() { params } else { json!({}) };
if let Some(print) = self.services.browser_print.as_mut() {
let result = deckcraft_engine::cmd::file::pdf_bytes(&active.doc, &params).map_err(|e| e.to_string()).and_then(|bytes| print(&bytes));
match result {
Ok(()) => {
self.set_status("Opening the browser print dialog");
return true;
}
Err(error) => {
self.set_status(format!("Couldn't open the browser print dialog: {error}"));
return false;
}
}
}
#[cfg(not(target_arch = "wasm32"))]
if !self.host.files().browser_saves() {
return self.print_preview(params);
@@ -272,6 +282,13 @@ impl SlideApp {
self.export_as("pdf", params)
}
/// The Print page's "Open as PDF instead": the print PDF in the system's PDF viewer.
#[cfg(not(target_arch = "wasm32"))]
pub fn print_pdf_viewer(&mut self, params: Value) -> bool {
let params = if params.is_object() { params } else { json!({}) };
self.print_preview(params)
}
/// Writes the print PDF to a private temporary file and opens it in the system's PDF viewer.
#[cfg(not(target_arch = "wasm32"))]
fn print_preview(&mut self, mut params: Value) -> bool {
+5
View File
@@ -206,6 +206,9 @@ pub struct Backstage {
pub print_landscape: bool,
/// Zero-based page displayed by the print preview.
pub preview_page: usize,
/// Desktop: printing straight to a printer from the Print page.
#[cfg(not(target_arch = "wasm32"))]
pub direct_print: print::DirectPrint,
/// The selected export task.
pub export: ExportTask,
/// Export › Change File Type / Save As: the chosen type (an [`SAVE_TYPES`] id).
@@ -237,6 +240,8 @@ impl Backstage {
print_paper: "letter",
print_landscape: false,
preview_page: 0,
#[cfg(not(target_arch = "wasm32"))]
direct_print: print::DirectPrint::default(),
export: ExportTask::Pdf,
file_type: "pptx",
handouts_per_page: 3,
+115 -9
View File
@@ -21,6 +21,8 @@ use craft::ui::primitives::{ContentPainterCx, DocRun, DocText, PaintShape};
use craft::ui::style::{Corners, DataColor, SurfaceKind, TypeRole};
use craft::ui::text::TextField;
use egui::{Color32, Rect, Shape, Stroke, StrokeKind, pos2, vec2};
#[cfg(not(target_arch = "wasm32"))]
use std::rc::Rc;
use std::sync::Arc;
/// The slides the Print page prints, in order (0-based).
@@ -94,15 +96,33 @@ pub(super) fn print(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs: &
let mut range_changed = false;
Stack::new().wrap_width(WrapWidth::Column).show(ui, |ui, _| {
let good_range = slides.as_ref().is_ok_and(|slides| !slides.is_empty());
let detail = if app.host.files().can_pick() {
"DeckCraft prints through a PDF: it opens in your PDF viewer, where you choose the printer."
} else {
"DeckCraft prints through a PDF: it downloads, ready to print from your browser or PDF viewer."
};
if task_row(ui, Icon::Print, "Print", "Print", detail, good_range)
&& let Ok(slides) = &slides
{
app.print_pdf(print_params(bs, slides));
#[cfg(not(target_arch = "wasm32"))]
let direct = app.print_spool.is_some();
#[cfg(target_arch = "wasm32")]
let direct = false;
#[cfg(not(target_arch = "wasm32"))]
if direct {
direct_print(app, ui, bs, &doc, slides.as_ref().ok().filter(|slides| !slides.is_empty()));
}
if !direct {
let browser = app.services.browser_print.is_some();
let detail = if browser {
"Opens the browser print dialog for the selected slides."
} else {
"DeckCraft prints through a PDF, ready to open in your browser or PDF viewer."
};
if task_row(ui, Icon::Print, "Print", "Print", detail, good_range)
&& let Ok(slides) = &slides
{
app.print_pdf(print_params(bs, slides));
}
if browser
&& let Ok(slides) = &slides
&& !slides.is_empty()
&& Link::new("Export PDF instead").show(ui).clicked()
{
app.export_as("pdf", print_params(bs, slides));
}
}
Text::new("Settings").role(TypeRole::Heading).show(ui);
FieldGroup::new("Settings").show(ui, |ui, _| {
@@ -388,3 +408,89 @@ pub(super) fn export(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs:
});
});
}
/// Printing straight to a printer: the spooler's printers, the chosen one, copies, and the job
/// being sent on a worker thread.
#[cfg(not(target_arch = "wasm32"))]
type PrinterDiscovery = Rc<std::sync::mpsc::Receiver<Vec<craft::print::Printer>>>;
#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Debug)]
pub struct DirectPrint {
printers: Option<Vec<craft::print::Printer>>,
discovery: Option<PrinterDiscovery>,
printer: String,
copies: String,
}
#[cfg(not(target_arch = "wasm32"))]
impl Default for DirectPrint {
fn default() -> Self {
DirectPrint { printers: None, discovery: None, printer: String::new(), copies: "1".into() }
}
}
/// Desktop Print sends the prepared PDF to the shared spooler. "Open as PDF instead" keeps the
/// PDF viewer route, including queues whose sign-in requires the system viewer.
#[cfg(not(target_arch = "wasm32"))]
fn direct_print(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage, doc: &deckcraft_model::Presentation, slides: Option<&Vec<usize>>) {
let Some(spool) = app.print_spool.clone() else { return };
let dp = &mut bs.direct_print;
if dp.printers.is_none() {
let discovery = dp.discovery.get_or_insert_with(|| Rc::new(spool.discover()));
match discovery.try_recv() {
Ok(printers) => {
dp.printer = printers.iter().find(|p| p.default).or(printers.first()).map(|p| p.name.clone()).unwrap_or_default();
dp.printers = Some(printers);
dp.discovery = None;
}
Err(std::sync::mpsc::TryRecvError::Empty) => ui.ctx().request_repaint_after(std::time::Duration::from_millis(200)),
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
dp.printers = Some(Vec::new());
dp.discovery = None;
app.set_status("Couldn't find printers");
}
}
}
let copies = dp.copies.trim().parse::<u32>().ok().filter(|c| (1..=999).contains(c));
let sending = app.print_receipt.is_some();
let ready = slides.is_some() && !sending && !dp.printer.is_empty() && copies.is_some();
let detail = if sending { "Sending the job to the printer…" } else { "Sends the slides straight to the printer chosen below." };
if task_row(ui, Icon::Print, "Print", "Print", detail, ready)
&& let (Some(slides), Some(copies)) = (slides, copies)
{
match deckcraft_engine::cmd::file::pdf_bytes(doc, &print_params(bs, slides)) {
Ok(bytes) => {
let dp = &mut bs.direct_print;
let title = app.session.active().map(|d| d.title()).unwrap_or_else(|| "DeckCraft".into());
let job = craft::print::Job { printer: Some(dp.printer.clone()), copies, collate: true, title, ..Default::default() };
app.print_receipt = Some((dp.printer.clone(), spool.submit(bytes, job)));
ui.ctx().request_repaint();
app.set_status(format!("Sending to {}…", dp.printer));
}
Err(e) => app.set_status(format!("Couldn't make the pages to print: {e}")),
}
}
let dp = &mut bs.direct_print;
let names: Vec<String> = dp.printers.iter().flatten().map(|p| p.name.clone()).collect();
FieldGroup::new("Printer").show(ui, |ui, _| {
if dp.discovery.is_some() {
Text::new("Finding printers…").shade(Shade::Muted).show(ui);
} else if names.is_empty() {
Text::new("No printers found.").shade(Shade::Muted).show(ui);
} else {
let entries: Vec<_> = names.iter().map(|n| Entry::new(n.clone(), n.clone())).collect();
Field::new("Printer").show(ui, |ui, _| {
Select::new("Printer", Bind::bound(&mut dp.printer), &entries).show(ui);
});
}
Field::new("Copies").show(ui, |ui, _| {
TextField::new("Copies", Bind::bound(&mut dp.copies)).show(ui);
});
});
if Link::new("Open as PDF instead").show(ui).clicked()
&& let Some(slides) = slides
{
app.print_pdf_viewer(print_params(bs, slides));
}
}
+108
View File
@@ -618,6 +618,114 @@ fn print_previews_pages_and_prints_a_pdf() {
assert!(std::fs::read(printed).unwrap().starts_with(b"%PDF"));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn direct_print_reports_the_spooler_failure_and_keeps_the_viewer() {
use craft::print::spool::{Pending, Spool, SpoolBackend};
use craft::print::{Error, Job, Printer};
struct RejectingPrinter;
impl SpoolBackend for RejectingPrinter {
fn printers(&self) -> Option<Vec<Printer>> {
Some(vec![Printer { name: "Test printer".into(), default: true, description: String::new(), two_sided: None }])
}
fn prepare(&self, pdf: Vec<u8>, job: Job) -> Pending {
assert!(pdf.starts_with(b"%PDF"));
assert_eq!(job.printer.as_deref(), Some("Test printer"));
Pending {
cancel: Box::new(|| true),
run: Box::new(|| Err(Error::Spool("test queue refused the print job".into()))),
waits_after_cancel: false,
}
}
}
let mut h = new_app();
h.state_mut().print_spool = Some(Spool::with_backend(Arc::new(craft::host::InlineJobs), Arc::new(RejectingPrinter)));
h.key_press_modifiers(Modifiers::COMMAND, Key::P);
h.run_steps(3);
page_button(&h, "Print").click();
h.run_steps(3);
assert!(h.state().status.as_ref().is_some_and(|(message, _)| message.contains("test queue refused the print job")));
assert!(h.query_by_label("Open as PDF instead").is_some());
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn print_from_quick_access_opens_settings_and_job_feedback_survives_leaving() {
let mut h = new_app();
h.state_mut().enable_direct_print();
h.state_mut().run("app.qat", json!({"add": "app.print", "label": "Print"})).unwrap();
let index = h.state().ui.qat.iter().position(|q| q.id == "app.print").unwrap();
assert!(crate::qat::run_index(h.state_mut(), index));
assert_eq!(page(&h), Some(Page::Print));
assert!(h.state().print_receipt.is_none());
let (sender, receiver) = std::sync::mpsc::channel();
h.state_mut().print_receipt = Some(("Studio printer".into(), receiver));
h.state_mut().run("app.backstage", json!({"on": false})).unwrap();
assert_eq!(page(&h), None);
sender.send(Err("queue rejected these sheets".into())).unwrap();
h.run_steps(3);
assert!(h.state().print_receipt.is_none());
assert!(h.state().status.as_ref().is_some_and(|(message, _)| message.contains("queue rejected these sheets")));
}
#[cfg(target_os = "linux")]
#[test]
fn direct_print_to_private_cups_from_quick_access() {
use std::os::unix::fs::FileTypeExt as _;
use std::time::{Duration, Instant};
if std::env::var("DECKCRAFT_PRIVATE_CUPS").as_deref() != Ok("1") {
return;
}
let server = PathBuf::from(std::env::var_os("CUPS_SERVER").expect("private CUPS socket"));
let state_dir = server.parent().and_then(Path::parent).expect("private CUPS state directory");
assert!(server.ends_with("socket/cups.sock"));
assert!(state_dir.starts_with("/run/cups") || state_dir.starts_with("/var/spool/cups"));
assert!(state_dir.file_name().unwrap().to_string_lossy().starts_with("craft-print-acceptance."));
assert!(std::fs::metadata(server).unwrap().file_type().is_socket());
let queue = "craft-print-capture";
let mut session = Session::with_new();
session.execute("design.background", &json!({"index": 0, "color": "#e02020"})).unwrap();
session.execute("slide.new", &json!({"layout": "blank"})).unwrap();
session.execute("design.background", &json!({"index": 1, "color": "#2040e0"})).unwrap();
let mut h = harness(session, Arc::new(ScriptedFiles::new()));
h.state_mut().enable_direct_print();
h.state_mut().run("app.qat", json!({"add": "app.print", "label": "QA Quick Print"})).unwrap();
h.run_steps(3);
h.get_by_label("QA Quick Print").click();
h.run_steps(3);
assert_eq!(page(&h), Some(Page::Print));
assert!(h.state().print_receipt.is_none());
let deadline = Instant::now() + Duration::from_secs(20);
while page_button(&h, "Print").accesskit_node().is_disabled() {
assert!(Instant::now() < deadline, "Print never became ready on the private queue");
std::thread::sleep(Duration::from_millis(20));
h.step();
}
page_button(&h, "Print").click();
h.step();
h.state_mut().run("app.backstage", json!({"on": false})).unwrap();
assert_eq!(page(&h), None);
let deadline = Instant::now() + Duration::from_secs(20);
while h.state().print_receipt.is_some() {
assert!(Instant::now() < deadline, "the native Spool did not finish");
std::thread::sleep(Duration::from_millis(20));
h.step();
}
let (status, _) = h.state().status.as_ref().expect("print job feedback");
let receipt = status.strip_prefix(&format!("Sent to {queue}: request id is {queue}-")).unwrap_or_else(|| panic!("{status}"));
assert!(receipt.parse::<u32>().is_ok_and(|id| id > 0), "{status}");
println!("DECKCRAFT_RECEIPT={queue}-{receipt}");
}
#[test]
fn print_slides_follow_the_settings() {
let mut s = Session::with_new();
+20
View File
@@ -122,6 +122,26 @@ fn host_exports_and_print_are_copies() {
assert_eq!(path(app).as_deref(), Some("deck.pptx"));
}
#[test]
fn browser_print_preserves_settings_and_reports_setup_failure() {
let (mut h, got) = host_app(false);
let app = h.state_mut();
app.open_from_host(Some("deck.pptx"), &pptx(3));
let params = json!({"slides": [1], "layout": "notes", "frame": true, "paper": "a4", "orientation": "landscape"});
let expected = deckcraft_engine::cmd::file::pdf_bytes(&app.session.active().unwrap().doc, &params).unwrap();
let mut opened = false;
app.services.browser_print = Some(Box::new(move |bytes| {
assert_eq!(bytes, expected);
if std::mem::replace(&mut opened, true) { Err("print frame unavailable".into()) } else { Ok(()) }
}));
assert!(app.print_pdf(params.clone()));
assert!(!app.print_pdf(params.clone()));
assert!(calls(&got).is_empty(), "a print error must not trigger an export");
assert!(app.status.as_ref().is_some_and(|(message, _)| message.contains("print frame unavailable")));
assert!(app.export_as("pdf", params));
assert_eq!(calls(&got), [("deck.pdf".into(), false)], "the user can still explicitly export");
}
/// The page not getting the file is a failed save: the presentation keeps its changes.
#[test]
fn a_host_save_that_fails_leaves_the_presentation_unsaved() {
+5
View File
@@ -222,6 +222,11 @@ pub struct SlideApp {
#[cfg(not(target_arch = "wasm32"))]
print_previews: craft::platform::temp::TempFiles,
#[cfg(not(target_arch = "wasm32"))]
print_spool: Option<craft::print::spool::Spool>,
/// The printer and its pending receipt outlive the File > Print view.
#[cfg(not(target_arch = "wasm32"))]
print_receipt: Option<(String, std::sync::mpsc::Receiver<Result<String, String>>)>,
#[cfg(not(target_arch = "wasm32"))]
updates_rt: updates_ui::Runtime,
/// Selection pane: folded groups and the Shift-run anchor.
pub selpane: selpane::State,
+6 -1
View File
@@ -1,6 +1,11 @@
/// The browser-owned connection to the presenter window.
/// Hands a prepared PDF to the browser's print dialog.
pub type BrowserPrint = Box<dyn FnMut(&[u8]) -> Result<(), String>>;
/// Browser-owned services.
#[derive(Default)]
pub struct Services {
/// Presenter popup link; absent on native hosts.
pub presenter: Option<Box<dyn craft::web_host::link::WindowLink>>,
/// Absent on hosts that cannot open the browser print dialog.
pub browser_print: Option<BrowserPrint>,
}
+1 -1
View File
@@ -1253,7 +1253,7 @@ fn remote_presenter_uses_the_audience_state_and_closes_with_the_show() {
let mut session = deckcraft_engine::Session::with_new();
session.execute("slide.new", &json!({})).unwrap();
session.execute("slide.new", &json!({})).unwrap();
let services = Services { presenter: Some(Box::new(Mock(bridge.clone()))) };
let services = Services { presenter: Some(Box::new(Mock(bridge.clone()))), ..Default::default() };
let mut h = harness_with(session, services, egui_kittest::Harness::builder().with_size(vec2(1000.0, 700.0)), |_| {});
h.state_mut().ui.presenter_view = true;
h.run_steps(3);