Compare commits

..
Author SHA1 Message Date
dependabot[bot] 67de44a803 ci(deps): bump step-security/harden-runner
Bumps the actions group with 1 update in the / directory: [step-security/harden-runner](https://github.com/step-security/harden-runner).


Updates `step-security/harden-runner` from 2.22.4 to 2.23.0
- [Release notes](https://github.com/step-security/harden-runner/releases)
- [Commits](https://github.com/step-security/harden-runner/compare/v2.22.4...v2.23.0)

---
updated-dependencies:
- dependency-name: step-security/harden-runner
  dependency-version: 2.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-12-03 11:06:52 +00:00
FredApps 577ada30b4 Merge pull request #2585 from storytold/fix/ppt-run-scaling-test-freebsd
Tests: the many-runs import test compares two sizes instead of timing one against 20 s
2026-12-03 02:05:32 +01:00
FredApps 75c29c27db Tests: the many-runs import test compares two sizes instead of timing one against 20 s
On FreeBSD x86_64 the test took 1.8 s in total on Nov 30, 20 s on Dec 1 and 31 s on Dec 2 (limit 20 s), mostly in the kernel; the same binary took 94 s with 14 s of system time and then 2 s on a busy Linux host. A fixed wall-clock limit follows the host's load, not the code. Import 40k and 160k runs in the same process, best of three each, and require less than 10x for 4x the runs.
2026-12-02 20:06:21 +01:00
24 changed files with 72 additions and 459 deletions
-55
View File
@@ -1,55 +0,0 @@
#!/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"
+7 -7
View File
@@ -5,23 +5,23 @@ version: 'v0.0.3'
workflows:
'.github/workflows/ci.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]2.4'
- 'step-security/[email protected]3.0'
'.github/workflows/freebsd.yml': []
'.github/workflows/house-rules.yml': []
'.github/workflows/lockfile.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]2.4'
- 'step-security/[email protected]3.0'
'.github/workflows/nightly-dispatch.yml': []
'.github/workflows/nightly-macos.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]2.4'
- 'step-security/[email protected]3.0'
'.github/workflows/nightly-sign.yml': []
'.github/workflows/nightly.yml': []
'.github/workflows/nix.yml': []
'.github/workflows/notify-services.yml': []
'.github/workflows/packaging-lint.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]2.4'
- 'step-security/[email protected]3.0'
'.github/workflows/release.yml': []
'.github/workflows/sonarcloud.yml': []
'.github/workflows/windows-arm64.yml': []
@@ -31,8 +31,8 @@ dependencies:
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
owner_id: 44036562
repo_id: 197814629
'step-security/[email protected]2.4':
ref: 'v2.22.4'
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
'step-security/[email protected]3.0':
ref: 'v2.23.0'
commit: 'sha1-aebdcf6156ab6691adf63218240e476564a1ed4c'
owner_id: 88700172
repo_id: 422287306
+1 -1
View File
@@ -27,7 +27,7 @@ jobs:
CRAFT_FONTS_REF: 37827adc41fd165f9a9234ac40f94dbad353aa69
steps:
- name: Harden runner
uses: step-security/[email protected]2.4
uses: step-security/[email protected]3.0
with:
egress-policy: audit
- name: Check out craft-fonts
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Harden runner
uses: step-security/[email protected]2.4
uses: step-security/[email protected]3.0
with:
egress-policy: audit
- uses: actions/[email protected]
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
RUST_BACKTRACE: 1
steps:
- name: Harden runner
uses: step-security/[email protected]2.4
uses: step-security/[email protected]3.0
with:
egress-policy: audit
- uses: actions/[email protected]
+2 -2
View File
@@ -28,7 +28,7 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/[email protected]2.4
uses: step-security/[email protected]3.0
with:
egress-policy: audit
- uses: actions/[email protected]
@@ -58,7 +58,7 @@ jobs:
contents: read
steps:
- name: Harden runner
uses: step-security/[email protected]2.4
uses: step-security/[email protected]3.0
with:
egress-policy: audit
- uses: actions/[email protected]
@@ -1,46 +0,0 @@
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", "print"] }
craft = { workspace = true, features = ["web-api", "web-host", "platform-browser"] }
# `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,7 +90,6 @@ 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", "print"] }
craft = { workspace = true, features = ["ui-app", "window", "gpu-startup", "quit", "dialogs", "platform", "platform-clipboard-system", "automation", "settings", "font-catalog"] }
# `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,10 +268,6 @@ 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.
@@ -437,7 +433,6 @@ 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();
+39 -15
View File
@@ -376,18 +376,15 @@ Then wave"
);
}
/// Text with very many formatting runs is laid into runs in about linear time. Each lookup used to
/// scan the run starts from the beginning, so the cost grew with runs²: in a debug build these 640k
/// one-character runs (about 6 MB of file) took 75 s that way, and take about 2 s with binary search.
#[test]
fn many_character_runs_are_not_quadratic() {
const N: usize = 640_000;
let text: String = (0..N).map(|i| if i % 2 == 0 { 'a' } else { '\u{0B}' }).collect();
/// A text box holding `n` one-character formatting runs (a character and a line break, alternating),
/// as a legacy .ppt file.
fn file_with_character_runs(n: usize) -> Vec<u8> {
let text: String = (0..n).map(|i| if i % 2 == 0 { 'a' } else { '\u{0B}' }).collect();
let mut style = vec![];
style.extend_from_slice(&(N as u32 + 1).to_le_bytes());
style.extend_from_slice(&(n as u32 + 1).to_le_bytes());
style.extend_from_slice(&0u16.to_le_bytes());
style.extend_from_slice(&0u32.to_le_bytes()); // a paragraph exception with no fields
for _ in 0..=N {
for _ in 0..=n {
style.extend_from_slice(&1u32.to_le_bytes());
style.extend_from_slice(&0u32.to_le_bytes()); // a character exception with no fields
}
@@ -398,12 +395,39 @@ fn many_character_runs_are_not_quadratic() {
);
let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[shape])]);
let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, None);
let bytes = crate::cfb::build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]);
let t = std::time::Instant::now();
let p = crate::import(&bytes).unwrap();
assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed());
let runs = &p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs;
assert_eq!(runs.iter().filter(|r| r.kind == RunKind::Break).count(), N / 2);
crate::cfb::build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])
}
/// Text with very many formatting runs is laid into runs in about linear time. Each lookup used to
/// scan the run starts from the beginning, so the cost grew with runs²: 640k one-character runs
/// (about 6 MB of file) took 75 s that way in a debug build, and about 2 s with binary search.
///
/// The test compares two sizes in the same process instead of timing one against a fixed limit, so
/// a slow or busy host (the FreeBSD CI VM took 20 to 31 s for the 640k file, mostly in the kernel,
/// where a quiet one takes 2 s) slows both alike. Four times the runs take about four times as long
/// when the work is linear and sixteen times as long when it is quadratic. Each size is the best of
/// three imports, so a stall in one of them doesn't decide the result.
#[test]
fn many_character_runs_are_not_quadratic() {
const SMALL: usize = 40_000;
const LARGE: usize = 4 * SMALL;
let best_of_three = |n: usize| {
let bytes = file_with_character_runs(n);
let mut best = std::time::Duration::MAX;
let mut breaks = 0;
for _ in 0..3 {
let t = std::time::Instant::now();
let p = crate::import(&bytes).unwrap();
best = best.min(t.elapsed());
let runs = &p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs;
breaks = runs.iter().filter(|r| r.kind == RunKind::Break).count();
}
(best, breaks)
};
let (small, small_breaks) = best_of_three(SMALL);
let (large, large_breaks) = best_of_three(LARGE);
assert_eq!((small_breaks, large_breaks), (SMALL / 2, LARGE / 2));
assert!(large < small * 10, "{LARGE} runs took {large:?}, {SMALL} runs took {small:?}: more than 10x for 4x the runs");
}
/// A slide naming a master that doesn't exist falls back to the first main master, every time. The
+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", "print"] }
craft = { workspace = true, features = ["update"] }
craft-update = { workspace = true }
[dev-dependencies]
-33
View File
@@ -195,10 +195,6 @@ 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,
@@ -224,12 +220,6 @@ 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();
@@ -258,32 +248,11 @@ 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));
@@ -406,8 +375,6 @@ 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} (no options opens desktop print settings when a system spooler is installed)",
params: "{layout?, perPage?, slides?, includeHidden?, frame?, paper?: letter|a4|legal|a3, orientation?: portrait|landscape}",
},
UiCommand { id: "app.about", label: "About DeckCraft", params: "{}" },
UiCommand { id: "app.checkUpdates", label: "Check for Updates…", params: "{}" },
-5
View File
@@ -275,11 +275,6 @@ 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()),
+6 -23
View File
@@ -257,24 +257,14 @@ impl SlideApp {
self.submit_save(uid, None, files, &suggested, false, instance)
}
/// 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.
/// 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.
pub fn print_pdf(&mut self, params: Value) -> bool {
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;
}
}
if self.session.active().is_none() {
return false;
}
let params = if params.is_object() { params } else { json!({}) };
#[cfg(not(target_arch = "wasm32"))]
if !self.host.files().browser_saves() {
return self.print_preview(params);
@@ -282,13 +272,6 @@ 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,9 +206,6 @@ 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).
@@ -240,8 +237,6 @@ 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,
+9 -115
View File
@@ -21,8 +21,6 @@ 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).
@@ -96,33 +94,15 @@ 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());
#[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));
}
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));
}
Text::new("Settings").role(TypeRole::Heading).show(ui);
FieldGroup::new("Settings").show(ui, |ui, _| {
@@ -408,89 +388,3 @@ 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,114 +618,6 @@ 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,26 +122,6 @@ 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,11 +222,6 @@ 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,
+1 -6
View File
@@ -1,11 +1,6 @@
/// Hands a prepared PDF to the browser's print dialog.
pub type BrowserPrint = Box<dyn FnMut(&[u8]) -> Result<(), String>>;
/// Browser-owned services.
/// The browser-owned connection to the presenter window.
#[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()))), ..Default::default() };
let services = Services { presenter: Some(Box::new(Mock(bridge.clone()))) };
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);