mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 05:53:08 -05:00
A `CUPS_SERVER` or `ServerName` of `localhost`, `127.0.0.1` or `::1` counts as this machine's scheduler only with no port or port 631. On another port (a second CUPS instance) the dialog no longer reads `/etc/cups/ppd`, whose queues belong to the default scheduler, and asks `lpoptions` and IPP instead. When the named server is one of CUPS's own domain sockets and neither the PPD nor `lpoptions` lists sizes, the IPP lookup asks `localhost` on the IPP default port, as it already does when no server is named. `ipptool` rejects a URI whose host is a socket path (`httpSeparateURI` in CUPS's `cups/http-support.c`), so another socket path is not asked.
691 lines
34 KiB
Rust
691 lines
34 KiB
Rust
//! Desktop printer transport. VectorCraft composes every page and copy before submission;
|
|
//! craft-print owns discovery and spooling.
|
|
use std::process::Command;
|
|
use vectorcraft_ui_egui::print::{Paper, Papers, PrintJob, PrintService, Printer};
|
|
|
|
mod direct_pdf;
|
|
|
|
#[derive(Default)]
|
|
pub struct SystemPrint {
|
|
/// The paper-size lookup in flight, dropped when its worker answers or disconnects.
|
|
papers: PaperLookup,
|
|
}
|
|
|
|
impl PrintService for SystemPrint {
|
|
fn printers(&mut self) -> Vec<Printer> {
|
|
system::printers()
|
|
}
|
|
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
|
|
let note = system::print(job)?;
|
|
Ok(sent(job.title, job.printer, ¬e))
|
|
}
|
|
fn shared_printers(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintersFn> {
|
|
Some(std::sync::Arc::new(system::queues))
|
|
}
|
|
fn shared_print(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintFn> {
|
|
Some(std::sync::Arc::new(|job| system::print(job).map(|note| sent(job.title, job.printer, ¬e))))
|
|
}
|
|
fn applies_paper(&self) -> bool {
|
|
!cfg!(windows)
|
|
}
|
|
fn turns_landscape(&self) -> bool {
|
|
// macOS's `lp` doesn't turn a landscape page to the paper: it cuts it off on upright
|
|
// paper. craft-print turns each sheet to its own orientation on Windows.
|
|
!cfg!(target_os = "macos")
|
|
}
|
|
fn has_setup(&self) -> bool {
|
|
true
|
|
}
|
|
fn setup(&mut self, printer: Option<&str>) -> Result<(), String> {
|
|
system::setup(printer)
|
|
}
|
|
fn scripts_may_print(&self) -> bool {
|
|
true
|
|
}
|
|
fn papers(&mut self, printer: &str, fresh: bool) -> Papers {
|
|
self.papers.poll(printer, fresh, std::time::Instant::now(), |printer| installed_papers(&printer))
|
|
}
|
|
}
|
|
|
|
/// A paper-size read that waits for the worker before it.
|
|
type PaperRead = Box<dyn FnOnce(String) -> Vec<Paper> + Send>;
|
|
|
|
/// How long the newest still-running worker runs before a waiting read may start beside it, and how long a read waits
|
|
/// when no worker may start before its printer is given no paper sizes.
|
|
const PAPER_WAIT: std::time::Duration = std::time::Duration::from_secs(15);
|
|
|
|
/// The most paper-size workers alive at once, stalled ones included.
|
|
const PAPER_WORKERS: usize = 4;
|
|
|
|
/// The paper-size lookup: the printer it reads with its worker's channel, the read waiting to start with the time it
|
|
/// began waiting, and the start times and completion flags of its workers. A read starts when no worker runs, or when
|
|
/// the newest still-running worker has run [`PAPER_WAIT`] and fewer than [`PAPER_WORKERS`] are alive.
|
|
#[derive(Default)]
|
|
struct PaperLookup {
|
|
current: Option<(String, std::sync::mpsc::Receiver<Vec<Paper>>)>,
|
|
waiting: Option<(String, PaperRead, std::time::Instant)>,
|
|
started: Vec<(std::time::Instant, std::sync::Arc<std::sync::atomic::AtomicBool>)>,
|
|
workers: std::sync::Arc<std::sync::atomic::AtomicUsize>,
|
|
}
|
|
|
|
/// Marks a worker finished and counts it down when it ends, including when it panics.
|
|
struct WorkerDone(std::sync::Arc<std::sync::atomic::AtomicUsize>, std::sync::Arc<std::sync::atomic::AtomicBool>);
|
|
|
|
impl Drop for WorkerDone {
|
|
fn drop(&mut self) {
|
|
self.1.store(false, std::sync::atomic::Ordering::SeqCst);
|
|
self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
|
|
}
|
|
}
|
|
|
|
impl PaperLookup {
|
|
/// Poll the lookup of `printer`. A new lookup of `read` is wanted when `fresh` is set, when the one in flight or
|
|
/// waiting reads another printer, or when none is in flight; the earlier one's answer is dropped. Only the newest
|
|
/// waiting read starts, when the workers allow it at `now`. Each new or replacement read begins waiting at `now`.
|
|
/// Finished workers do not delay a waiting read. A read that has waited [`PAPER_WAIT`] while
|
|
/// [`PAPER_WORKERS`] workers stall is dropped, and the printer gets no paper sizes.
|
|
fn poll(&mut self, printer: &str, fresh: bool, now: std::time::Instant, read: impl FnOnce(String) -> Vec<Paper> + Send + 'static) -> Papers {
|
|
let wanted = self.waiting.as_ref().map(|(p, ..)| p).or(self.current.as_ref().map(|(p, _)| p));
|
|
if fresh || wanted.is_none_or(|p| p != printer) {
|
|
self.current = None;
|
|
self.waiting = Some((printer.to_string(), Box::new(read), now));
|
|
}
|
|
self.started.retain(|(_, running)| running.load(std::sync::atomic::Ordering::SeqCst));
|
|
let alive = self.workers.load(std::sync::atomic::Ordering::SeqCst);
|
|
let may_start = alive == 0
|
|
|| (alive < PAPER_WORKERS && self.started.last().is_none_or(|(started, _)| now.saturating_duration_since(*started) >= PAPER_WAIT));
|
|
if may_start && let Some((name, read, _)) = self.waiting.take() {
|
|
let (send, receive) = std::sync::mpsc::channel();
|
|
self.workers.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
|
let running = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
|
|
let done = WorkerDone(self.workers.clone(), running.clone());
|
|
let printer = name.clone();
|
|
let spawned = std::thread::Builder::new().name("printer-papers".into()).spawn(move || {
|
|
let worker = done;
|
|
let papers = read(printer);
|
|
worker.1.store(false, std::sync::atomic::Ordering::SeqCst);
|
|
let _ = send.send(papers);
|
|
});
|
|
if spawned.is_err() {
|
|
return Papers::Ready(Vec::new());
|
|
}
|
|
self.started.push((now, running));
|
|
self.current = Some((name, receive));
|
|
}
|
|
if let Some((.., since)) = &self.waiting {
|
|
if now.saturating_duration_since(*since) < PAPER_WAIT {
|
|
return Papers::Pending;
|
|
}
|
|
self.waiting = None;
|
|
return Papers::Ready(Vec::new());
|
|
}
|
|
let result = match self.current.as_ref().map(|(_, receive)| receive.try_recv()) {
|
|
Some(Ok(papers)) => Papers::Ready(papers),
|
|
Some(Err(std::sync::mpsc::TryRecvError::Empty)) => return Papers::Pending,
|
|
Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) | None => Papers::Ready(Vec::new()),
|
|
};
|
|
self.current = None;
|
|
result
|
|
}
|
|
}
|
|
|
|
/// Look up only an installed printer's own name.
|
|
fn installed_papers(printer: &str) -> Vec<Paper> {
|
|
if printer.is_empty() || !system::printers().iter().any(|p| p.name == printer) {
|
|
return Vec::new();
|
|
}
|
|
system::papers(printer)
|
|
}
|
|
|
|
/// The status after the job `title` went to `printer` (the default one without a name), with the
|
|
/// spooler's `note` when it gave one. Each message has text between its values, so a catalog can
|
|
/// match it and translate it. The note follows as its own sentence: a printer name can end in
|
|
/// parentheses ("HP LaserJet (Copy 1)"), and a note in parentheses would match that name.
|
|
fn sent(title: &str, printer: Option<&str>, note: &str) -> String {
|
|
let to = printer.unwrap_or("the default printer");
|
|
if note.is_empty() { format!("Sent “{title}” to {to}") } else { format!("Sent “{title}” to {to}. The spooler replied: {note}") }
|
|
}
|
|
|
|
mod system {
|
|
use super::{Command, Paper, PrintJob, Printer};
|
|
pub fn printers() -> Vec<Printer> {
|
|
craft::print::printers().into_iter().map(Printer::from).collect()
|
|
}
|
|
/// The installed queues and the default one, without asking each driver for its capabilities.
|
|
pub fn queues() -> Vec<Printer> {
|
|
craft::print::printer_queues().into_iter().map(Printer::from).collect()
|
|
}
|
|
/// The paper sizes of an installed printer's driver: its CUPS PPD, or Windows' printer settings.
|
|
pub fn papers(printer: &str) -> Vec<Paper> {
|
|
#[cfg(windows)]
|
|
{
|
|
// The name goes in as an environment variable, never into the script's text.
|
|
const SCRIPT: &str = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Add-Type -AssemblyName System.Drawing; $s = New-Object System.Drawing.Printing.PrinterSettings; \
|
|
$s.PrinterName = $env:VC_PRINTER; foreach ($p in $s.PaperSizes) { \"$($p.RawKind)`t$($p.PaperName)`t$($p.Width)`t$($p.Height)\" }";
|
|
use std::os::windows::process::CommandExt as _;
|
|
// CREATE_NO_WINDOW: no console window opens over the app.
|
|
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
|
let mut command = Command::new("powershell.exe");
|
|
command.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("VC_PRINTER", printer).creation_flags(CREATE_NO_WINDOW);
|
|
paper_output(&mut command).map(|out| vectorcraft_ui_egui::print::windows_papers(&String::from_utf8_lossy(&out))).unwrap_or_default()
|
|
}
|
|
#[cfg(not(windows))]
|
|
{
|
|
use std::io::Read as _;
|
|
// CUPS queue names never hold `/`, so the name can't leave the PPD folder.
|
|
if printer.contains(['/', '\\']) || printer.starts_with('.') {
|
|
return Vec::new();
|
|
}
|
|
let named = cups_server();
|
|
// A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue,
|
|
// so its sizes come from the server.
|
|
if scheduler_is_local(named.as_deref()) {
|
|
const PPD_CAP: u64 = 16 << 20;
|
|
let mut bytes = Vec::new();
|
|
let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes));
|
|
let papers = if read.is_ok() { vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) } else { Vec::new() };
|
|
if !papers.is_empty() {
|
|
return papers;
|
|
}
|
|
}
|
|
// A driverless or remote queue has no PPD here: `lpoptions` asks the queue's server for its sizes.
|
|
let mut command = Command::new("lpoptions");
|
|
command.args(["-p", printer, "-l"]);
|
|
let papers = paper_output(&mut command)
|
|
.map(|out| vectorcraft_ui_egui::print::lpoptions_papers(&String::from_utf8_lossy(&out)))
|
|
.unwrap_or_default();
|
|
if !papers.is_empty() {
|
|
return papers;
|
|
}
|
|
// A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses.
|
|
let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref());
|
|
let server = ipp_server(named, |s| std::path::Path::new(s).exists());
|
|
let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers };
|
|
use std::io::Write as _;
|
|
use std::sync::atomic::{AtomicU64, Ordering};
|
|
static NEXT: AtomicU64 = AtomicU64::new(0);
|
|
let test_path =
|
|
std::env::temp_dir().join(format!("vectorcraft-printer-papers-{}-{}.test", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
|
let Ok(mut test) = std::fs::File::options().write(true).create_new(true).open(&test_path) else { return papers };
|
|
let written = test.write_all(
|
|
b"{\n\
|
|
VERSION 1.1\n\
|
|
OPERATION Get-Printer-Attributes\n\
|
|
GROUP operation-attributes-tag\n\
|
|
ATTR charset attributes-charset utf-8\n\
|
|
ATTR language attributes-natural-language en\n\
|
|
ATTR uri printer-uri $uri\n\
|
|
ATTR keyword requested-attributes media-supported\n\
|
|
STATUS successful-ok\n\
|
|
}\n",
|
|
);
|
|
drop(test);
|
|
if written.is_err() {
|
|
let _ = std::fs::remove_file(&test_path);
|
|
return papers;
|
|
}
|
|
let mut command = Command::new("ipptool");
|
|
command.args(["-T", "10", "-tv", &uri]).arg(&test_path);
|
|
let output = paper_output(&mut command);
|
|
let _ = std::fs::remove_file(&test_path);
|
|
output.map(|out| vectorcraft_ui_egui::print::ipp_papers(&String::from_utf8_lossy(&out))).unwrap_or_default()
|
|
}
|
|
}
|
|
/// CUPS's own domain sockets, where the local scheduler listens next to `localhost:631`.
|
|
#[cfg(not(windows))]
|
|
const CUPS_SOCKETS: [&str; 3] = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"];
|
|
/// The server for the IPP lookup, given the one `cups_server` names and whether a path exists. With no server
|
|
/// named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` on the IPP default
|
|
/// port), and `localhost` on `IPP_PORT` otherwise. A named domain socket that is one of CUPS's own is the same local
|
|
/// scheduler; any other socket path stays as named, so the lookup is skipped rather than asking a scheduler the job
|
|
/// does not go to.
|
|
///
|
|
/// [`ipp_queue_uri`]: vectorcraft_ui_egui::print::ipp_queue_uri
|
|
#[cfg(not(windows))]
|
|
pub(super) fn ipp_server(named: Option<String>, exists: impl Fn(&str) -> bool) -> Option<String> {
|
|
match named {
|
|
Some(server) if CUPS_SOCKETS.contains(&server.trim()) => None,
|
|
Some(server) => Some(server),
|
|
None => (!CUPS_SOCKETS.iter().any(|s| exists(s))).then(|| "localhost".to_string()),
|
|
}
|
|
}
|
|
/// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or
|
|
/// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName`
|
|
/// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts.
|
|
#[cfg(not(windows))]
|
|
fn cups_server() -> Option<String> {
|
|
if let Some(server) = std::env::var("CUPS_SERVER").ok().filter(|s| !s.trim().is_empty()) {
|
|
return Some(server.trim().to_string());
|
|
}
|
|
if cfg!(target_os = "macos") {
|
|
return None;
|
|
}
|
|
let home = std::env::var_os("HOME").map(|h| std::path::Path::new(&h).join(".cups/client.conf"));
|
|
home.into_iter().chain([std::path::PathBuf::from("/etc/cups/client.conf")]).find_map(|path| {
|
|
use std::io::Read as _;
|
|
let mut text = String::new();
|
|
std::fs::File::open(path).and_then(|f| f.take(1 << 16).read_to_string(&mut text)).ok()?;
|
|
client_conf_server_name(&text)
|
|
})
|
|
}
|
|
/// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path,
|
|
/// or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. A loopback
|
|
/// name on another port is a second scheduler, whose queues the local PPD folder does not describe.
|
|
#[cfg(not(windows))]
|
|
pub(super) fn scheduler_is_local(server: Option<&str>) -> bool {
|
|
let Some(server) = server.map(str::trim) else { return true };
|
|
if server.starts_with('/') {
|
|
return true;
|
|
}
|
|
// A network name may end in `/version=1.1`.
|
|
let server = server.split_once('/').map_or(server, |(server, _)| server);
|
|
let (host, port) = if let Some(rest) = server.strip_prefix('[') {
|
|
rest.split_once(']').map_or((rest, None), |(host, after)| (host, after.strip_prefix(':')))
|
|
} else if server.matches(':').count() == 1 {
|
|
server.split_once(':').map_or((server, None), |(host, port)| (host, Some(port)))
|
|
} else {
|
|
(server, None)
|
|
};
|
|
let loopback = host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1";
|
|
loopback && port.is_none_or(|port| port.trim() == "631")
|
|
}
|
|
/// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a
|
|
/// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is
|
|
/// dropped and the rest of the line is kept as written.
|
|
#[cfg(not(windows))]
|
|
pub(super) fn client_conf_server_name(text: &str) -> Option<String> {
|
|
text.lines().rev().find_map(|line| {
|
|
let kept = match line.find('#') {
|
|
Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]),
|
|
Some(at) => line[..at].to_string(),
|
|
None => line.to_string(),
|
|
};
|
|
let (key, value) = kept.trim().split_once(char::is_whitespace)?;
|
|
(key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string())
|
|
})
|
|
}
|
|
/// Drain output while polling the child, and stop discovery after ten seconds.
|
|
fn paper_output(command: &mut Command) -> Option<Vec<u8>> {
|
|
use std::io::Read as _;
|
|
use std::process::Stdio;
|
|
use std::time::{Duration, Instant};
|
|
|
|
const LIMIT: Duration = Duration::from_secs(10);
|
|
let started = Instant::now();
|
|
let mut child = command.stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?;
|
|
let (send, receive) = std::sync::mpsc::channel();
|
|
let stdout = child.stdout.take();
|
|
let reader = std::thread::Builder::new().name("printer-paper-output".into()).spawn(move || {
|
|
let mut bytes = Vec::new();
|
|
// Retain at most 16 MiB, but drain the rest so the child can finish.
|
|
let read = stdout.map(|mut out| {
|
|
out.by_ref().take(16 << 20).read_to_end(&mut bytes)?;
|
|
std::io::copy(&mut out, &mut std::io::sink())
|
|
});
|
|
let _ = send.send(read.and_then(Result::ok).map(|_| bytes));
|
|
});
|
|
if reader.is_err() {
|
|
let _ = child.kill();
|
|
let _ = child.wait();
|
|
return None;
|
|
}
|
|
loop {
|
|
match child.try_wait() {
|
|
Ok(Some(status)) => {
|
|
return if status.success() { receive.recv_timeout(LIMIT.saturating_sub(started.elapsed())).ok().flatten() } else { None };
|
|
}
|
|
Ok(None) if started.elapsed() < LIMIT => std::thread::sleep(Duration::from_millis(25)),
|
|
_ => {
|
|
let _ = child.kill();
|
|
let _ = child.wait();
|
|
return None;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
pub fn print(job: &PrintJob) -> Result<String, String> {
|
|
if job.direct_pdf {
|
|
return super::direct_pdf::print(job);
|
|
}
|
|
craft::print::submit(job.pdf, &settings(job)).map_err(|e| e.to_string())
|
|
}
|
|
/// The spooler's settings for `job`. Copies, layout, marks and colour management are already in the PDF. Preserve
|
|
/// its physical sheet size and the queue's duplex default without printing copies twice. The driver's paper
|
|
/// keyword goes to CUPS as `media`, so the queue feeds the paper the job was laid out for.
|
|
pub(crate) fn settings(job: &PrintJob) -> craft::print::Job {
|
|
let options = job.paper.map(|paper| ("media".to_string(), paper.to_string())).into_iter().collect();
|
|
craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), options, ..Default::default() }
|
|
}
|
|
#[cfg(windows)]
|
|
pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command {
|
|
let target = printer.map(str::trim).filter(|p| !p.is_empty()).or_else(|| default_printer.map(str::trim).filter(|p| !p.is_empty()));
|
|
if let Some(name) = target {
|
|
let mut cmd = Command::new("rundll32.exe");
|
|
cmd.args(["printui.dll,PrintUIEntry", "/e", "/n", name]);
|
|
cmd
|
|
} else {
|
|
let mut cmd = Command::new("explorer");
|
|
cmd.arg("ms-settings:printers");
|
|
cmd
|
|
}
|
|
}
|
|
pub fn setup(printer: Option<&str>) -> Result<(), String> {
|
|
#[cfg(windows)]
|
|
{
|
|
let list = printers();
|
|
let default = list.iter().find(|p| p.default).or_else(|| list.first()).map(|p| p.name.as_str());
|
|
// Only an installed printer's own name reaches the command line: `printer` can come
|
|
// from a command or MCP, and PrintUIEntry reads options from its arguments.
|
|
let printer = printer.map(str::trim).filter(|p| list.iter().any(|q| q.name == *p));
|
|
let mut cmd = setup_command(printer, default);
|
|
match cmd.spawn() {
|
|
Ok(_) => Ok(()),
|
|
Err(_) => Command::new("explorer").arg("ms-settings:printers").spawn().map(|_| ()).map_err(|e| e.to_string()),
|
|
}
|
|
}
|
|
#[cfg(target_os = "macos")]
|
|
{
|
|
let _ = printer;
|
|
Command::new("open")
|
|
.arg("x-apple.systempreferences:com.apple.Print-Scan-Settings.extension")
|
|
.spawn()
|
|
.map(|_| ())
|
|
.map_err(|e| e.to_string())
|
|
}
|
|
#[cfg(not(any(windows, target_os = "macos")))]
|
|
{
|
|
if Command::new("system-config-printer").spawn().is_ok() {
|
|
return Ok(());
|
|
}
|
|
let url = printer.map_or_else(|| "http://localhost:631/printers/".to_string(), |p| format!("http://localhost:631/printers/{p}"));
|
|
Command::new("xdg-open").arg(url).spawn().map(|_| ()).map_err(|e| e.to_string())
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(all(test, windows))]
|
|
mod tests {
|
|
use super::system::setup_command;
|
|
use std::ffi::OsStr;
|
|
|
|
#[test]
|
|
fn setup_command_uses_printui_for_specified_printer() {
|
|
let cmd = setup_command(Some("Office Laser"), None);
|
|
assert_eq!(cmd.get_program(), "rundll32.exe");
|
|
let args: Vec<&OsStr> = cmd.get_args().collect();
|
|
assert_eq!(args, ["printui.dll,PrintUIEntry", "/e", "/n", "Office Laser"]);
|
|
}
|
|
|
|
#[test]
|
|
fn setup_command_trims_whitespace_and_skips_empty() {
|
|
let cmd = setup_command(Some(" "), Some("Default Proofer"));
|
|
assert_eq!(cmd.get_program(), "rundll32.exe");
|
|
let args: Vec<&OsStr> = cmd.get_args().collect();
|
|
assert_eq!(args, ["printui.dll,PrintUIEntry", "/e", "/n", "Default Proofer"]);
|
|
}
|
|
|
|
#[test]
|
|
fn setup_command_falls_back_to_settings_when_no_printer() {
|
|
let cmd = setup_command(None, None);
|
|
assert_eq!(cmd.get_program(), "explorer");
|
|
let args: Vec<&OsStr> = cmd.get_args().collect();
|
|
assert_eq!(args, ["ms-settings:printers"]);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod paper_lookup_tests {
|
|
use super::PaperLookup;
|
|
use vectorcraft_ui_egui::print::{Paper, Papers};
|
|
|
|
fn paper(key: &str) -> Vec<Paper> {
|
|
vec![Paper { key: key.into(), label: key.into(), width: 100.0, height: 200.0 }]
|
|
}
|
|
|
|
/// The test clock: `secs` seconds after a fixed start.
|
|
fn at(secs: u64) -> std::time::Instant {
|
|
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
|
|
*START.get_or_init(std::time::Instant::now) + std::time::Duration::from_secs(secs)
|
|
}
|
|
|
|
/// Poll the lookup of `printer` at `now` until it answers.
|
|
fn settle(lookup: &mut PaperLookup, printer: &str, now: std::time::Instant) -> Vec<Paper> {
|
|
loop {
|
|
match lookup.poll(printer, false, now, |_| panic!("polling starts no lookup")) {
|
|
Papers::Ready(papers) => return papers,
|
|
Papers::Pending => std::thread::yield_now(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Start a fresh lookup of `printer` that answers `key`, and poll it until it answers.
|
|
fn answer(lookup: &mut PaperLookup, printer: &str, key: &'static str) -> Vec<Paper> {
|
|
match lookup.poll(printer, true, at(0), move |_| paper(key)) {
|
|
Papers::Ready(papers) => papers,
|
|
Papers::Pending => settle(lookup, printer, at(0)),
|
|
}
|
|
}
|
|
|
|
/// A read that answers `key` once `gate` lets it.
|
|
fn gated(key: &'static str) -> (std::sync::mpsc::Sender<()>, impl FnOnce(String) -> Vec<Paper> + Send + 'static) {
|
|
let (open, gate) = std::sync::mpsc::channel::<()>();
|
|
(open, move |_| {
|
|
let _ = gate.recv();
|
|
paper(key)
|
|
})
|
|
}
|
|
|
|
#[test]
|
|
fn a_fresh_lookup_drops_the_answer_of_an_earlier_one() {
|
|
let mut lookup = PaperLookup::default();
|
|
let (open, read) = gated("Old");
|
|
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
|
|
let (other, read) = gated("Office");
|
|
assert!(matches!(lookup.poll("Office", true, at(0), read), Papers::Pending));
|
|
let _ = open.send(());
|
|
let _ = other.send(());
|
|
// Back on the card printer.
|
|
assert_eq!(answer(&mut lookup, "Card", "New"), paper("New"));
|
|
// The dialog opens again on the card printer while a lookup of it is still running.
|
|
let (open, read) = gated("Stale");
|
|
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
|
|
let _ = open.send(());
|
|
assert_eq!(answer(&mut lookup, "Card", "Newer"), paper("Newer"));
|
|
}
|
|
|
|
#[test]
|
|
fn a_stalled_lookup_holds_the_only_worker_while_the_printer_changes() {
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
let mut lookup = PaperLookup::default();
|
|
let (open, read) = gated("Stalled");
|
|
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
|
|
let started = std::sync::Arc::new(AtomicUsize::new(0));
|
|
for (i, printer) in ["Office", "Card", "Office", "Plotter"].into_iter().cycle().take(40).enumerate() {
|
|
let count = started.clone();
|
|
let polled = lookup.poll(printer, i % 3 == 0, at(1), move |_| {
|
|
count.fetch_add(1, Ordering::SeqCst);
|
|
paper("Changed")
|
|
});
|
|
assert!(matches!(polled, Papers::Pending), "{printer}");
|
|
assert_eq!(lookup.workers.load(Ordering::SeqCst), 1, "only the stalled worker runs");
|
|
}
|
|
let _ = open.send(());
|
|
// Only the newest choice is read, once the stalled worker ends.
|
|
assert_eq!(settle(&mut lookup, "Plotter", at(2)), paper("Changed"));
|
|
assert_eq!(started.load(Ordering::SeqCst), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn a_waiting_read_starts_beside_a_worker_stalled_for_the_wait() {
|
|
use std::sync::atomic::Ordering;
|
|
let mut lookup = PaperLookup::default();
|
|
let (card, read) = gated("Stalled");
|
|
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
|
|
let (office, read) = gated("Office");
|
|
assert!(matches!(lookup.poll("Office", false, at(1), read), Papers::Pending));
|
|
assert!(matches!(lookup.poll("Office", false, at(14), |_| panic!("polling starts no lookup")), Papers::Pending));
|
|
assert_eq!(lookup.workers.load(Ordering::SeqCst), 1, "the read waits while the worker is new");
|
|
// The worker has stalled for the whole wait: the waiting read starts beside it.
|
|
assert!(matches!(lookup.poll("Office", false, at(15), |_| panic!("polling starts no lookup")), Papers::Pending));
|
|
assert_eq!(lookup.workers.load(Ordering::SeqCst), 2, "the waiting read starts beside the stalled worker");
|
|
let _ = office.send(());
|
|
assert_eq!(settle(&mut lookup, "Office", at(15)), paper("Office"));
|
|
// The worker that answered counts itself down once its thread ends.
|
|
while lookup.workers.load(Ordering::SeqCst) > 1 {
|
|
std::thread::yield_now();
|
|
}
|
|
// The older worker has stalled long enough for another read to start immediately.
|
|
let (next, began) = std::sync::mpsc::channel();
|
|
let (open, read) = gated("Next");
|
|
assert!(matches!(
|
|
lookup.poll("Next", false, at(16), move |printer| {
|
|
let _ = next.send(());
|
|
read(printer)
|
|
}),
|
|
Papers::Pending
|
|
));
|
|
assert_eq!(lookup.workers.load(Ordering::SeqCst), 2, "the next read starts without another wait");
|
|
began.recv().expect("the next read started");
|
|
let _ = open.send(());
|
|
assert_eq!(settle(&mut lookup, "Next", at(16)), paper("Next"));
|
|
drop(card);
|
|
}
|
|
|
|
#[test]
|
|
fn a_printer_waiting_on_stalled_workers_gets_no_sizes_after_the_wait() {
|
|
use std::sync::atomic::Ordering;
|
|
let mut lookup = PaperLookup::default();
|
|
let (card, read) = gated("Stalled");
|
|
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
|
|
// More stalls fill the workers up to the limit, one wait apart.
|
|
let mut stalls = vec![card];
|
|
for (i, printer) in ["Plotter", "Scanner", "Fax"].into_iter().enumerate() {
|
|
let (gate, read) = gated("Stalled");
|
|
stalls.push(gate);
|
|
assert!(matches!(lookup.poll(printer, true, at(30 + 15 * i as u64), read), Papers::Pending), "{printer}");
|
|
}
|
|
assert!(matches!(lookup.poll("Label", true, at(61), |_| panic!("no worker may start")), Papers::Pending));
|
|
assert!(matches!(lookup.poll("Label", false, at(75), |_| panic!("polling starts no lookup")), Papers::Pending));
|
|
// Reopening the same printer and choosing another printer each starts a new wait.
|
|
assert!(matches!(lookup.poll("Label", true, at(76), |_| panic!("no worker may start")), Papers::Pending));
|
|
assert!(matches!(lookup.poll("Photo", false, at(91), |_| panic!("no worker may start")), Papers::Pending));
|
|
assert!(matches!(lookup.poll("Photo", false, at(105), |_| panic!("polling starts no lookup")), Papers::Pending));
|
|
match lookup.poll("Photo", false, at(106), |_| panic!("polling starts no lookup")) {
|
|
Papers::Ready(papers) => assert_eq!(papers, []),
|
|
Papers::Pending => panic!("the wait for the stalled workers did not end"),
|
|
}
|
|
assert!(lookup.workers.load(Ordering::SeqCst) <= super::PAPER_WORKERS);
|
|
// Once the stalled workers end, the next choice is read again.
|
|
drop(stalls);
|
|
let papers = match lookup.poll("Photo", true, at(107), |_| paper("Ready")) {
|
|
Papers::Ready(papers) => papers,
|
|
Papers::Pending => settle(&mut lookup, "Photo", at(107)),
|
|
};
|
|
assert_eq!(papers, paper("Ready"));
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod turn_tests {
|
|
use super::sent;
|
|
|
|
#[test]
|
|
fn a_printer_name_ending_in_parentheses_stays_whole_in_a_translation() {
|
|
use vectorcraft_ui_egui::i18n::{Lang, LangExt, message};
|
|
let Some(de) = Lang::from_code("de") else { panic!("no German catalog") };
|
|
let printer = Some("HP LaserJet (Copy 1)");
|
|
assert_eq!(message(de, &sent("Poster", printer, "")), "“Poster” an HP LaserJet (Copy 1) gesendet");
|
|
assert_eq!(
|
|
message(de, &sent("Poster", printer, "job 12")),
|
|
"“Poster” an HP LaserJet (Copy 1) gesendet. Antwort der Druckwarteschlange: job 12"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[cfg(all(test, not(windows)))]
|
|
mod client_conf_tests {
|
|
use super::system::{client_conf_server_name, ipp_server, scheduler_is_local};
|
|
|
|
#[test]
|
|
fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() {
|
|
let none = |_: &str| false;
|
|
let socket = |s: &str| s == "/run/cups/cups.sock";
|
|
assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none), None, "CUPS's socket is asked as localhost:631");
|
|
assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none), None);
|
|
assert_eq!(ipp_server(Some("/tmp/other.sock".into()), socket).as_deref(), Some("/tmp/other.sock"), "another socket is not asked");
|
|
assert_eq!(ipp_server(Some("localhost:8631".into()), socket).as_deref(), Some("localhost:8631"));
|
|
assert_eq!(ipp_server(None, socket), None);
|
|
assert_eq!(ipp_server(None, none).as_deref(), Some("localhost"));
|
|
}
|
|
|
|
#[test]
|
|
fn only_a_scheduler_on_this_machine_counts_as_local() {
|
|
for local in [
|
|
None,
|
|
Some("/run/cups/cups.sock"),
|
|
Some("localhost"),
|
|
Some("LocalHost:631"),
|
|
Some("localhost:631"),
|
|
Some("127.0.0.1:631"),
|
|
Some("::1"),
|
|
Some("[::1]:631"),
|
|
Some("[::1]"),
|
|
Some("localhost/version=1.1"),
|
|
Some("localhost:631/version=1.1"),
|
|
] {
|
|
assert!(scheduler_is_local(local), "{local:?}");
|
|
}
|
|
for remote in [
|
|
"print.example.com",
|
|
"print.example.com:631",
|
|
"192.0.2.7",
|
|
"[2001:db8::1]:631",
|
|
"2001:db8::1",
|
|
"localhost.example.com",
|
|
"print.example.com:631/version=1.1",
|
|
"localhost:8631",
|
|
"127.0.0.1:8631",
|
|
"[::1]:8631",
|
|
"localhost:8631/version=1.1",
|
|
] {
|
|
assert!(!scheduler_is_local(Some(remote)), "{remote}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn server_name_drops_a_trailing_comment_and_keeps_an_escaped_hash() {
|
|
assert_eq!(client_conf_server_name("ServerName print.example.com\n").as_deref(), Some("print.example.com"));
|
|
assert_eq!(client_conf_server_name("ServerName print.example.com # office\n").as_deref(), Some("print.example.com"));
|
|
assert_eq!(client_conf_server_name("ServerName print.example.com#office\n").as_deref(), Some("print.example.com"));
|
|
assert_eq!(client_conf_server_name("ServerName /run/cups\\#1.sock\n").as_deref(), Some("/run/cups#1.sock"));
|
|
// After an escaped first `#`, a later `#` stays as written.
|
|
assert_eq!(client_conf_server_name("ServerName a\\#b#c\n").as_deref(), Some("a#b#c"));
|
|
// A later line that is only a comment, or a directive whose value is all comment, leaves the earlier one.
|
|
assert_eq!(client_conf_server_name("ServerName a.example\n# ServerName b.example\nServerName # none\n").as_deref(), Some("a.example"));
|
|
assert_eq!(client_conf_server_name("ServerName a.example\nServerName b.example\n").as_deref(), Some("b.example"));
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod job_settings_tests {
|
|
use super::system::settings;
|
|
use vectorcraft_ui_egui::print::PrintJob;
|
|
|
|
fn job(paper: Option<&str>) -> PrintJob<'_> {
|
|
PrintJob { printer: Some("Card"), title: "Badge", pdf: b"%PDF", paper, direct_pdf: false }
|
|
}
|
|
|
|
#[test]
|
|
fn the_chosen_paper_goes_to_cups_as_media() {
|
|
let args = craft::print::lp_args(&settings(&job(Some("CR80"))));
|
|
assert!(args.windows(2).any(|w| w == ["-o", "media=CR80"]), "{args:?}");
|
|
assert!(args.windows(2).any(|w| w == ["-d", "Card"]), "{args:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn without_a_paper_the_queue_keeps_its_own() {
|
|
let args = craft::print::lp_args(&settings(&job(None)));
|
|
assert!(!args.iter().any(|a| a.starts_with("media=")), "{args:?}");
|
|
}
|
|
}
|