Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions apps/deckcraft/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,51 @@ fn services() -> Services {
audio_out: std::env::var_os("DECKCRAFT_NO_AUDIO")
.is_none()
.then(|| Box::new(audio::CpalOut::default()) as Box<dyn deckcraft_media::AudioOut>),
printers: cfg!(unix).then(|| Box::new(printing::printers) as Box<dyn Fn() -> Vec<String>>),
print_file: cfg!(unix).then(|| Box::new(printing::print_file) as deckcraft_ui_egui::PrintFn),
..Default::default()
}
}

/// Printing through CUPS (`lpstat`, `lp`), which Linux and macOS ship. Windows has no command for
/// it, so there the PDF opens in the viewer as before.
mod printing {
use std::process::Command;

/// Printer names from `lpstat -e`; none when CUPS is missing or lists none.
pub fn printers() -> Vec<String> {
match Command::new("lpstat").arg("-e").output() {
Ok(o) if o.status.success() => parse(&String::from_utf8_lossy(&o.stdout)),
_ => vec![],
}
}

pub fn parse(out: &str) -> Vec<String> {
out.lines().map(str::trim).filter(|l| !l.is_empty() && !l.contains(char::is_whitespace)).take(200).map(str::to_string).collect()
}

pub fn print_file(path: &str, printer: &str, copies: u32) -> Result<(), String> {
if printer.starts_with('-') || printer.contains(char::is_whitespace) {
return Err("not a printer name".into());
}
let o = Command::new("lp")
.args(["-d", printer, "-n", &copies.clamp(1, 999).to_string(), "-t", "DeckCraft", "--", path])
.output()
.map_err(|e| format!("lp: {e}"))?;
if o.status.success() { Ok(()) } else { Err(String::from_utf8_lossy(&o.stderr).trim().to_string()) }
}

#[cfg(test)]
mod tests {
#[test]
fn lpstat_lines_are_printer_names() {
assert_eq!(super::parse("Office_Laser\nHP-4100\n\n"), ["Office_Laser", "HP-4100"]);
assert!(super::parse("lpstat: No destinations added.\n").is_empty());
assert!(super::print_file("/tmp/x.pdf", "-o evil", 1).is_err());
}
}
}

const APP_ID: &str = "ai.storyteller.deckcraft";

const USAGE: &str = "\
Expand Down
49 changes: 47 additions & 2 deletions crates/ui-egui/src/backstage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,11 @@ pub struct Backstage {
/// Notes and handouts: a paper id from [`deckcraft_engine::cmd::file::PAPERS`] and its orientation.
pub print_paper: &'static str,
pub print_landscape: bool,
/// File › Print printer: empty for the PDF viewer (which has its own printer list).
pub print_printer: String,
pub print_copies: u32,
/// The system's printers, listed once per visit of the Print page.
pub printers: Option<Vec<String>>,
pub preview_page: usize,
pub export: ExportTask,
/// Export › Change File Type / Save As: the chosen type (an [`SAVE_TYPES`] id).
Expand All @@ -192,6 +197,9 @@ impl Backstage {
print_frame: true,
print_paper: "letter",
print_landscape: false,
print_printer: String::new(),
print_copies: 1,
printers: None,
preview_page: 0,
export: ExportTask::Pdf,
file_type: "pptx",
Expand Down Expand Up @@ -1031,15 +1039,52 @@ fn print(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage) {
ui.vertical(|ui| {
ui.set_width(250.0);
let ok = slides.as_ref().is_ok_and(|s| !s.is_empty());
if bs.printers.is_none() {
bs.printers = Some(app.services.printers.as_ref().map(|f| f()).unwrap_or_default());
}
let printers = bs.printers.clone().unwrap_or_default();
if !printers.contains(&bs.print_printer) {
bs.print_printer.clear();
}
let direct = !bs.print_printer.is_empty();
if square_button(ui, Icon::Print, "Print", ok).clicked()
&& let Ok(s) = &slides
{
app.print_pdf(print_params(bs, s));
let mut p = print_params(bs, s);
if direct {
p["printer"] = json!(bs.print_printer);
p["copies"] = json!(bs.print_copies.clamp(1, 999));
}
app.print_pdf(p);
}
ui.add_space(6.0);
if !printers.is_empty() {
heading(ui, "Printer");
let viewer = "PDF viewer (choose a printer there)";
let shown = if direct { bs.print_printer.clone() } else { viewer.to_string() };
egui::ComboBox::from_id_salt("backstage_printer").width(240.0).selected_text(shown).show_ui(ui, |ui| {
if ui.selectable_label(!direct, viewer).clicked() {
bs.print_printer.clear();
}
for p in &printers {
if ui.selectable_label(&bs.print_printer == p, p).clicked() {
bs.print_printer = p.clone();
}
}
});
if direct {
ui.horizontal(|ui| {
ui.label("Copies:");
ui.add(egui::DragValue::new(&mut bs.print_copies).range(1..=999));
});
}
ui.add_space(6.0);
}
dim(
ui,
if app.services.pick_save.is_some() {
if direct {
"DeckCraft sends a PDF of these pages to the printer."
} else if app.services.pick_save.is_some() {
"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."
Expand Down
36 changes: 36 additions & 0 deletions crates/ui-egui/src/backstage_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -535,3 +535,39 @@ fn print_slides_follow_the_settings() {
bs.print_layout = "slides";
assert_eq!(print_page_size(&bs, &doc), (doc.slide_size.width as f32, doc.slide_size.height as f32), "slides print slide-shaped");
}

/// With printers listed by the host, File › Print offers them; picking one sends the PDF to it
/// with the copies asked for instead of opening the viewer.
#[test]
fn print_sends_the_pdf_to_a_chosen_printer() {
let dir = temp_dir("print-direct");
let (mut services, _) = saving_into(&dir);
let sent: std::sync::Arc<std::sync::Mutex<Vec<(String, String, u32)>>> = Default::default();
let log = sent.clone();
services.printers = Some(Box::new(|| vec!["Office_Laser".to_string()]));
services.print_file = Some(Box::new(move |path: &str, printer: &str, copies: u32| {
let ok = std::fs::read(path).is_ok_and(|b| b.starts_with(b"%PDF"));
log.lock().unwrap().push((printer.to_string(), if ok { "pdf".into() } else { path.to_string() }, copies));
Ok(())
}));
let app = SlideApp::new(Session::with_new(), services);
let mut h = harness(app);
h.key_press_modifiers(Modifiers::COMMAND, Key::P);
h.run_steps(3);
{
let bs = h.state().backstage.as_ref().unwrap();
assert_eq!(bs.printers.as_deref(), Some(&["Office_Laser".to_string()][..]), "the host's printers are listed");
assert!(bs.print_printer.is_empty(), "the printer starts on the PDF viewer");
}
{
let bs = h.state_mut().backstage.as_mut().unwrap();
bs.print_printer = "Office_Laser".into();
bs.print_copies = 3;
}
h.run_steps(2);
click_on_page(&h, "Print");
h.run_steps(2);
assert_eq!(sent.lock().unwrap().as_slice(), [("Office_Laser".to_string(), "pdf".to_string(), 3)]);
assert!(h.state().pending_urls.is_empty(), "no viewer opened");
let _ = std::fs::remove_dir_all(&dir);
}
28 changes: 28 additions & 0 deletions crates/ui-egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,15 @@ pub struct Services {
pub clipboard_set_html: Option<Box<dyn FnMut(&str, &str) -> bool>>,
/// Audio output for media playback (cpal on desktop); without one media plays silently.
pub audio_out: Option<Box<dyn deckcraft_media::AudioOut>>,
/// The system's printers, by name, when the host can list them (CUPS on Linux and macOS).
pub printers: Option<Box<dyn Fn() -> Vec<String>>>,
/// Send a PDF file to a printer: (path, printer, copies).
pub print_file: Option<PrintFn>,
}

/// Print a PDF file on a named printer, `copies` times.
pub type PrintFn = Box<dyn FnMut(&str, &str, u32) -> Result<(), String>>;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ViewMode {
Expand Down Expand Up @@ -817,7 +824,28 @@ impl SlideApp {
o.insert("path".into(), json!(path));
o.insert("format".into(), json!("pdf"));
}
let printer = params.get("printer").and_then(Value::as_str).map(str::to_string).filter(|p| !p.is_empty());
let copies = params.get("copies").and_then(Value::as_u64).map_or(1, |c| c.clamp(1, 999) as u32);
if let Some(o) = params.as_object_mut() {
o.remove("printer");
o.remove("copies");
}
match self.run("file.export", params) {
Ok(_) if printer.is_some() && self.services.print_file.is_some() => {
let printer = printer.unwrap_or_default();
let sent = self.services.print_file.as_mut().map(|f| f(&path, &printer, copies));
match sent {
Some(Ok(())) => {
self.set_status(format!("Sent to {printer}"));
true
}
Some(Err(e)) => {
self.set_status(format!("Couldn't print on {printer}: {e}"));
false
}
None => false,
}
}
Ok(_) => {
self.open_url(&format!("file:///{}", path.replace('\\', "/").trim_start_matches('/')));
self.set_status("Opened the presentation as a PDF to print");
Expand Down
4 changes: 2 additions & 2 deletions docs/gaps.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,8 +285,8 @@ Detail in [ui-parity.md](ui-parity.md).
blocker.**
- **Format Shape pane thinner than PowerPoint's** (Fill/Line/Effects/Size/Text Box pages, picture
and texture options, 3-D). 6–10 h. **Beta blocker.**
- **File tab depth** (#76 landed the Backstage): no online templates, cloud places, printer
choice, video/GIF/CD exports or document protection. 4–8 h for the parts that need no cloud.
- **File tab depth** (#76 landed the Backstage): no online templates, cloud places,
video/GIF/CD exports (printer choice is CUPS-only: Linux and macOS) or document protection. 4–8 h for the parts that need no cloud.
- **Window chrome** (#71 macOS controls misaligned, #26 GNOME title bar, #41 system light/dark).
2–4 h.
- **Icon consistency across Craft apps** (#73, #56). 2–4 h; coordinate in craftrules.
Expand Down
Loading