mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-02 22:30:47 +00:00
Compare commits
66
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc6c68015d | ||
|
|
0d17c1b811 | ||
|
|
045c1d2dbf | ||
|
|
e04c7d14f2 | ||
|
|
3231456e2a | ||
|
|
ca2490e3d7 | ||
|
|
6660ae2d6f | ||
|
|
22cd111b22 | ||
|
|
8582019940 | ||
|
|
771ced822d | ||
|
|
868465a89b | ||
|
|
eb8b51abec | ||
|
|
5d7415b20d | ||
|
|
cbcb674adf | ||
|
|
37a33b9993 | ||
|
|
0b541c8203 | ||
|
|
97b5e91779 | ||
|
|
e1913b0263 | ||
|
|
4be441ed9d | ||
|
|
d02e392030 | ||
|
|
a627effe1e | ||
|
|
d5468e38d1 | ||
|
|
92f071b2a9 | ||
|
|
1fb38a7b46 | ||
|
|
1dfbb088d1 | ||
|
|
5edeebfdd6 | ||
|
|
6dcbac1964 | ||
|
|
cf463a93d5 | ||
|
|
dbf64ae094 | ||
|
|
153195452f | ||
|
|
76b0b633da | ||
|
|
e5ea6bcb75 | ||
|
|
b443e03542 | ||
|
|
a58a110db8 | ||
|
|
ddc81677ca | ||
|
|
aacf8ea548 | ||
|
|
33ba00c16e | ||
|
|
e51c3e76be | ||
|
|
240ec04584 | ||
|
|
b9e0609b93 | ||
|
|
e50e9039d4 | ||
|
|
d0c59b1994 | ||
|
|
04ad0142a8 | ||
|
|
172932a490 | ||
|
|
3df303c366 | ||
|
|
211437b689 | ||
|
|
cfffee99e3 | ||
|
|
973e7983c6 | ||
|
|
e30bc0604a | ||
|
|
ecc0a8450a | ||
|
|
cf34c26c4f | ||
|
|
d8d0b5b253 | ||
|
|
b95fb287a6 | ||
|
|
7e4edfe24c | ||
|
|
d9a5606389 | ||
|
|
806bca13e1 | ||
|
|
611643be31 | ||
|
|
ea546718c2 | ||
|
|
f205fe06df | ||
|
|
1c3d8a51f8 | ||
|
|
9ca6ef5010 | ||
|
|
ce3291b4a6 | ||
|
|
fd473225d5 | ||
|
|
a5009b5fc1 | ||
|
|
16dd36eadc | ||
|
|
c7965ebf52 |
@@ -0,0 +1,53 @@
|
||||
name: CadCraft Windows plotter catalog
|
||||
on:
|
||||
push:
|
||||
branches: [verify/cadcraft-driver-media-4859]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
catalog:
|
||||
runs-on: windows-2025
|
||||
timeout-minutes: 100
|
||||
env:
|
||||
CARGO_PROFILE_DEV_DEBUG: '0'
|
||||
CARGO_PROFILE_TEST_DEBUG: '0'
|
||||
CARGO_INCREMENTAL: '0'
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@58848078cd09e3ca182891a8b76ee979f1eb6e1c
|
||||
with:
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
- name: Choose build volume and resolve the combined app
|
||||
shell: pwsh
|
||||
run: |
|
||||
$disk = Get-PSDrive -PSProvider FileSystem | Where-Object { $_.Free -gt 0 -and $_.Root -match '^[A-Za-z]:\\$' } | Sort-Object -Descending Free | Select-Object -First 1
|
||||
$dir = Join-Path $disk.Root "cad-print-$env:GITHUB_RUN_ID"
|
||||
"CARGO_TARGET_DIR=$dir" >> $env:GITHUB_ENV
|
||||
$env:CARGO_TARGET_DIR = $dir
|
||||
cargo metadata --format-version 1 > "$env:RUNNER_TEMP/cad-graph.json"
|
||||
- name: Run media mapping and conservative margins tests
|
||||
shell: bash
|
||||
run: |
|
||||
set -eo pipefail
|
||||
cargo test --locked -p cadcraft-io --lib winprint::tests | tee cad-results.txt
|
||||
grep -E 'driver_papers_become_a_device.*ok' cad-results.txt
|
||||
grep -E 'a_borderless_variant_shares_one_entry_with_printable_margins.*ok' cad-results.txt
|
||||
- name: Query a Windows virtual printer through the app
|
||||
shell: pwsh
|
||||
run: |
|
||||
Start-Service Spooler
|
||||
$driver = 'Microsoft Print To PDF'
|
||||
$queue = Get-Printer | Where-Object DriverName -eq $driver | Select-Object -First 1
|
||||
if (!$queue) {
|
||||
if (!(Get-PrinterDriver -Name $driver -ErrorAction SilentlyContinue)) {
|
||||
$feature = Get-WindowsOptionalFeature -Online -FeatureName Printing-PrintToPDFServices-Features -ErrorAction SilentlyContinue
|
||||
if ($feature -and $feature.State -ne 'Enabled') { Enable-WindowsOptionalFeature -Online -FeatureName $feature.FeatureName -NoRestart | Out-Host }
|
||||
Add-PrinterDriver -Name $driver -ErrorAction Stop
|
||||
}
|
||||
$name = "CadCraft catalog $env:GITHUB_RUN_ID"
|
||||
Add-Printer -Name $name -DriverName $driver -PortName 'PORTPROMPT:' -ErrorAction Stop
|
||||
$queue = Get-Printer -Name $name
|
||||
}
|
||||
$env:CADCRAFT_TEST_QUEUE = $queue.Name
|
||||
Get-PrintConfiguration -PrinterName $queue.Name | Format-List PaperSize,Color,DuplexingMode
|
||||
cargo test --locked -p cadcraft-io --test hosted_catalog -- --nocapture
|
||||
Generated
+971
-5
File diff suppressed because it is too large
Load Diff
@@ -45,6 +45,9 @@ craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
clap_complete = "4.6.11"
|
||||
clap_mangen = { version = "0.3.3", features = ["env"] }
|
||||
# Printing a plot's PDF on a Windows printer (the spooler's list and the job), from
|
||||
# craft-libs (pinned at its own revision; craft-print does not depend on craft-pdf).
|
||||
craft-print = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9e4d53d6b093591a3b24ad950592caf81c702e5a" }
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
|
||||
@@ -56,6 +56,17 @@ fn install_io() {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
|
||||
// System printers, as in the app: CUPS on macOS and Linux, the spooler on Windows.
|
||||
#[cfg(unix)]
|
||||
cadcraft_engine::cmd::plotters::set_system_printers(cadcraft_engine::cmd::plotters::SystemPrinters {
|
||||
list: cadcraft_io::cups::printers,
|
||||
print: |j| cadcraft_io::cups::print(j.printer, j.paper_key, j.size_mm, j.copies, j.title, j.pdf),
|
||||
});
|
||||
#[cfg(windows)]
|
||||
cadcraft_engine::cmd::plotters::set_system_printers(cadcraft_engine::cmd::plotters::SystemPrinters {
|
||||
list: cadcraft_io::winprint::printers,
|
||||
print: |j| cadcraft_io::winprint::print(j.printer, j.paper, j.copies, j.title, j.pdf),
|
||||
});
|
||||
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
|
||||
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
|
||||
@@ -238,7 +238,7 @@ fn plotter_settings_outside_the_roots_are_refused() {
|
||||
let device = cadcraft_engine::doc::PlotterConfig {
|
||||
name: "Office".into(),
|
||||
description: "not the agent's".into(),
|
||||
papers: vec![cadcraft_engine::doc::DevicePaper { name: "A4".into(), width: 210.0, height: 297.0, margins: [5.0; 4] }],
|
||||
papers: vec![cadcraft_engine::doc::DevicePaper { native_key: None, name: "A4".into(), width: 210.0, height: 297.0, margins: [5.0; 4] }],
|
||||
..Default::default()
|
||||
};
|
||||
let file = settings.join("Office.plotter.json");
|
||||
|
||||
@@ -194,6 +194,18 @@ pub fn install_io() {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
|
||||
// System printers: CUPS on macOS and Linux.
|
||||
#[cfg(unix)]
|
||||
cadcraft_engine::cmd::plotters::set_system_printers(cadcraft_engine::cmd::plotters::SystemPrinters {
|
||||
list: cadcraft_io::cups::printers,
|
||||
print: |j| cadcraft_io::cups::print(j.printer, j.paper_key, j.size_mm, j.copies, j.title, j.pdf),
|
||||
});
|
||||
// System printers: the Windows spooler.
|
||||
#[cfg(windows)]
|
||||
cadcraft_engine::cmd::plotters::set_system_printers(cadcraft_engine::cmd::plotters::SystemPrinters {
|
||||
list: cadcraft_io::winprint::printers,
|
||||
print: |j| cadcraft_io::winprint::print(j.printer, j.paper, j.copies, j.title, j.pdf),
|
||||
});
|
||||
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
|
||||
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
|
||||
@@ -64,6 +64,9 @@ pub enum Orientation {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct DevicePaper {
|
||||
/// Native media identifier, retained exactly for system-printer submission.
|
||||
#[serde(skip)]
|
||||
pub native_key: Option<String>,
|
||||
pub name: String,
|
||||
pub width: f64,
|
||||
pub height: f64,
|
||||
@@ -72,7 +75,7 @@ pub struct DevicePaper {
|
||||
|
||||
impl Default for DevicePaper {
|
||||
fn default() -> Self {
|
||||
DevicePaper { name: String::new(), width: 210.0, height: 297.0, margins: [0.0; 4] }
|
||||
DevicePaper { native_key: None, name: String::new(), width: 210.0, height: 297.0, margins: [0.0; 4] }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,9 +122,17 @@ pub struct PlotterConfig {
|
||||
/// Name of the paper chosen when a page setup switches to this device.
|
||||
pub default_paper: String,
|
||||
pub papers: Vec<DevicePaper>,
|
||||
/// A printer of the operating system (listed by the host, never read from or written to a
|
||||
/// file): a plot to it is a PDF the host prints rather than a file.
|
||||
#[serde(skip)]
|
||||
pub system: bool,
|
||||
/// With `system`: the operating system's default printer (never in a file either).
|
||||
#[serde(skip)]
|
||||
pub system_default: bool,
|
||||
}
|
||||
|
||||
impl Default for PlotterConfig {
|
||||
/// An unnamed PDF device at 300 dpi, landscape, with no papers: a user device before its settings are filled in.
|
||||
fn default() -> Self {
|
||||
PlotterConfig {
|
||||
name: String::new(),
|
||||
@@ -131,6 +142,8 @@ impl Default for PlotterConfig {
|
||||
orientation: Orientation::Landscape,
|
||||
default_paper: String::new(),
|
||||
papers: Vec::new(),
|
||||
system: false,
|
||||
system_default: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -145,6 +158,13 @@ fn key(s: &str) -> String {
|
||||
s.chars().filter(|c| !c.is_whitespace() && *c != '_' && *c != '-').collect::<String>().to_ascii_lowercase()
|
||||
}
|
||||
|
||||
/// What tells a paper's name apart from the other papers of a device once it is sanitized
|
||||
/// ([`PlotterConfig::sanitized`], [`PlotterConfig::paper`]): two names with the same key are one
|
||||
/// paper, and the second is dropped. Empty for a name no lookup finds.
|
||||
pub fn paper_name_key(name: &str) -> String {
|
||||
key(&clean_name(name))
|
||||
}
|
||||
|
||||
impl PlotterConfig {
|
||||
/// The configuration with hostile values fixed: a clean name and description, resolution
|
||||
/// 50..=2400 dpi, at most [`MAX_DEVICE_PAPERS`] sanitized papers with unique names, and a
|
||||
@@ -221,6 +241,46 @@ pub fn plotter_file_name(name: &str) -> Option<String> {
|
||||
(!base.is_empty()).then(|| format!("{base}{PLOTTER_FILE_EXT}"))
|
||||
}
|
||||
|
||||
/// Fill the `{name}` fields of a plot stamp in one pass over `template`, so a value is never
|
||||
/// filled again: a layout named `Detail {paper}` stays as it is. `{{` stands for a literal `{`;
|
||||
/// other text and fields not in `fields` are copied. A stamp is filled in steps (the command
|
||||
/// knows the drawing and the device, the plotter each sheet's layout, paper and scale): before
|
||||
/// the `last` step a value's braces are doubled and `{{` is kept, so a later step neither fills
|
||||
/// a value nor loses a literal brace; the `last` step turns `{{` into `{`.
|
||||
pub fn fill_stamp(template: &str, fields: &[(&str, &str)], last: bool) -> String {
|
||||
let mut out = String::with_capacity(template.len());
|
||||
let mut rest = template;
|
||||
while let Some(i) = rest.find('{') {
|
||||
out.push_str(&rest[..i]);
|
||||
rest = &rest[i..];
|
||||
if let Some(after) = rest.strip_prefix("{{") {
|
||||
out.push_str(if last { "{" } else { "{{" });
|
||||
rest = after;
|
||||
continue;
|
||||
}
|
||||
let field = fields.iter().find_map(|(name, value)| {
|
||||
let after = rest.strip_prefix('{')?.strip_prefix(*name)?.strip_prefix('}')?;
|
||||
Some((*value, after))
|
||||
});
|
||||
match field {
|
||||
Some((value, after)) => {
|
||||
if last {
|
||||
out.push_str(value);
|
||||
} else {
|
||||
out.push_str(&value.replace('{', "{{"));
|
||||
}
|
||||
rest = after;
|
||||
}
|
||||
None => {
|
||||
out.push('{');
|
||||
rest = &rest[1..];
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -233,9 +293,9 @@ mod tests {
|
||||
resolution: 1_000_000,
|
||||
default_paper: "nope".into(),
|
||||
papers: vec![
|
||||
DevicePaper { name: "A3 borderless".into(), width: 420.0, height: 297.0, margins: [0.0; 4] },
|
||||
DevicePaper { native_key: None, name: "A3 borderless".into(), width: 420.0, height: 297.0, margins: [0.0; 4] },
|
||||
DevicePaper { name: "a3-BORDERLESS".into(), ..DevicePaper::default() },
|
||||
DevicePaper { name: String::new(), width: f64::NAN, height: 1e12, margins: [f64::INFINITY, 9e9, -1.0, 5.0] },
|
||||
DevicePaper { native_key: None, name: String::new(), width: f64::NAN, height: 1e12, margins: [f64::INFINITY, 9e9, -1.0, 5.0] },
|
||||
],
|
||||
..PlotterConfig::default()
|
||||
};
|
||||
@@ -249,7 +309,8 @@ mod tests {
|
||||
assert_eq!(back.papers[1].margins, [0.0, 1000.0, 0.0, 5.0], "hostile margins clamped");
|
||||
let wide = DevicePaper { margins: [150.0, 0.0, 100.0, 0.0], ..DevicePaper::default() }.sanitized();
|
||||
assert_eq!(wide.margins, [0.0; 4], "margins wider than the paper are dropped");
|
||||
let turned = DevicePaper { name: "Banner".into(), width: 400.0, height: 200.0, margins: [150.0, 0.0, 150.0, 0.0] }.sanitized();
|
||||
let turned =
|
||||
DevicePaper { native_key: None, name: "Banner".into(), width: 400.0, height: 200.0, margins: [150.0, 0.0, 150.0, 0.0] }.sanitized();
|
||||
assert_eq!((turned.width, turned.height), (200.0, 400.0), "portrait");
|
||||
assert_eq!(turned.margins, [0.0, 150.0, 0.0, 150.0], "margins turn with the sheet");
|
||||
assert!(back.paper("a3 BORDERLESS").is_some());
|
||||
@@ -259,4 +320,16 @@ mod tests {
|
||||
assert_eq!(plotter_file_name("../a/b:c").as_deref(), Some("___a_b_c.plotter.json"));
|
||||
assert_eq!(plotter_file_name(" "), None);
|
||||
}
|
||||
|
||||
/// Stamp fields are filled in one pass: a value that looks like a field is copied as it is,
|
||||
/// through every step, and `{{` is a literal brace (#2171 review).
|
||||
#[test]
|
||||
fn stamp_fields_are_filled_once() {
|
||||
let sheet = |t: &str| fill_stamp(t, &[("layout", "Detail {paper}"), ("paper", "A4"), ("scale", "1:50")], true);
|
||||
assert_eq!(sheet("{layout} · {paper}"), "Detail {paper} · A4");
|
||||
assert_eq!(sheet("{{paper}} {scale} {other} {"), "{paper}} 1:50 {other} {");
|
||||
// The command's step first: a drawing named like a field stays so in the sheet's step.
|
||||
let cmd = fill_stamp("{drawing}, {layout}, {{x}", &[("drawing", "Plan {layout}.dwg")], false);
|
||||
assert_eq!(sheet(&cmd), "Plan {layout}.dwg, Detail {paper}, {x}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("preview", "Plot Preview", run_preview)
|
||||
.menu(&["File", "Plot Preview"])
|
||||
.alias(&["pre"])
|
||||
.params("{layout?: current|\"Model\", paper?, landscape?, fit?, scale?, lineweights?, plotTransparency?, width?: pixels (default 1200)} → {data: base64 PNG, width, height, layout, paper}")
|
||||
.params("{layout?: current|\"Model\", paper?, landscape?, fit?, scale?, lineweights?, plotTransparency?, width?: pixels (default 1200)} → {data: base64 PNG, width, height, layout, paper} (no plot stamp)")
|
||||
.noundo(),
|
||||
CommandSpec::new("publish", "Batch Publish...", run_publish)
|
||||
.menu(&["File", "Batch Publish..."])
|
||||
@@ -428,6 +428,9 @@ fn plot_scale(b: &Bounds2, sheet: &Sheet, fit: bool, scale: Option<f64>) -> f64
|
||||
if s.is_finite() && s > 0.0 { s } else { 1.0 }
|
||||
}
|
||||
|
||||
/// PREVIEW: a PNG of the sheet the parameters (or the layout's page setup) describe: the drawing
|
||||
/// as it plots, without a plot stamp (PREVIEW takes none; the Plot dialog's preview of a stamped
|
||||
/// PDF or PNG plot is a PLOT and shows it).
|
||||
fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let space = plot_space("preview", s, p)?;
|
||||
let d = s.doc()?;
|
||||
@@ -467,6 +470,10 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Curves are flattened to about half a pixel.
|
||||
let est = plot_scale(&saved.window.unwrap_or_else(|| d.extents(&space)), &sheet, fit, scale);
|
||||
let tol = 0.5 / (px_per_paper_unit * est);
|
||||
// The plot style table the sheet plots with (the `plotStyleTable` option, else its page setup's),
|
||||
// so the preview shows the printed colours, screening and lineweights.
|
||||
let style_name = str_param(p, "plotStyleTable").map_or_else(|| page.plot_style_table.clone(), str::to_string);
|
||||
let plot_style_table = cadcraft_doc::plot_style_table(d, &style_name).map(std::sync::Arc::new);
|
||||
let ropts = cadcraft_render::Options {
|
||||
tolerance: if tol.is_finite() && tol > 0.0 { tol } else { 0.01 },
|
||||
min_dash: 0.0,
|
||||
@@ -474,9 +481,10 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fill: true,
|
||||
lineweights,
|
||||
transparency,
|
||||
plot_style_table,
|
||||
..Default::default()
|
||||
};
|
||||
let list = cadcraft_render::build_plot(d, &space, &ropts);
|
||||
let mut list = cadcraft_render::build_plot(d, &space, &ropts);
|
||||
let b = saved.window.unwrap_or(list.bounds);
|
||||
// Paper point q shows drawing point (q - to) / k + from.
|
||||
let (from, k, to) = if saved.window.is_some() {
|
||||
@@ -488,6 +496,12 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
(Vec2::ZERO, plot_scale(&b, &sheet, fit, scale), Vec2::ZERO)
|
||||
};
|
||||
// A saved window shows only what is inside it, as the plotters plot it.
|
||||
if let Some(w) = saved.window.filter(|w| !w.is_empty()) {
|
||||
list.retain_within(&cadcraft_render::pen::plot_window_reach(&w, sheet.unit_mm * k));
|
||||
}
|
||||
// The table's line ends, joins and fill patterns at the plot scale, as the plotters draw them.
|
||||
cadcraft_render::pen::apply(&mut list, k * sheet.unit_mm);
|
||||
let world = Bounds2::new((Vec2::ZERO - to) / k + from, (sheet.size - to) / k + from);
|
||||
if ![world.min.x, world.min.y, world.max.x, world.max.y].iter().all(|v| v.is_finite()) {
|
||||
return Err(bad("preview", "the drawing is too large to preview at this scale"));
|
||||
@@ -511,7 +525,17 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(f64::from(x), f64::from(y))
|
||||
};
|
||||
let (min, max) = (sheet.printable.min, sheet.printable.max);
|
||||
let (a, b) = (screen(Vec2::new(min.x, max.y)), screen(Vec2::new(max.x, min.y)));
|
||||
let (mut a, mut b) = (screen(Vec2::new(min.x, max.y)), screen(Vec2::new(max.x, min.y)));
|
||||
// A saved window also cuts the plot at its own edges.
|
||||
if let Some(w) = saved.window.filter(|w| !w.is_empty()) {
|
||||
let (x0, y1) = view.to_screen(w.min);
|
||||
let (x1, y0) = view.to_screen(w.max);
|
||||
a = (a.0.max(f64::from(x0)), a.1.max(f64::from(y0)));
|
||||
b = (b.0.min(f64::from(x1)), b.1.min(f64::from(y1)));
|
||||
if a.0 >= b.0 || a.1 >= b.1 {
|
||||
(a, b) = ((0.0, 0.0), (0.0, 0.0));
|
||||
}
|
||||
}
|
||||
cadcraft_render::raster::blank_outside_pixels(&mut pm, a, b);
|
||||
}
|
||||
let png = cadcraft_render::raster::encode_png(&pm).ok_or_else(|| bad("preview", "rendering the preview failed"))?;
|
||||
|
||||
@@ -18,6 +18,7 @@ mod plotstyle;
|
||||
mod prompts;
|
||||
mod viewports;
|
||||
|
||||
/// The layout, page setup, viewport and plot commands.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("layout", "Layout", run_layout)
|
||||
@@ -82,13 +83,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("pagesetup", "Page Setup Manager...", run_pagesetup)
|
||||
.menu(&["File", "Page Setup Manager..."])
|
||||
.params(
|
||||
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|\"B4 (JIS)\"|\"Japanese Postcard\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
|
||||
"{layout?: current | layouts?: [names] | \"all\" (the same changes to each, in one step), device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|\"B4 (JIS)\"|\"Japanese Postcard\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
|
||||
),
|
||||
CommandSpec::new("plot", "Print...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "plot")?, "plot"))
|
||||
.menu(&["File", "Print..."])
|
||||
.key("Cmd+P")
|
||||
.alias(&["print"])
|
||||
.params("{path? (else returns base64 `data`), layout?: current|\"Model\", device?: \"CADCraft PDF\"|\"CADCraft PNG\"|\"CADCraft SVG\" | a plotter from PLOTTERMANAGER | \"None\" (default: a layout's page setup device; Model, or \"None\": no device, PDF; a device sets the output format and the papers), paper?: the device's paper (default: a layout keeps its page setup's; Model takes the device's default), landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)")
|
||||
.params("{path? (else returns base64 `data`), layout?: current|\"Model\", device?: \"CADCraft PDF\"|\"CADCraft PNG\"|\"CADCraft SVG\" | a plotter from PLOTTERMANAGER | a system printer (then printed: `copies`?: 1..999, and the reply is the `job`; with `path` the PDF is also written there first: plot to file) | \"None\" (default: a layout's page setup device; Model, or \"None\": no device, PDF; a device sets the output format and the papers), paper?: the device's paper (default: a layout keeps its page setup's; Model takes the device's default), landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]], stamp?: true | text (a plot stamp at the printable area's lower-left corner; `{drawing}`, `{layout}`, `{device}`, `{paper}` and `{scale}` are filled in; true: \"{drawing}, {layout}, {device}, {paper}, {scale}\")} (typed or from the menu: the Plot dialog)")
|
||||
.noundo(),
|
||||
CommandSpec::new("exportpdf", "Export to PDF...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "exportpdf")?, "exportpdf"))
|
||||
.menu(&["File", "Export to PDF..."])
|
||||
@@ -696,6 +697,7 @@ fn viewport_json(h: Handle, v: &Viewport) -> Value {
|
||||
/// VPLAYER's command-line prompts.
|
||||
mod vplayer;
|
||||
|
||||
/// VIEWPORT.SET: change the scale, centre, lock or frozen layers of the given viewports, or of the active one inside a viewport.
|
||||
fn run_viewport_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "viewport.set";
|
||||
let d = s.doc()?;
|
||||
@@ -792,7 +794,64 @@ fn run_viewport_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
// ---------- page setup ----------
|
||||
|
||||
/// PAGESETUP. With `layouts` (a list of layout names, or "all") the same changes are applied to
|
||||
/// each of those layouts, as one step: if any of them refuses a change, none is changed.
|
||||
fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "pagesetup";
|
||||
let Some(list) = p.get("layouts").filter(|v| !v.is_null()) else { return pagesetup_one(s, p) };
|
||||
if p.get("layout").is_some() {
|
||||
return Err(bad(cmd, "pass `layout` or `layouts`, not both"));
|
||||
}
|
||||
let names: Vec<String> = match list {
|
||||
Value::String(a) if a.eq_ignore_ascii_case("all") => {
|
||||
let mut ls: Vec<&Layout> = s.doc()?.layouts.iter().collect();
|
||||
ls.sort_by_key(|l| l.tab_order);
|
||||
ls.iter().map(|l| l.name.clone()).collect()
|
||||
}
|
||||
Value::Array(a) => {
|
||||
let mut names = Vec::new();
|
||||
for n in a {
|
||||
let n = n.as_str().ok_or_else(|| bad(cmd, "`layouts` must be a list of layout names or \"all\""))?;
|
||||
let n = layout_name(cmd, s.doc()?, n)?;
|
||||
if !names.contains(&n) {
|
||||
names.push(n);
|
||||
if names.len() > MAX_PLOT_SHEETS {
|
||||
return Err(bad(cmd, format!("at most {MAX_PLOT_SHEETS} layouts can be selected")));
|
||||
}
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
_ => return Err(bad(cmd, "`layouts` must be a list of layout names or \"all\"")),
|
||||
};
|
||||
if names.is_empty() || names.len() > MAX_PLOT_SHEETS {
|
||||
return Err(bad(cmd, format!("`layouts` needs between 1 and {MAX_PLOT_SHEETS} layouts")));
|
||||
}
|
||||
let before = s.state()?.doc.clone();
|
||||
let mut done = Vec::new();
|
||||
// The options for one layout, without the selection (which may be long), copied per layout.
|
||||
let mut base = p.clone();
|
||||
if let Some(o) = base.as_object_mut() {
|
||||
o.remove("layouts");
|
||||
}
|
||||
for n in &names {
|
||||
let mut one = base.clone();
|
||||
if let Some(o) = one.as_object_mut() {
|
||||
o.insert("layout".into(), json!(n));
|
||||
}
|
||||
match pagesetup_one(s, &one) {
|
||||
Ok(r) => done.push(r),
|
||||
Err(e) => {
|
||||
s.state_mut()?.doc = before;
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(json!({ "layouts": done }))
|
||||
}
|
||||
|
||||
/// PAGESETUP for one layout: the changes the options ask for, reported with the resulting page setup.
|
||||
fn pagesetup_one(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "pagesetup";
|
||||
let keys = [
|
||||
"device",
|
||||
@@ -992,14 +1051,20 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
{
|
||||
return Err(bad(cmd, "`layout` and `layouts` name different sheets; give only one of them"));
|
||||
}
|
||||
let is_image = p.get("output").and_then(Value::as_str).is_some_and(|o| o.eq_ignore_ascii_case("png") || o.eq_ignore_ascii_case("svg"));
|
||||
let printer = str_param(p, "printer").map(str::trim).filter(|n| !n.is_empty());
|
||||
if printer.is_some() && sheets.as_ref().is_some_and(|names| names.len() > 1) {
|
||||
return Err(bad(cmd, "several sheets require PDF file output; print one sheet at a time"));
|
||||
}
|
||||
// A printer takes the PDF, whatever `output` says.
|
||||
let is_image =
|
||||
printer.is_none() && p.get("output").and_then(Value::as_str).is_some_and(|o| o.eq_ignore_ascii_case("png") || o.eq_ignore_ascii_case("svg"));
|
||||
let space = match str_param(p, "layout") {
|
||||
Some(n) if n.eq_ignore_ascii_case("model") => Space::Model,
|
||||
Some(n) => Space::Paper(layout_name(cmd, s.doc()?, n)?),
|
||||
// A PNG or SVG holds one render: a single `layouts` entry names the sheet to draw (the PDF
|
||||
// path resolves `layouts` itself), not whatever space the session happens to show.
|
||||
// A single `layouts` entry names the sheet plotted, whatever the output: its plot area
|
||||
// and window are checked against it, not against whatever space the session shows.
|
||||
None => match sheets.as_deref() {
|
||||
Some([only]) if is_image => {
|
||||
Some([only]) => {
|
||||
if only.eq_ignore_ascii_case("model") {
|
||||
Space::Model
|
||||
} else {
|
||||
@@ -1026,6 +1091,14 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
return Err(bad(cmd, "`offset` must contain exactly two finite millimetre values within ±100000"));
|
||||
}
|
||||
}
|
||||
// A printer takes the PDF (before the output's own checks: an SVG asked for is not what prints).
|
||||
if printer.is_some()
|
||||
&& let Some(o) = opts.as_object_mut()
|
||||
{
|
||||
o.insert("output".into(), json!("pdf"));
|
||||
// Printers feed portrait sheets: a landscape plot comes already turned.
|
||||
o.insert("portraitMedia".into(), json!(true));
|
||||
}
|
||||
if matches!(space, Space::Model)
|
||||
&& opts.get("output").and_then(Value::as_str).is_some_and(|output| output.eq_ignore_ascii_case("svg"))
|
||||
&& opts.get("center").and_then(Value::as_bool) == Some(false)
|
||||
@@ -1050,12 +1123,53 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
if is_image && sheets.as_ref().is_some_and(|names| names.len() > 1) {
|
||||
return Err(bad(cmd, "`layouts` with several sheets needs PDF output; PNG and SVG hold one sheet, so plot each layout separately"));
|
||||
}
|
||||
if printer.is_some() {
|
||||
let d = s.doc()?;
|
||||
let page = space.layout().and_then(|name| d.layout(name)).map(|l| l.page.clone()).unwrap_or_else(|| cadcraft_render::paper::model_page(d));
|
||||
let (w, h) = match (opts.get("width").and_then(Value::as_f64), opts.get("height").and_then(Value::as_f64)) {
|
||||
(Some(w), Some(h)) if w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0 => (w, h),
|
||||
_ => (page.width_mm, page.height_mm),
|
||||
};
|
||||
opts["printerSheetSize"] = json!([w.clamp(1.0, cadcraft_doc::MAX_PAPER_MM), h.clamp(1.0, cadcraft_doc::MAX_PAPER_MM)]);
|
||||
}
|
||||
let (bytes, notes) = super::file::plot_noted(hook, s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?;
|
||||
let layout = match &sheets {
|
||||
Some(names) => names.first().cloned().unwrap_or_default(),
|
||||
None => space.tab_name().to_string(),
|
||||
};
|
||||
let pages = sheets.as_ref().map_or(1, Vec::len);
|
||||
if let Some(printer) = printer {
|
||||
// "Plot to file" too: the PDF is written first, so a file that can't be written stops
|
||||
// the plot before anything is printed (and a retry doesn't print it twice).
|
||||
let mut folder = None;
|
||||
let saved: Option<&str> = match str_param(p, "path") {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Some(path) => {
|
||||
crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?;
|
||||
folder = super::file::new_folder(path);
|
||||
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
Some(path)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let copies = p.get("copies").and_then(Value::as_u64).unwrap_or(1);
|
||||
let title = format!("{} - {layout}", s.state()?.title);
|
||||
let paper = str_param(p, "printerPaper").or_else(|| str_param(p, "paper")).unwrap_or_default();
|
||||
// The PDF is already on disk when the printer refuses the job: say so, with its path.
|
||||
let job = super::plotters::print_pdf(cmd, printer, paper, copies, &title, &bytes, &opts).map_err(|e| match (saved, e) {
|
||||
(Some(path), crate::EngineError::BadParams { cmd, msg }) => {
|
||||
crate::EngineError::BadParams { msg: format!("the PDF was saved to {path}, but printing failed: {msg}"), cmd }
|
||||
}
|
||||
(_, e) => e,
|
||||
})?;
|
||||
let mut r = json!({ "printer": printer, "job": job, "copies": copies.clamp(1, super::plotters::MAX_COPIES), "bytes": bytes.len(), "layout": layout, "pages": pages });
|
||||
if let (Some(path), Some(o)) = (saved, r.as_object_mut()) {
|
||||
o.insert("path".into(), json!(path));
|
||||
}
|
||||
super::file::report_new_folder(s, &mut r, folder);
|
||||
super::file::report_notes(s, &mut r, notes);
|
||||
return Ok(r);
|
||||
}
|
||||
let format = opts.get("output").and_then(Value::as_str).map(str::to_ascii_lowercase).unwrap_or_else(|| "pdf".into());
|
||||
match str_param(p, "path") {
|
||||
Some(_path) => {
|
||||
|
||||
@@ -603,6 +603,78 @@ fn plot_path_extension_picks_the_format_like_export() {
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
/// The paper name of layout `name`.
|
||||
fn paper_of(s: &Session, name: &str) -> String {
|
||||
s.doc().unwrap().layout(name).unwrap().page.paper.clone()
|
||||
}
|
||||
|
||||
/// One change given to several layouts is applied to each, as one undo step.
|
||||
#[test]
|
||||
fn pagesetup_applies_one_change_to_several_layouts_in_one_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("layout.new", &json!({"name": "Sheet 3"})).unwrap();
|
||||
let a1 = paper_of(&s, "Layout1");
|
||||
assert_ne!(a1, "ISO A3 (420.00 x 297.00 MM)", "the test needs another starting paper");
|
||||
let r = s.execute("pagesetup", &json!({"layouts": ["Layout1", "layout2"], "paper": "A3", "plotStyleTable": "monochrome.ctb"})).unwrap();
|
||||
assert_eq!(r["layouts"].as_array().map(Vec::len), Some(2));
|
||||
for n in ["Layout1", "Layout2"] {
|
||||
let page = &s.doc().unwrap().layout(n).unwrap().page;
|
||||
assert_eq!((page.width_mm.max(page.height_mm), page.plot_style_table.as_str()), (420.0, "monochrome.ctb"), "{n}");
|
||||
}
|
||||
assert_ne!(paper_of(&s, "Sheet 3"), paper_of(&s, "Layout1"), "a layout not named keeps its settings");
|
||||
// "all" takes every layout; one undo step reverts all of it.
|
||||
s.execute("pagesetup", &json!({"layouts": ["Layout1", "Layout2"], "landscape": true})).unwrap();
|
||||
let pages = |s: &Session| s.doc().unwrap().layouts.iter().map(|l| (l.name.clone(), l.page.clone())).collect::<Vec<_>>();
|
||||
let before = pages(&s);
|
||||
assert!(before.iter().filter(|(_, p)| p.landscape).count() >= 2);
|
||||
s.execute("pagesetup", &json!({"layouts": "all", "landscape": false})).unwrap();
|
||||
assert!(s.doc().unwrap().layouts.iter().all(|l| !l.page.landscape));
|
||||
s.undo().unwrap();
|
||||
assert_eq!(pages(&s), before, "the whole change is one undo step");
|
||||
}
|
||||
|
||||
/// A change a layout refuses leaves every layout as it was.
|
||||
#[test]
|
||||
fn pagesetup_for_several_layouts_is_all_or_nothing() {
|
||||
let mut s = Session::new();
|
||||
let before: Vec<String> = ["Layout1", "Layout2"].iter().map(|n| paper_of(&s, n)).collect();
|
||||
for p in [
|
||||
json!({"layouts": ["Layout1", "Nope"], "paper": "A3"}),
|
||||
json!({"layouts": ["Layout1", "Layout2"], "paper": "Z12"}),
|
||||
json!({"layouts": ["Layout1"], "layout": "Layout2", "paper": "A3"}),
|
||||
json!({"layouts": ["Model"], "paper": "A3"}),
|
||||
json!({"layouts": [], "paper": "A3"}),
|
||||
json!({"layouts": "Layout1", "paper": "A3"}),
|
||||
json!({"layouts": [7], "paper": "A3"}),
|
||||
] {
|
||||
assert!(s.execute("pagesetup", &p).is_err(), "{p}");
|
||||
}
|
||||
let after: Vec<String> = ["Layout1", "Layout2"].iter().map(|n| paper_of(&s, n)).collect();
|
||||
assert_eq!(before, after, "a refused change leaves every layout as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pagesetup_validates_the_whole_selection_after_duplicates() {
|
||||
let mut s = Session::new();
|
||||
let mut names = vec![json!("Layout1"); MAX_PLOT_SHEETS + 1];
|
||||
names.push(json!("Layout2"));
|
||||
let r = s.execute("pagesetup", &json!({ "layouts": names, "paper": "A3" })).unwrap();
|
||||
assert_eq!(r["layouts"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(paper_of(&s, "Layout1"), paper_of(&s, "Layout2"));
|
||||
names.push(json!(17));
|
||||
assert!(s.execute("pagesetup", &json!({ "layouts": names, "paper": "A4" })).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pagesetup_rolls_back_a_change_to_an_earlier_layout() {
|
||||
let mut s = Session::new();
|
||||
s.doc_mut().unwrap().layouts.iter_mut().find(|l| l.name == "Layout1").unwrap().page.plot_area = "window".into();
|
||||
let before: Vec<_> = s.doc().unwrap().layouts.iter().map(|l| l.page.clone()).collect();
|
||||
assert!(s.execute("pagesetup", &json!({ "layouts": ["Layout1", "Layout2"], "paper": "A3", "plotArea": "window" })).is_err());
|
||||
let after: Vec<_> = s.doc().unwrap().layouts.iter().map(|l| l.page.clone()).collect();
|
||||
assert_eq!(before, after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_set_frames_extents_away_from_origin() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -117,6 +117,7 @@ impl PlotterStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where user devices are kept: the settings folder natively, memory on the web (or what a host or test installed).
|
||||
fn store() -> PlotterStore {
|
||||
*STORE.get_or_init(|| {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -130,6 +131,268 @@ fn store() -> PlotterStore {
|
||||
})
|
||||
}
|
||||
|
||||
/// A plot for a system printer: the PDF the PDF plotter wrote, and how to print it.
|
||||
pub struct PrintJob<'a> {
|
||||
pub printer: &'a str,
|
||||
/// The paper's name as the printer's device lists it.
|
||||
pub paper: &'a str,
|
||||
pub paper_key: &'a str,
|
||||
/// Sheet dimensions used to render the PDF, in millimetres.
|
||||
pub size_mm: (f64, f64),
|
||||
pub copies: u32,
|
||||
pub title: &'a str,
|
||||
pub pdf: &'a [u8],
|
||||
}
|
||||
|
||||
/// The host's printers: `list` gives them as devices (`system` set), `print` sends a job and
|
||||
/// returns its id.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct SystemPrinters {
|
||||
pub list: fn() -> Vec<PlotterConfig>,
|
||||
pub print: fn(&PrintJob) -> std::result::Result<String, String>,
|
||||
}
|
||||
|
||||
static PRINTERS: OnceLock<SystemPrinters> = OnceLock::new();
|
||||
|
||||
/// Install the host's printers (first call wins). Without them only files are plotted.
|
||||
pub fn set_system_printers(p: SystemPrinters) {
|
||||
let _ = PRINTERS.set(p);
|
||||
}
|
||||
|
||||
/// Most copies of one print job.
|
||||
pub const MAX_COPIES: u64 = 999;
|
||||
|
||||
/// The system printers as last listed. Listing asks the system (CUPS can be slow, or hang), so
|
||||
/// it runs on a background thread and this never waits for it: it returns the last list, and
|
||||
/// starts listing again when there is none yet or it is a few seconds old. Until the first
|
||||
/// listing finishes there are none; [`system_printers_pending`] says one is under way.
|
||||
fn system_printers() -> Vec<PlotterConfig> {
|
||||
let Some(h) = PRINTERS.get() else { return Vec::new() };
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let mut c = printer_cache();
|
||||
// A listing that hangs (a driver that never answers) is given up after PRINTERS_WAIT:
|
||||
// a new one may start, and nothing waits for the old one any more.
|
||||
if !c.listing_live() && c.workers < MAX_LISTING_WORKERS && c.at.is_none_or(|at| at.elapsed() >= PRINTERS_TTL) {
|
||||
let started = std::time::Instant::now();
|
||||
c.listing = Some(started);
|
||||
c.workers += 1;
|
||||
let list = h.list;
|
||||
let spawned = std::thread::Builder::new().name("system-printers".into()).spawn(move || {
|
||||
let _worker = ListingWorker { started };
|
||||
let found: Vec<PlotterConfig> = list().into_iter().filter(|p| p.system && !is_builtin(&p.name)).collect();
|
||||
printer_cache().complete(started, found);
|
||||
});
|
||||
if spawned.is_err() {
|
||||
c.listing = None;
|
||||
c.workers = c.workers.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
c.list.clone()
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
(h.list)().into_iter().filter(|p| p.system && !is_builtin(&p.name)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a printer list is used before the system is asked again.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const PRINTERS_TTL: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// An expired driver call can remain blocked forever. Permit a replacement, but never let
|
||||
/// repeated refreshes or TTL retries accumulate an unbounded number of blocked threads.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_LISTING_WORKERS: usize = 2;
|
||||
|
||||
/// Return the worker slot on completion, even if a host's listing hook panics: a listing that
|
||||
/// ended without a list (the hook panicked) is no longer under way either, so nothing waits for
|
||||
/// it and Refresh can start another.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
struct ListingWorker {
|
||||
/// When the listing this worker runs started: its mark in [`PrinterCache::listing`].
|
||||
started: std::time::Instant,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Drop for ListingWorker {
|
||||
fn drop(&mut self) {
|
||||
printer_cache().worker_ended(self.started);
|
||||
}
|
||||
}
|
||||
|
||||
/// The last printer list, when it was made, and when a listing under way started.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[derive(Default)]
|
||||
struct PrinterCache {
|
||||
list: Vec<PlotterConfig>,
|
||||
at: Option<std::time::Instant>,
|
||||
listing: Option<std::time::Instant>,
|
||||
published: Option<std::time::Instant>,
|
||||
/// Running calls, including expired listings whose driver has not returned yet.
|
||||
workers: usize,
|
||||
/// A wait for a listing ran out (a driver that never answers): commands stop waiting until a
|
||||
/// listing finishes again.
|
||||
hung: bool,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl PrinterCache {
|
||||
fn complete(&mut self, started: std::time::Instant, found: Vec<PlotterConfig>) {
|
||||
if self.published.is_none_or(|published| started > published) {
|
||||
(self.list, self.at, self.hung, self.published) = (found, Some(std::time::Instant::now()), false, Some(started));
|
||||
}
|
||||
if self.listing == Some(started) {
|
||||
self.listing = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// A listing worker ended, with or without a list: its slot is free, and its listing (not a
|
||||
/// replacement started since) is no longer under way.
|
||||
fn worker_ended(&mut self, started: std::time::Instant) {
|
||||
self.workers = self.workers.saturating_sub(1);
|
||||
if self.listing == Some(started) {
|
||||
self.listing = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// A wait ran out: if the listing under way has itself run for [`PRINTERS_WAIT`], its driver
|
||||
/// doesn't answer and commands stop waiting for it. A listing started during the wait (after
|
||||
/// an older one expired) is younger and still gets its own wait.
|
||||
fn give_up(&mut self) {
|
||||
if self.listing.is_some_and(|t| t.elapsed() >= PRINTERS_WAIT) {
|
||||
self.hung = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a listing is under way and not yet given up (younger than [`PRINTERS_WAIT`]).
|
||||
fn listing_live(&self) -> bool {
|
||||
self.listing.is_some_and(|t| t.elapsed() < PRINTERS_WAIT)
|
||||
}
|
||||
}
|
||||
|
||||
/// The process-wide printer cache; a panic while it was held doesn't keep the printers away.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn printer_cache() -> std::sync::MutexGuard<'static, PrinterCache> {
|
||||
static CACHE: OnceLock<Mutex<PrinterCache>> = OnceLock::new();
|
||||
CACHE.get_or_init(Mutex::default).lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Ask the system for its printers again now (a printer was just installed or switched on):
|
||||
/// the next device list starts a new listing instead of using one a few seconds old. A listing
|
||||
/// under way is left to finish. Returns whether there are system printers in this build.
|
||||
pub fn refresh_system_printers() -> bool {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
if PRINTERS.get().is_none() {
|
||||
return false;
|
||||
}
|
||||
{
|
||||
let mut c = printer_cache();
|
||||
(c.at, c.hung) = (None, false);
|
||||
}
|
||||
let _ = system_printers();
|
||||
true
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
PRINTERS.get().is_some()
|
||||
}
|
||||
|
||||
/// Whether the system printers are being listed (a dialog showing devices redraws when it ends).
|
||||
pub fn system_printers_pending() -> bool {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
PRINTERS.get().is_some() && printer_cache().listing_live()
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
false
|
||||
}
|
||||
|
||||
/// The system printer called `name`, for a command that is about to use it: from the last list,
|
||||
/// else, while a listing is under way (the first one, or one started because the list is old),
|
||||
/// waiting for it up to [`PRINTERS_WAIT`], so a printer named before the first listing ended is
|
||||
/// still found. Only a command naming a device waits, never a dialog drawing its device list.
|
||||
fn system_printer(name: &str) -> Option<PlotterConfig> {
|
||||
let find = |list: Vec<PlotterConfig>| list.into_iter().find(|p| p.name.eq_ignore_ascii_case(name.trim()));
|
||||
if let Some(p) = find(system_printers()) {
|
||||
return Some(p);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
wait_for_printers();
|
||||
find(printer_cache().list.clone())
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
None
|
||||
}
|
||||
|
||||
/// Wait (up to [`PRINTERS_WAIT`]) for a system printer listing under way, starting one when the
|
||||
/// list is old: for commands that report the devices, not for dialogs drawing them.
|
||||
fn wait_for_printers() {
|
||||
let _ = system_printers();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
if printer_cache().hung {
|
||||
return;
|
||||
}
|
||||
let start = std::time::Instant::now();
|
||||
while system_printers_pending() && start.elapsed() < PRINTERS_WAIT {
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
// A listing still under way after the wait: given up only once it has run the full wait.
|
||||
printer_cache().give_up();
|
||||
}
|
||||
}
|
||||
|
||||
/// [`devices`] for a command reporting them: the system printers listed first, if that is
|
||||
/// under way.
|
||||
fn listed_devices() -> Vec<PlotterConfig> {
|
||||
wait_for_printers();
|
||||
devices()
|
||||
}
|
||||
|
||||
/// The device a command names (or a layout's page setup names, for a command about to plot):
|
||||
/// a built-in device at once; otherwise, once a system printer listing under way has ended (up
|
||||
/// to [`PRINTERS_WAIT`]), [`find_device`], so a printer is found and wins over a user device of
|
||||
/// the same name even on the first plot after the app starts. Dialogs never wait.
|
||||
fn named_device(name: &str) -> Option<PlotterConfig> {
|
||||
let n = name.trim();
|
||||
// No device ("" or "None", a page setup's usual one) needs no printer list.
|
||||
let none = n.is_empty() || n.eq_ignore_ascii_case("none");
|
||||
if !none && !BUILTIN.iter().any(|(b, _, _)| b.eq_ignore_ascii_case(n.strip_suffix(cadcraft_doc::PLOTTER_FILE_EXT).unwrap_or(n))) {
|
||||
wait_for_printers();
|
||||
}
|
||||
// One wait only: the printers as listed by now (a listing still under way after the wait
|
||||
// isn't waited for again here, nor by the unknown-device error).
|
||||
find_device(name)
|
||||
}
|
||||
|
||||
/// Longest a plot waits for the system printers to be listed.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const PRINTERS_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
|
||||
/// Print `pdf` on the system printer `printer`; returns the job id.
|
||||
pub(crate) fn print_pdf(cmd: &str, printer: &str, paper: &str, copies: u64, title: &str, pdf: &[u8], opts: &Value) -> Result<String> {
|
||||
let h = PRINTERS.get().ok_or_else(|| bad(cmd, "there are no system printers in this build"))?;
|
||||
let Some(dev) = system_printer(printer) else {
|
||||
return Err(bad(cmd, format!("unknown printer `{printer}`")));
|
||||
};
|
||||
let copies = copies.clamp(1, MAX_COPIES) as u32;
|
||||
(h.print)(&PrintJob {
|
||||
printer: &dev.name,
|
||||
paper,
|
||||
copies,
|
||||
title,
|
||||
pdf,
|
||||
paper_key: str_param(opts, "printerPaperKey").unwrap_or(paper),
|
||||
size_mm: (
|
||||
opts.get("printerSheetSize").and_then(|v| v.get(0)).and_then(Value::as_f64).unwrap_or(0.0),
|
||||
opts.get("printerSheetSize").and_then(|v| v.get(1)).and_then(Value::as_f64).unwrap_or(0.0),
|
||||
),
|
||||
})
|
||||
.map_err(|e| bad(cmd, format!("{}: {e}", dev.name)))
|
||||
}
|
||||
|
||||
/// Most user devices listed.
|
||||
const MAX_DEVICES: usize = 1000;
|
||||
|
||||
@@ -143,10 +406,11 @@ const BUILTIN: [(&str, PlotOutput, &str); 3] = [
|
||||
/// A page setup's "no device" name.
|
||||
const NO_DEVICE: &str = "None";
|
||||
|
||||
/// A built-in device writing `output` files on every standard paper, A4 by default.
|
||||
fn builtin(name: &str, output: PlotOutput, description: &str) -> PlotterConfig {
|
||||
let papers = cadcraft_render::PAPER_SIZES
|
||||
.iter()
|
||||
.map(|p| DevicePaper { name: p.name.into(), width: p.width_mm, height: p.height_mm, margins: p.margins_mm() })
|
||||
.map(|p| DevicePaper { native_key: None, name: p.name.into(), width: p.width_mm, height: p.height_mm, margins: p.margins_mm() })
|
||||
.collect();
|
||||
let default_paper = cadcraft_render::paper_size("A4").map(|p| p.name.to_string()).unwrap_or_default();
|
||||
PlotterConfig {
|
||||
@@ -157,6 +421,8 @@ fn builtin(name: &str, output: PlotOutput, description: &str) -> PlotterConfig {
|
||||
orientation: Orientation::Landscape,
|
||||
default_paper,
|
||||
papers,
|
||||
system: false,
|
||||
system_default: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,16 +449,20 @@ fn user_devices() -> Vec<PlotterConfig> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Every device: the built-in ones first, then the user's.
|
||||
/// Every device: the built-in ones first, then the system printers, then the user's.
|
||||
pub fn devices() -> Vec<PlotterConfig> {
|
||||
let mut v = builtins();
|
||||
v.extend(user_devices());
|
||||
let printers = system_printers();
|
||||
v.extend(user_devices().into_iter().filter(|u| !printers.iter().any(|p| p.name.eq_ignore_ascii_case(&u.name))));
|
||||
let at = BUILTIN.len();
|
||||
v.splice(at..at, printers);
|
||||
v
|
||||
}
|
||||
|
||||
/// Device names, built-in ones first.
|
||||
/// Device names, built-in ones first, for a command reporting them (it waits for a system
|
||||
/// printer listing under way).
|
||||
pub fn device_names() -> Vec<String> {
|
||||
devices().into_iter().map(|c| c.name).collect()
|
||||
listed_devices().into_iter().map(|c| c.name).collect()
|
||||
}
|
||||
|
||||
/// The device called `name` (any case; a `.plotter.json` suffix is ignored).
|
||||
@@ -205,14 +475,21 @@ pub fn find_device(name: &str) -> Option<PlotterConfig> {
|
||||
if let Some((b, o, d)) = BUILTIN.iter().find(|(b, _, _)| b.eq_ignore_ascii_case(n)) {
|
||||
return Some(builtin(b, *o, d));
|
||||
}
|
||||
if let Some(p) = system_printers().into_iter().find(|p| p.name.eq_ignore_ascii_case(n)) {
|
||||
return Some(p);
|
||||
}
|
||||
let st = store();
|
||||
let direct = cadcraft_doc::plotter_file_name(n).and_then(|f| PlotterConfig::from_file_text(&(st.read)(&f).ok()?).ok());
|
||||
direct.filter(|c| c.name.eq_ignore_ascii_case(n)).or_else(|| user_devices().into_iter().find(|c| c.name.eq_ignore_ascii_case(n)))
|
||||
}
|
||||
|
||||
/// The paper of `dev` called `name`, also by a standard size's short name (`A3`, `Letter`…).
|
||||
/// The paper of `dev` called `name`, also by a standard size's short name (`A3`, `Letter`…):
|
||||
/// either way round, so a layout's `ISO A4 (210.00 x 297.00 MM)` finds a printer's `A4`.
|
||||
fn device_paper<'a>(dev: &'a PlotterConfig, name: &str) -> Option<&'a DevicePaper> {
|
||||
dev.paper(name).or_else(|| dev.paper(cadcraft_render::paper_size(name)?.name))
|
||||
dev.paper(name).or_else(|| {
|
||||
let standard = cadcraft_render::paper_size(name)?.name;
|
||||
dev.paper(standard).or_else(|| dev.papers.iter().find(|p| cadcraft_render::paper_size(&p.name).is_some_and(|s| s.name == standard)))
|
||||
})
|
||||
}
|
||||
|
||||
/// A paper's stored portrait margins on the landscape sheet: the sheet's axes swap, so left and
|
||||
@@ -227,6 +504,7 @@ pub(crate) fn portrait_margins([l, b, r, t]: [f64; 4]) -> [f64; 4] {
|
||||
[b, r, t, l]
|
||||
}
|
||||
|
||||
/// Put a device paper's name, size and printable area on a page setup.
|
||||
fn set_paper(page: &mut PageSetup, p: &DevicePaper) {
|
||||
page.paper = p.name.clone();
|
||||
page.width_mm = p.width;
|
||||
@@ -236,8 +514,11 @@ fn set_paper(page: &mut PageSetup, p: &DevicePaper) {
|
||||
page.margins_mm = if page.landscape { landscape_margins(p.margins) } else { p.margins };
|
||||
}
|
||||
|
||||
/// The error for a device name not found, with the devices as listed now: it never waits for a
|
||||
/// printer listing (the lookup that failed already did).
|
||||
fn unknown_device(cmd: &str, name: &str) -> EngineError {
|
||||
bad(cmd, format!("unknown plotter `{name}` (devices: {})", device_names().join(", ")))
|
||||
let names: Vec<String> = devices().into_iter().map(|c| c.name).collect();
|
||||
bad(cmd, format!("unknown plotter `{name}` (devices: {})", names.join(", ")))
|
||||
}
|
||||
|
||||
/// PAGESETUP's `device` and the device's papers. Sets `page.device` from `device` (`"None"`:
|
||||
@@ -247,6 +528,15 @@ fn unknown_device(cmd: &str, name: &str) -> EngineError {
|
||||
/// `landscape` is given. Returns whether the paper was set here (else `paper`, if any, is a
|
||||
/// standard size for the caller to look up).
|
||||
pub fn page_device(cmd: &str, p: &Value, page: &mut PageSetup) -> Result<bool> {
|
||||
page_device_with(cmd, p, page, named_device)
|
||||
}
|
||||
|
||||
/// Apply a dialog's device change from the cached list without waiting for drivers.
|
||||
pub fn page_device_now(cmd: &str, p: &Value, page: &mut PageSetup) -> Result<bool> {
|
||||
page_device_with(cmd, p, page, find_device)
|
||||
}
|
||||
|
||||
fn page_device_with(cmd: &str, p: &Value, page: &mut PageSetup, lookup: fn(&str) -> Option<PlotterConfig>) -> Result<bool> {
|
||||
let given = match p.get("device") {
|
||||
Some(v) => Some(v.as_str().ok_or_else(|| bad(cmd, "`device` must be a plotter name"))?.trim()),
|
||||
None => None,
|
||||
@@ -256,7 +546,10 @@ pub fn page_device(cmd: &str, p: &Value, page: &mut PageSetup) -> Result<bool> {
|
||||
page.device = NO_DEVICE.into();
|
||||
return Ok(false);
|
||||
}
|
||||
Some(n) => Some(find_device(n).ok_or_else(|| unknown_device(cmd, n))?),
|
||||
Some(n) => Some(lookup(n).ok_or_else(|| unknown_device(cmd, n))?),
|
||||
// A paper asked for on the page's own device: that device's papers, so a printer saved in
|
||||
// the page setup is waited for as one named would be (a command only; a dialog never waits).
|
||||
None if p.get("paper").is_some() => lookup(&page.device),
|
||||
None => find_device(&page.device),
|
||||
};
|
||||
let Some(dev) = dev else { return Ok(false) };
|
||||
@@ -300,7 +593,14 @@ fn path_output(path: &str) -> Option<PlotOutput> {
|
||||
/// without a device are unchanged.
|
||||
pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
let given = str_param(p, "device").map(str::trim);
|
||||
let layout = match str_param(p, "layout") {
|
||||
// A single `layouts` entry is the sheet plotted, as `layout` names it: its page setup gives
|
||||
// the device and the paper. Several sheets plot each with its own page setup, into one PDF.
|
||||
let single = match p.get("layouts") {
|
||||
Some(Value::Array(a)) if a.len() == 1 => a.first().and_then(Value::as_str),
|
||||
_ => None,
|
||||
};
|
||||
let several = single.is_none() && p.get("layouts").is_some_and(|v| !v.is_null());
|
||||
let layout = match str_param(p, "layout").or(single) {
|
||||
Some(n) if n.eq_ignore_ascii_case("model") => None,
|
||||
Some(n) => s.doc()?.layout(n).map(|l| l.page.clone()),
|
||||
None => match s.space().layout() {
|
||||
@@ -310,13 +610,40 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
};
|
||||
let dev = match given {
|
||||
Some(n) if n.is_empty() || n.eq_ignore_ascii_case(NO_DEVICE) => None,
|
||||
Some(n) => Some(find_device(n).ok_or_else(|| unknown_device(cmd, n))?),
|
||||
None => layout.as_ref().and_then(|pg| find_device(&pg.device)),
|
||||
Some(n) => Some(named_device(n).ok_or_else(|| unknown_device(cmd, n))?),
|
||||
// The shown layout's device is not the sheets' device: it would send a set of sheets
|
||||
// meant for a PDF file to that layout's printer.
|
||||
None if several => None,
|
||||
None => layout.as_ref().and_then(|pg| named_device(&pg.device)),
|
||||
};
|
||||
let mut out = if p.is_object() { p.clone() } else { json!({}) };
|
||||
// Only a system printer chosen as the device prints (below): a `printer` passed with the
|
||||
// call is dropped, so EXPORTPDF always writes the PDF and PLOT without one writes its file.
|
||||
if let Some(o) = out.as_object_mut() {
|
||||
o.remove("printer");
|
||||
o.remove("printerPaper");
|
||||
o.remove("printerPaperKey");
|
||||
}
|
||||
// The plot stamp names the drawing and the device here; the plotter fills in each sheet's
|
||||
// layout, paper and scale.
|
||||
// Without a device, the built-in one for the format the path or `output` asks for.
|
||||
let by_path = if cmd == "exportpdf" { None } else { str_param(p, "path").and_then(path_output) };
|
||||
let no_device = if cmd == "exportpdf" {
|
||||
PlotOutput::Pdf
|
||||
} else {
|
||||
by_path.or_else(|| p.get("output").and_then(Value::as_str).and_then(PlotOutput::parse)).unwrap_or(PlotOutput::Pdf)
|
||||
};
|
||||
let builtin_name = BUILTIN.iter().find(|(_, o, _)| *o == no_device).map_or("CADCraft PDF", |(n, _, _)| *n);
|
||||
let device_name = dev.as_ref().map_or_else(|| builtin_name.to_string(), |d| d.name.clone());
|
||||
let text = stamp(s, p, cmd, &device_name)?;
|
||||
if let Some(o) = out.as_object_mut() {
|
||||
o.remove("stamp");
|
||||
if let Some(text) = text {
|
||||
o.insert("stamp".into(), json!(text));
|
||||
}
|
||||
}
|
||||
// The path's extension names the format, like EXPORT, unless a device is given; a given
|
||||
// device that writes another format is refused. EXPORTPDF always writes PDF.
|
||||
let by_path = if cmd == "exportpdf" { None } else { str_param(p, "path").and_then(path_output) };
|
||||
// A path whose extension names no format (or has none) would hold a PDF under that name:
|
||||
// refuse it, as EXPORT does, unless `output` or a device says what to write.
|
||||
if cmd == "plot"
|
||||
@@ -364,6 +691,20 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
None if layout.is_none() => dev.default_paper(),
|
||||
None => None,
|
||||
};
|
||||
// A system printer gets the plotter's PDF, on the paper by its name on that printer
|
||||
// (EXPORTPDF still writes the PDF).
|
||||
if dev.system && cmd == "plot" && output == PlotOutput::Pdf {
|
||||
o.insert("printer".into(), json!(dev.name));
|
||||
let on = paper.map(|pp| pp.name.clone()).or_else(|| layout.as_ref().map(|pg| pg.paper.clone())).unwrap_or_default();
|
||||
if let Some(key) = paper.or_else(|| device_paper(&dev, &on)).and_then(|pp| pp.native_key.as_ref()) {
|
||||
o.insert("printerPaperKey".into(), json!(key));
|
||||
}
|
||||
o.insert("printerPaper".into(), json!(on));
|
||||
}
|
||||
// The stamp names the device's paper (the plotter only sees its size).
|
||||
if let (Some(pp), Some(Value::String(t))) = (paper, o.get_mut("stamp")) {
|
||||
*t = cadcraft_doc::fill_stamp(t, &[("paper", &pp.name)], false);
|
||||
}
|
||||
if let Some(pp) = paper {
|
||||
o.remove("paper");
|
||||
o.insert("width".into(), json!(pp.width));
|
||||
@@ -383,6 +724,27 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What PLOT's default plot stamp says: the drawing, the sheet, the device, the paper and the
|
||||
/// scale.
|
||||
pub const DEFAULT_STAMP: &str = "{drawing}, {layout}, {device}, {paper}, {scale}";
|
||||
|
||||
/// The plot stamp of a plot: `stamp: true` stamps [`DEFAULT_STAMP`], a text stamps that text
|
||||
/// (with `{drawing}` and `{device}` filled in here, `{layout}`, `{paper}` and `{scale}` by the
|
||||
/// plotter for each sheet), `false` or none doesn't stamp.
|
||||
fn stamp(s: &Session, p: &Value, cmd: &str, device: &str) -> Result<Option<String>> {
|
||||
let template = match p.get("stamp") {
|
||||
None | Some(Value::Null) | Some(Value::Bool(false)) => return Ok(None),
|
||||
Some(Value::Bool(true)) => DEFAULT_STAMP.to_string(),
|
||||
Some(Value::String(t)) => t.clone(),
|
||||
Some(_) => return Err(bad(cmd, "`stamp` must be true, false or the stamp's text")),
|
||||
};
|
||||
let drawing = s.state()?.title.clone();
|
||||
// One pass, and not the last: the plotter fills each sheet's fields, never these values.
|
||||
let template: String = template.chars().filter(|c| !c.is_control()).take(300).collect();
|
||||
let text = cadcraft_doc::fill_stamp(&template, &[("drawing", &drawing), ("device", device)], false);
|
||||
Ok((!text.trim().is_empty()).then_some(text))
|
||||
}
|
||||
|
||||
/// Whether a plot draws transparency, as PLOTTRANSPARENCYOVERRIDE decides: 0 never, 2 always,
|
||||
/// otherwise the plot's `plotTransparency` (`None` when it has none: the page setup decides).
|
||||
pub(crate) fn plot_transparency(s: &Session, p: &Value) -> Option<bool> {
|
||||
@@ -456,6 +818,7 @@ impl Interactive for PlotWindowM {
|
||||
|
||||
// ---------- PLOTTERMANAGER ----------
|
||||
|
||||
/// PLOTWINDOW and PLOTTERMANAGER.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("plotwindow", "Plot Window", run_plotwindow)
|
||||
@@ -466,7 +829,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("plottermanager", "Plotter Manager...", run_plottermanager)
|
||||
.menu(&["File", "Plotter Manager..."])
|
||||
.params(
|
||||
"{action?: list (default)|get|new|set|delete|load|save, name?: device, from?: device to copy (new), output?: pdf|png|svg, description?, resolution?: dpi, orientation?: portrait|landscape, defaultPaper?, paper?: {name, width, height (mm), margins?: [l,b,r,t] mm} (set: add or replace), removePaper?: name (set), text? (load), path? (save: native only; without it returns `text`)} (typed: option prompts)",
|
||||
"{action?: list (default)|get|new|set|delete|load|save|refresh (ask the system for its printers again), name?: device, from?: device to copy (new), output?: pdf|png|svg, description?, resolution?: dpi, orientation?: portrait|landscape, defaultPaper?, paper?: {name, width, height (mm), margins?: [l,b,r,t] mm} (set: add or replace), removePaper?: name (set), text? (load), path? (save: native only; without it returns `text`)} (typed: option prompts)",
|
||||
)
|
||||
.enabled(always)
|
||||
.noundo()
|
||||
@@ -479,12 +842,22 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// A system printer is the system's: PLOTTERMANAGER doesn't change or delete it (a user file
|
||||
/// by its name would only be hidden behind it). A copy made with action `new` can be edited.
|
||||
fn system_read_only(cmd: &str, name: &str) -> EngineError {
|
||||
bad(cmd, format!("`{name}` is a system printer: make a copy with action new, from `{name}`"))
|
||||
}
|
||||
|
||||
/// A device as PLOTTERMANAGER reports it: name, description, output, whether it is built in, a
|
||||
/// system printer or the default one, how many papers it has and its default paper.
|
||||
fn summary(c: &PlotterConfig) -> Value {
|
||||
json!({
|
||||
"name": c.name,
|
||||
"description": c.description,
|
||||
"output": c.output.as_str(),
|
||||
"builtin": is_builtin(&c.name),
|
||||
"system": c.system,
|
||||
"default": c.system_default,
|
||||
"papers": c.papers.len(),
|
||||
"defaultPaper": c.default_paper,
|
||||
})
|
||||
@@ -492,7 +865,9 @@ fn summary(c: &PlotterConfig) -> Value {
|
||||
|
||||
fn device_name(cmd: &str, p: &Value) -> Result<String> {
|
||||
let n = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "`name` (a plotter name) is required"))?;
|
||||
Ok(n.chars().take(cadcraft_doc::MAX_PLOTTER_NAME).collect())
|
||||
// The whole name: a system printer's may be longer than a user device's, and a shortened
|
||||
// one could name another printer. `new` shortens the name it gives a user device.
|
||||
Ok(n.to_string())
|
||||
}
|
||||
|
||||
/// Write a user device to the store.
|
||||
@@ -568,7 +943,7 @@ fn edit_device(cmd: &str, c: &mut PlotterConfig, p: &Value) -> Result<()> {
|
||||
}
|
||||
}
|
||||
};
|
||||
let new = DevicePaper { name: name.into(), width: w, height: h, margins };
|
||||
let new = DevicePaper { native_key: None, name: name.into(), width: w, height: h, margins };
|
||||
match existing.and_then(|e| c.papers.iter().position(|x| x.name == e.name)) {
|
||||
Some(i) => {
|
||||
if let Some(slot) = c.papers.get_mut(i) {
|
||||
@@ -586,7 +961,8 @@ fn edit_device(cmd: &str, c: &mut PlotterConfig, p: &Value) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// List, read, change, load, export and delete plotter configurations; any file is held to the automation roots.
|
||||
/// PLOTTERMANAGER: list, refresh, read, change, load, export and delete plotter configurations
|
||||
/// (user devices only; system printers are listed, not edited); any file is held to the automation roots.
|
||||
fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "plottermanager";
|
||||
let action = str_param(p, "action").unwrap_or("list").trim().to_ascii_lowercase();
|
||||
@@ -596,19 +972,25 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if crate::file_access::current().is_some() {
|
||||
(store().list)().map_err(|e| bad(cmd, e))?;
|
||||
}
|
||||
Ok(json!({ "devices": devices().iter().map(summary).collect::<Vec<_>>() }))
|
||||
Ok(json!({ "devices": listed_devices().iter().map(summary).collect::<Vec<_>>() }))
|
||||
}
|
||||
// The system's printers asked for again; `list` (or the Plot dialog) shows them once
|
||||
// that listing ends.
|
||||
"refresh" => Ok(json!({ "printers": refresh_system_printers(), "pending": system_printers_pending() })),
|
||||
"get" => {
|
||||
let n = device_name(cmd, p)?;
|
||||
let c = find_device(&n).ok_or_else(|| unknown_device(cmd, &n))?;
|
||||
// A printer named before the first listing ended is waited for, as PLOT does.
|
||||
let c = named_device(&n).ok_or_else(|| unknown_device(cmd, &n))?;
|
||||
let mut v = serde_json::to_value(&c).unwrap_or(Value::Null);
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert("builtin".into(), json!(is_builtin(&c.name)));
|
||||
o.insert("system".into(), json!(c.system));
|
||||
o.insert("default".into(), json!(c.system_default));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
"new" => {
|
||||
let name = device_name(cmd, p)?;
|
||||
let name: String = device_name(cmd, p)?.chars().take(cadcraft_doc::MAX_PLOTTER_NAME).collect();
|
||||
if find_device(&name).is_some() {
|
||||
return Err(bad(cmd, format!("plotter `{name}` already exists")));
|
||||
}
|
||||
@@ -617,7 +999,9 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(cmd, format!("a plotter file `{file}` already exists")));
|
||||
}
|
||||
let mut c = match str_param(p, "from") {
|
||||
Some(f) => find_device(f).ok_or_else(|| unknown_device(cmd, f))?,
|
||||
// A system printer named before the first listing ended is waited for, as `get`
|
||||
// does: it wins over a user device of the same name whenever the copy is made.
|
||||
Some(f) => named_device(f).ok_or_else(|| unknown_device(cmd, f))?,
|
||||
None => {
|
||||
// A copy of the built-in device for the output: the standard papers.
|
||||
let output = match p.get("output") {
|
||||
@@ -630,6 +1014,8 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
c.name = name;
|
||||
c.description = String::new();
|
||||
// A copy of a system printer is a user device: it is neither the spooler's nor its default.
|
||||
(c.system, c.system_default) = (false, false);
|
||||
edit_device(cmd, &mut c, p)?;
|
||||
let c = c.sanitized();
|
||||
save_device(cmd, &c)?;
|
||||
@@ -641,6 +1027,9 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(cmd, format!("`{name}` is built in: make a copy with action new, from `{name}`")));
|
||||
}
|
||||
let mut c = find_device(&name).ok_or_else(|| unknown_device(cmd, &name))?;
|
||||
if c.system {
|
||||
return Err(system_read_only(cmd, &c.name));
|
||||
}
|
||||
edit_device(cmd, &mut c, p)?;
|
||||
if c.papers.is_empty() {
|
||||
return Err(bad(cmd, "a plotter needs at least one paper"));
|
||||
@@ -655,6 +1044,9 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(cmd, format!("`{name}` is built in and can't be deleted")));
|
||||
}
|
||||
let c = find_device(&name).ok_or_else(|| unknown_device(cmd, &name))?;
|
||||
if c.system {
|
||||
return Err(system_read_only(cmd, &c.name));
|
||||
}
|
||||
let file = cadcraft_doc::plotter_file_name(&c.name).ok_or_else(|| bad(cmd, "the plotter has no name"))?;
|
||||
(store().delete)(&file).map_err(|e| bad(cmd, e))?;
|
||||
Ok(json!({ "deleted": c.name }))
|
||||
@@ -676,7 +1068,7 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
"save" => {
|
||||
let name = device_name(cmd, p)?;
|
||||
let text = find_device(&name).ok_or_else(|| unknown_device(cmd, &name))?.to_file_text();
|
||||
let text = named_device(&name).ok_or_else(|| unknown_device(cmd, &name))?.to_file_text();
|
||||
match str_param(p, "path") {
|
||||
None => Ok(json!({ "name": name, "text": text })),
|
||||
Some(_path) => {
|
||||
@@ -691,7 +1083,7 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
other => Err(bad(cmd, format!("unknown action `{other}` (list, get, new, set, delete, load, save)"))),
|
||||
other => Err(bad(cmd, format!("unknown action `{other}` (list, get, new, set, delete, load, save, refresh)"))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -749,6 +1141,7 @@ impl Interactive for PlotterManagerM {
|
||||
Stage::PaperSize(..) => Prompt::new("Enter the paper width,height in mm", Accept::TEXT),
|
||||
}
|
||||
}
|
||||
/// The next answer at the PLOTTERMANAGER prompts: an option, then the names and sizes it asks for.
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
if i == Input::Cancel {
|
||||
return Ok(Step::Cancel);
|
||||
@@ -767,9 +1160,17 @@ impl Interactive for PlotterManagerM {
|
||||
"Delete" => Stage::Delete,
|
||||
"Paper" => Stage::PaperDevice,
|
||||
_ => {
|
||||
for c in devices() {
|
||||
let kind = if is_builtin(&c.name) { "built-in" } else { "user" };
|
||||
s.echo(format!("{} ({}, {kind}, {} paper sizes)", c.name, c.output.as_str().to_uppercase(), c.papers.len()));
|
||||
for c in listed_devices() {
|
||||
let kind = if is_builtin(&c.name) {
|
||||
"built-in"
|
||||
} else if c.system {
|
||||
"system printer"
|
||||
} else {
|
||||
"user"
|
||||
};
|
||||
// The system's default printer says so, as in the dialogs' device lists.
|
||||
let default = if c.system_default { " (default)" } else { "" };
|
||||
s.echo(format!("{}{default} ({}, {kind}, {} paper sizes)", c.name, c.output.as_str().to_uppercase(), c.papers.len()));
|
||||
}
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
@@ -802,6 +1203,9 @@ impl Interactive for PlotterManagerM {
|
||||
if is_builtin(&c.name) {
|
||||
return Err(EngineError::Other(format!("\"{}\" is built in; create a new plotter first.", c.name)));
|
||||
}
|
||||
if c.system {
|
||||
return Err(system_read_only("plottermanager", &c.name));
|
||||
}
|
||||
self.stage = Stage::PaperName(c.name);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
@@ -823,3 +1227,57 @@ impl Interactive for PlotterManagerM {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod cache_regressions {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn replacement_listings_do_not_starve_completed_results_or_overwrite_newer_lists() {
|
||||
let older = std::time::Instant::now();
|
||||
let newer = older + std::time::Duration::from_secs(1);
|
||||
let mut cache = PrinterCache { listing: Some(newer), ..Default::default() };
|
||||
let device = |name: &str| PlotterConfig { name: name.into(), ..Default::default() };
|
||||
cache.complete(older, vec![device("older")]);
|
||||
assert_eq!(cache.list[0].name, "older");
|
||||
assert_eq!(cache.listing, Some(newer), "the replacement is still pending");
|
||||
cache.complete(newer, vec![device("newer")]);
|
||||
cache.complete(older, vec![device("stale")]);
|
||||
assert_eq!(cache.list[0].name, "newer");
|
||||
assert!(cache.listing.is_none());
|
||||
}
|
||||
|
||||
/// A wait that runs out gives up only on a listing that has run the full wait itself, not on
|
||||
/// one that started during the wait (#2171 review).
|
||||
#[test]
|
||||
fn only_a_listing_that_ran_the_full_wait_is_given_up() {
|
||||
let now = std::time::Instant::now();
|
||||
let mut fresh = PrinterCache { listing: Some(now), ..PrinterCache::default() };
|
||||
fresh.give_up();
|
||||
assert!(!fresh.hung, "a listing that just started is not hung");
|
||||
let Some(old) = now.checked_sub(PRINTERS_WAIT + std::time::Duration::from_millis(50)) else { return };
|
||||
let mut stuck = PrinterCache { listing: Some(old), ..PrinterCache::default() };
|
||||
stuck.give_up();
|
||||
assert!(stuck.hung, "a listing past the wait is given up");
|
||||
let mut idle = PrinterCache::default();
|
||||
idle.give_up();
|
||||
assert!(!idle.hung, "no listing, nothing to give up");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod paper_regressions {
|
||||
use super::*;
|
||||
|
||||
/// A layout's paper by its standard full name finds the printer's paper listed by the short
|
||||
/// name (`A4`), so the job carries the printer's own key (#2171 review).
|
||||
#[test]
|
||||
fn a_standard_full_name_finds_a_printers_short_name() {
|
||||
let a4 = DevicePaper { native_key: Some("A4".into()), name: "A4".into(), width: 210.0, height: 297.0, margins: [5.0; 4] };
|
||||
let dev = PlotterConfig { name: "Office".into(), papers: vec![a4], system: true, ..PlotterConfig::default() };
|
||||
let full = cadcraft_render::paper_size("A4").map(|p| p.name).unwrap_or_default();
|
||||
assert_ne!(full, "A4", "the standard size has a longer name");
|
||||
assert_eq!(device_paper(&dev, full).and_then(|p| p.native_key.as_deref()), Some("A4"));
|
||||
assert!(device_paper(&dev, "A3").is_none(), "another size is not found");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,3 +67,19 @@ fn a_device_that_disagrees_with_the_extension_is_refused() {
|
||||
assert_eq!(magic(&none), b"<svg ");
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
/// The Plot dialog's payload for several sheets (`layouts` with no device) writes one PDF with a
|
||||
/// page per sheet; without `device`, the shown layout's device (here a PNG one) is not used either.
|
||||
#[test]
|
||||
fn several_sheets_write_one_pdf_page_each_whatever_the_shown_layouts_device() {
|
||||
let mut s = session();
|
||||
s.execute("pagesetup", &json!({ "layout": "Layout1", "device": "CADCraft PNG" })).unwrap();
|
||||
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
|
||||
for p in [json!({ "layouts": ["Layout1", "Layout2"], "device": "None" }), json!({ "layouts": ["Layout1", "Layout2"] })] {
|
||||
let r = s.execute("plot", &p).unwrap();
|
||||
assert_eq!(r["pages"], 2, "{p}");
|
||||
let pdf = cadcraft_engine::cmd::file::base64_decode(r["data"].as_str().unwrap()).unwrap();
|
||||
let (_, pages) = cadcraft_io::pdf_read::read(&pdf, &cadcraft_io::pdf_read::PdfImportOptions::default()).unwrap();
|
||||
assert_eq!(pages, 2, "{p}: one PDF page per sheet");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,3 +47,15 @@ fn bad_sheet_lists_are_errors() {
|
||||
assert!(s.execute("exportpdf", &p).is_err(), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A single `layouts` entry plotted to PDF from the Model tab is that sheet, as `layout` names
|
||||
/// it: its plot area is the layout's, not model space's (#2171 review).
|
||||
#[test]
|
||||
fn a_single_sheet_pdf_from_the_model_tab_plots_that_layout() {
|
||||
let mut s = session();
|
||||
assert!(s.space().layout().is_none(), "the Model tab is shown");
|
||||
let r = s.execute("plot", &json!({"layouts": ["Sheet B"], "device": "CADCraft PDF", "plotArea": "layout"})).unwrap();
|
||||
assert_eq!(r["layout"], "Sheet B");
|
||||
let by_name = s.execute("plot", &json!({"layout": "Sheet B", "device": "CADCraft PDF", "plotArea": "layout"})).unwrap();
|
||||
assert_eq!(by_name["layout"], r["layout"]);
|
||||
}
|
||||
|
||||
@@ -342,6 +342,13 @@ fn plotwindow_picks_both_corners_with_ortho_on() {
|
||||
assert!(c.near(Vec2::new(10.0, 0.0), 1e-9), "ortho keeps the line horizontal: {c:?}");
|
||||
}
|
||||
|
||||
/// A misspelled action reports refresh along with the other supported actions.
|
||||
#[test]
|
||||
fn unknown_plottermanager_action_reports_refresh() {
|
||||
let error = Session::new().execute("plottermanager", &json!({ "action": "refersh" })).unwrap_err().to_string();
|
||||
assert!(error.contains("refresh"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paper_margins_are_checked_against_their_own_axis() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
//! System printers (#670 step 2): the host lists them as devices, and PLOT to one sends the
|
||||
//! plotter's PDF to the host instead of returning a file.
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
use cadcraft_doc::{DevicePaper, Drawing, PlotterConfig, Space};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{IoHooks, set_io};
|
||||
use cadcraft_engine::cmd::plotters::{PlotterStore, PrintJob, SystemPrinters, set_plotter_store, set_system_printers};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The jobs printed: printer, paper, copies, title, the options the plot hook got.
|
||||
static JOBS: Mutex<Vec<(String, String, u32, String, Value)>> = Mutex::new(Vec::new());
|
||||
/// The tests share [`JOBS`]: one at a time.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// A plotter that returns its options as the file, so a print job shows what was plotted.
|
||||
fn echo_plot(_: &Drawing, _: &Space, opts: &Value) -> Result<Vec<u8>, String> {
|
||||
Ok(opts.to_string().into_bytes())
|
||||
}
|
||||
|
||||
/// How many times the system was asked for its printers.
|
||||
static LISTINGS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
|
||||
/// One system printer, a roll plotter with Letter and a 24 in roll, as the system would list it.
|
||||
fn printers() -> Vec<PlotterConfig> {
|
||||
LISTINGS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
vec![PlotterConfig {
|
||||
name: "Office_T120".into(),
|
||||
description: "HP DesignJet T120".into(),
|
||||
default_paper: "Letter".into(),
|
||||
papers: vec![
|
||||
DevicePaper { native_key: None, name: "Letter".into(), width: 215.9, height: 279.4, margins: [5.0; 4] },
|
||||
DevicePaper { native_key: None, name: "Roll 24 in".into(), width: 609.6, height: 914.4, margins: [5.0; 4] },
|
||||
],
|
||||
system: true,
|
||||
system_default: true,
|
||||
..PlotterConfig::default()
|
||||
}]
|
||||
}
|
||||
|
||||
/// Records each print job (printer, paper, copies, title and plotted options) and answers with a job id.
|
||||
fn print(j: &PrintJob) -> Result<String, String> {
|
||||
// Thirteen copies stand for a printer that refuses the job.
|
||||
if j.copies == 13 {
|
||||
return Err("the printer refused the job".into());
|
||||
}
|
||||
let opts = serde_json::from_slice(j.pdf).map_err(|e| e.to_string())?;
|
||||
JOBS.lock().unwrap().push((j.printer.into(), j.paper.into(), j.copies, j.title.into(), opts));
|
||||
Ok(format!("{}-7", j.printer))
|
||||
}
|
||||
|
||||
/// A session with the stand-in printers and plotter installed and a line to plot.
|
||||
fn session() -> Session {
|
||||
set_plotter_store(PlotterStore::memory());
|
||||
set_system_printers(SystemPrinters { list: printers, print });
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Err("no writer in this test".into()), plot: Some(echo_plot) });
|
||||
// Wait for the first listing, so every test starts with the printer listed, whichever runs first.
|
||||
cadcraft_engine::cmd::plotters::page_device("pagesetup", &json!({ "device": "Office_T120" }), &mut cadcraft_doc::PageSetup::default()).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.cmdline("line 0,0 100,0").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// System printers are listed after the built-in devices, and PLOT on one sends the job with its paper, copies and title.
|
||||
#[test]
|
||||
fn system_printers_are_devices_and_plot_prints_on_them() {
|
||||
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut s = session();
|
||||
JOBS.lock().unwrap().clear();
|
||||
let r = s.execute("plottermanager", &json!({})).unwrap();
|
||||
let names: Vec<&str> = r["devices"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["CADCraft PDF", "CADCraft PNG", "CADCraft SVG", "Office_T120"]);
|
||||
|
||||
let r = s.execute("plot", &json!({ "layout": "Model", "device": "office_t120", "paper": "Roll 24 in", "copies": 2 })).unwrap();
|
||||
assert_eq!(r["job"], "Office_T120-7");
|
||||
assert_eq!(r["copies"], 2);
|
||||
assert!(r.get("data").is_none());
|
||||
let (printer, paper, copies, title, opts) = JOBS.lock().unwrap().pop().unwrap();
|
||||
assert_eq!((printer.as_str(), paper.as_str(), copies), ("Office_T120", "Roll 24 in", 2));
|
||||
assert!(title.ends_with(" - Model"), "{title}");
|
||||
// The plotter wrote a PDF on the printer's paper.
|
||||
assert_eq!(opts["output"], "pdf");
|
||||
assert_eq!(opts["width"], 609.6);
|
||||
|
||||
// EXPORTPDF to the same device still returns the PDF.
|
||||
let r = s.execute("exportpdf", &json!({ "layout": "Model", "device": "Office_T120" })).unwrap();
|
||||
assert!(r.get("data").is_some() && r.get("job").is_none());
|
||||
assert!(JOBS.lock().unwrap().is_empty());
|
||||
|
||||
// A printer takes the PDF before the output's own checks: an SVG with a model-space offset
|
||||
// (which SVG refuses) still prints.
|
||||
let r = s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "output": "svg", "center": false, "offset": [5, 5] })).unwrap();
|
||||
assert_eq!(r["job"], "Office_T120-7", "{r}");
|
||||
assert_eq!(JOBS.lock().unwrap().pop().unwrap().4["output"], "pdf");
|
||||
|
||||
// A `printer` passed with the call never prints: EXPORTPDF and PLOT without a printer
|
||||
// device write their file.
|
||||
let r = s.execute("exportpdf", &json!({ "layout": "Model", "printer": "Office_T120" })).unwrap();
|
||||
assert!(r.get("data").is_some() && r.get("job").is_none());
|
||||
let r = s.execute("plot", &json!({ "layout": "Model", "device": "CADCraft PDF", "printer": "Office_T120" })).unwrap();
|
||||
assert!(r.get("job").is_none(), "{r}");
|
||||
assert!(JOBS.lock().unwrap().is_empty());
|
||||
|
||||
// An unknown printer is refused, and copies are bounded.
|
||||
assert!(s.execute("plot", &json!({ "layout": "Model", "device": "Nope" })).is_err());
|
||||
let r = s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "copies": 100000 })).unwrap();
|
||||
assert_eq!(r["copies"], 999);
|
||||
assert_eq!(JOBS.lock().unwrap().pop().unwrap().2, 999);
|
||||
|
||||
// A system printer is listed as one, and PLOTTERMANAGER neither edits nor deletes it.
|
||||
let list = s.execute("plottermanager", &json!({ "action": "list" })).unwrap();
|
||||
let t120 = list["devices"].as_array().unwrap().iter().find(|d| d["name"] == "Office_T120").cloned().unwrap();
|
||||
assert_eq!(t120["system"], true);
|
||||
assert_eq!(t120["default"], true, "the system's default printer says so");
|
||||
let set = s.execute("plottermanager", &json!({ "action": "set", "name": "Office_T120", "description": "x" }));
|
||||
assert!(set.unwrap_err().to_string().contains("system printer"));
|
||||
assert!(s.execute("plottermanager", &json!({ "action": "delete", "name": "Office_T120" })).is_err());
|
||||
}
|
||||
|
||||
/// Plot to file with a printer: the PDF is written first, then printed; a file that can't be
|
||||
/// written stops the plot before anything prints (a missing folder is made, see
|
||||
/// `plot_to_file_creates_missing_folders_before_submitting`). REFRESH asks for the printers again.
|
||||
#[test]
|
||||
fn plot_to_file_and_print_and_refresh_the_printers() {
|
||||
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut s = session();
|
||||
JOBS.lock().unwrap().clear();
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-plot-to-file-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("plan.pdf");
|
||||
let path_s = path.to_string_lossy().to_string();
|
||||
let r = s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "path": path_s })).unwrap();
|
||||
assert_eq!(r["job"], "Office_T120-7");
|
||||
assert_eq!(r["path"], path_s.as_str());
|
||||
let written = std::fs::read(&path).unwrap();
|
||||
let (printer, _, _, _, opts) = JOBS.lock().unwrap().pop().unwrap();
|
||||
assert_eq!(printer, "Office_T120");
|
||||
// The file is the PDF that was printed.
|
||||
assert_eq!(serde_json::from_slice::<Value>(&written).unwrap(), opts);
|
||||
|
||||
// A folder can't be made under a file: the PDF can't be written, so nothing is printed.
|
||||
let bad = path.join("plan.pdf");
|
||||
let e = s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "path": bad.to_string_lossy() })).unwrap_err();
|
||||
assert!(e.to_string().contains("plan.pdf"), "{e}");
|
||||
assert!(JOBS.lock().unwrap().is_empty(), "nothing printed when the file couldn't be written");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
// The plot stamp: the drawing and the device named here, the rest left to the plotter.
|
||||
s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "stamp": true })).unwrap();
|
||||
let stamp = JOBS.lock().unwrap().pop().unwrap().4["stamp"].as_str().unwrap().to_string();
|
||||
let title = s.state().unwrap().title.clone();
|
||||
assert_eq!(stamp, format!("{title}, {{layout}}, Office_T120, Letter, {{scale}}"), "the device's paper by its name");
|
||||
let r = s.execute("exportpdf", &json!({ "layout": "Model", "stamp": "Checked {device}\u{7}" })).unwrap();
|
||||
let opts: Value = serde_json::from_slice(&cadcraft_engine::cmd::file::base64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap();
|
||||
assert_eq!(opts["stamp"], "Checked CADCraft PDF");
|
||||
// Without a device, the stamp names the built-in device of the format written.
|
||||
let r = s.execute("plot", &json!({ "layout": "Model", "output": "png", "stamp": "Checked {device}" })).unwrap();
|
||||
let opts: Value = serde_json::from_slice(&cadcraft_engine::cmd::file::base64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap();
|
||||
assert_eq!(opts["stamp"], "Checked CADCraft PNG");
|
||||
let r = s.execute("exportpdf", &json!({ "layout": "Model", "stamp": false })).unwrap();
|
||||
let opts: Value = serde_json::from_slice(&cadcraft_engine::cmd::file::base64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap();
|
||||
assert!(opts.get("stamp").is_none());
|
||||
assert!(s.execute("plot", &json!({ "layout": "Model", "stamp": 5 })).is_err());
|
||||
|
||||
let asked = LISTINGS.load(std::sync::atomic::Ordering::SeqCst);
|
||||
let r = s.execute("plottermanager", &json!({ "action": "refresh" })).unwrap();
|
||||
assert_eq!(r["printers"], true);
|
||||
// A refresh asks the system again rather than answering from the cache (bounded wait for
|
||||
// the background listing).
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while LISTINGS.load(std::sync::atomic::Ordering::SeqCst) == asked && std::time::Instant::now() < deadline {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(LISTINGS.load(std::sync::atomic::Ordering::SeqCst) > asked, "refresh listed the printers again");
|
||||
let list = s.execute("plottermanager", &json!({ "action": "list" })).unwrap();
|
||||
assert!(list["devices"].as_array().unwrap().iter().any(|d| d["name"] == "Office_T120"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inferred_image_output_does_not_submit_to_a_layouts_printer() {
|
||||
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut s = session();
|
||||
JOBS.lock().unwrap().clear();
|
||||
s.execute("pagesetup", &json!({ "layout": "Layout1", "device": "Office_T120" })).unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-image-no-print-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for output in ["png", "svg"] {
|
||||
let path = dir.join(format!("plan.{output}"));
|
||||
let r = s.execute("plot", &json!({ "layout": "Layout1", "path": path })).unwrap();
|
||||
let options: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
|
||||
assert_eq!(options["output"], output);
|
||||
assert!(r.get("job").is_none());
|
||||
assert!(JOBS.lock().unwrap().is_empty());
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plot_to_file_creates_missing_folders_before_submitting() {
|
||||
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut s = session();
|
||||
JOBS.lock().unwrap().clear();
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-new-plot-folder-{}", std::process::id()));
|
||||
let path = dir.join("nested/plan.pdf");
|
||||
let r = s.execute("plot", &json!({ "device": "Office_T120", "path": path })).unwrap();
|
||||
assert!(path.is_file());
|
||||
assert!(r.get("createdFolder").is_some(), "{r}");
|
||||
// Take the job: the tests share JOBS and run in any order.
|
||||
assert!(JOBS.lock().unwrap().pop().is_some());
|
||||
assert!(JOBS.lock().unwrap().is_empty());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_sheet_printer_plot_is_refused_before_writing_or_submitting() {
|
||||
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut s = session();
|
||||
JOBS.lock().unwrap().clear();
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-multi-print-{}", std::process::id()));
|
||||
let path = dir.join("new-folder/plot.pdf");
|
||||
let e = s.execute("plot", &json!({ "layouts": ["Layout1", "Layout2"], "device": "Office_T120", "path": path })).unwrap_err();
|
||||
assert!(e.to_string().contains("several sheets"), "{e}");
|
||||
assert!(!dir.exists());
|
||||
assert!(JOBS.lock().unwrap().is_empty());
|
||||
let r = s.execute("plot", &json!({ "layouts": ["Layout1", "Layout2"], "device": "CADCraft PDF" })).unwrap();
|
||||
assert_eq!(r["pages"], 2);
|
||||
s.execute("plot", &json!({ "layouts": ["Layout1"], "device": "Office_T120", "paper": "Letter" })).unwrap();
|
||||
assert_eq!(JOBS.lock().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printer_pdf_file_output_obeys_the_write_root_before_creating_folders() {
|
||||
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut s = session();
|
||||
JOBS.lock().unwrap().clear();
|
||||
let base = std::env::temp_dir().join(format!("cadcraft-printer-root-{}", std::process::id()));
|
||||
let allowed = base.join("allowed");
|
||||
std::fs::create_dir_all(&allowed).unwrap();
|
||||
let roots = cadcraft_engine::file_access::AutomationRoots::new(None, Some(&allowed)).unwrap();
|
||||
cadcraft_engine::file_access::confine(roots.as_ref(), || {
|
||||
let outside = base.join("outside/new/plot.pdf");
|
||||
let e = s.execute("plot", &json!({ "device": "Office_T120", "path": outside })).unwrap_err();
|
||||
assert!(e.to_string().contains("outside the write root"), "{e}");
|
||||
assert!(!base.join("outside").exists());
|
||||
assert!(JOBS.lock().unwrap().is_empty());
|
||||
let inside = allowed.join("new/plot.pdf");
|
||||
s.execute("plot", &json!({ "device": "Office_T120", "path": inside })).unwrap();
|
||||
assert!(inside.is_file());
|
||||
assert_eq!(JOBS.lock().unwrap().len(), 1);
|
||||
});
|
||||
std::fs::remove_dir_all(base).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_of_a_system_printer_is_a_user_device() {
|
||||
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut s = session();
|
||||
let made = s.execute("plottermanager", &json!({ "action": "new", "name": "My T120", "from": "Office_T120" })).unwrap();
|
||||
let got = s.execute("plottermanager", &json!({ "action": "get", "name": "My T120" })).unwrap();
|
||||
for r in [&made, &got] {
|
||||
assert_eq!((&r["system"], &r["default"]), (&json!(false), &json!(false)), "{r}");
|
||||
}
|
||||
let printer = s.execute("plottermanager", &json!({ "action": "get", "name": "Office_T120" })).unwrap();
|
||||
assert_eq!((&printer["system"], &printer["default"]), (&json!(true), &json!(true)), "the printer keeps its flags");
|
||||
// The device store is shared by the tests: leave it as it was.
|
||||
s.execute("plottermanager", &json!({ "action": "delete", "name": "My T120" })).unwrap();
|
||||
}
|
||||
|
||||
/// The typed device list (`-PLOTTERMANAGER ?`) marks the system's default printer, as the
|
||||
/// dialogs' device lists do (#2171 review).
|
||||
#[test]
|
||||
fn the_typed_device_list_marks_the_default_printer() {
|
||||
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut s = session();
|
||||
s.cmdline("-plottermanager").unwrap();
|
||||
s.cmdline("?").unwrap();
|
||||
let line = s.log.iter().rev().find(|l| l.starts_with("Office_T120")).cloned().unwrap_or_default();
|
||||
assert!(line.starts_with("Office_T120 (default)"), "{line:?}");
|
||||
let builtin = s.log.iter().rev().find(|l| l.starts_with("CADCraft PDF")).cloned().unwrap_or_default();
|
||||
assert!(!builtin.contains("(default)"), "{builtin:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_print_job_reports_the_pdf_already_saved() {
|
||||
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut s = session();
|
||||
JOBS.lock().unwrap().clear();
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-refused-print-{}", std::process::id()));
|
||||
let path = dir.join("plot.pdf");
|
||||
let e = s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "path": path, "copies": 13 })).unwrap_err().to_string();
|
||||
assert!(path.is_file());
|
||||
assert!(e.contains(path.to_str().unwrap()) && e.contains("refused"), "{e}");
|
||||
let e = s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "copies": 13 })).unwrap_err().to_string();
|
||||
assert!(!e.contains("saved"), "nothing was saved without a path: {e}");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// The sheets a call names decide the device: one `layouts` entry plots with that layout's own
|
||||
/// page setup, as `layout` would; several sheets without a device go to the PDF file, never to
|
||||
/// the printer of the layout shown.
|
||||
#[test]
|
||||
fn the_sheets_named_decide_the_device_not_the_layout_shown() {
|
||||
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut s = session();
|
||||
JOBS.lock().unwrap().clear();
|
||||
s.execute("pagesetup", &json!({ "layout": "Layout1", "device": "Office_T120" })).unwrap();
|
||||
s.execute("pagesetup", &json!({ "layout": "Layout2", "device": "CADCraft PDF", "paper": "A3" })).unwrap();
|
||||
// Layout1 (on the printer) shown, Layout2 (the PDF device) named: a file, no print job.
|
||||
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
|
||||
let r = s.execute("plot", &json!({ "layouts": ["Layout2"] })).unwrap();
|
||||
assert!(r.get("job").is_none() && r.get("data").is_some(), "{r}");
|
||||
assert!(JOBS.lock().unwrap().is_empty());
|
||||
// Layout2 shown, Layout1 named: Layout1's printer, on Layout1's paper.
|
||||
s.execute("layout.set", &json!({ "name": "Layout2" })).unwrap();
|
||||
let r = s.execute("plot", &json!({ "layouts": ["Layout1"] })).unwrap();
|
||||
assert_eq!(r["job"], "Office_T120-7", "{r}");
|
||||
let (printer, paper, ..) = JOBS.lock().unwrap().pop().unwrap();
|
||||
assert_eq!((printer.as_str(), paper.as_str()), ("Office_T120", "Letter"));
|
||||
// Several sheets with the printer's layout shown: one PDF of both, nothing printed.
|
||||
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
|
||||
let r = s.execute("plot", &json!({ "layouts": ["Layout1", "Layout2"] })).unwrap();
|
||||
assert_eq!(r["pages"], 2);
|
||||
assert!(r.get("job").is_none() && r.get("data").is_some(), "{r}");
|
||||
assert!(JOBS.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// A drawing named like a stamp field is stamped by its name: the command fills its fields in one
|
||||
/// pass, and the plotter's step leaves the filled values alone (#2171 review).
|
||||
#[test]
|
||||
fn a_drawing_named_like_a_field_keeps_its_name_in_the_stamp() {
|
||||
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut s = session();
|
||||
JOBS.lock().unwrap().clear();
|
||||
s.state_mut().unwrap().title = "Plan {paper} {layout}.dwg".into();
|
||||
s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "stamp": "{drawing} | {paper}" })).unwrap();
|
||||
let stamp = JOBS.lock().unwrap().pop().unwrap().4["stamp"].as_str().unwrap().to_string();
|
||||
let sheet = cadcraft_doc::fill_stamp(&stamp, &[("layout", "Model"), ("paper", "A4"), ("scale", "1:1")], true);
|
||||
assert_eq!(sheet, "Plan {paper} {layout}.dwg | Letter");
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Commands that name a system printer while a listing is still under way, and a listing whose
|
||||
//! host hook fails (#2171 review). Its own test binary: the system printers are set once per
|
||||
//! process, and each step needs a listing that has not ended yet.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use cadcraft_doc::{DevicePaper, PlotterConfig};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::plotters::{
|
||||
PlotterStore, PrintJob, SystemPrinters, refresh_system_printers, set_plotter_store, set_system_printers, system_printers_pending,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
static LISTINGS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
fn printer(name: &str, papers: &[(&str, f64, f64)]) -> PlotterConfig {
|
||||
PlotterConfig {
|
||||
name: name.into(),
|
||||
default_paper: papers[0].0.into(),
|
||||
papers: papers
|
||||
.iter()
|
||||
.map(|(n, w, h)| DevicePaper { native_key: None, name: (*n).into(), width: *w, height: *h, margins: [5.0; 4] })
|
||||
.collect(),
|
||||
system: true,
|
||||
..PlotterConfig::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The first listing fails (the host's hook panics); the next ones answer after 300 ms, the
|
||||
/// second with `Office` only, later ones with the roll plotter `Office_T120` as well.
|
||||
fn printers() -> Vec<PlotterConfig> {
|
||||
let n = LISTINGS.fetch_add(1, Ordering::SeqCst);
|
||||
assert!(n > 0, "the first listing fails");
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
let mut v = vec![printer("Office", &[("Tabloid", 279.4, 431.8)])];
|
||||
if n > 1 {
|
||||
v.push(printer("Office_T120", &[("Letter", 215.9, 279.4), ("Roll 24 in", 609.6, 914.4)]));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn print(_: &PrintJob) -> Result<String, String> {
|
||||
Err("no printing in this test".into())
|
||||
}
|
||||
|
||||
/// Wait (at most `limit`) for the listing under way to end.
|
||||
fn until_listed(limit: std::time::Duration) -> std::time::Duration {
|
||||
let start = std::time::Instant::now();
|
||||
while system_printers_pending() && start.elapsed() < limit {
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
start.elapsed()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_naming_a_printer_wait_for_the_listing_under_way() {
|
||||
set_plotter_store(PlotterStore::memory());
|
||||
// A user device named like a system printer, kept before anything is listed.
|
||||
let user = PlotterConfig {
|
||||
name: "Office".into(),
|
||||
papers: vec![DevicePaper { native_key: None, name: "A4".into(), width: 210.0, height: 297.0, margins: [5.0; 4] }],
|
||||
..PlotterConfig::default()
|
||||
};
|
||||
let file = cadcraft_doc::plotter_file_name("Office").unwrap();
|
||||
(PlotterStore::memory().write)(&file, &user.to_file_text()).unwrap();
|
||||
set_system_printers(SystemPrinters { list: printers, print });
|
||||
|
||||
// A listing whose hook fails ends at once: nothing waits for it the full ten seconds, and the
|
||||
// next device list starts another.
|
||||
assert!(refresh_system_printers());
|
||||
let took = until_listed(std::time::Duration::from_secs(9));
|
||||
assert!(took < std::time::Duration::from_secs(5), "a failed listing is not waited for: {took:?}");
|
||||
assert_eq!(LISTINGS.load(Ordering::SeqCst), 1);
|
||||
|
||||
// `new` copies the system printer `Office`, not the user device of that name, though the
|
||||
// listing it starts has not ended when the copy is asked for.
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("plottermanager", &json!({ "action": "new", "name": "Office copy", "from": "Office" })).unwrap();
|
||||
assert_eq!(r["defaultPaper"], "Tabloid", "a copy of the system printer: {r}");
|
||||
|
||||
// PAGESETUP changing the paper of the printer a layout already uses waits for the listing
|
||||
// under way, as it would with the printer named: the roll is that printer's paper.
|
||||
let layout = s.doc_mut().unwrap().layouts.iter_mut().find(|l| l.name == "Layout1").map(|l| l.page.device = "Office_T120".into());
|
||||
assert!(layout.is_some(), "the drawing has Layout1");
|
||||
assert!(refresh_system_printers());
|
||||
assert!(system_printers_pending(), "a listing is under way");
|
||||
s.execute("pagesetup", &json!({ "layout": "Layout1", "paper": "Roll 24 in" })).unwrap();
|
||||
let page = &s.doc().unwrap().layout("Layout1").unwrap().page;
|
||||
assert_eq!((page.device.as_str(), page.paper.as_str()), ("Office_T120", "Roll 24 in"));
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Dialog edits use cached devices even while the refresh worker is blocked.
|
||||
use cadcraft_doc::{PageSetup, PlotterConfig};
|
||||
use cadcraft_engine::cmd::plotters::{self, PrintJob, SystemPrinters};
|
||||
use serde_json::json;
|
||||
use std::sync::{
|
||||
Condvar, Mutex,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
static CALLS: AtomicUsize = AtomicUsize::new(0);
|
||||
/// Refresh listings that have returned (the blocked one only after RELEASE or its timeout).
|
||||
static RETURNED: AtomicUsize = AtomicUsize::new(0);
|
||||
static RELEASE: (Mutex<bool>, Condvar) = (Mutex::new(false), Condvar::new());
|
||||
fn list() -> Vec<PlotterConfig> {
|
||||
if CALLS.fetch_add(1, Ordering::SeqCst) > 0 {
|
||||
let _ = RELEASE.1.wait_timeout_while(RELEASE.0.lock().unwrap(), std::time::Duration::from_secs(10), |ready| !*ready).unwrap();
|
||||
RETURNED.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
vec![PlotterConfig { name: "Cached printer".into(), system: true, ..PlotterConfig::default() }]
|
||||
}
|
||||
fn print(_: &PrintJob) -> Result<String, String> {
|
||||
Err("not printing".into())
|
||||
}
|
||||
#[test]
|
||||
fn dialog_device_lookup_does_not_wait_for_refresh() {
|
||||
plotters::set_system_printers(SystemPrinters { list, print });
|
||||
// The command path waits for the initial list.
|
||||
let mut page = PageSetup::default();
|
||||
plotters::page_device("pagesetup", &json!({ "device": "Cached printer" }), &mut page).unwrap();
|
||||
plotters::refresh_system_printers();
|
||||
// Wait (bounded, so a broken refresh fails instead of hanging) until the refresh worker is
|
||||
// inside the blocked listing.
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while CALLS.load(Ordering::SeqCst) < 2 && std::time::Instant::now() < deadline {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(CALLS.load(Ordering::SeqCst) >= 2, "the refresh started a listing");
|
||||
plotters::page_device_now("plot", &json!({ "device": "Cached printer" }), &mut page).unwrap();
|
||||
let still_blocked = RETURNED.load(Ordering::SeqCst) == 0;
|
||||
*RELEASE.0.lock().unwrap() = true;
|
||||
RELEASE.1.notify_all();
|
||||
assert!(still_blocked, "the dialog lookup returned while the refresh was still blocked");
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
//! PLOTTERMANAGER `get` naming a system printer while the first listing is still under way (a
|
||||
//! fresh CLI process) waits for the listing instead of reporting an unknown plotter. Its own test
|
||||
//! binary: the system printers are set once per process, and the listing must not have run yet.
|
||||
|
||||
use cadcraft_doc::{DevicePaper, PlotterConfig};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::plotters::{PlotterStore, PrintJob, SystemPrinters, set_plotter_store, set_system_printers};
|
||||
use serde_json::json;
|
||||
|
||||
/// A slow listing: the system answers after 300 ms.
|
||||
fn printers() -> Vec<PlotterConfig> {
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
vec![PlotterConfig {
|
||||
name: "Office_T120".into(),
|
||||
default_paper: "Letter".into(),
|
||||
papers: vec![DevicePaper { native_key: None, name: "Letter".into(), width: 215.9, height: 279.4, margins: [5.0; 4] }],
|
||||
system: true,
|
||||
..PlotterConfig::default()
|
||||
}]
|
||||
}
|
||||
|
||||
/// Refuses every job: this test never prints.
|
||||
fn print(_: &PrintJob) -> Result<String, String> {
|
||||
Err("no printing in this test".into())
|
||||
}
|
||||
|
||||
/// `get` and `save` wait (bounded) for the first listing, as PLOT does.
|
||||
#[test]
|
||||
fn get_waits_for_the_first_printer_listing() {
|
||||
set_plotter_store(PlotterStore::memory());
|
||||
set_system_printers(SystemPrinters { list: printers, print });
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("plottermanager", &json!({ "action": "get", "name": "Office_T120" })).unwrap();
|
||||
assert_eq!((&r["name"], &r["system"]), (&json!("Office_T120"), &json!(true)), "{r}");
|
||||
let r = s.execute("plottermanager", &json!({ "action": "save", "name": "Office_T120" })).unwrap();
|
||||
assert!(r["text"].as_str().is_some_and(|t| t.contains("Letter")), "{r}");
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//! A plot that names a system printer while the printers are still being listed (the first plot
|
||||
//! after the app starts) waits for the list, and the printer wins over a user device of the same
|
||||
//! name. Its own test binary: the system printers are set once per process.
|
||||
|
||||
use cadcraft_doc::{DevicePaper, Drawing, PlotterConfig, Space};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{IoHooks, set_io};
|
||||
use cadcraft_engine::cmd::plotters::{PlotterStore, PrintJob, SystemPrinters, set_plotter_store, set_system_printers};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A plotter that returns its options as the file.
|
||||
fn echo_plot(_: &Drawing, _: &Space, opts: &Value) -> Result<Vec<u8>, String> {
|
||||
Ok(opts.to_string().into_bytes())
|
||||
}
|
||||
|
||||
/// A slow listing: the system answers after 300 ms.
|
||||
fn printers() -> Vec<PlotterConfig> {
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
vec![PlotterConfig {
|
||||
name: "Office_T120".into(),
|
||||
default_paper: "Letter".into(),
|
||||
papers: vec![DevicePaper { native_key: None, name: "Letter".into(), width: 215.9, height: 279.4, margins: [5.0; 4] }],
|
||||
system: true,
|
||||
..PlotterConfig::default()
|
||||
}]
|
||||
}
|
||||
|
||||
/// Accepts every job with a fixed job id.
|
||||
fn print(j: &PrintJob) -> Result<String, String> {
|
||||
Ok(format!("{}-1", j.printer))
|
||||
}
|
||||
|
||||
/// A plot naming a printer still being listed waits for the listing, and the printer wins over a user device of the same name.
|
||||
#[test]
|
||||
fn a_printer_still_being_listed_is_waited_for_and_wins_over_a_user_device() {
|
||||
set_plotter_store(PlotterStore::memory());
|
||||
set_system_printers(SystemPrinters { list: printers, print });
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Err("no writer in this test".into()), plot: Some(echo_plot) });
|
||||
let mut s = Session::new();
|
||||
s.cmdline("line 0,0 100,0").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
// A user plotter with the printer's name, made while the listing is under way.
|
||||
s.execute("plottermanager", &json!({ "action": "new", "name": "Office_T120" })).unwrap();
|
||||
let r = s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120" })).unwrap();
|
||||
assert_eq!(r["job"], "Office_T120-1", "the printer, not the user plotter: {r}");
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! A printer listing that doesn't end within the wait: PLOT naming an unknown device waits for it
|
||||
//! once, not again for its fallback and its error message. Its own test binary: the system
|
||||
//! printers are set once per process.
|
||||
|
||||
use cadcraft_doc::PlotterConfig;
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::plotters::{PlotterStore, PrintJob, SystemPrinters, refresh_system_printers, set_plotter_store, set_system_printers};
|
||||
use serde_json::json;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
static LISTINGS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// A listing that hangs far past the wait.
|
||||
fn printers() -> Vec<PlotterConfig> {
|
||||
LISTINGS.fetch_add(1, Ordering::SeqCst);
|
||||
std::thread::sleep(std::time::Duration::from_secs(120));
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Refuses every job: this test never gets as far as printing.
|
||||
fn print(_: &PrintJob) -> Result<String, String> {
|
||||
Err("no printing in this test".into())
|
||||
}
|
||||
|
||||
/// A hung listing costs one wait: the unknown device's error, a second plot and a plot with no device don't wait again.
|
||||
#[test]
|
||||
fn an_unknown_device_waits_for_a_hung_listing_only_once() {
|
||||
set_plotter_store(PlotterStore::memory());
|
||||
set_system_printers(SystemPrinters { list: printers, print });
|
||||
let mut s = Session::new();
|
||||
s.cmdline("line 0,0 100,0").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
let start = std::time::Instant::now();
|
||||
let r = s.execute("plot", &json!({ "layout": "Model", "device": "Nope" }));
|
||||
let took = start.elapsed();
|
||||
assert!(r.unwrap_err().to_string().contains("unknown plotter `Nope`"));
|
||||
// One wait of PRINTERS_WAIT (10 s), not three.
|
||||
assert!(took < std::time::Duration::from_secs(15), "{took:?}");
|
||||
// After a wait that ran out, later plots don't wait again while the listings hang.
|
||||
let start = std::time::Instant::now();
|
||||
assert!(s.execute("plot", &json!({ "layout": "Model", "device": "Nope2" })).is_err());
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(2), "no second wait: {:?}", start.elapsed());
|
||||
let start = std::time::Instant::now();
|
||||
let _ = s.execute("plot", &json!({ "layout": "Model", "device": "None" }));
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(2), "no device needs no printer list: {:?}", start.elapsed());
|
||||
// Even after the replacement expires, refreshes must not accumulate blocked driver threads.
|
||||
std::thread::sleep(std::time::Duration::from_millis(10_100));
|
||||
for _ in 0..5 {
|
||||
assert!(refresh_system_printers());
|
||||
}
|
||||
// Let a replacement worker start if one was incorrectly spawned.
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
let listings = LISTINGS.load(Ordering::SeqCst);
|
||||
assert!((1..=2).contains(&listings), "at most two blocked listings, got {listings}");
|
||||
}
|
||||
@@ -79,6 +79,13 @@ impl Bounds2 {
|
||||
pub fn intersects(&self, o: &Bounds2) -> bool {
|
||||
!(self.is_empty() || o.is_empty() || o.min.x > self.max.x || o.max.x < self.min.x || o.min.y > self.max.y || o.max.y < self.min.y)
|
||||
}
|
||||
/// The part both boxes cover; [`Bounds2::EMPTY`] when they don't meet.
|
||||
pub fn intersection(&self, o: &Bounds2) -> Bounds2 {
|
||||
if !self.intersects(o) {
|
||||
return Bounds2::EMPTY;
|
||||
}
|
||||
Bounds2 { min: self.min.max(o.min), max: self.max.min(o.max) }
|
||||
}
|
||||
pub fn expand(&self, d: f64) -> Bounds2 {
|
||||
if self.is_empty() {
|
||||
return *self;
|
||||
|
||||
@@ -25,7 +25,13 @@ craft-pdf = { workspace = true, features = ["write", "interpret"] }
|
||||
kurbo = { workspace = true }
|
||||
lyon_tessellation = { workspace = true }
|
||||
|
||||
# System printers, paper geometry and job submission on Windows (winprint.rs).
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
craft-print = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# The print catalog mapping tests also run on hosts without Windows printers.
|
||||
craft-print = { workspace = true }
|
||||
miniz_oxide = "0.9"
|
||||
tiff = "0.11"
|
||||
image = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,732 @@
|
||||
//! System printers through CUPS (macOS and Linux): the destinations `lpstat` lists, each with
|
||||
//! the papers and printable areas of its PPD, and printing a plot's PDF with `lp`. A destination
|
||||
//! without a PPD file the user can read (a driverless IPP queue CUPS made on the fly, or a PPD
|
||||
//! readable only by root) takes its papers from `lpoptions -l` instead, with the margins IPP
|
||||
//! printers commonly report. `lpstat -d` names the system's default printer.
|
||||
//!
|
||||
//! The PDF is the one the PDF plotter writes for the chosen paper, so it is sent unscaled: the
|
||||
//! plot's scale is already applied. The parsers take text, so they are tested without a printer.
|
||||
|
||||
use cadcraft_doc::{DevicePaper, Orientation, PlotOutput, PlotterConfig};
|
||||
|
||||
/// Most destinations listed.
|
||||
const MAX_PRINTERS: usize = 64;
|
||||
/// Largest PPD file read (bytes).
|
||||
#[cfg_attr(not(all(unix, not(target_arch = "wasm32"))), allow(dead_code))]
|
||||
const MAX_PPD: u64 = 4 << 20;
|
||||
/// Most copies of one job.
|
||||
pub const MAX_COPIES: u32 = 999;
|
||||
/// PostScript points per millimetre.
|
||||
const PT_PER_MM: f64 = 72.0 / 25.4;
|
||||
|
||||
/// A paper size of a PPD: its option keyword, the name shown, size and printable area (points).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PpdPaper {
|
||||
pub keyword: String,
|
||||
pub name: String,
|
||||
pub width: f64,
|
||||
pub height: f64,
|
||||
/// Printable area: lower-left x, y and upper-right x, y (points).
|
||||
pub imageable: Option<[f64; 4]>,
|
||||
}
|
||||
|
||||
/// What a PPD says about a printer's papers.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Ppd {
|
||||
pub nick_name: String,
|
||||
/// The default paper's keyword.
|
||||
pub default_size: String,
|
||||
pub papers: Vec<PpdPaper>,
|
||||
}
|
||||
|
||||
/// A PPD main keyword line: `*Key Option/Label: Value` → (key, option, label, value).
|
||||
fn ppd_line(line: &str) -> Option<(&str, &str, &str, &str)> {
|
||||
let rest = line.strip_prefix('*')?;
|
||||
let (head, value) = rest.split_once(':')?;
|
||||
let (key, option) = head.split_once(' ').unwrap_or((head, ""));
|
||||
let (option, label) = option.split_once('/').unwrap_or((option, ""));
|
||||
Some((key.trim(), option.trim(), label.trim(), value.trim().trim_matches('"').trim()))
|
||||
}
|
||||
|
||||
/// Exactly `N` finite numbers separated by spaces (a PPD's sizes and areas), else `None`.
|
||||
fn numbers<const N: usize>(s: &str) -> Option<[f64; N]> {
|
||||
let v: Vec<f64> = s.split_whitespace().filter_map(|t| t.parse().ok()).filter(|x: &f64| x.is_finite()).collect();
|
||||
v.try_into().ok()
|
||||
}
|
||||
|
||||
/// The name a paper is shown with: its label, else its keyword; a borderless variant
|
||||
/// (`Letter.Fullbleed`) says so.
|
||||
fn paper_name(keyword: &str, label: &str) -> String {
|
||||
let (base, borderless) = match keyword.strip_suffix(".Fullbleed") {
|
||||
Some(b) => (b, true),
|
||||
None => (keyword, false),
|
||||
};
|
||||
let shown = if label.is_empty() { base } else { label.trim_end_matches(" (Borderless)").trim_end_matches(" Borderless") };
|
||||
if borderless { format!("{shown} (borderless)") } else { shown.to_string() }
|
||||
}
|
||||
|
||||
/// Parse a PPD's nickname, default page size and page sizes (with `PaperDimension` and
|
||||
/// `ImageableArea`). Page sizes without dimensions are dropped.
|
||||
pub fn parse_ppd(text: &str) -> Ppd {
|
||||
let mut ppd = Ppd::default();
|
||||
let mut sizes: Vec<(String, String)> = Vec::new();
|
||||
let mut dims: Vec<(String, [f64; 2])> = Vec::new();
|
||||
let mut areas: Vec<(String, [f64; 4])> = Vec::new();
|
||||
for line in text.lines() {
|
||||
let Some((key, option, label, value)) = ppd_line(line) else { continue };
|
||||
match key {
|
||||
"NickName" => ppd.nick_name = value.to_string(),
|
||||
"DefaultPageSize" => ppd.default_size = value.to_string(),
|
||||
"PageSize" if !option.is_empty() && !sizes.iter().any(|(k, _)| k == option) => sizes.push((option.into(), label.into())),
|
||||
"PaperDimension" => {
|
||||
if let Some(d) = numbers::<2>(value) {
|
||||
dims.push((option.into(), d));
|
||||
}
|
||||
}
|
||||
"ImageableArea" => {
|
||||
if let Some(a) = numbers::<4>(value) {
|
||||
areas.push((option.into(), a));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for (keyword, label) in sizes {
|
||||
let Some((_, [w, h])) = dims.iter().find(|(k, _)| *k == keyword) else { continue };
|
||||
if *w <= 0.0 || *h <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let imageable = areas.iter().find(|(k, _)| *k == keyword).map(|(_, a)| *a);
|
||||
ppd.papers.push(PpdPaper { name: paper_name(&keyword, &label), keyword, width: *w, height: *h, imageable });
|
||||
}
|
||||
ppd
|
||||
}
|
||||
|
||||
/// The margin IPP printers commonly report for each edge of a sheet that is not borderless
|
||||
/// (`media-*-margin` 423, in hundredths of a millimetre), used when nothing better is known.
|
||||
const IPP_MARGIN_MM: f64 = 4.23;
|
||||
|
||||
/// The size of a media keyword `lpoptions -l` lists, in points: a PWG self-describing name
|
||||
/// (`iso_a4_210x297mm`, `na_letter_8.5x11in`), Adobe's `w612h792` (points), or a standard size
|
||||
/// CADCraft knows (`A4`, `Letter`, `Legal`, `Tabloid`…, shown by its keyword). `None` for custom
|
||||
/// and unknown ones.
|
||||
fn media_size(keyword: &str) -> Option<(String, f64, f64)> {
|
||||
let k = keyword.trim();
|
||||
if k.is_empty() || k.to_ascii_lowercase().starts_with("custom") {
|
||||
return None;
|
||||
}
|
||||
// PWG 5101.1: `class_name_WxHunit`, the size as the last part.
|
||||
if let Some((head, dims)) = k.rsplit_once('_') {
|
||||
let (dims, mm) = match (dims.strip_suffix("mm"), dims.strip_suffix("in")) {
|
||||
(Some(d), _) => (d, 1.0),
|
||||
(None, Some(d)) => (d, 25.4),
|
||||
(None, None) => ("", 0.0),
|
||||
};
|
||||
if let Some((w, h)) = dims.split_once('x')
|
||||
&& let (Ok(w), Ok(h)) = (w.parse::<f64>(), h.parse::<f64>())
|
||||
&& w.is_finite()
|
||||
&& h.is_finite()
|
||||
&& w > 0.0
|
||||
&& h > 0.0
|
||||
{
|
||||
// `iso_a4` → "A4", `na_letter` → "Letter": the name part after the class.
|
||||
let name = head.split_once('_').map_or(head, |(_, n)| n);
|
||||
let shown = if name.is_empty() { k.to_string() } else { pwg_name(name) };
|
||||
return Some((shown, w * mm * PT_PER_MM, h * mm * PT_PER_MM));
|
||||
}
|
||||
}
|
||||
if let Some(rest) = k.strip_prefix('w')
|
||||
&& let Some((w, h)) = rest.split_once('h')
|
||||
&& let (Ok(w), Ok(h)) = (w.parse::<f64>(), h.parse::<f64>())
|
||||
&& w.is_finite()
|
||||
&& h.is_finite()
|
||||
&& w > 0.0
|
||||
&& h > 0.0
|
||||
{
|
||||
return Some((format!("{:.0} x {:.0} mm", w / PT_PER_MM, h / PT_PER_MM), w, h));
|
||||
}
|
||||
// A PPD's `B4`/`B5` are the JIS sizes, not ISO's: left out rather than guessed.
|
||||
let base = k.strip_suffix(".Fullbleed").unwrap_or(k);
|
||||
if base.starts_with(['B', 'b']) {
|
||||
return None;
|
||||
}
|
||||
let p = cadcraft_render::paper_size(base)?;
|
||||
Some((base.to_string(), p.width_mm * PT_PER_MM, p.height_mm * PT_PER_MM))
|
||||
}
|
||||
|
||||
/// A PWG media name shown as people write it: `a4` → "A4", `letter` → "Letter",
|
||||
/// `govt-letter` → "Govt Letter".
|
||||
fn pwg_name(name: &str) -> String {
|
||||
let words: Vec<String> = name
|
||||
.split(['-', '.'])
|
||||
.filter(|w| !w.is_empty())
|
||||
.map(|w| {
|
||||
// ISO and JIS sizes are written in capitals (A4, B5, C6).
|
||||
if w.len() <= 3 && w.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) && w.chars().skip(1).all(|c| c.is_ascii_digit()) {
|
||||
w.to_ascii_uppercase()
|
||||
} else {
|
||||
let mut c = w.chars();
|
||||
c.next().map_or(String::new(), |f| f.to_uppercase().chain(c).collect())
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
words.join(" ")
|
||||
}
|
||||
|
||||
/// `lpoptions -p NAME -l` (in the C locale): the `PageSize` (or `media`) choices as papers with
|
||||
/// [`IPP_MARGIN_MM`] margins, the default (marked `*`) as the default size. Keywords whose size
|
||||
/// isn't known are left out.
|
||||
pub fn parse_lpoptions(text: &str) -> Ppd {
|
||||
let mut ppd = Ppd::default();
|
||||
let line = text
|
||||
.lines()
|
||||
.find(|l| l.starts_with("PageSize/") || l.starts_with("PageSize:"))
|
||||
.or_else(|| text.lines().find(|l| l.starts_with("media/") || l.starts_with("media:")));
|
||||
let Some((_, choices)) = line.and_then(|l| l.split_once(':')) else { return ppd };
|
||||
let m = IPP_MARGIN_MM * PT_PER_MM;
|
||||
for choice in choices.split_whitespace().take(MAX_LPOPTIONS_CHOICES) {
|
||||
let (keyword, default) = match choice.strip_prefix('*') {
|
||||
Some(k) => (k, true),
|
||||
None => (choice, false),
|
||||
};
|
||||
let Some((name, w, h)) = media_size(keyword) else { continue };
|
||||
let borderless = keyword.ends_with(".Fullbleed") || keyword.contains(".Borderless");
|
||||
let name = if borderless { format!("{name} (borderless)") } else { name };
|
||||
let imageable = (!borderless && w > 2.0 * m && h > 2.0 * m).then_some([m, m, w - m, h - m]);
|
||||
let paper = PpdPaper { keyword: keyword.to_string(), name, width: w, height: h, imageable };
|
||||
if default {
|
||||
ppd.default_size = keyword.to_string();
|
||||
}
|
||||
// Two keywords with one display name are listed once; the starred one (the queue's
|
||||
// default) wins, so the default keeps its own keyword.
|
||||
match ppd.papers.iter_mut().find(|p| p.name == paper.name) {
|
||||
Some(listed) if default => *listed = paper,
|
||||
Some(_) => {}
|
||||
None => ppd.papers.push(paper),
|
||||
}
|
||||
}
|
||||
ppd
|
||||
}
|
||||
|
||||
/// Most `lpoptions` choices read for one option.
|
||||
const MAX_LPOPTIONS_CHOICES: usize = 500;
|
||||
|
||||
/// `lpstat -d` (in the C locale): the default destination, if there is one.
|
||||
pub fn parse_default_destination(text: &str) -> Option<String> {
|
||||
let name = text.lines().find_map(|l| l.trim().strip_prefix("system default destination:"))?.trim();
|
||||
valid_name(name).then(|| name.to_string())
|
||||
}
|
||||
|
||||
/// The device a destination becomes: a system printer (PDF in, printed with `lp`) with the
|
||||
/// PPD's papers.
|
||||
pub fn printer_config(name: &str, ppd: &Ppd) -> PlotterConfig {
|
||||
let papers: Vec<DevicePaper> = ppd
|
||||
.papers
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let margins = p.imageable.map_or([0.0; 4], |[llx, lly, urx, ury]| {
|
||||
[llx / PT_PER_MM, lly / PT_PER_MM, (p.width - urx) / PT_PER_MM, (p.height - ury) / PT_PER_MM]
|
||||
});
|
||||
DevicePaper {
|
||||
native_key: Some(p.keyword.clone()),
|
||||
name: p.name.clone(),
|
||||
width: p.width / PT_PER_MM,
|
||||
height: p.height / PT_PER_MM,
|
||||
margins,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let default_paper = ppd.papers.iter().find(|p| p.keyword == ppd.default_size).map(|p| p.name.clone()).unwrap_or_default();
|
||||
let description = if ppd.nick_name.is_empty() { "System printer".to_string() } else { ppd.nick_name.clone() };
|
||||
let mut config = PlotterConfig {
|
||||
name: name.to_string(),
|
||||
description,
|
||||
output: PlotOutput::Pdf,
|
||||
resolution: 300,
|
||||
orientation: Orientation::Landscape,
|
||||
default_paper,
|
||||
papers,
|
||||
system: true,
|
||||
system_default: false,
|
||||
}
|
||||
.sanitized();
|
||||
// Queue names are routing identifiers, not display labels. Truncating a valid CUPS name
|
||||
// can route a job to a different queue with the same prefix.
|
||||
config.name = if valid_name(name) { name.to_string() } else { String::new() };
|
||||
config
|
||||
}
|
||||
|
||||
/// Whether `lpstat -H` (the scheduler `lp` and `lpstat` talk to, in the C locale) names this
|
||||
/// computer's own CUPS: a local socket, or `localhost`. Only then are the PPD files in
|
||||
/// `/etc/cups/ppd` the destinations' own; a remote server (`CUPS_SERVER`, `client.conf`) is
|
||||
/// asked for its destinations' papers instead.
|
||||
pub fn local_scheduler(text: &str) -> bool {
|
||||
let Some(server) = text.lines().map(str::trim).find(|l| !l.is_empty()) else { return false };
|
||||
if server.starts_with('/') {
|
||||
return true;
|
||||
}
|
||||
// `host:port`, `[v6]:port` or `host`.
|
||||
let host = match server.strip_prefix('[') {
|
||||
Some(rest) => rest.split(']').next().unwrap_or(""),
|
||||
None => server.rsplit_once(':').map_or(server, |(h, port)| if port.chars().all(|c| c.is_ascii_digit()) { h } else { server }),
|
||||
};
|
||||
let host = host.trim_end_matches('.').to_ascii_lowercase();
|
||||
host == "localhost" || host == "::1" || host.starts_with("127.") || host.ends_with(".localhost")
|
||||
}
|
||||
|
||||
/// `lpstat -e`: one destination per line.
|
||||
pub fn parse_destinations(text: &str) -> Vec<String> {
|
||||
let mut v: Vec<String> = text.lines().map(str::trim).filter(|n| valid_name(n)).map(String::from).collect();
|
||||
v.dedup();
|
||||
v.truncate(MAX_PRINTERS);
|
||||
v
|
||||
}
|
||||
|
||||
/// `lp`'s reply: the job id from `request id is NAME-12 (1 file(s))`.
|
||||
pub fn parse_request_id(text: &str) -> Option<String> {
|
||||
let rest = text.split("request id is ").nth(1)?;
|
||||
rest.split_whitespace().next().map(String::from)
|
||||
}
|
||||
|
||||
/// A destination name CUPS could have made (no path separators or control characters).
|
||||
pub fn valid_name(n: &str) -> bool {
|
||||
!n.is_empty() && n.len() <= 127 && !n.starts_with('.') && !n.contains(['/', '\\', '#']) && !n.chars().any(|c| c.is_control() || c.is_whitespace())
|
||||
}
|
||||
|
||||
/// The `lp` option choosing the paper `keyword`: `PageSize` for a paper of the printer's PPD,
|
||||
/// IPP's `media` for one `lpoptions` listed for a queue without one.
|
||||
pub fn paper_option(keyword: &str, from_ppd: bool) -> String {
|
||||
if from_ppd { format!("PageSize={keyword}") } else { format!("media={keyword}") }
|
||||
}
|
||||
|
||||
/// Resolve the requested sheet before spawning `lp`: an absent override would print on the
|
||||
/// queue's default paper instead of the paper the preview showed.
|
||||
#[cfg_attr(not(all(unix, not(target_arch = "wasm32"))), allow(dead_code))]
|
||||
fn required_paper(papers: Option<(Ppd, bool)>, paper: &str, size_mm: (f64, f64)) -> Result<String, String> {
|
||||
let (ppd, from_ppd) = papers.ok_or_else(|| "could not read the printer's paper capabilities".to_string())?;
|
||||
let selected = ppd.papers.iter().find(|p| p.keyword == paper).ok_or_else(|| format!("the printer no longer offers paper `{paper}`"))?;
|
||||
let (w, h) = (selected.width / PT_PER_MM, selected.height / PT_PER_MM);
|
||||
if !size_mm.0.is_finite()
|
||||
|| !size_mm.1.is_finite()
|
||||
|| size_mm.0 <= 0.0
|
||||
|| size_mm.1 <= 0.0
|
||||
|| (w.min(h) - size_mm.0.min(size_mm.1)).abs() > 0.1
|
||||
|| (w.max(h) - size_mm.0.max(size_mm.1)).abs() > 0.1
|
||||
{
|
||||
return Err("the printer paper size changed; refresh the printer and plot again".into());
|
||||
}
|
||||
Ok(paper_option(&selected.keyword, from_ppd))
|
||||
}
|
||||
|
||||
/// The `lp` arguments for a job (the PDF goes to standard input); `paper` is a
|
||||
/// [`paper_option`].
|
||||
pub fn lp_args(printer: &str, paper: Option<&str>, copies: u32, title: &str) -> Vec<String> {
|
||||
let mut a = vec!["-d".into(), printer.into(), "-n".into(), copies.clamp(1, MAX_COPIES).to_string()];
|
||||
let title: String = title.chars().filter(|c| !c.is_control()).take(100).collect();
|
||||
if !title.trim().is_empty() {
|
||||
a.extend(["-t".into(), title]);
|
||||
}
|
||||
if let Some(o) = paper {
|
||||
a.extend(["-o".into(), o.to_string()]);
|
||||
}
|
||||
// The plot is already at its scale: no fitting to the page.
|
||||
a.extend(["-o".into(), "print-scaling=none".into(), "-o".into(), "fit-to-page=false".into(), "-".into()]);
|
||||
a
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_arch = "wasm32")))]
|
||||
mod system {
|
||||
use super::{
|
||||
MAX_PPD, PlotterConfig, Ppd, local_scheduler, lp_args, parse_default_destination, parse_destinations, parse_lpoptions, parse_ppd,
|
||||
parse_request_id, printer_config, valid_name,
|
||||
};
|
||||
use std::io::Write;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// The destination's PPD from the CUPS folder, when it is readable and not too large.
|
||||
fn ppd(name: &str) -> Option<Ppd> {
|
||||
let path = format!("/etc/cups/ppd/{name}.ppd");
|
||||
if std::fs::metadata(&path).ok()?.len() > MAX_PPD {
|
||||
return None;
|
||||
}
|
||||
Some(parse_ppd(&std::fs::read_to_string(path).ok()?))
|
||||
}
|
||||
|
||||
/// Longest a CUPS command may take: a CUPS that doesn't answer gives no printers instead of
|
||||
/// a listing that never ends.
|
||||
const CUPS_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
/// Longest `lp` may take to take a job (it carries the whole PDF).
|
||||
const LP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
|
||||
|
||||
/// Start a pipe worker, or `None` when the system refuses a thread (the caller then stops
|
||||
/// its command instead of panicking).
|
||||
fn worker<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Option<std::thread::JoinHandle<T>> {
|
||||
#[cfg(test)]
|
||||
if tests::REFUSE_THREADS.with(std::cell::Cell::get) {
|
||||
return None;
|
||||
}
|
||||
std::thread::Builder::new().name("cups-pipe".into()).spawn(f).ok()
|
||||
}
|
||||
|
||||
/// Stop a command and reap it, so no zombie is left behind.
|
||||
fn stop(child: &mut std::process::Child) {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
/// A CUPS command's output in the C locale (its messages untranslated, so they parse), or
|
||||
/// `None` when it fails or takes longer than [`CUPS_TIMEOUT`] (then it is stopped).
|
||||
fn cups_output(program: &str, args: &[&str]) -> Option<String> {
|
||||
use std::io::Read;
|
||||
let mut child = Command::new(program)
|
||||
.args(args)
|
||||
.env("LC_ALL", "C")
|
||||
.env("LANG", "C")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.ok()?;
|
||||
let Some(stdout) = child.stdout.take() else {
|
||||
stop(&mut child);
|
||||
return None;
|
||||
};
|
||||
// Read on a thread, so a full pipe can't keep the command from ending.
|
||||
let Some(reader) = worker(move || {
|
||||
let mut s = String::new();
|
||||
let _ = stdout.take(MAX_PPD).read_to_string(&mut s);
|
||||
s
|
||||
}) else {
|
||||
stop(&mut child);
|
||||
return None;
|
||||
};
|
||||
let start = std::time::Instant::now();
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) if status.success() => return reader.join().ok(),
|
||||
Ok(Some(_)) => return None,
|
||||
Err(_) => {
|
||||
stop(&mut child);
|
||||
return None;
|
||||
}
|
||||
Ok(None) if start.elapsed() > CUPS_TIMEOUT => {
|
||||
stop(&mut child);
|
||||
return None;
|
||||
}
|
||||
Ok(None) => std::thread::sleep(std::time::Duration::from_millis(20)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the scheduler `lp` sends jobs to is this computer's own ([`local_scheduler`]); not
|
||||
/// knowing counts as not.
|
||||
fn local() -> bool {
|
||||
cups_output("lpstat", &["-H"]).is_some_and(|t| local_scheduler(&t))
|
||||
}
|
||||
|
||||
/// The papers of destination `name`: its PPD's when the scheduler is this computer's own
|
||||
/// (`local`), else (a remote server, or no PPD file the user can read) the ones `lpoptions`
|
||||
/// lists, which come from the server that takes the job. The flag says which.
|
||||
fn papers(name: &str, local: bool) -> Option<(Ppd, bool)> {
|
||||
if let Some(p) = local.then(|| ppd(name)).flatten().filter(|p| !p.papers.is_empty()) {
|
||||
return Some((p, true));
|
||||
}
|
||||
let p = parse_lpoptions(&cups_output("lpoptions", &["-p", name, "-l"])?);
|
||||
(!p.papers.is_empty()).then_some((p, false))
|
||||
}
|
||||
|
||||
/// Destinations asked about their papers at once, so slow ones don't hold up the others.
|
||||
static ASKING: crate::printer_queries::Asking = std::sync::Mutex::new(Vec::new());
|
||||
/// How long the destinations' papers are waited for: a destination that answers later is
|
||||
/// left out of this listing, and the engine's own wait for the listing is not run out.
|
||||
const PAPERS_TIME: std::time::Duration = std::time::Duration::from_secs(6);
|
||||
|
||||
/// The CUPS destinations as devices (none when CUPS is missing), the system's default
|
||||
/// printer marked. A destination whose papers can't be read, or are not read in time, is
|
||||
/// left out.
|
||||
pub fn printers() -> Vec<PlotterConfig> {
|
||||
let Some(out) = cups_output("lpstat", &["-e"]) else { return Vec::new() };
|
||||
let default = cups_output("lpstat", &["-d"]).and_then(|t| parse_default_destination(&t));
|
||||
let local = local();
|
||||
let names: Vec<(String, String)> = parse_destinations(&out).into_iter().map(|n| (n.clone(), n)).collect();
|
||||
crate::printer_queries::ask_each(&ASKING, names, PAPERS_TIME, move |n: String| {
|
||||
let (p, _) = papers(&n, local)?;
|
||||
let mut c = printer_config(&n, &p);
|
||||
c.system_default = default.as_deref() == Some(n.as_str());
|
||||
Some(c)
|
||||
})
|
||||
}
|
||||
|
||||
/// Send `pdf` to `printer` on the paper called `paper` (a name [`printers`] gave).
|
||||
/// Returns the job id.
|
||||
pub fn print(printer: &str, paper: &str, size_mm: (f64, f64), copies: u32, title: &str, pdf: &[u8]) -> Result<String, String> {
|
||||
if !valid_name(printer) {
|
||||
return Err(format!("`{printer}` is not a printer name"));
|
||||
}
|
||||
let option = super::required_paper(papers(printer, local()), paper, size_mm)?;
|
||||
let mut child = Command::new("lp")
|
||||
.args(lp_args(printer, Some(&option), copies, title))
|
||||
.env("LC_ALL", "C")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| format!("lp: {e}"))?;
|
||||
// The PDF goes in and the answers come out on threads, and `lp` is stopped when it doesn't
|
||||
// finish in time, so a CUPS that stopped answering can't hold PLOT (and the window) up.
|
||||
let no_thread = |child: &mut std::process::Child| {
|
||||
// Workers already started end when the stopped `lp`'s pipes close.
|
||||
stop(child);
|
||||
"lp: the system could not start a thread for the job".to_string()
|
||||
};
|
||||
let writer = match child.stdin.take() {
|
||||
Some(mut stdin) => {
|
||||
let pdf = pdf.to_vec();
|
||||
Some(worker(move || stdin.write_all(&pdf)).ok_or_else(|| no_thread(&mut child))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let drain = |pipe: Option<Box<dyn std::io::Read + Send>>| {
|
||||
worker(move || {
|
||||
let mut s = String::new();
|
||||
if let Some(p) = pipe {
|
||||
let _ = std::io::Read::read_to_string(&mut std::io::Read::take(p, 64 * 1024), &mut s);
|
||||
}
|
||||
s
|
||||
})
|
||||
};
|
||||
let out = drain(child.stdout.take().map(|p| Box::new(p) as Box<dyn std::io::Read + Send>)).ok_or_else(|| no_thread(&mut child))?;
|
||||
let err = drain(child.stderr.take().map(|p| Box::new(p) as Box<dyn std::io::Read + Send>)).ok_or_else(|| no_thread(&mut child))?;
|
||||
let start = std::time::Instant::now();
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status,
|
||||
Err(e) => {
|
||||
stop(&mut child);
|
||||
return Err(format!("lp: {e}"));
|
||||
}
|
||||
Ok(None) if start.elapsed() > LP_TIMEOUT => {
|
||||
stop(&mut child);
|
||||
// Stopping `lp` cancels nothing CUPS already took: the job may be queued.
|
||||
return Err(format!(
|
||||
"lp did not answer within {} s; the job may already be queued: check the printer's queue (lpstat -o {printer}) before plotting again",
|
||||
LP_TIMEOUT.as_secs()
|
||||
));
|
||||
}
|
||||
Ok(None) => std::thread::sleep(std::time::Duration::from_millis(20)),
|
||||
}
|
||||
};
|
||||
if let Some(Ok(Err(e))) = writer.map(std::thread::JoinHandle::join) {
|
||||
return Err(format!("lp: {e}"));
|
||||
}
|
||||
let said = out.join().unwrap_or_default();
|
||||
if !status.success() {
|
||||
let err = err.join().unwrap_or_default().trim().to_string();
|
||||
return Err(if err.is_empty() { format!("lp failed ({status})") } else { err });
|
||||
}
|
||||
Ok(parse_request_id(&said).unwrap_or_else(|| said.trim().to_string()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) mod tests {
|
||||
use super::*;
|
||||
|
||||
thread_local! {
|
||||
/// Stands for a system that refuses new threads.
|
||||
pub(super) static REFUSE_THREADS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// A CUPS command whose pipe reader can't start gives no output (it is stopped and
|
||||
/// reaped) instead of panicking; with threads it reads as usual.
|
||||
#[test]
|
||||
fn a_refused_reader_thread_stops_the_command_without_panicking() {
|
||||
assert_eq!(cups_output("echo", &["lpstat"]).as_deref().map(str::trim), Some("lpstat"));
|
||||
REFUSE_THREADS.with(|r| r.set(true));
|
||||
let start = std::time::Instant::now();
|
||||
let out = cups_output("sleep", &["30"]);
|
||||
REFUSE_THREADS.with(|r| r.set(false));
|
||||
assert_eq!(out, None);
|
||||
assert!(start.elapsed() < CUPS_TIMEOUT, "the command was stopped at once, not waited for: {:?}", start.elapsed());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_arch = "wasm32")))]
|
||||
pub use system::{print, printers};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const PPD: &str = r#"*PPD-Adobe: "4.3"
|
||||
*NickName: "EPSON Example Series-AirPrint"
|
||||
*OpenUI *PageSize/Media Size: PickOne
|
||||
*DefaultPageSize: Letter
|
||||
*PageSize A4: "<</PageSize[595.2756 841.8898]>>setpagedevice"
|
||||
*PageSize Letter/US Letter: "<</PageSize[612 792]>>setpagedevice"
|
||||
*PageSize Letter.Fullbleed: "<</PageSize[612 792]>>setpagedevice"
|
||||
*PageSize Roll610/Roll 24 in: "<</PageSize[1728 2592]>>setpagedevice"
|
||||
*PageSize NoDims: "<</PageSize[1 1]>>setpagedevice"
|
||||
*CloseUI: *PageSize
|
||||
*PageRegion A4: "<</PageSize[595.2756 841.8898]>>setpagedevice"
|
||||
*PaperDimension A4: "595.2756 841.8898"
|
||||
*ImageableArea A4: "8.5039 8.5039 586.7717 833.3858"
|
||||
*PaperDimension Letter/US Letter: "612.0000 792.0000"
|
||||
*ImageableArea Letter/US Letter: "18 36 594 756"
|
||||
*PaperDimension Letter.Fullbleed: "612 792"
|
||||
*ImageableArea Letter.Fullbleed: "0 0 612 792"
|
||||
*PaperDimension Roll610: "1728 2592"
|
||||
"#;
|
||||
|
||||
/// A PPD gives the papers with their sizes and printable areas, borderless and roll papers named as such.
|
||||
#[test]
|
||||
fn ppd_papers_sizes_and_printable_areas() {
|
||||
let p = parse_ppd(PPD);
|
||||
assert_eq!(p.nick_name, "EPSON Example Series-AirPrint");
|
||||
assert_eq!(p.default_size, "Letter");
|
||||
let names: Vec<&str> = p.papers.iter().map(|x| x.name.as_str()).collect();
|
||||
assert_eq!(names, ["A4", "US Letter", "Letter (borderless)", "Roll 24 in"]);
|
||||
let c = printer_config("EPSON_Example", &p);
|
||||
assert!(c.system);
|
||||
assert_eq!(c.output, PlotOutput::Pdf);
|
||||
assert_eq!(c.default_paper, "US Letter");
|
||||
let letter = c.paper("US Letter").unwrap();
|
||||
assert!((letter.width - 215.9).abs() < 0.01 && (letter.height - 279.4).abs() < 0.01);
|
||||
let [l, b, r, t] = letter.margins;
|
||||
assert!((l - 6.35).abs() < 0.01 && (b - 12.7).abs() < 0.01 && (r - 6.35).abs() < 0.01 && (t - 12.7).abs() < 0.01);
|
||||
assert_eq!(c.paper("Letter (borderless)").unwrap().margins, [0.0; 4]);
|
||||
// No ImageableArea: the whole sheet.
|
||||
assert_eq!(c.paper("Roll 24 in").unwrap().margins, [0.0; 4]);
|
||||
}
|
||||
|
||||
/// Destination names and job ids are read from lpstat and lp, and the lp arguments are safe and complete.
|
||||
#[test]
|
||||
fn lpstat_and_lp_replies() {
|
||||
assert_eq!(parse_destinations("EPSON_A\nEPSON_B\n\nbad/name\n"), ["EPSON_A", "EPSON_B"]);
|
||||
assert_eq!(parse_request_id("request id is EPSON_A-42 (1 file(s))\n").as_deref(), Some("EPSON_A-42"));
|
||||
assert_eq!(parse_request_id("nothing"), None);
|
||||
let a = lp_args("EPSON_A", Some(&paper_option("Letter", true)), 0, "Plan\u{7}.dwg - Model");
|
||||
assert_eq!(
|
||||
a,
|
||||
[
|
||||
"-d",
|
||||
"EPSON_A",
|
||||
"-n",
|
||||
"1",
|
||||
"-t",
|
||||
"Plan.dwg - Model",
|
||||
"-o",
|
||||
"PageSize=Letter",
|
||||
"-o",
|
||||
"print-scaling=none",
|
||||
"-o",
|
||||
"fit-to-page=false",
|
||||
"-"
|
||||
]
|
||||
);
|
||||
assert_eq!(lp_args("P", None, 5000, "")[3], "999");
|
||||
assert_eq!(paper_option("iso_a4_210x297mm", false), "media=iso_a4_210x297mm");
|
||||
}
|
||||
|
||||
/// A queue without a readable PPD: its papers from `lpoptions -l`, PWG, Adobe and plain
|
||||
/// keywords, the default marked, unknown and custom sizes left out.
|
||||
#[test]
|
||||
fn lpoptions_papers_of_a_driverless_queue() {
|
||||
let text = "ColorModel/Color Mode: *RGB Gray\n\
|
||||
PageSize/Media Size: iso_a3_297x420mm *iso_a4_210x297mm na_letter_8.5x11in w612h1008 Legal A4.Fullbleed Custom.WIDTHxHEIGHT EnvWeird\n\
|
||||
Duplex/2-Sided Printing: *None DuplexNoTumble\n";
|
||||
let p = parse_lpoptions(text);
|
||||
let names: Vec<&str> = p.papers.iter().map(|x| x.name.as_str()).collect();
|
||||
assert_eq!(names, ["A3", "A4", "Letter", "216 x 356 mm", "Legal", "A4 (borderless)"]);
|
||||
assert_eq!(p.default_size, "iso_a4_210x297mm");
|
||||
let c = printer_config("Office", &p);
|
||||
assert_eq!(c.default_paper, "A4");
|
||||
assert_eq!(c.description, "System printer");
|
||||
let a4 = c.paper("A4").unwrap();
|
||||
assert!((a4.width - 210.0).abs() < 0.01 && (a4.height - 297.0).abs() < 0.01, "{a4:?}");
|
||||
assert!(a4.margins.iter().all(|m| (m - IPP_MARGIN_MM).abs() < 0.01), "{a4:?}");
|
||||
let letter = c.paper("Letter").unwrap();
|
||||
assert!((letter.width - 215.9).abs() < 0.01 && (letter.height - 279.4).abs() < 0.01);
|
||||
assert_eq!(c.paper("A4 (borderless)").unwrap().margins, [0.0; 4]);
|
||||
// A `media` option when there is no PageSize; nothing at all gives no papers.
|
||||
assert_eq!(parse_lpoptions("media/Media: *na_legal_8.5x14in\n").papers.len(), 1);
|
||||
assert!(parse_lpoptions("Duplex/2-Sided Printing: *None\n").papers.is_empty());
|
||||
assert!(parse_lpoptions("PageSize/Media Size: iso_a4_0x0mm iso_a4_NaNxNaNmm w-1h5\n").papers.is_empty());
|
||||
}
|
||||
|
||||
/// Only this computer's own scheduler has its destinations' PPD files in `/etc/cups/ppd`
|
||||
/// (#2171 review).
|
||||
#[test]
|
||||
fn the_scheduler_lpstat_names() {
|
||||
for local in ["/run/cups/cups.sock\n", "localhost:631\n", "127.0.0.1:631", "[::1]:631", "localhost"] {
|
||||
assert!(local_scheduler(local), "{local}");
|
||||
}
|
||||
for remote in ["print.example.org:631\n", "10.0.0.5", "[fe80::1]:631", "", "localhost.example.org:631"] {
|
||||
assert!(!local_scheduler(remote), "{remote}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The default printer is read from `lpstat -d`; none, or a bad name, gives none.
|
||||
#[test]
|
||||
fn the_default_destination() {
|
||||
assert_eq!(parse_default_destination("system default destination: Office_T120\n").as_deref(), Some("Office_T120"));
|
||||
assert_eq!(parse_default_destination("no system default destination\n"), None);
|
||||
assert_eq!(parse_default_destination("system default destination: bad/name\n"), None);
|
||||
}
|
||||
#[test]
|
||||
fn native_queue_names_do_not_alias_after_one_hundred_characters() {
|
||||
let name = "Q".repeat(100);
|
||||
let other = format!("{name}X");
|
||||
let ppd = parse_lpoptions("PageSize: *A4 A3");
|
||||
assert_eq!(printer_config(&name, &ppd).name, name);
|
||||
assert_eq!(printer_config(&other, &ppd).name, other);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_selected_paper_is_not_replaced_by_the_queue_default() {
|
||||
assert!(required_paper(None, "A3", (297.0, 420.0)).is_err());
|
||||
let papers = || parse_lpoptions("PageSize: *A4");
|
||||
assert!(required_paper(Some((papers(), true)), "A3", (297.0, 420.0)).is_err());
|
||||
assert_eq!(required_paper(Some((papers(), true)), "A4", (210.0, 297.0)).unwrap(), "PageSize=A4");
|
||||
assert_eq!(required_paper(Some((papers(), false)), "A4", (210.0, 297.0)).unwrap(), "media=A4");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod media_regressions {
|
||||
// Synthetic PPD records authored here; no printer driver files or samples are copied.
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_shortened_display_label_keeps_its_native_media_identifier() {
|
||||
let label = "A long display label ".repeat(8);
|
||||
let text = format!("*PageSize Roll24/{label}: \"\"\n*PaperDimension Roll24: \"1728 2592\"\n");
|
||||
let ppd = parse_ppd(&text);
|
||||
let config = printer_config("Office", &ppd);
|
||||
let paper = &config.papers[0];
|
||||
assert!(paper.name.len() < label.len());
|
||||
assert_eq!(required_paper(Some((ppd, true)), paper.native_key.as_deref().unwrap(), (paper.width, paper.height)).unwrap(), "PageSize=Roll24");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_media_dimensions_are_refused_before_submission() {
|
||||
let papers = || parse_ppd("*PageSize Roll24/Roll 24 in: \"\"\n*PaperDimension Roll24: \"1728 3456\"\n");
|
||||
assert!(required_paper(Some((papers(), true)), "Roll24", (609.6, 914.4)).is_err());
|
||||
assert!(required_paper(Some((papers(), true)), "Roll24", (609.6, 1219.2)).is_ok());
|
||||
assert!(required_paper(Some((papers(), true)), "removed", (609.6, 1219.2)).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod starred_collision_regressions {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_starred_choice_wins_a_display_name_collision() {
|
||||
let ppd = parse_lpoptions("PageSize/Media Size: na_letter_8.5x11in iso_a4_210x297mm *A4\n");
|
||||
let a4: Vec<&PpdPaper> = ppd.papers.iter().filter(|p| p.name == "A4").collect();
|
||||
assert_eq!(a4.len(), 1, "one entry per display name");
|
||||
assert_eq!(a4[0].keyword, ppd.default_size, "the default keeps its own keyword");
|
||||
assert_eq!(printer_config("Office", &ppd).default_paper, "A4");
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ mod dwg_hatch;
|
||||
/// What a DXF file holds that CADCraft doesn't model, kept and written back (#528).
|
||||
mod dxf_raw;
|
||||
|
||||
pub mod cups;
|
||||
/// Annotative text, MText and dimensions: AutoCAD's annotation scale contexts.
|
||||
mod dxf_anno;
|
||||
/// XCLIP boundaries as SPATIAL_FILTER objects.
|
||||
@@ -22,12 +23,17 @@ mod dxf_xref;
|
||||
pub mod pdf;
|
||||
pub mod pdf_read;
|
||||
pub mod plotter;
|
||||
/// The system's printers asked about at once, so one that doesn't answer holds up no other.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod printer_queries;
|
||||
/// Raster image files (PNG, JPEG, BMP, TIFF) decoded to pixels.
|
||||
pub mod raster;
|
||||
/// Open → save → reopen comparison and the real-file corpus harness (gaps FF1, FF5).
|
||||
pub mod roundtrip;
|
||||
pub mod stamp;
|
||||
pub mod svg;
|
||||
mod svg_read;
|
||||
pub mod winprint;
|
||||
|
||||
/// Multilines and their styles (MLINE, MLINESTYLE).
|
||||
mod dxf_mline;
|
||||
|
||||
+130
-22
@@ -102,12 +102,20 @@ pub struct PdfOptions {
|
||||
/// Entity hyperlinks read from a drawing file (`PE_URL` extended data) become link
|
||||
/// annotations too, after [`PdfOptions::links`]. Default on.
|
||||
pub hyperlinks: bool,
|
||||
/// Landscape pages on portrait media: the sheet turned a quarter turn on a page of the
|
||||
/// paper's portrait size (for printers, which feed portrait sheets and may not turn a
|
||||
/// landscape page themselves). Link annotations are left out of turned pages.
|
||||
pub portrait_media: bool,
|
||||
/// Plot objects with their transparency (PDF alpha). `None` = the page setup's "Plot
|
||||
/// transparency" (off for model space).
|
||||
pub plot_transparency: Option<bool>,
|
||||
/// The plot stamp ([`crate::stamp`]): a line of text at the lower-left corner of each
|
||||
/// sheet's printable area.
|
||||
pub stamp: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for PdfOptions {
|
||||
/// Every option unset: the page setup's paper, orientation, scale and plot style decide.
|
||||
fn default() -> Self {
|
||||
PdfOptions {
|
||||
plot_style_table: None,
|
||||
@@ -128,7 +136,9 @@ impl Default for PdfOptions {
|
||||
text_as_geometry: false,
|
||||
margins: None,
|
||||
hyperlinks: true,
|
||||
portrait_media: false,
|
||||
plot_transparency: None,
|
||||
stamp: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -136,7 +146,7 @@ impl Default for PdfOptions {
|
||||
impl PdfOptions {
|
||||
/// Parse `{paper?, width?, height?, landscape?, fit?, scale?, center?, offset?: [x,y] mm,
|
||||
/// lineweights?, compress?, title?, window?: [[x1, y1], [x2, y2]], margins?: [l, b, r, t] (mm),
|
||||
/// hyperlinks?: bool, plotTransparency?: bool}`.
|
||||
/// hyperlinks?: bool, plotTransparency?: bool, stamp?: text}`.
|
||||
pub fn from_json(v: &Value) -> PdfOptions {
|
||||
let num = |k: &str| v.get(k).and_then(Value::as_f64).filter(|x| x.is_finite());
|
||||
let paper_mm = match (num("width"), num("height")) {
|
||||
@@ -164,7 +174,9 @@ impl PdfOptions {
|
||||
window: window(v.get("window")),
|
||||
margins: margins(v.get("margins")),
|
||||
hyperlinks: v.get("hyperlinks").and_then(Value::as_bool).unwrap_or(true),
|
||||
portrait_media: v.get("portraitMedia").and_then(Value::as_bool).unwrap_or(false),
|
||||
plot_transparency: v.get("plotTransparency").and_then(Value::as_bool),
|
||||
stamp: crate::stamp::stamp_text(v),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -250,6 +262,7 @@ pub fn plot_noted(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>,
|
||||
po.window = Some(w);
|
||||
po.fit = Some(true);
|
||||
po.compress = o.compress;
|
||||
po.stamp = o.stamp.clone();
|
||||
Ok((Space::Model, po))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
@@ -492,7 +505,7 @@ fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as
|
||||
let doc = writer.document_mut();
|
||||
// Groups are added to the document, so they must exist before the page starts.
|
||||
groups.add(doc, d, &page.layers);
|
||||
write_page(doc, &page, &groups, &mut fonts)?;
|
||||
write_page(doc, &page, &groups, &mut fonts, o.portrait_media)?;
|
||||
undashed = undashed.saturating_add(page.list.undashed);
|
||||
}
|
||||
if items.len() == 1 && !groups.ids.is_empty() {
|
||||
@@ -534,6 +547,8 @@ struct SheetPage {
|
||||
list: cadcraft_render::DisplayList,
|
||||
map: Map,
|
||||
clip_pt: Bounds2,
|
||||
stamp: cadcraft_render::DisplayList,
|
||||
printable_pt: Bounds2,
|
||||
/// The drawing layers (indices in the layer table) drawn on, in order of first use: the
|
||||
/// candidates for PDF layers.
|
||||
layers: Vec<u32>,
|
||||
@@ -603,7 +618,8 @@ fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String
|
||||
let tolerance = if tol.is_finite() && tol > 0.0 { tol } else { ropts.tolerance };
|
||||
// Relative point sizes follow the plotted window (else the extents).
|
||||
let view_height = window.map(|w| w.height()).unwrap_or(0.0);
|
||||
let list = cadcraft_render::build_plot(d, space, &cadcraft_render::Options { tolerance, view_height, ..ropts });
|
||||
let ropts = cadcraft_render::Options { tolerance, view_height, ..ropts };
|
||||
let list = cadcraft_render::build_plot(d, space, &ropts);
|
||||
let b = window.unwrap_or(list.bounds);
|
||||
let s = plot_scale(&b, &sheet, fit, o.scale);
|
||||
// A layout plotted over a window is placed like model space: the window on the printable area.
|
||||
@@ -615,11 +631,33 @@ fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String
|
||||
} else {
|
||||
Map { from: Vec2::ZERO, s, to: Vec2::ZERO, k }
|
||||
};
|
||||
// Plot style ends, joins and fill patterns at the plot scale (a layout's are already drawn).
|
||||
// A window plots what is inside it only: what lies wholly outside is left out of the page
|
||||
// (a small window of a large drawing stays small), the rest is cut at the window's edges.
|
||||
let mut list = list;
|
||||
if let Some(w) = window {
|
||||
list.retain_within(&window_margin(&w, map.s, unit_mm));
|
||||
}
|
||||
// Plot style ends, joins and fill patterns at the plot scale (a layout's are already drawn).
|
||||
cadcraft_render::pen::apply(&mut list, map.s * unit_mm);
|
||||
let stamp = o
|
||||
.stamp
|
||||
.as_ref()
|
||||
.map(|text| {
|
||||
let text = crate::stamp::fill(text, &sheet_name(space), &page.paper, &crate::stamp::scale_label(map.s));
|
||||
let to_world = |p: Vec2| (p - map.to) / map.s + map.from;
|
||||
crate::stamp::display_list(&text, sheet.printable.min, unit_mm, to_world, 1.0 / map.s, &ropts)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let media = sheet.size * k;
|
||||
let clip_pt = if placed { Bounds2::new(sheet.printable.min * k, sheet.printable.max * k) } else { Bounds2::new(Vec2::ZERO, media) };
|
||||
let printable_pt = Bounds2::new(sheet.printable.min * k, sheet.printable.max * k);
|
||||
let clip_pt = match window {
|
||||
// A window off the printable area plots nothing: a hair-thin clip at its corner.
|
||||
Some(w) => Some(window_on_paper(&w, &map).intersection(&printable_pt))
|
||||
.filter(|c| !c.is_empty())
|
||||
.unwrap_or_else(|| Bounds2::new(printable_pt.min, printable_pt.min + Vec2::new(1e-3, 1e-3))),
|
||||
None if placed => printable_pt,
|
||||
None => Bounds2::new(Vec2::ZERO, media),
|
||||
};
|
||||
// The layers drawn on, in order of first use.
|
||||
let mut layers: Vec<u32> = Vec::new();
|
||||
if o.layers {
|
||||
@@ -631,7 +669,19 @@ fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String
|
||||
}
|
||||
}
|
||||
let links = links(&list, &map, &clip_pt, links_to);
|
||||
Ok(SheetPage { media, list, map, clip_pt, layers, links, label: sheet_name(space) })
|
||||
Ok(SheetPage { media, list, map, clip_pt, stamp, printable_pt, layers, links, label: sheet_name(space) })
|
||||
}
|
||||
|
||||
/// `w` grown by what a plotted line may reach past it, at `s` paper units per drawing unit (see
|
||||
/// [`cadcraft_render::pen::plot_window_reach`]).
|
||||
pub(crate) fn window_margin(w: &Bounds2, s: f64, unit_mm: f64) -> Bounds2 {
|
||||
cadcraft_render::pen::plot_window_reach(w, unit_mm * s)
|
||||
}
|
||||
|
||||
/// A plotted window `w` on the sheet, in points: where its corners land through `map`.
|
||||
fn window_on_paper(w: &Bounds2, map: &Map) -> Bounds2 {
|
||||
let at = |p: Vec2| ((p - map.from) * map.s + map.to) * map.k;
|
||||
Bounds2::new(at(w.min), at(w.max))
|
||||
}
|
||||
|
||||
/// Source and destination origins for the shared model-space PDF/PNG placement behavior.
|
||||
@@ -776,13 +826,24 @@ fn circle_path(x: f32, y: f32, r: f32) -> Option<Path> {
|
||||
pb.finish()
|
||||
}
|
||||
|
||||
/// Write one sheet as a page: its size, label, link annotations and marks.
|
||||
fn write_page(doc: &mut kr::Document, p: &SheetPage, groups: &Groups, fonts: &mut fonts::Fonts) -> std::result::Result<(), Failure> {
|
||||
/// Write one sheet as a page: its size, label, link annotations and marks. With
|
||||
/// `portrait_media`, a landscape sheet goes on a page of the paper's portrait size, turned a
|
||||
/// quarter turn counterclockwise (the sheet's bottom edge up the page's right edge), for
|
||||
/// printers that feed portrait sheets; a turned page has no link annotations.
|
||||
fn write_page(
|
||||
doc: &mut kr::Document,
|
||||
p: &SheetPage,
|
||||
groups: &Groups,
|
||||
fonts: &mut fonts::Fonts,
|
||||
portrait_media: bool,
|
||||
) -> std::result::Result<(), Failure> {
|
||||
let (w, h) = (p.media.x as f32, p.media.y as f32);
|
||||
let turned = portrait_media && w > h;
|
||||
let (pw, ph) = if turned { (h, w) } else { (w, h) };
|
||||
let label = PageLabel::new(None, Some(p.label.chars().take(MAX_TEXT).collect()), None);
|
||||
let settings = PageSettings::from_wh(w, h).ok_or_else(|| IoError::Format("the sheet has no area".into()))?.with_page_label(label);
|
||||
let settings = PageSettings::from_wh(pw, ph).ok_or_else(|| IoError::Format("the sheet has no area".into()))?.with_page_label(label);
|
||||
let mut page = doc.start_page_with(settings);
|
||||
for (r, url) in &p.links {
|
||||
for (r, url) in p.links.iter().filter(|_| !turned) {
|
||||
let Some(uri) = uri(url) else { continue };
|
||||
// Annotation rectangles are given top-down, like the writer's page surface.
|
||||
let Some(rect) = Rect::from_ltrb(r.min.x as f32, h - r.max.y as f32, r.max.x as f32, h - r.min.y as f32) else { continue };
|
||||
@@ -790,13 +851,23 @@ fn write_page(doc: &mut kr::Document, p: &SheetPage, groups: &Groups, fonts: &mu
|
||||
page.add_annotation(Annotation::new_link(link, None));
|
||||
}
|
||||
let mut surface = page.surface();
|
||||
// The surface's y axis points down; flip it so we draw in PDF points (y up).
|
||||
surface.push_transform(&Transform::from_row(1.0, 0.0, 0.0, -1.0, 0.0, h));
|
||||
// The surface's y axis points down; flip it so we draw in PDF points (y up). Turned: the
|
||||
// sheet's (x, y) lands at (h - y, x) on the page, y up.
|
||||
let to_page = if turned { Transform::from_row(0.0, -1.0, -1.0, 0.0, h, w) } else { Transform::from_row(1.0, 0.0, 0.0, -1.0, 0.0, h) };
|
||||
surface.push_transform(&to_page);
|
||||
// Clip to the plot area.
|
||||
let mut drawn = Ok(());
|
||||
if let Some(clip) = rect_path(p.clip_pt.min, p.clip_pt.max) {
|
||||
surface.push_clip_path(&clip, &FillRule::NonZero);
|
||||
drawn = marks(&mut surface, p, groups, fonts);
|
||||
drawn = marks(&mut surface, p, &p.list, &p.clip_pt, groups, fonts);
|
||||
surface.pop();
|
||||
}
|
||||
if drawn.is_ok()
|
||||
&& !p.stamp.prims.is_empty()
|
||||
&& let Some(clip) = rect_path(p.printable_pt.min, p.printable_pt.max)
|
||||
{
|
||||
surface.push_clip_path(&clip, &FillRule::NonZero);
|
||||
drawn = marks(&mut surface, p, &p.stamp, &p.printable_pt, groups, fonts);
|
||||
surface.pop();
|
||||
}
|
||||
surface.pop();
|
||||
@@ -873,8 +944,14 @@ fn krilla_failure(e: KrillaError) -> Failure {
|
||||
/// Primitives that stand for a glyph in an embeddable font (see [`fonts::Fonts`]) are written
|
||||
/// as text instead: the glyph at font size 1 under its glyph matrix (the matrix axes are one
|
||||
/// em).
|
||||
fn marks(s: &mut Surface<'_>, p: &SheetPage, groups: &Groups, fonts: &mut fonts::Fonts) -> std::result::Result<(), Failure> {
|
||||
let list = &p.list;
|
||||
fn marks(
|
||||
s: &mut Surface<'_>,
|
||||
p: &SheetPage,
|
||||
list: &cadcraft_render::DisplayList,
|
||||
clip_pt: &Bounds2,
|
||||
groups: &Groups,
|
||||
fonts: &mut fonts::Fonts,
|
||||
) -> std::result::Result<(), Failure> {
|
||||
let texts = fonts::texts(list);
|
||||
let white = Rgb(255, 255, 255);
|
||||
let mut batch: Option<(StrokeStyle, PathBuilder)> = None;
|
||||
@@ -897,7 +974,7 @@ fn marks(s: &mut Surface<'_>, p: &SheetPage, groups: &Groups, fonts: &mut fonts:
|
||||
let w = if w.is_finite() && w > 0.0 { w.min(100.0) } else { 0.0 };
|
||||
let m = Mark { rgb, t, w };
|
||||
match prim.kind {
|
||||
Kind::Polyline | Kind::Infinite { .. } => polyline(s, &mut batch, p, prim, raw, m),
|
||||
Kind::Polyline | Kind::Infinite { .. } => polyline(s, &mut batch, p, clip_pt, prim, raw, m),
|
||||
Kind::Tris | Kind::Mask => {
|
||||
flush(s, &mut batch);
|
||||
// A wipeout's mask is paper white.
|
||||
@@ -906,7 +983,7 @@ fn marks(s: &mut Surface<'_>, p: &SheetPage, groups: &Groups, fonts: &mut fonts:
|
||||
u32::try_from(i).ok().and_then(|i| texts.get(&i).copied()).and_then(|text| fonts.font(&text.glyph.face).map(|font| (text, font)));
|
||||
match text_font {
|
||||
Some((text, font)) => glyph(s, font, text, &p.map, m.rgb, m.t),
|
||||
None => fill_tris(s, p, raw, m.rgb, m.t),
|
||||
None => fill_tris(s, p, clip_pt, raw, m.rgb, m.t),
|
||||
}
|
||||
}
|
||||
Kind::Point => point(s, &mut batch, &p.map, raw, m),
|
||||
@@ -927,14 +1004,22 @@ struct Mark {
|
||||
}
|
||||
|
||||
/// Stroke a polyline or infinite line, clipped to the plot area, into the open batch.
|
||||
fn polyline(s: &mut Surface<'_>, batch: &mut Option<(StrokeStyle, PathBuilder)>, p: &SheetPage, prim: &DPrim, raw: &[Vec2], m: Mark) {
|
||||
let Some(pts) = polyline_points(prim, raw, &p.map, &p.clip_pt) else { return };
|
||||
fn polyline(
|
||||
s: &mut Surface<'_>,
|
||||
batch: &mut Option<(StrokeStyle, PathBuilder)>,
|
||||
p: &SheetPage,
|
||||
clip_pt: &Bounds2,
|
||||
prim: &DPrim,
|
||||
raw: &[Vec2],
|
||||
m: Mark,
|
||||
) {
|
||||
let Some(pts) = polyline_points(prim, raw, &p.map, clip_pt) else { return };
|
||||
if pts.len() < 2 {
|
||||
return;
|
||||
}
|
||||
// With a vertex out of range, keep the pieces inside the plot area, widened so
|
||||
// a wide stroke just outside it still shows its edge.
|
||||
let runs = if pts.iter().all(|q| coord(*q).is_some()) { vec![pts] } else { clip::clip_polyline(&pts, &p.clip_pt.expand(m.w + 1.0)) };
|
||||
let runs = if pts.iter().all(|q| coord(*q).is_some()) { vec![pts] } else { clip::clip_polyline(&pts, &clip_pt.expand(m.w + 1.0)) };
|
||||
let style = StrokeStyle { rgb: m.rgb, width: m.w as f32, transparency: m.t };
|
||||
if m.t > 0 || batch.as_ref().is_some_and(|(b, _)| *b != style) {
|
||||
flush(s, batch);
|
||||
@@ -986,10 +1071,10 @@ fn stroke_run(s: &mut Surface<'_>, batch: &mut Option<(StrokeStyle, PathBuilder)
|
||||
|
||||
/// Fill a set of triangles, clipped to the plot area, as the loops of their outline (see
|
||||
/// [`outline`]), which fill the same as the triangles with far less path data.
|
||||
fn fill_tris(s: &mut Surface<'_>, p: &SheetPage, raw: &[Vec2], rgb: Rgb, t: u8) {
|
||||
fn fill_tris(s: &mut Surface<'_>, p: &SheetPage, clip_pt: &Bounds2, raw: &[Vec2], rgb: Rgb, t: u8) {
|
||||
let mapped: Vec<Vec2> = raw.iter().map(|q| p.map.pt(*q)).collect();
|
||||
// With a vertex out of range, keep the parts inside the plot area.
|
||||
let tris = if mapped.iter().all(|q| coord(*q).is_some()) { mapped } else { clip::clip_triangles(&mapped, &p.clip_pt) };
|
||||
let tris = if mapped.iter().all(|q| coord(*q).is_some()) { mapped } else { clip::clip_triangles(&mapped, clip_pt) };
|
||||
let tris: Vec<[outline::Pt; 3]> = tris.as_chunks::<3>().0.iter().filter_map(|[a, b, c]| Some([coord(*a)?, coord(*b)?, coord(*c)?])).collect();
|
||||
let rings = outline::loops(&tris).unwrap_or_else(|| tris.iter().map(|t| t.to_vec()).collect());
|
||||
let mut pb = PathBuilder::new();
|
||||
@@ -1141,3 +1226,26 @@ mod saved_setup_tests {
|
||||
assert!(m.from.dist(Vec2::new(428.0, 297.0)) < 1e-9 && m.to.dist(Vec2::new(148.5, 105.0)) < 1e-9, "still placed: {:?} {:?}", m.from, m.to);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod stamp_clip_regressions {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn a_narrow_window_and_its_stamp_have_independent_clips() {
|
||||
let d = Drawing::new_metric();
|
||||
let page = sheet(
|
||||
&d,
|
||||
&Space::Model,
|
||||
&PdfOptions::from_json(&json!({
|
||||
"paper": "A4", "landscape": false, "fit": true, "window": [[0, 0], [1, 100]], "stamp": "Checked"
|
||||
})),
|
||||
&[],
|
||||
)
|
||||
.unwrap();
|
||||
let b = Bounds2::from_points(page.stamp.verts.iter().chain(&page.stamp.tris).map(|p| page.map.pt(*p)));
|
||||
assert!(b.max.x < page.clip_pt.min.x, "the stamp is outside the drawing clip");
|
||||
assert!(page.printable_pt.contains(b.min) && page.printable_pt.contains(b.max), "the stamp remains inside its printable clip");
|
||||
}
|
||||
}
|
||||
|
||||
+198
-7
@@ -3,7 +3,8 @@
|
||||
//!
|
||||
//! PDF goes to [`crate::pdf`]. PNG draws the sheet on white paper at the device resolution
|
||||
//! (capped at [`MAX_PNG_PIXELS`]), with the plot style table and lineweights as PDF uses them.
|
||||
//! SVG shows the sheet of a layout or the model-space extents.
|
||||
//! SVG shows the sheet of a layout or the model-space extents. PDF and PNG plots draw the plot
|
||||
//! stamp (`stamp`, [`crate::stamp`]); SVG doesn't.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -69,21 +70,44 @@ fn fit_scale(b: &Bounds2, sheet: &Sheet, o: &PdfOptions) -> f64 {
|
||||
pdf::plot_scale(b, sheet, o.fit != Some(false), o.scale)
|
||||
}
|
||||
|
||||
/// The PNG plot and the dashed runs it drew continuous because of a dash limit.
|
||||
/// The part of the sheet a PNG plot draws, from the `crop` option: `[x0, y0, x1, y1]` as fractions
|
||||
/// of the sheet, measured from its top-left corner (so `[0, 0, 1, 1]` is the whole sheet). A preview
|
||||
/// zoomed in on a detail asks for just that part at the resolution it needs.
|
||||
fn crop(opts: &Value) -> Result<Option<[f64; 4]>> {
|
||||
let Some(raw) = opts.get("crop").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let v: Vec<f64> = raw.as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
|
||||
match v[..] {
|
||||
[x0, y0, x1, y1]
|
||||
if raw.as_array().is_some_and(|a| a.len() == 4)
|
||||
&& [x0, y0, x1, y1].iter().all(|f| f.is_finite() && (0.0..=1.0).contains(f))
|
||||
&& x1 - x0 >= 1e-6
|
||||
&& y1 - y0 >= 1e-6 =>
|
||||
{
|
||||
Ok(Some([x0, y0, x1, y1]))
|
||||
}
|
||||
_ => Err(IoError::Format("`crop` must be [x0, y0, x1, y1]: fractions of the sheet from 0 to 1, with x0 < x1 and y0 < y1".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// A raster plot: the sheet at the asked resolution (capped in pixels), cropped when asked, with
|
||||
/// the stamp; and the dashed runs it drew continuous because of a dash limit.
|
||||
fn png(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, usize)> {
|
||||
let o = pdf::with_saved_setup(d, space, &PdfOptions::from_json(opts));
|
||||
let (sheet, page) = sheet(d, space, &o)?;
|
||||
let crop = crop(opts)?;
|
||||
// The size of what is drawn, as fractions of the sheet.
|
||||
let (frac_x, frac_y) = crop.map_or((1.0, 1.0), |c| (c[2] - c[0], c[3] - c[1]));
|
||||
let dpi = opts.get("resolution").and_then(Value::as_f64).filter(|r| r.is_finite()).unwrap_or(300.0).clamp(50.0, 2400.0);
|
||||
// Pixels per paper unit, lowered so the image stays within the caps.
|
||||
let mut k = sheet.unit_mm / 25.4 * dpi;
|
||||
let (w, h) = (sheet.size.x * k, sheet.size.y * k);
|
||||
let (w, h) = (sheet.size.x * frac_x * k, sheet.size.y * frac_y * k);
|
||||
let shrink = (MAX_PNG_PIXELS / (w * h).max(1.0)).sqrt().min(16384.0 / w.max(h).max(1.0)).min(1.0);
|
||||
if !(shrink.is_finite() && shrink > 0.0) {
|
||||
return Err(IoError::Format("the sheet is too large to plot as an image".into()));
|
||||
}
|
||||
k *= shrink;
|
||||
let px = |v: f64| (v * k).round().clamp(1.0, 16384.0) as u32;
|
||||
let (width, height) = (px(sheet.size.x), px(sheet.size.y));
|
||||
let (width, height) = (px(sheet.size.x * frac_x), px(sheet.size.y * frac_y));
|
||||
let lineweights = o.lineweights.unwrap_or(if space.is_paper() { page.lineweights } else { true });
|
||||
let table = cadcraft_doc::plot_style_table(d, &page.plot_style_table).map(Arc::new);
|
||||
// Paper units per drawing unit: the fitted scale for model space or a fitted layout, else the
|
||||
@@ -102,9 +126,18 @@ fn png(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, usize)> {
|
||||
let transparency = o.plot_transparency.unwrap_or(page.plot_transparency);
|
||||
let ropts = cadcraft_render::Options { tolerance, lineweights, plot_style_table: table, transparency, ..cadcraft_render::Options::default() };
|
||||
let mut list = cadcraft_render::build_plot(d, space, &ropts);
|
||||
let half = Vec2::new(f64::from(width), f64::from(height)) / (2.0 * k);
|
||||
// The paper point at the image centre (the sheet's centre, or the middle of the crop; the
|
||||
// sheet's origin is its lower-left corner and the crop's is its top-left).
|
||||
let half = match crop {
|
||||
Some(c) => Vec2::new((c[0] + c[2]) / 2.0 * sheet.size.x, (1.0 - (c[1] + c[3]) / 2.0) * sheet.size.y),
|
||||
None => Vec2::new(f64::from(width), f64::from(height)) / (2.0 * k),
|
||||
};
|
||||
let b = window.unwrap_or(list.bounds);
|
||||
let s = if fit { fit_scale(&b, &sheet, &o) } else { est };
|
||||
// A window plots only what is inside it, as PDF does.
|
||||
if let Some(w) = window {
|
||||
list.retain_within(&pdf::window_margin(&w, s, sheet.unit_mm));
|
||||
}
|
||||
// Plot style ends, joins and fill patterns at the plot scale, as PDF draws them (a layout's
|
||||
// are already drawn).
|
||||
cadcraft_render::pen::apply(&mut list, s * sheet.unit_mm);
|
||||
@@ -121,8 +154,31 @@ fn png(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, usize)> {
|
||||
let ro = raster::RasterOptions { background: Rgb(255, 255, 255), hairline: 1.0, px_per_mm, antialias: true };
|
||||
let mut pm = raster::render(&list, &view, &ro).ok_or_else(|| IoError::Format("render failed".into()))?;
|
||||
if placed {
|
||||
// PDF clips a placed plot to the printable area: blank the rest of the sheet.
|
||||
raster::blank_outside_printable(&mut pm, &sheet.printable, k);
|
||||
// PDF clips a placed plot to the printable area, and a window plot to the window too:
|
||||
// blank the rest. Corners go through the view, so a crop is blanked in the same place.
|
||||
let to_world = |q: Vec2| (q - to) / s + from;
|
||||
let printable = Bounds2::new(to_world(sheet.printable.min), to_world(sheet.printable.max));
|
||||
let keep = match window {
|
||||
Some(w) => w.intersection(&printable),
|
||||
None => printable,
|
||||
};
|
||||
if keep.is_empty() {
|
||||
raster::blank_outside_pixels(&mut pm, (0.0, 0.0), (0.0, 0.0));
|
||||
} else {
|
||||
let (x0, y1) = view.to_screen(keep.min);
|
||||
let (x1, y0) = view.to_screen(keep.max);
|
||||
raster::blank_outside_pixels(&mut pm, (f64::from(x0), f64::from(y0)), (f64::from(x1), f64::from(y1)));
|
||||
}
|
||||
}
|
||||
if let Some(text) = &o.stamp {
|
||||
let text = crate::stamp::fill(text, space.tab_name(), &page.paper, &crate::stamp::scale_label(s));
|
||||
let to_world = |p: Vec2| (p - to) / s + from;
|
||||
let stamp = crate::stamp::display_list(&text, sheet.printable.min, sheet.unit_mm, to_world, 1.0 / s, &ropts);
|
||||
// Only the stamp is cut to the printable area: marks the sheet already has in its
|
||||
// margins (a layout not placed keeps them, as in PDF) stay.
|
||||
let (x0, y1) = view.to_screen(to_world(sheet.printable.min));
|
||||
let (x1, y0) = view.to_screen(to_world(sheet.printable.max));
|
||||
raster::render_within(&stamp, &view, &ro, &mut pm, (x0, y0), (x1, y1)).ok_or_else(|| IoError::Format("render failed".into()))?;
|
||||
}
|
||||
let png = raster::encode_png(&pm).ok_or_else(|| IoError::Format("render failed".into()))?;
|
||||
Ok((png, list.undashed))
|
||||
@@ -151,6 +207,9 @@ fn svg(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, usize)> {
|
||||
let ropts = cadcraft_render::Options { tolerance, lineweights, plot_style_table: table, transparency, ..cadcraft_render::Options::default() };
|
||||
let mut list = cadcraft_render::build_plot(d, space, &ropts);
|
||||
let s = fit_scale(&window.unwrap_or(list.bounds), &sheet, &o);
|
||||
if let Some(w) = window {
|
||||
list.retain_within(&pdf::window_margin(&w, s, sheet.unit_mm));
|
||||
}
|
||||
cadcraft_render::pen::apply(&mut list, s * sheet.unit_mm);
|
||||
Ok((crate::svg::export_list(&list, window).into_bytes(), list.undashed))
|
||||
}
|
||||
@@ -168,12 +227,144 @@ mod tests {
|
||||
(be(16), be(20))
|
||||
}
|
||||
|
||||
/// A drawing with one line, enough for a plot to have something on the sheet.
|
||||
fn drawing() -> Drawing {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(100.0, 50.0, 0.0) })).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// A PNG plot decoded.
|
||||
fn decode(bytes: &[u8]) -> tiny_skia::Pixmap {
|
||||
tiny_skia::Pixmap::decode_png(bytes).unwrap()
|
||||
}
|
||||
|
||||
/// A PNG crop is that part of the sheet at the same scale.
|
||||
#[test]
|
||||
fn a_png_crop_is_that_part_of_the_sheet_at_the_same_scale() {
|
||||
let d = drawing();
|
||||
// 127 dpi is 5 pixels per mm: a 200 x 100 mm sheet is 1000 x 500 pixels, and a crop of its
|
||||
// middle half starts on whole pixels.
|
||||
let base = json!({"output": "png", "resolution": 127, "width": 100, "height": 200, "landscape": true, "margins": [0, 0, 0, 0]});
|
||||
let full = decode(&plot(&d, &Space::Model, &base).unwrap());
|
||||
assert_eq!((full.width(), full.height()), (1000, 500));
|
||||
let mut cropped = base.clone();
|
||||
cropped["crop"] = json!([0.25, 0.25, 0.75, 0.75]);
|
||||
let part = decode(&plot(&d, &Space::Model, &cropped).unwrap());
|
||||
assert_eq!((part.width(), part.height()), (500, 250), "half the sheet each way");
|
||||
let mut drawn = 0;
|
||||
for y in 0..part.height() {
|
||||
for x in 0..part.width() {
|
||||
let (a, b) = (part.pixel(x, y).unwrap(), full.pixel(x + 250, y + 125).unwrap());
|
||||
let close = |p: u8, q: u8| p.abs_diff(q) <= 2;
|
||||
assert!(close(a.red(), b.red()) && close(a.green(), b.green()) && close(a.blue(), b.blue()), "pixel {x},{y}");
|
||||
drawn += usize::from(a.red() < 128);
|
||||
}
|
||||
}
|
||||
assert!(drawn > 100, "the crop shows part of the drawing ({drawn} dark pixels)");
|
||||
// A layout is cropped the same way.
|
||||
let layout = Space::Paper(d.layouts[0].name.clone());
|
||||
let lay = json!({"output": "png", "resolution": 127, "width": 100, "height": 200, "landscape": true, "margins": [0, 0, 0, 0]});
|
||||
let l_full = decode(&plot(&d, &layout, &lay).unwrap());
|
||||
let mut l_crop = lay.clone();
|
||||
l_crop["crop"] = json!([0.0, 0.5, 0.5, 1.0]);
|
||||
let l_part = decode(&plot(&d, &layout, &l_crop).unwrap());
|
||||
assert_eq!((l_part.width(), l_part.height()), (l_full.width() / 2, l_full.height() / 2));
|
||||
}
|
||||
|
||||
/// The plot stamp is cut to the printable area on its own: a layout's marks in the sheet
|
||||
/// margins (kept when the layout is not placed) stay where a stamp is drawn (#2171 review).
|
||||
#[test]
|
||||
fn the_stamp_keeps_a_layouts_marks_in_the_margins() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let layout = Space::Paper(d.layouts[0].name.clone());
|
||||
let line = |a: Vec3, b: Vec3| EntityKind::Line(Line { a, b });
|
||||
d.add(&layout, Common::default(), line(Vec3::new(-500.0, 30.0, 0.0), Vec3::new(500.0, 30.0, 0.0))).unwrap();
|
||||
d.add(&layout, Common::default(), line(Vec3::new(30.0, -500.0, 0.0), Vec3::new(30.0, 500.0, 0.0))).unwrap();
|
||||
// 5 pixels per mm on a 200 x 100 mm sheet with 20 mm margins: the printable area is
|
||||
// pixels 100..900 across and 100..400 down.
|
||||
let opts =
|
||||
json!({"output": "png", "resolution": 127, "width": 100, "height": 200, "landscape": true, "margins": [20, 20, 20, 20], "fit": false});
|
||||
let plain = decode(&plot(&d, &layout, &opts).unwrap());
|
||||
let mut with_stamp = opts.clone();
|
||||
with_stamp["stamp"] = json!("STAMP {layout}");
|
||||
let stamped = decode(&plot(&d, &layout, &with_stamp).unwrap());
|
||||
assert_eq!((plain.width(), plain.height()), (1000, 500));
|
||||
let (mut margin_ink, mut changed) = (0, 0);
|
||||
for y in 0..plain.height() {
|
||||
for x in 0..plain.width() {
|
||||
let (a, b) = (plain.pixel(x, y).unwrap(), stamped.pixel(x, y).unwrap());
|
||||
changed += usize::from(a != b);
|
||||
if !(98..902).contains(&x) || !(98..402).contains(&y) {
|
||||
assert_eq!(a, b, "pixel {x},{y} in the margin");
|
||||
margin_ink += usize::from(a.red() < 128);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(margin_ink > 0, "the layout draws in the margins");
|
||||
assert!(changed > 0, "the stamp is drawn");
|
||||
}
|
||||
|
||||
/// Bad crops are errors; no crop, or the whole sheet, is fine.
|
||||
#[test]
|
||||
fn a_bad_png_crop_is_an_error() {
|
||||
let d = drawing();
|
||||
for crop in [
|
||||
json!([0.5, 0.0, 0.5, 1.0]),
|
||||
json!([0.0, 0.8, 1.0, 0.2]),
|
||||
json!([0, 0, 1]),
|
||||
json!([0, 0, 1, 2]),
|
||||
json!([-0.1, 0, 1, 1]),
|
||||
json!("all"),
|
||||
json!([0, 0, 1, f64::NAN]),
|
||||
] {
|
||||
assert!(plot(&d, &Space::Model, &json!({"output": "png", "resolution": 50, "crop": crop})).is_err(), "{crop}");
|
||||
}
|
||||
assert!(plot(&d, &Space::Model, &json!({"output": "png", "resolution": 50, "crop": null})).is_ok(), "no crop is the whole sheet");
|
||||
assert!(plot(&d, &Space::Model, &json!({"output": "png", "resolution": 50, "crop": [0, 0, 1, 1]})).is_ok());
|
||||
}
|
||||
|
||||
/// A drawing with a short line inside the window [0,0]-[10,10], a line outside it to the
|
||||
/// right (inside the sheet once the square window is fitted on a landscape page), and many
|
||||
/// circles far away.
|
||||
fn windowed_drawing() -> Drawing {
|
||||
let mut d = Drawing::new_metric();
|
||||
let line = |a: Vec3, b: Vec3| EntityKind::Line(Line { a, b });
|
||||
d.add(&Space::Model, Common::default(), line(Vec3::new(2.0, 5.0, 0.0), Vec3::new(8.0, 5.0, 0.0))).unwrap();
|
||||
d.add(&Space::Model, Common::default(), line(Vec3::new(12.0, 1.0, 0.0), Vec3::new(12.0, 9.0, 0.0))).unwrap();
|
||||
for i in 0..2000 {
|
||||
let c =
|
||||
cadcraft_doc::Circle { center: Vec3::new(1000.0 + f64::from(i % 50) * 10.0, 1000.0 + f64::from(i / 50) * 10.0, 0.0), radius: 4.0 };
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Circle(c)).unwrap();
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// A window plots only what is inside it (#window): the PNG is blank outside the window even
|
||||
/// where the sheet goes on, and the PDF leaves out what lies outside instead of carrying it.
|
||||
#[test]
|
||||
fn a_window_plots_only_what_is_inside_it() {
|
||||
let d = windowed_drawing();
|
||||
let opts = json!({"output": "png", "resolution": 50, "width": 210, "height": 297, "landscape": true, "plotArea": "window", "window": [[0, 0], [10, 10]], "fit": true});
|
||||
let png = decode(&plot(&d, &Space::Model, &opts).unwrap());
|
||||
let dark = |x0: u32, x1: u32| {
|
||||
(x0..x1).flat_map(|x| (0..png.height()).map(move |y| (x, y))).filter(|(x, y)| png.pixel(*x, *y).is_some_and(|p| p.red() < 128)).count()
|
||||
};
|
||||
let (w, h) = (png.width(), png.height());
|
||||
// The square window fills the page's height, centred: its right edge is at w/2 + h/2.
|
||||
let right_edge = w / 2 + h / 2;
|
||||
assert!(dark(w / 2 - h / 4, w / 2 + h / 4) > 10, "the line inside the window is drawn");
|
||||
assert_eq!(dark(right_edge + 2, w), 0, "nothing outside the window is drawn");
|
||||
let mut pdf_opts = opts.clone();
|
||||
pdf_opts["output"] = json!("pdf");
|
||||
let windowed = plot(&d, &Space::Model, &pdf_opts).unwrap();
|
||||
let mut all = pdf_opts.clone();
|
||||
all["plotArea"] = json!("extents");
|
||||
all.as_object_mut().unwrap().remove("window");
|
||||
let whole = plot(&d, &Space::Model, &all).unwrap();
|
||||
assert!(windowed.len() * 5 < whole.len(), "the window's PDF leaves out the far circles ({} vs {} bytes)", windowed.len(), whole.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_and_svg_devices() {
|
||||
let d = drawing();
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
//! Asking the system about each of its printers at once: a printer whose driver (or print server)
|
||||
//! is slow or never answers holds up neither the others nor the listing. Each printer is asked on
|
||||
//! a thread of its own; the listing takes the answers that came within its time and leaves the
|
||||
//! rest out. A printer whose question from an earlier listing is still unanswered is not asked
|
||||
//! again until it is answered, so listings never pile up threads blocked in one driver.
|
||||
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The printers being asked about, by name: a question still unanswered (perhaps forever).
|
||||
pub(crate) type Asking = Mutex<Vec<String>>;
|
||||
|
||||
/// Takes a printer's name off [`Asking`] when its question ends, answered or not (a panic too).
|
||||
struct Asked {
|
||||
asking: &'static Asking,
|
||||
name: String,
|
||||
}
|
||||
|
||||
impl Drop for Asked {
|
||||
fn drop(&mut self) {
|
||||
let mut a = self.asking.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(i) = a.iter().position(|n| *n == self.name) {
|
||||
a.swap_remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `query` asked about every printer of `items` (a name and what the query needs) at once, each
|
||||
/// on a thread of its own: the answers that came within `time`, in the order of `items`. A
|
||||
/// printer still being asked about since an earlier call (listed in `asking`) is left out, as
|
||||
/// is one whose thread can't be started or whose query gives nothing.
|
||||
pub(crate) fn ask_each<D, T, F>(asking: &'static Asking, items: Vec<(String, D)>, time: Duration, query: F) -> Vec<T>
|
||||
where
|
||||
D: Send + 'static,
|
||||
T: Send + 'static,
|
||||
F: Fn(D) -> Option<T> + Send + Sync + 'static,
|
||||
{
|
||||
let end = Instant::now() + time;
|
||||
let query = Arc::new(query);
|
||||
let (tx, rx) = mpsc::channel::<(usize, Option<T>)>();
|
||||
let mut started = 0usize;
|
||||
for (i, (name, item)) in items.into_iter().enumerate() {
|
||||
{
|
||||
let mut a = asking.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if a.contains(&name) {
|
||||
continue;
|
||||
}
|
||||
a.push(name.clone());
|
||||
}
|
||||
let guard = Asked { asking, name };
|
||||
let (tx, query) = (tx.clone(), query.clone());
|
||||
let spawned = std::thread::Builder::new().name("printer-query".into()).spawn(move || {
|
||||
let _asked = guard;
|
||||
let _ = tx.send((i, query(item)));
|
||||
});
|
||||
// A thread that could not start dropped its guard: the printer is free to be asked again.
|
||||
if spawned.is_ok() {
|
||||
started += 1;
|
||||
}
|
||||
}
|
||||
drop(tx);
|
||||
let mut answers: Vec<(usize, T)> = Vec::new();
|
||||
for _ in 0..started {
|
||||
let left = end.saturating_duration_since(Instant::now());
|
||||
match rx.recv_timeout(left) {
|
||||
Ok((i, Some(t))) => answers.push((i, t)),
|
||||
Ok((_, None)) => {}
|
||||
// Out of time, or every thread still running ended without an answer (a panic).
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
answers.sort_by_key(|(i, _)| *i);
|
||||
answers.into_iter().map(|(_, t)| t).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
static ASKING: Asking = Mutex::new(Vec::new());
|
||||
static ASKED_SLOW: AtomicUsize = AtomicUsize::new(0);
|
||||
static RELEASE: Mutex<Option<mpsc::Receiver<()>>> = Mutex::new(None);
|
||||
|
||||
/// `Slow` doesn't answer until the test lets it; the others answer at once.
|
||||
fn query(name: &'static str) -> Option<&'static str> {
|
||||
if name == "Slow" {
|
||||
ASKED_SLOW.fetch_add(1, Ordering::SeqCst);
|
||||
let held = RELEASE.lock().ok().and_then(|mut r| r.take());
|
||||
if let Some(rx) = held {
|
||||
let _ = rx.recv();
|
||||
}
|
||||
}
|
||||
Some(name)
|
||||
}
|
||||
|
||||
fn items() -> Vec<(String, &'static str)> {
|
||||
["Office", "Slow", "Plotter"].iter().map(|n| (n.to_string(), *n)).collect()
|
||||
}
|
||||
|
||||
/// A printer that doesn't answer leaves the others listed, is not asked again while its
|
||||
/// question is unanswered, and is listed again once it answers (#2171 review).
|
||||
#[test]
|
||||
fn a_printer_that_does_not_answer_holds_up_none_of_the_others() {
|
||||
let (release, rx) = mpsc::channel();
|
||||
*RELEASE.lock().unwrap() = Some(rx);
|
||||
let first = ask_each(&ASKING, items(), Duration::from_millis(300), query);
|
||||
assert_eq!(first, ["Office", "Plotter"]);
|
||||
let second = ask_each(&ASKING, items(), Duration::from_millis(300), query);
|
||||
assert_eq!(second, ["Office", "Plotter"]);
|
||||
assert_eq!(ASKED_SLOW.load(Ordering::SeqCst), 1, "the unanswered printer is not asked again");
|
||||
release.send(()).unwrap();
|
||||
let start = Instant::now();
|
||||
while ASKING.lock().unwrap().contains(&"Slow".to_string()) && start.elapsed() < Duration::from_secs(5) {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
let third = ask_each(&ASKING, items(), Duration::from_secs(5), query);
|
||||
assert_eq!(third, ["Office", "Slow", "Plotter"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
//! The plot stamp (PLOT's `stamp` option): one line of text plotted at the lower-left corner of
|
||||
//! the printable area, as a record of what was plotted where. The text is given; `{layout}`,
|
||||
//! `{paper}` and `{scale}` in it become each sheet's own, so a plot of several sheets stamps
|
||||
//! every sheet with its name.
|
||||
|
||||
use cadcraft_color::Color;
|
||||
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Text};
|
||||
use cadcraft_geom::{Vec2, Vec3};
|
||||
use serde_json::Value;
|
||||
|
||||
/// Height of the stamp's characters on paper (mm).
|
||||
pub const STAMP_HEIGHT_MM: f64 = 2.0;
|
||||
/// Gap between the printable area's corner and the stamp (mm).
|
||||
const STAMP_GAP_MM: f64 = 1.0;
|
||||
/// Most characters of a stamp, as it is drawn.
|
||||
pub const MAX_STAMP: usize = 300;
|
||||
/// Most characters of the `stamp` option read: the command fills in names before the plotter
|
||||
/// does, writing each `{` in them as `{{`, so the text read can be longer than what is drawn.
|
||||
/// [`fill`] limits the drawn text to [`MAX_STAMP`].
|
||||
const MAX_STAMP_INPUT: usize = 16 * MAX_STAMP;
|
||||
/// A text style no drawing is expected to have, so the stamp is always in CADCraft's own
|
||||
/// stroke font (a missing style plots with the default one).
|
||||
const STAMP_STYLE: &str = "CADCraft plot stamp";
|
||||
|
||||
/// The `stamp` option's text: printable characters, at most [`MAX_STAMP_INPUT`] (the drawn
|
||||
/// text is limited once [`fill`] has decoded it); `None` without one (or an empty one).
|
||||
pub fn stamp_text(opts: &Value) -> Option<String> {
|
||||
let t: String = opts.get("stamp")?.as_str()?.chars().filter(|c| !c.is_control()).take(MAX_STAMP_INPUT).collect();
|
||||
let t = t.trim();
|
||||
(!t.is_empty()).then(|| t.to_string())
|
||||
}
|
||||
|
||||
/// A plot scale as people write it: `1:100`, `2:1`, `1:1`.
|
||||
pub fn scale_label(paper_per_drawing: f64) -> String {
|
||||
if !(paper_per_drawing.is_finite() && paper_per_drawing > 0.0) {
|
||||
return "1:1".into();
|
||||
}
|
||||
let trim = |v: f64| {
|
||||
let s = format!("{v:.3}");
|
||||
s.trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
};
|
||||
if paper_per_drawing >= 1.0 { format!("{}:1", trim(paper_per_drawing)) } else { format!("1:{}", trim(1.0 / paper_per_drawing)) }
|
||||
}
|
||||
|
||||
/// The stamp with `{layout}`, `{paper}` and `{scale}` filled in for one sheet, in one pass (a
|
||||
/// layout named `Detail {paper}` is copied as it is), `{{` as a literal brace.
|
||||
pub fn fill(text: &str, layout: &str, paper: &str, scale: &str) -> String {
|
||||
cadcraft_doc::fill_stamp(text, &[("layout", layout), ("paper", paper), ("scale", scale)], true).chars().take(MAX_STAMP).collect()
|
||||
}
|
||||
|
||||
/// What the stamp draws on a sheet whose printable area starts at `corner` (paper units, `unit_mm`
|
||||
/// millimetres each): `to_world` maps a paper point to the coordinates the sheet is built in, where
|
||||
/// one paper unit is `world_per_paper` units. The stamp is not a part of the drawing: it is built
|
||||
/// against an empty drawing, so no layer, style or setting of the plotted one (layer 0 turned off
|
||||
/// or frozen) hides or changes it.
|
||||
pub fn display_list(
|
||||
text: &str,
|
||||
corner: Vec2,
|
||||
unit_mm: f64,
|
||||
to_world: impl Fn(Vec2) -> Vec2,
|
||||
world_per_paper: f64,
|
||||
opts: &cadcraft_render::Options,
|
||||
) -> cadcraft_render::DisplayList {
|
||||
let unit = if unit_mm.is_finite() && unit_mm > 0.0 { unit_mm } else { 1.0 };
|
||||
let gap = STAMP_GAP_MM / unit;
|
||||
let at = to_world(corner + Vec2::new(gap, gap));
|
||||
let height = STAMP_HEIGHT_MM / unit * world_per_paper;
|
||||
if !(at.x.is_finite() && at.y.is_finite() && height.is_finite() && height > 0.0) {
|
||||
return cadcraft_render::DisplayList::default();
|
||||
}
|
||||
let t = Text {
|
||||
insert: Vec3::new(at.x, at.y, 0.0),
|
||||
align_pt: None,
|
||||
height,
|
||||
value: text.to_string(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: STAMP_STYLE.into(),
|
||||
halign: Default::default(),
|
||||
valign: Default::default(),
|
||||
backwards: false,
|
||||
upside_down: false,
|
||||
};
|
||||
let e = Entity { handle: Handle(0), common: Common { color: Color::Index(7), ..Common::default() }, kind: EntityKind::Text(t) };
|
||||
cadcraft_render::build_entities(&Drawing::default(), [&e], opts)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
/// The stamp's text is trimmed, capped and filled in, and scales read as AutoCAD writes them.
|
||||
#[test]
|
||||
fn stamp_text_scale_and_placeholders() {
|
||||
assert_eq!(stamp_text(&json!({ "stamp": " Plan\u{7}.dwg " })).as_deref(), Some("Plan.dwg"));
|
||||
assert_eq!(stamp_text(&json!({ "stamp": " " })), None);
|
||||
assert_eq!(stamp_text(&json!({ "stamp": true })), None);
|
||||
// Capped as drawn: the limit applies once the plotter has filled the text in.
|
||||
assert_eq!(stamp_text(&json!({ "stamp": "x".repeat(1000) })).map(|s| fill(&s, "", "", "").len()), Some(MAX_STAMP));
|
||||
assert_eq!(scale_label(0.01), "1:100");
|
||||
assert_eq!(scale_label(2.0), "2:1");
|
||||
assert_eq!(scale_label(1.0), "1:1");
|
||||
assert_eq!(scale_label(1.0 / 66.6667), "1:66.667");
|
||||
assert_eq!(scale_label(f64::NAN), "1:1");
|
||||
assert_eq!(fill("{layout} · {paper} · {scale}", "Sheet 1", "A3", "1:50"), "Sheet 1 · A3 · 1:50");
|
||||
// A sheet name that looks like a field is copied, not filled (#2171 review).
|
||||
assert_eq!(fill("{layout} · {paper}", "Detail {paper}", "A4", "1:1"), "Detail {paper} · A4");
|
||||
}
|
||||
|
||||
/// The stamp is drawn just inside the printable area's lower-left corner, about 2 mm high.
|
||||
#[test]
|
||||
fn the_stamp_draws_text_at_the_corner() {
|
||||
let opts = cadcraft_render::Options { text: true, fill: true, ..cadcraft_render::Options::default() };
|
||||
let list = display_list("Plan.dwg", Vec2::new(10.0, 20.0), 1.0, |p| p, 1.0, &opts);
|
||||
assert!(!list.prims.is_empty(), "the stamp's characters are drawn");
|
||||
// Just inside the printable area's lower-left corner, about 2 mm high.
|
||||
assert!(list.bounds.min.x >= 10.0 && list.bounds.min.y >= 20.0, "{:?}", list.bounds);
|
||||
assert!(list.bounds.max.y < 20.0 + STAMP_GAP_MM + STAMP_HEIGHT_MM * 1.5, "{:?}", list.bounds);
|
||||
// A mapping that goes nowhere draws nothing rather than failing.
|
||||
assert!(display_list("x", Vec2::ZERO, 1.0, |_| Vec2::new(f64::NAN, 0.0), 1.0, &opts).prims.is_empty());
|
||||
}
|
||||
|
||||
/// PDF and PNG plots draw the stamp; without one they are as before.
|
||||
#[test]
|
||||
fn pdf_and_png_plots_carry_the_stamp() {
|
||||
let mut d = Drawing::default();
|
||||
let line = cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(100.0, 50.0, 0.0) };
|
||||
d.add(&cadcraft_doc::Space::Model, Common::default(), EntityKind::Line(line)).unwrap();
|
||||
let plot = |extra: Value| {
|
||||
let mut o = json!({ "paper": "A4", "compress": false });
|
||||
if let (Some(o), Some(e)) = (o.as_object_mut(), extra.as_object()) {
|
||||
o.extend(e.clone());
|
||||
}
|
||||
crate::plotter::plot(&d, &cadcraft_doc::Space::Model, &o).unwrap()
|
||||
};
|
||||
let pdf_plain = plot(json!({}));
|
||||
let pdf_stamped = plot(json!({ "stamp": "Plan.dwg {layout} {paper} {scale}" }));
|
||||
assert!(pdf_stamped.len() > pdf_plain.len() + 200, "{} vs {}", pdf_stamped.len(), pdf_plain.len());
|
||||
let png_plain = plot(json!({ "output": "png", "resolution": 100 }));
|
||||
let png_stamped = plot(json!({ "output": "png", "resolution": 100, "stamp": "Plan.dwg {layout}" }));
|
||||
assert_ne!(png_plain, png_stamped);
|
||||
// An empty stamp is no stamp.
|
||||
assert_eq!(plot(json!({ "output": "png", "resolution": 100, "stamp": " " })), png_plain);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod window_stamp_regressions {
|
||||
use super::*;
|
||||
use cadcraft_doc::Space;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn a_centered_narrow_window_does_not_erase_the_png_stamp() {
|
||||
let d = Drawing::new_metric();
|
||||
let mut opts = json!({ "output": "png", "resolution": 100, "paper": "A4", "landscape": false, "fit": true, "window": [[0, 0], [1, 100]] });
|
||||
let plain = crate::plotter::plot(&d, &Space::Model, &opts).unwrap();
|
||||
opts["stamp"] = json!("Checked");
|
||||
let stamped = crate::plotter::plot(&d, &Space::Model, &opts).unwrap();
|
||||
assert_ne!(plain, stamped, "the stamp remains visible outside the narrow drawing window");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod stamp_review_regressions {
|
||||
use super::*;
|
||||
use cadcraft_doc::Space;
|
||||
use serde_json::json;
|
||||
|
||||
/// The drawn-text limit applies after `{{` is decoded: a name of 200 braces filled in by the
|
||||
/// command (as 400 characters) is drawn whole (#2171 review).
|
||||
#[test]
|
||||
fn the_limit_counts_the_decoded_text() {
|
||||
let encoded = "{{".repeat(200);
|
||||
let text = stamp_text(&json!({ "stamp": encoded })).unwrap_or_default();
|
||||
assert_eq!(fill(&text, "Model", "A4", "1:1"), "{".repeat(200));
|
||||
// Still bounded: a hostile text is cut before it is drawn.
|
||||
let long = fill(&stamp_text(&json!({ "stamp": "x".repeat(100_000) })).unwrap_or_default(), "", "", "");
|
||||
assert_eq!(long.chars().count(), MAX_STAMP);
|
||||
}
|
||||
|
||||
/// Layer 0 off or frozen in the drawing hides none of the stamp (#2171 review).
|
||||
#[test]
|
||||
fn layer_0_off_or_frozen_keeps_the_stamp() {
|
||||
let opts = json!({ "output": "png", "resolution": 100, "paper": "A4", "landscape": false });
|
||||
for hide in [|l: &mut cadcraft_doc::Layer| l.on = false, |l: &mut cadcraft_doc::Layer| l.frozen = true] {
|
||||
let mut d = Drawing::new_metric();
|
||||
if let Some(l) = d.layer_mut("0") {
|
||||
hide(l);
|
||||
}
|
||||
let plain = crate::plotter::plot(&d, &Space::Model, &opts).unwrap();
|
||||
let mut with = opts.clone();
|
||||
with["stamp"] = json!("Checked");
|
||||
assert_ne!(crate::plotter::plot(&d, &Space::Model, &with).unwrap(), plain, "the stamp is drawn");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5487,3 +5487,54 @@ fn a_layer_state_saved_before_masks_restores_everything() {
|
||||
let got: Vec<(&str, u32, &str, &str)> = states.iter().map(|s| (s.name.as_str(), s.mask, s.current.as_str(), s.description.as_str())).collect();
|
||||
assert_eq!(got, [("S", LayerState::ALL, "", "")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_pages_keep_the_plot_stamp_on_every_sheet() {
|
||||
let d = sample();
|
||||
let mut options = serde_json::json!({ "pages": [
|
||||
{ "window": [[0, 0], [10, 10]], "paper": "A4" },
|
||||
{ "window": [[10, 0], [20, 10]], "paper": "A3" }
|
||||
], "text": "geometry", "compress": false });
|
||||
let plain = pdf_read::read(&crate::pdf::plot(&d, &Space::Model, &options).unwrap());
|
||||
options["stamp"] = serde_json::json!("CADCRAFT STAMP");
|
||||
let stamped = pdf_read::read(&crate::pdf::plot(&d, &Space::Model, &options).unwrap());
|
||||
assert_eq!(stamped.pages.len(), 2);
|
||||
for (before, after) in plain.pages.iter().zip(&stamped.pages) {
|
||||
assert!(after.content_bytes.len() > before.content_bytes.len(), "each sheet must draw the stamp");
|
||||
}
|
||||
// The stamp's ink is outside the window: each page restores the window's clip, then paints
|
||||
// the stamp under the wider printable-area clip (#2171 review).
|
||||
for page in &stamped.pages {
|
||||
let ops = pdf_read::ops(&page.content);
|
||||
let (mut depth, mut path, mut clips) = (0i32, Vec::<Vec2>::new(), Vec::new());
|
||||
for (i, o) in ops.iter().enumerate() {
|
||||
match o.op.as_str() {
|
||||
"q" => depth += 1,
|
||||
"Q" => depth -= 1,
|
||||
"m" | "l" | "c" | "v" | "y" => path.extend(o.nums.as_chunks::<2>().0.iter().map(|[x, y]| Vec2::new(*x, *y))),
|
||||
"re" if o.nums.len() == 4 => {
|
||||
let (x, y, w, h) = (o.nums[0], o.nums[1], o.nums[2], o.nums[3]);
|
||||
path.extend([Vec2::new(x, y), Vec2::new(x + w, y + h)]);
|
||||
}
|
||||
"W" | "W*" => clips.push((i, depth, cadcraft_geom::Bounds2::from_points(path.iter().copied()))),
|
||||
"n" | "S" | "s" | "f" | "F" | "f*" | "B" | "B*" | "b" | "b*" => path.clear(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let [(window_at, window_depth, window), (stamp_at, stamp_depth, printable)] = clips[..] else {
|
||||
panic!("a clip for the drawing and one for the stamp: {clips:?}");
|
||||
};
|
||||
let area = |b: &cadcraft_geom::Bounds2| b.width() * b.height();
|
||||
assert!(printable.expand(0.01).contains_box(&window) && area(&printable) > area(&window) + 1.0, "{printable:?} vs {window:?}");
|
||||
assert!(stamp_depth <= window_depth && ops[window_at..stamp_at].iter().any(|o| o.op == "Q"), "the window's clip is restored first");
|
||||
let ink: Vec<Vec2> = ops[stamp_at + 1..]
|
||||
.iter()
|
||||
.filter(|o| matches!(o.op.as_str(), "m" | "l" | "c"))
|
||||
.flat_map(|o| o.nums.as_chunks::<2>().0.iter().map(|[x, y]| Vec2::new(*x, *y)).collect::<Vec<_>>())
|
||||
.collect();
|
||||
assert!(
|
||||
ink.iter().any(|q| !window.contains(*q) && printable.contains(*q)),
|
||||
"the stamp is painted outside the window, inside the printable area"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
//! System printers on Windows: the spooler's printers, each with the papers its driver offers
|
||||
//! and their printable areas (from the driver's PrintCapabilities), and printing a plot's PDF
|
||||
//! through craft-print (Windows.Data.Pdf drawn as vectors into the XPS print API, no program
|
||||
//! started). craft-print also owns the Windows driver capability queries.
|
||||
//!
|
||||
//! The PDF is the one the PDF plotter writes for the chosen paper, so it is printed at its exact
|
||||
//! size: craft-print picks the driver's paper of that size and refuses a driver that would scale
|
||||
//! it. The conversions take plain values, so they are tested without a printer.
|
||||
|
||||
use cadcraft_doc::{DevicePaper, Orientation, PlotOutput, PlotterConfig};
|
||||
|
||||
/// Most printers listed.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
const MAX_PRINTERS: usize = 64;
|
||||
/// Most papers of one printer.
|
||||
const MAX_PAPERS: usize = 256;
|
||||
/// Most copies of one job.
|
||||
pub const MAX_COPIES: u32 = 999;
|
||||
|
||||
pub use craft_print::WindowsPaper as WinPaper;
|
||||
#[cfg(test)]
|
||||
use craft_print::margins_from_imageable_mm as margins_from_imageable;
|
||||
|
||||
/// The paper that stands for its size among the papers that can be listed (`listable`): the
|
||||
/// one with the widest margins (the plain sheet rather than its borderless variant), the first
|
||||
/// on a tie.
|
||||
fn represents_its_size(listable: &[&WinPaper], p: &WinPaper) -> bool {
|
||||
let total = |m: Option<[f64; 4]>| m.map_or(0.0, |m| m.iter().sum::<f64>());
|
||||
let chosen = listable.iter().copied().filter(|o| o.same_size(p)).fold(None::<&WinPaper>, |best, o| match best {
|
||||
Some(b) if total(b.margins) >= total(o.margins) => Some(b),
|
||||
_ => Some(o),
|
||||
});
|
||||
chosen.is_some_and(|c| std::ptr::eq(c, p))
|
||||
}
|
||||
|
||||
/// The papers that can be listed, in the driver's order: named, with a length, and the first
|
||||
/// of each name as the device tells names apart ([`cadcraft_doc::paper_name_key`]: `Label X` and
|
||||
/// `Label-X` are one name). A representative is chosen among these only, so a paper the device
|
||||
/// would drop for its repeated name never stands for (and hides) a paper of another name.
|
||||
fn listable(papers: &[WinPaper]) -> Vec<&WinPaper> {
|
||||
let mut out: Vec<(String, &WinPaper)> = Vec::new();
|
||||
for p in papers {
|
||||
let key = cadcraft_doc::paper_name_key(&p.name);
|
||||
if p.width != 0 && p.height != 0 && !key.is_empty() && !out.iter().any(|(k, _)| *k == key) {
|
||||
out.push((key, p));
|
||||
}
|
||||
}
|
||||
out.into_iter().map(|(_, p)| p).collect()
|
||||
}
|
||||
|
||||
/// The device a printer becomes: a system printer (PDF in, printed by craft-print) with its
|
||||
/// driver's papers. Roll papers (no length), unnamed papers and repeated names are dropped; the
|
||||
/// default paper is the driver's default (`default_key`) when it is one of them, else the first.
|
||||
/// Papers of one size are listed once (see [`represents_its_size`]) with margins every one of
|
||||
/// them can print, so the preview never shows a borderless area the driver may not use.
|
||||
pub fn printer_config(name: &str, default_printer: bool, papers: &[WinPaper], default_key: Option<&str>) -> PlotterConfig {
|
||||
let mut device_papers: Vec<DevicePaper> = Vec::new();
|
||||
let mut default_paper = String::new();
|
||||
let candidates = listable(papers);
|
||||
for &p in &candidates {
|
||||
if device_papers.len() >= MAX_PAPERS {
|
||||
break;
|
||||
}
|
||||
// Sizes chain within the tolerance (210.0, 210.2, 210.4 mm): leave a paper out only when
|
||||
// a paper that is listed stands for it.
|
||||
if !represents_its_size(&candidates, p) && candidates.iter().any(|q| p.same_size(q) && represents_its_size(&candidates, q)) {
|
||||
continue;
|
||||
}
|
||||
if default_paper.is_empty() && default_key.is_some_and(|k| papers.iter().any(|o| o.key == k && o.same_size(p))) {
|
||||
default_paper = p.name.clone();
|
||||
}
|
||||
let margins = p.conservative_margins(papers);
|
||||
device_papers.push(DevicePaper {
|
||||
native_key: None,
|
||||
name: p.name.clone(),
|
||||
width: f64::from(p.width) / 1000.0,
|
||||
height: f64::from(p.height) / 1000.0,
|
||||
margins,
|
||||
});
|
||||
}
|
||||
if default_paper.is_empty() {
|
||||
default_paper = device_papers.first().map(|p| p.name.clone()).unwrap_or_default();
|
||||
}
|
||||
let description = if default_printer { "Windows printer (default)" } else { "Windows printer" };
|
||||
let mut config = PlotterConfig {
|
||||
name: name.to_string(),
|
||||
description: description.to_string(),
|
||||
output: PlotOutput::Pdf,
|
||||
resolution: 300,
|
||||
orientation: Orientation::Landscape,
|
||||
default_paper,
|
||||
papers: device_papers,
|
||||
system: true,
|
||||
system_default: default_printer,
|
||||
}
|
||||
.sanitized();
|
||||
// The spooler's identifier must survive display-data sanitization exactly.
|
||||
config.name = if name.chars().count() <= 32_767 && !name.chars().any(char::is_control) { name.to_string() } else { String::new() };
|
||||
config
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod system {
|
||||
use super::{MAX_COPIES, MAX_PRINTERS, PlotterConfig, printer_config};
|
||||
|
||||
fn printer(queue: craft_print::Printer) -> Option<PlotterConfig> {
|
||||
let catalog = craft_print::windows_paper_catalog(&queue.name)?;
|
||||
let config = printer_config(&queue.name, queue.default, &catalog.papers, catalog.default_key.as_deref());
|
||||
(!config.name.is_empty() && !config.papers.is_empty()).then_some(config)
|
||||
}
|
||||
|
||||
/// Printers whose drivers are being asked for their papers.
|
||||
static ASKING: crate::printer_queries::Asking = std::sync::Mutex::new(Vec::new());
|
||||
/// How long the drivers' answers are waited for: a printer whose driver answers later (or
|
||||
/// never) is left out of this listing, and the engine's own wait for it is not run out.
|
||||
const PRINTERS_TIME: std::time::Duration = std::time::Duration::from_secs(8);
|
||||
|
||||
/// The spooler's printers as devices, with a bounded wait for driver answers. A question
|
||||
/// that is still outstanding from an earlier listing is left running without a retry.
|
||||
/// The shared provider serializes the underlying Windows capability calls.
|
||||
pub fn printers() -> Vec<PlotterConfig> {
|
||||
let items: Vec<_> = craft_print::printer_queues().into_iter().take(MAX_PRINTERS).map(|queue| (queue.name.clone(), queue)).collect();
|
||||
crate::printer_queries::ask_each(&ASKING, items, PRINTERS_TIME, printer)
|
||||
}
|
||||
|
||||
/// Print `pdf` on `printer`. The paper is the PDF's own sheet size: craft-print chooses the
|
||||
/// driver's paper of that size, so `paper` only names it. Returns the spooler's reply.
|
||||
pub fn print(printer: &str, paper: &str, copies: u32, title: &str, pdf: &[u8]) -> Result<String, String> {
|
||||
// craft-print picks the driver's paper of the PDF's size; the list offers one paper per
|
||||
// size, with margins every option of that size can print (see `printer_config`).
|
||||
let _ = paper;
|
||||
let title: String = title.chars().filter(|c| !c.is_control()).take(100).collect();
|
||||
let job = craft_print::Job {
|
||||
printer: Some(printer.to_string()),
|
||||
copies: copies.clamp(1, MAX_COPIES),
|
||||
collate: true,
|
||||
// The printer's own duplex default.
|
||||
duplex: None,
|
||||
// The plot is already at its scale: no fitting to the page.
|
||||
scaling: craft_print::Scaling::Exact,
|
||||
grayscale: false,
|
||||
title: if title.trim().is_empty() { "CADCraft".into() } else { title },
|
||||
..craft_print::Job::default()
|
||||
};
|
||||
craft_print::submit(pdf, &job).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub use system::{print, printers};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// This machine's printers and papers, and how long listing them takes
|
||||
/// (`cargo test -p cadcraft-io --lib winprint -- --ignored --nocapture`).
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
#[ignore = "asks this machine's printer drivers"]
|
||||
fn list_this_machines_printers() {
|
||||
let start = std::time::Instant::now();
|
||||
let names: Vec<_> = craft_print::printer_queues().into_iter().map(|queue| queue.name).collect();
|
||||
println!("spooler: {names:?} ({:?})", start.elapsed());
|
||||
for c in printers() {
|
||||
println!("{} [{}] default paper {:?}, {} papers", c.name, c.description, c.default_paper, c.papers.len());
|
||||
for p in c.papers.iter().take(8) {
|
||||
println!(" {} {:.1} x {:.1} mm, margins {:?}", p.name, p.width, p.height, p.margins);
|
||||
}
|
||||
}
|
||||
println!("listed in {:?}", start.elapsed());
|
||||
}
|
||||
|
||||
/// The printable area's origin and size become left, bottom, right and top margins in millimetres.
|
||||
#[test]
|
||||
fn margins_from_the_printable_area() {
|
||||
// A4 with 3.4 mm unprintable left and right, 3 mm at the top and 5 mm at the bottom.
|
||||
let m = margins_from_imageable((210_000, 297_000), (3_400, 3_000), (203_200, 289_000)).unwrap();
|
||||
let want = [3.4, 5.0, 3.4, 3.0];
|
||||
for (a, b) in m.iter().zip(want) {
|
||||
assert!((a - b).abs() < 1e-9, "{m:?}");
|
||||
}
|
||||
// Borderless.
|
||||
assert_eq!(margins_from_imageable((210_000, 297_000), (0, 0), (210_000, 297_000)), Some([0.0; 4]));
|
||||
// An area past the page's edge, or none.
|
||||
assert_eq!(margins_from_imageable((210_000, 297_000), (5_000, 0), (210_000, 297_000)), None);
|
||||
assert_eq!(margins_from_imageable((210_000, 297_000), (0, 0), (0, 0)), None);
|
||||
}
|
||||
|
||||
/// Driver papers become device papers in mm with their margins, duplicate names and rolls left
|
||||
/// out; the default printer is marked, and an unknown default paper falls back to the first.
|
||||
#[test]
|
||||
fn driver_papers_become_a_device() {
|
||||
let p = |key: &str, name: &str, width, height, margins| WinPaper { key: key.into(), name: name.into(), width, height, margins };
|
||||
let papers = [
|
||||
p("NorthAmericaLetter", "Letter", 215_900, 279_400, Some([3.4, 5.0, 3.4, 3.0])),
|
||||
p("ISOA4", "A4", 210_000, 297_000, Some([0.0; 4])),
|
||||
p("Custom1", "a4", 210_000, 297_000, Some([0.0; 4])),
|
||||
p("Roll", "Roll 24 in", 609_600, 0, None),
|
||||
p("ISOA3", "A3", 297_000, 420_000, None),
|
||||
];
|
||||
let c = printer_config("HP LaserJet", true, &papers, Some("ISOA4"));
|
||||
assert!(c.system);
|
||||
assert_eq!(c.output, PlotOutput::Pdf);
|
||||
assert_eq!(c.description, "Windows printer (default)");
|
||||
assert!(c.system_default);
|
||||
let names: Vec<&str> = c.papers.iter().map(|p| p.name.as_str()).collect();
|
||||
assert_eq!(names, ["Letter", "A4", "A3"]);
|
||||
assert_eq!(c.default_paper, "A4");
|
||||
let a4 = c.paper("A4").unwrap();
|
||||
assert!((a4.width - 210.0).abs() < 1e-9 && (a4.height - 297.0).abs() < 1e-9);
|
||||
assert_eq!(a4.margins, [0.0; 4]);
|
||||
assert_eq!(c.paper("Letter").unwrap().margins, [3.4, 5.0, 3.4, 3.0]);
|
||||
// A paper past the margin queries stays listed, with margins at least the driver's widest.
|
||||
let a3 = c.paper("A3").unwrap().margins;
|
||||
assert!(a3.iter().zip([3.4, 5.0, 3.4, 3.0]).all(|(m, widest)| *m >= widest && *m > 0.0), "{a3:?}");
|
||||
// An unknown default falls back to the first paper.
|
||||
let other = printer_config("Canon", false, &papers, Some("JapanHagaki"));
|
||||
assert_eq!(other.default_paper, "Letter");
|
||||
assert_eq!(other.description, "Windows printer");
|
||||
}
|
||||
/// craft-print picks a paper by its size, so a size with a borderless variant is listed once,
|
||||
/// as the plain sheet, with margins both options can print; the spooler's name is kept whole.
|
||||
#[test]
|
||||
fn a_borderless_variant_shares_one_entry_with_printable_margins() {
|
||||
let p = |key: &str, name: &str, margins| WinPaper { key: key.into(), name: name.into(), width: 210_000, height: 297_000, margins };
|
||||
let papers = [
|
||||
p("Borderless", "A4 Borderless", Some([0.0; 4])),
|
||||
p("ISOA4", "A4", Some([5.0, 4.0, 5.0, 3.0])),
|
||||
p("ISOA4Wide", "A4 (wide top)", Some([3.0, 4.0, 3.0, 6.0])),
|
||||
];
|
||||
let name = format!("{}X", "Q".repeat(100));
|
||||
let config = printer_config(&name, false, &papers, Some("Borderless"));
|
||||
assert_eq!(config.name, name, "a long spooler name is not truncated into another printer's");
|
||||
let names: Vec<&str> = config.papers.iter().map(|p| p.name.as_str()).collect();
|
||||
assert_eq!(names, ["A4"]);
|
||||
assert_eq!(config.default_paper, "A4", "the driver's default variant maps to its size's entry");
|
||||
assert_eq!(config.papers[0].margins, [5.0, 4.0, 5.0, 6.0]);
|
||||
// An unknown printable area is not advertised as borderless.
|
||||
let config = printer_config("P", false, &[p("ISOA4", "A4", None)], None);
|
||||
assert!(config.papers[0].margins.iter().all(|m| *m > 0.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod unknown_margin_regressions {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_known_borderless_variant_does_not_hide_unknown_plain_margins() {
|
||||
let papers = [
|
||||
WinPaper { key: "Borderless".into(), name: "A4 Borderless".into(), width: 210_000, height: 297_000, margins: Some([0.0; 4]) },
|
||||
WinPaper { key: "ISOA4".into(), name: "A4".into(), width: 210_000, height: 297_000, margins: None },
|
||||
];
|
||||
let config = printer_config("P", false, &papers, None);
|
||||
assert_eq!(config.papers.len(), 1, "the size stays listed");
|
||||
assert!(config.papers[0].margins.iter().all(|m| *m > 0.0), "{:?}", config.papers[0].margins);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_left_out_paper_has_a_listed_paper_within_tolerance() {
|
||||
let p = |key: &str, width, total: f64| WinPaper { key: key.into(), name: key.into(), width, height: 297_000, margins: Some([total; 4]) };
|
||||
let papers = [p("W0", 210_000, 1.0), p("W2", 210_200, 2.0), p("W4", 210_400, 3.0)];
|
||||
let config = printer_config("P", false, &papers, None);
|
||||
for o in &papers {
|
||||
let w = f64::from(o.width) / 1000.0;
|
||||
assert!(config.papers.iter().any(|d| (d.width - w).abs() <= 0.25), "{} has no listed paper within tolerance", o.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// A paper left out for its repeated name does not stand for a paper of another name: `Label`
|
||||
/// at 210 mm and again at 215 mm, and `Other` at 215.1 mm, list `Label` and `Other` (#2171 review).
|
||||
#[test]
|
||||
fn a_paper_dropped_for_its_name_does_not_hide_another_size() {
|
||||
let p = |name: &str, width, m: f64| WinPaper { key: name.into(), name: name.into(), width, height: 297_000, margins: Some([m; 4]) };
|
||||
let papers = [p("Label", 210_000, 1.0), p("Label", 215_000, 9.0), p("Other", 215_100, 2.0)];
|
||||
let config = printer_config("P", false, &papers, None);
|
||||
let listed: Vec<(&str, f64)> = config.papers.iter().map(|d| (d.name.as_str(), d.width)).collect();
|
||||
assert_eq!(listed, [("Label", 210.0), ("Other", 215.1)]);
|
||||
// Other keeps margins every option of its size prints, the left-out Label's included.
|
||||
assert_eq!(config.papers[1].margins, [9.0; 4]);
|
||||
}
|
||||
|
||||
/// Names the device tells apart the same way are one name before a representative is chosen:
|
||||
/// `Label X` at 210 mm and `Label-X` at 215 mm leave `Other` at 215.1 mm listed (#2171 review).
|
||||
#[test]
|
||||
fn a_name_the_device_merges_does_not_hide_another_size() {
|
||||
let p = |name: &str, width, m: f64| WinPaper { key: name.into(), name: name.into(), width, height: 297_000, margins: Some([m; 4]) };
|
||||
let papers = [p("Label X", 210_000, 1.0), p("Label-X", 215_000, 9.0), p("Other", 215_100, 2.0)];
|
||||
let config = printer_config("P", false, &papers, None);
|
||||
let listed: Vec<(&str, f64)> = config.papers.iter().map(|d| (d.name.as_str(), d.width)).collect();
|
||||
assert_eq!(listed, [("Label X", 210.0), ("Other", 215.1)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#![cfg(windows)]
|
||||
|
||||
#[test]
|
||||
fn the_plot_dialog_lists_the_real_queues_papers_and_default() {
|
||||
let queue = std::env::var("CADCRAFT_TEST_QUEUE").expect("selected Windows test queue");
|
||||
let config = cadcraft_io::winprint::printers().into_iter().find(|item| item.name == queue).expect("queue in CadCraft plotter list");
|
||||
assert!(config.paper(&config.default_paper).is_some());
|
||||
for (width, height) in [(210.0, 297.0), (215.9, 279.4)] {
|
||||
let form = config
|
||||
.papers
|
||||
.iter()
|
||||
.find(|paper| (paper.width - width).abs() < 0.6 && (paper.height - height).abs() < 0.6)
|
||||
.expect("driver-advertised A4 and US Letter");
|
||||
assert!(form.margins.iter().all(|margin| margin.is_finite() && *margin >= 0.0));
|
||||
println!("{}: {} x {} mm, margins {:?}", form.name, form.width, form.height, form.margins);
|
||||
}
|
||||
println!("{}: {} media, default {}", config.name, config.papers.len(), config.default_paper);
|
||||
}
|
||||
@@ -256,6 +256,7 @@ fn unusual_titles_are_kept() {
|
||||
assert_eq!(doc.title.as_deref(), Some("Plan ü (1)\\"));
|
||||
}
|
||||
|
||||
/// Layers beyond the PDF layer cap still print; only their PDF layers are left out.
|
||||
#[test]
|
||||
fn layers_past_the_cap_print_without_a_pdf_layer() {
|
||||
// One more drawing layer than a file has PDF layers (4096).
|
||||
@@ -273,3 +274,23 @@ fn layers_past_the_cap_print_without_a_pdf_layer() {
|
||||
assert_eq!(pdf_read::drawn(c).iter().filter(|o| o.op == "m").count(), 4097);
|
||||
assert_eq!((pdf_read::count(c, "BDC"), pdf_read::count(c, "EMC")), (4096, 4096));
|
||||
}
|
||||
|
||||
/// With `portraitMedia`, a landscape sheet is drawn a quarter turn on a portrait page; without it the page stays landscape.
|
||||
#[test]
|
||||
fn portrait_media_turns_landscape_sheets_for_printers() {
|
||||
let d = layered();
|
||||
let page = |o: serde_json::Value| read(&plot(&d, &Space::Model, &o).unwrap()).pages.into_iter().next().unwrap();
|
||||
// The page's transforms (`cm`): the writer's own y flip, and the quarter turn when turned.
|
||||
let cms = |p: &pdf_read::Page| -> Vec<Vec<f64>> { pdf_read::ops(&p.content).into_iter().filter(|o| o.op == "cm").map(|o| o.nums).collect() };
|
||||
let plain = page(json!({ "paper": "Letter", "landscape": true }));
|
||||
assert_eq!(plain.media, [0.0, 0.0, 792.0, 612.0]);
|
||||
assert!(cms(&plain).is_empty());
|
||||
// On portrait media: a portrait page, the sheet turned a quarter turn counterclockwise.
|
||||
let turned = page(json!({ "paper": "Letter", "landscape": true, "portraitMedia": true }));
|
||||
assert_eq!(turned.media, [0.0, 0.0, 612.0, 792.0]);
|
||||
assert!(cms(&turned).iter().any(|m| m == &[0.0, 1.0, -1.0, 0.0, 612.0, 0.0]), "{:?}", cms(&turned));
|
||||
// A portrait sheet is not turned.
|
||||
let portrait = page(json!({ "paper": "Letter", "landscape": false, "portraitMedia": true }));
|
||||
assert_eq!(portrait.media, [0.0, 0.0, 612.0, 792.0]);
|
||||
assert!(cms(&portrait).is_empty());
|
||||
}
|
||||
|
||||
@@ -168,6 +168,65 @@ pub fn alpha(transparency: u8) -> u8 {
|
||||
pub const MAX_TRANSPARENCY: u8 = 90;
|
||||
|
||||
impl DisplayList {
|
||||
/// Add what `other` draws (built for the same drawing, in the same coordinates) after what
|
||||
/// this list draws: a plot stamp, say.
|
||||
pub fn append(&mut self, other: DisplayList) {
|
||||
append(self, other);
|
||||
}
|
||||
|
||||
/// Keep only the primitives that reach into `area` (same coordinates as the list): what a
|
||||
/// plot of a window draws. Infinite lines are kept (they are cut where they are drawn); text
|
||||
/// glyphs, layers and pens follow their primitives. The vertex and triangle arrays are
|
||||
/// compacted, so a small window of a large drawing writes and rasterises only its part.
|
||||
pub fn retain_within(&mut self, area: &Bounds2) {
|
||||
if area.is_empty() || !area.min.is_finite() || !area.max.is_finite() {
|
||||
return;
|
||||
}
|
||||
let keep: Vec<bool> = self
|
||||
.prims
|
||||
.iter()
|
||||
.map(|p| matches!(p.kind, Kind::Infinite { .. }) || Bounds2::from_points(self.points(p).iter().copied()).intersects(area))
|
||||
.collect();
|
||||
if keep.iter().all(|k| *k) {
|
||||
return;
|
||||
}
|
||||
let (mut prims, mut verts, mut tris) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let (mut layers, mut pens) = (Vec::new(), Vec::new());
|
||||
// The new index of each old primitive that is kept.
|
||||
let mut moved: Vec<Option<u32>> = Vec::with_capacity(self.prims.len());
|
||||
for (i, (p, k)) in self.prims.iter().zip(&keep).enumerate() {
|
||||
let tri = matches!(p.kind, Kind::Tris | Kind::Mask);
|
||||
let (src, dst) = if tri { (&self.tris, &mut tris) } else { (&self.verts, &mut verts) };
|
||||
let (Ok(index), Ok(start), true) = (u32::try_from(prims.len()), u32::try_from(dst.len()), *k) else {
|
||||
moved.push(None);
|
||||
continue;
|
||||
};
|
||||
let from = p.start as usize;
|
||||
dst.extend_from_slice(src.get(from..from.saturating_add(p.len as usize)).unwrap_or(&[]));
|
||||
if let Some(pen) = self.pens.get(i) {
|
||||
pens.resize(prims.len(), Pen::default());
|
||||
pens.push(*pen);
|
||||
}
|
||||
prims.push(DPrim { start, ..*p });
|
||||
if let Some(l) = self.prim_layers.get(i) {
|
||||
layers.push(*l);
|
||||
}
|
||||
moved.push(Some(index));
|
||||
}
|
||||
self.texts.retain_mut(|t| {
|
||||
if t.prim >= PlotText::CLIPPED {
|
||||
return t.bounds.intersects(area);
|
||||
}
|
||||
match moved.get(t.prim as usize).copied().flatten() {
|
||||
Some(i) => {
|
||||
t.prim = i;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
});
|
||||
(self.prims, self.verts, self.tris, self.prim_layers, self.pens) = (prims, verts, tris, layers, pens);
|
||||
}
|
||||
pub fn segment_count(&self) -> usize {
|
||||
self.prims.iter().filter(|p| p.kind == Kind::Polyline).map(|p| p.len.saturating_sub(1) as usize).sum()
|
||||
}
|
||||
@@ -189,10 +248,10 @@ impl DisplayList {
|
||||
}
|
||||
|
||||
/// Append `src` to `dst`: its primitives index into `dst`'s vertex and triangle arrays.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn append(dst: &mut DisplayList, src: DisplayList) {
|
||||
let (verts, tris, prims) = (dst.verts.len() as u32, dst.tris.len() as u32, dst.prims.len() as u32);
|
||||
let images = dst.images.len() as u32;
|
||||
let src_prims = src.prims.len();
|
||||
// Pens are parallel to the primitives, with missing entries meaning "use object".
|
||||
if !src.pens.is_empty() {
|
||||
dst.pens.resize(dst.prims.len(), Pen::default());
|
||||
@@ -207,7 +266,13 @@ pub(crate) fn append(dst: &mut DisplayList, src: DisplayList) {
|
||||
dst.images.extend(src.images);
|
||||
dst.verts.extend(src.verts);
|
||||
dst.tris.extend(src.tris);
|
||||
dst.prim_layers.extend(src.prim_layers);
|
||||
// Layers are parallel to the primitives too: when either list has them, a primitive without
|
||||
// one gets NO_LAYER, so every later primitive keeps its own layer.
|
||||
if !src.prim_layers.is_empty() || !dst.prim_layers.is_empty() {
|
||||
dst.prim_layers.resize(prims as usize, NO_LAYER);
|
||||
dst.prim_layers.extend(src.prim_layers.into_iter().take(src_prims));
|
||||
dst.prim_layers.resize(prims as usize + src_prims, NO_LAYER);
|
||||
}
|
||||
dst.texts.extend(src.texts.into_iter().map(|mut t| {
|
||||
if t.prim < PlotText::CLIPPED {
|
||||
t.prim += prims;
|
||||
|
||||
@@ -64,6 +64,19 @@ pub const MAX_PATTERN_CELLS: usize = 2_000_000;
|
||||
/// Miters longer than this many half widths are drawn bevelled (as PDF's default miter limit).
|
||||
pub(crate) const MITER_LIMIT: f64 = 10.0;
|
||||
|
||||
/// The widest plotted lineweight, in paper millimetres.
|
||||
const MAX_PLOT_WIDTH_MM: f64 = 2.11;
|
||||
|
||||
/// `w` (in drawing units) grown by the most a plotted stroke can reach past the line it draws:
|
||||
/// a sharp mitred corner of the widest lineweight (half its width times [`MITER_LIMIT`]) and a
|
||||
/// millimetre more, at `mm_per_unit` paper millimetres per drawing unit, plus 1 % of the window.
|
||||
/// What a window plot keeps ([`crate::DisplayList::retain_within`]); the final clip stays at `w`.
|
||||
pub fn plot_window_reach(w: &cadcraft_geom::Bounds2, mm_per_unit: f64) -> cadcraft_geom::Bounds2 {
|
||||
let reach = (MAX_PLOT_WIDTH_MM / 2.0 * MITER_LIMIT + 1.0) / mm_per_unit;
|
||||
let margin = if reach.is_finite() && reach > 0.0 { reach } else { 0.0 };
|
||||
w.expand(margin + w.width().max(w.height()) * 0.01)
|
||||
}
|
||||
|
||||
/// Segments of a half circle (round ends and joins).
|
||||
const ROUND_STEPS: usize = 12;
|
||||
|
||||
|
||||
@@ -82,6 +82,15 @@ pub fn render(list: &DisplayList, view: &View, o: &RasterOptions) -> Option<Pixm
|
||||
}
|
||||
let mut pm = Pixmap::new(view.width, view.height)?;
|
||||
pm.fill(tiny_skia::Color::from_rgba8(o.background.0, o.background.1, o.background.2, 255));
|
||||
render_into(list, view, o, &mut pm)?;
|
||||
Some(pm)
|
||||
}
|
||||
|
||||
/// Draw onto an existing pixmap, preserving its background and earlier marks.
|
||||
pub fn render_into(list: &DisplayList, view: &View, o: &RasterOptions, pm: &mut Pixmap) -> Option<()> {
|
||||
if pm.width() != view.width || pm.height() != view.height {
|
||||
return None;
|
||||
}
|
||||
let vis = view.world_bounds();
|
||||
let mut hairlines = Hairlines::default();
|
||||
let mut screen: Vec<(f32, f32)> = Vec::new();
|
||||
@@ -93,7 +102,7 @@ pub fn render(list: &DisplayList, view: &View, o: &RasterOptions) -> Option<Pixm
|
||||
paint.anti_alias = o.antialias;
|
||||
let pts = list.points(p);
|
||||
if p.kind != Kind::Polyline {
|
||||
hairlines.flush(&mut pm, o.antialias);
|
||||
hairlines.flush(pm, o.antialias);
|
||||
}
|
||||
match p.kind {
|
||||
Kind::Polyline => {
|
||||
@@ -105,10 +114,10 @@ pub fn render(list: &DisplayList, view: &View, o: &RasterOptions) -> Option<Pixm
|
||||
screen.clear();
|
||||
screen.extend(pts.iter().map(|q| view.to_screen(*q)));
|
||||
if is_hairline(w, o.antialias) && screen.len() >= 2 && screen.iter().all(|&(x, y)| batchable(x) && batchable(y)) {
|
||||
hairlines.add(&mut pm, [c.0, c.1, c.2, p.alpha()], w, &screen, o.antialias);
|
||||
hairlines.add(pm, [c.0, c.1, c.2, p.alpha()], w, &screen, o.antialias);
|
||||
continue;
|
||||
}
|
||||
hairlines.flush(&mut pm, o.antialias);
|
||||
hairlines.flush(pm, o.antialias);
|
||||
let mut pb = PathBuilder::new();
|
||||
for (i, (x, y)) in screen.iter().enumerate() {
|
||||
if i == 0 {
|
||||
@@ -156,7 +165,7 @@ pub fn render(list: &DisplayList, view: &View, o: &RasterOptions) -> Option<Pixm
|
||||
if let Some(img) = list.images.get(index as usize)
|
||||
&& Bounds2::from_points(pts.iter().copied()).intersects(&vis)
|
||||
{
|
||||
image(&mut pm, img, view, p.alpha(), o.antialias);
|
||||
image(pm, img, view, p.alpha(), o.antialias);
|
||||
}
|
||||
}
|
||||
Kind::Infinite { ray } => {
|
||||
@@ -175,8 +184,39 @@ pub fn render(list: &DisplayList, view: &View, o: &RasterOptions) -> Option<Pixm
|
||||
}
|
||||
}
|
||||
}
|
||||
hairlines.flush(&mut pm, o.antialias);
|
||||
Some(pm)
|
||||
hairlines.flush(pm, o.antialias);
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Draw onto an existing pixmap, but only inside the pixel rectangle from `top_left` to
|
||||
/// `bottom_right` (image coordinates, y down; rounded and clamped to the image): what the list
|
||||
/// draws outside it is cut, and what the pixmap already holds there stays as it is.
|
||||
pub fn render_within(
|
||||
list: &DisplayList,
|
||||
view: &View,
|
||||
o: &RasterOptions,
|
||||
pm: &mut Pixmap,
|
||||
top_left: (f32, f32),
|
||||
bottom_right: (f32, f32),
|
||||
) -> Option<()> {
|
||||
if pm.width() != view.width || pm.height() != view.height {
|
||||
return None;
|
||||
}
|
||||
let edge = |v: f32, max: u32| f64::from(v).round().clamp(0.0, f64::from(max)) as u32;
|
||||
let (x0, x1) = (edge(top_left.0, view.width), edge(bottom_right.0, view.width));
|
||||
let (y0, y1) = (edge(top_left.1, view.height), edge(bottom_right.1, view.height));
|
||||
if x1 <= x0 || y1 <= y0 {
|
||||
return Some(());
|
||||
}
|
||||
let (w, h) = (x1 - x0, y1 - y0);
|
||||
// The same view, cut to the rectangle: its centre is the world point at the rectangle's centre.
|
||||
let dx = (f64::from(x0) + f64::from(w) / 2.0 - f64::from(view.width) / 2.0) / view.scale;
|
||||
let dy = (f64::from(y0) + f64::from(h) / 2.0 - f64::from(view.height) / 2.0) / view.scale;
|
||||
let sub = View { center: view.center + Vec2::new(dx, -dy), scale: view.scale, width: w, height: h };
|
||||
let mut layer = Pixmap::new(w, h)?;
|
||||
render_into(list, &sub, o, &mut layer)?;
|
||||
pm.draw_pixmap(i32::try_from(x0).ok()?, i32::try_from(y0).ok()?, layer.as_ref(), &tiny_skia::PixmapPaint::default(), Transform::identity(), None);
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Whether tiny-skia strokes a line `width` pixels wide (untransformed) as a hairline: zero
|
||||
|
||||
@@ -1907,6 +1907,68 @@ fn rotated_and_reversed_copies_of_a_curved_loop_fill_once() {
|
||||
assert_eq!(loops_of(&h).len(), 2);
|
||||
}
|
||||
|
||||
/// `retain_within` keeps the primitives that reach into the area, with their layers, and
|
||||
/// compacts the vertex arrays; one that is all inside or all outside decides alone.
|
||||
#[test]
|
||||
fn retain_within_keeps_what_reaches_the_area() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let line = |a: Vec3, b: Vec3| EntityKind::Line(cadcraft_doc::Line { a, b });
|
||||
d.add(&Space::Model, Common::default(), line(Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 0.0))).unwrap();
|
||||
d.add(&Space::Model, Common::default(), line(Vec3::new(100.0, 100.0, 0.0), Vec3::new(110.0, 100.0, 0.0))).unwrap();
|
||||
d.add(&Space::Model, Common::default(), line(Vec3::new(-5.0, -50.0, 0.0), Vec3::new(-5.0, 50.0, 0.0))).unwrap();
|
||||
let mut list = build_plot(&d, &Space::Model, &Options::default());
|
||||
assert_eq!(list.prims.len(), 3);
|
||||
// Distinct layers, so compaction is seen to keep each primitive's own.
|
||||
list.prim_layers = vec![10, 11, 12];
|
||||
list.retain_within(&Bounds2::new(Vec2::new(-10.0, -1.0), Vec2::new(20.0, 1.0)));
|
||||
assert_eq!(list.prims.len(), 2, "the far line goes, the one crossing the area stays");
|
||||
assert_eq!(list.prim_layers, [10, 12]);
|
||||
assert!(list.verts.iter().all(|p| p.x < 50.0), "the far line's vertices are gone");
|
||||
for p in &list.prims {
|
||||
assert_eq!(list.points(p).len(), p.len as usize);
|
||||
}
|
||||
// An empty or non-finite area keeps everything.
|
||||
let before = list.prims.len();
|
||||
list.retain_within(&Bounds2::EMPTY);
|
||||
assert_eq!(list.prims.len(), before);
|
||||
}
|
||||
|
||||
/// A window plot keeps a line whose sharp mitred corner (the widest lineweight, 2.11 mm, at the
|
||||
/// miter limit) reaches into the window from outside the old 3 mm margin.
|
||||
#[test]
|
||||
fn the_window_reach_covers_a_mitred_corner() {
|
||||
let w = Bounds2::new(Vec2::ZERO, Vec2::new(100.0, 100.0));
|
||||
let kept = crate::pen::plot_window_reach(&w, 1.0);
|
||||
// Points (-15, 48.5), (-5, 50), (-15, 51.5): the miter tip reaches about 7.1 mm right of (-5, 50).
|
||||
let corner = Bounds2::from_points([Vec2::new(-15.0, 48.5), Vec2::new(-5.0, 50.0), Vec2::new(-15.0, 51.5)]);
|
||||
assert!(corner.intersects(&kept));
|
||||
// At a smaller plot scale (fewer paper mm per unit) the same reach covers more drawing units.
|
||||
assert!(crate::pen::plot_window_reach(&w, 0.1).width() > kept.width());
|
||||
}
|
||||
|
||||
/// Appending keeps each primitive's layer, whichever list had layers.
|
||||
#[test]
|
||||
fn append_keeps_layers_aligned_with_primitives() {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })).unwrap();
|
||||
let one = || build_plot(&d, &Space::Model, &Options::default());
|
||||
let (mut plain, mut layered) = (one(), one());
|
||||
plain.prim_layers.clear();
|
||||
layered.prim_layers = vec![7];
|
||||
plain.append(layered.clone());
|
||||
assert_eq!(plain.prim_layers, [NO_LAYER, 7]);
|
||||
let mut first = layered;
|
||||
let mut other = one();
|
||||
other.prim_layers.clear();
|
||||
first.append(other);
|
||||
assert_eq!(first.prim_layers, [7, NO_LAYER]);
|
||||
let (mut a, mut b) = (one(), one());
|
||||
a.prim_layers.clear();
|
||||
b.prim_layers.clear();
|
||||
a.append(b);
|
||||
assert!(a.prim_layers.is_empty(), "lists without layers stay without");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_background_mask_emits_mask_before_text() {
|
||||
let mut d = Drawing::new_metric();
|
||||
|
||||
+478
-54
@@ -4,9 +4,10 @@
|
||||
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
use egui::TextureHandle;
|
||||
use egui::{Pos2, Rect, Sense, TextureHandle, Vec2, pos2, vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::managers::PreviewRequest;
|
||||
use crate::{CadApp, Pick};
|
||||
|
||||
/// Bumped each time PREVIEW is started, so the window renders the drawing as it is now.
|
||||
@@ -167,84 +168,345 @@ pub(crate) fn version_params(ui: &crate::UiState, path: &str) -> Value {
|
||||
}
|
||||
}
|
||||
|
||||
/// Without a file dialog, say on the command line how to run the command with parameters.
|
||||
fn no_picker(app: &mut CadApp, name: &str, example: &str) -> Result<Value, String> {
|
||||
let msg = format!("{name}: there is no file dialog here; run it with parameters, e.g. {example}");
|
||||
app.session.echo(msg.clone());
|
||||
Err(msg)
|
||||
}
|
||||
|
||||
/// How far the preview can be zoomed in, as a multiple of the whole sheet fitting its area.
|
||||
const MAX_ZOOM: f32 = 24.0;
|
||||
/// How long (seconds) the view must rest before the part in view is drawn again in more detail.
|
||||
const SETTLE: f64 = 0.15;
|
||||
|
||||
/// How the sheet's image sits in the preview area: `zoom` 1 fits the whole sheet, `pan` moves the
|
||||
/// image's centre from the area's centre (points).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct PanZoom {
|
||||
zoom: f32,
|
||||
pan: Vec2,
|
||||
}
|
||||
|
||||
impl Default for PanZoom {
|
||||
/// The whole sheet in view.
|
||||
fn default() -> Self {
|
||||
PanZoom { zoom: 1.0, pan: Vec2::ZERO }
|
||||
}
|
||||
}
|
||||
|
||||
impl PanZoom {
|
||||
/// Points per image pixel when the whole image fits `area`.
|
||||
fn fit(area: Rect, image: Vec2) -> f32 {
|
||||
(area.width() / image.x.max(1.0)).min(area.height() / image.y.max(1.0)).max(1e-6)
|
||||
}
|
||||
|
||||
/// Where the whole image is drawn.
|
||||
fn image_rect(&self, area: Rect, image: Vec2) -> Rect {
|
||||
Rect::from_center_size(area.center() + self.pan, image * (Self::fit(area, image) * self.zoom))
|
||||
}
|
||||
|
||||
/// Keep the zoom in range and the image over the area: it can't be dragged away, and is
|
||||
/// centred along an axis where it is smaller than the area.
|
||||
fn clamp(&mut self, area: Rect, image: Vec2) {
|
||||
self.zoom = if self.zoom.is_finite() { self.zoom.clamp(1.0, MAX_ZOOM) } else { 1.0 };
|
||||
let size = image * (Self::fit(area, image) * self.zoom);
|
||||
let room = |image: f32, area: f32| ((image - area) / 2.0).max(0.0);
|
||||
let (rx, ry) = (room(size.x, area.width()), room(size.y, area.height()));
|
||||
self.pan =
|
||||
if self.pan.x.is_finite() && self.pan.y.is_finite() { vec2(self.pan.x.clamp(-rx, rx), self.pan.y.clamp(-ry, ry)) } else { Vec2::ZERO };
|
||||
}
|
||||
|
||||
/// Zoom by `factor` about the screen point `at`, which stays over the same point of the image.
|
||||
fn zoom_at(&mut self, area: Rect, image: Vec2, at: Pos2, factor: f32) {
|
||||
if !(factor.is_finite() && factor > 0.0) {
|
||||
return;
|
||||
}
|
||||
let centre = self.image_rect(area, image).center();
|
||||
let zoom = (self.zoom * factor).clamp(1.0, MAX_ZOOM);
|
||||
let moved = at + (centre - at) * (zoom / self.zoom);
|
||||
self.zoom = zoom;
|
||||
self.pan = moved - area.center();
|
||||
self.clamp(area, image);
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of the image drawn at `shown` that is inside `area`, as fractions of the image from its
|
||||
/// top-left corner `[x0, y0, x1, y1]`; `None` when none of it is.
|
||||
fn visible_crop(area: Rect, shown: Rect) -> Option<[f32; 4]> {
|
||||
let v = area.intersect(shown);
|
||||
if shown.width() < 1.0 || shown.height() < 1.0 || v.width() < 1.0 || v.height() < 1.0 {
|
||||
return None;
|
||||
}
|
||||
let (w, h) = (shown.width(), shown.height());
|
||||
Some([(v.min.x - shown.min.x) / w, (v.min.y - shown.min.y) / h, (v.max.x - shown.min.x) / w, (v.max.y - shown.min.y) / h])
|
||||
}
|
||||
|
||||
/// `crop` grown by a quarter of its size on each side (within the sheet): what is drawn in detail,
|
||||
/// so that a small pan stays sharp.
|
||||
fn with_margin(c: [f32; 4]) -> [f32; 4] {
|
||||
let (mx, my) = ((c[2] - c[0]) / 4.0, (c[3] - c[1]) / 4.0);
|
||||
[(c[0] - mx).max(0.0), (c[1] - my).max(0.0), (c[2] + mx).min(1.0), (c[3] + my).min(1.0)]
|
||||
}
|
||||
|
||||
/// Whether crop `outer` covers crop `inner`.
|
||||
fn covers(outer: [f32; 4], inner: [f32; 4]) -> bool {
|
||||
outer[0] <= inner[0] + 1e-4 && outer[1] <= inner[1] + 1e-4 && outer[2] >= inner[2] - 1e-4 && outer[3] >= inner[3] - 1e-4
|
||||
}
|
||||
|
||||
/// The sheet as plotted: the whole of it drawn once, and what the preview needs to draw parts of it
|
||||
/// again in more detail.
|
||||
#[derive(Clone)]
|
||||
struct Shown {
|
||||
base: TextureHandle,
|
||||
info: String,
|
||||
/// The sheet's width and height in mm, as plotted (the orientation applied).
|
||||
sheet_mm: Vec2,
|
||||
/// The `plot` parameters of the whole sheet.
|
||||
params: Value,
|
||||
}
|
||||
|
||||
/// A part of the sheet drawn at the resolution of the screen it is shown on.
|
||||
#[derive(Clone)]
|
||||
struct Detail {
|
||||
tex: TextureHandle,
|
||||
/// The part, as fractions of the sheet from its top-left corner.
|
||||
crop: [f32; 4],
|
||||
/// The width in points the whole sheet had on screen when it was drawn.
|
||||
sheet_width: f32,
|
||||
}
|
||||
|
||||
impl Detail {
|
||||
/// Whether it is drawn at the scale the sheet has on screen now.
|
||||
fn matches(&self, sheet_width: f32) -> bool {
|
||||
sheet_width > 0.0 && (self.sheet_width / sheet_width - 1.0).abs() < 0.01
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Preview {
|
||||
generation: u32,
|
||||
shown: Result<(TextureHandle, String), String>,
|
||||
}
|
||||
|
||||
/// A preview the Plot dialog asked for: its PLOT parameters (PNG output) and a caption.
|
||||
#[derive(Clone)]
|
||||
struct FromPlot {
|
||||
params: Value,
|
||||
info: String,
|
||||
document: (u64, Option<(u64, u64)>),
|
||||
shown: Result<Shown, String>,
|
||||
view: PanZoom,
|
||||
detail: Option<Detail>,
|
||||
/// When the view, or the size the sheet is drawn at, last changed (seconds), to draw in detail
|
||||
/// once it rests.
|
||||
changed: f64,
|
||||
/// Where the sheet was drawn last: a resized window changes it with the view unchanged.
|
||||
drawn: Rect,
|
||||
/// The part and scale last drawn in detail, so a failure is not retried every frame.
|
||||
tried: Option<([i32; 4], i32)>,
|
||||
}
|
||||
|
||||
/// Where the preview the Plot dialog asked for is kept ([`PreviewRequest`]).
|
||||
const FROM_PLOT: &str = "cc_plot_preview_from_plot";
|
||||
|
||||
/// Show the Plot dialog's settings as they plot (PLOT with `params`, a PNG); Print... and Close
|
||||
/// return to the dialog.
|
||||
pub(crate) fn preview_plot(app: &mut CadApp, ctx: &egui::Context, params: Value, info: String) {
|
||||
/// Show the Plot dialog's settings as they plot (PLOT with the request's parameters, a PNG);
|
||||
/// Print... and Close return to the dialog.
|
||||
pub(crate) fn preview_plot(app: &mut CadApp, ctx: &egui::Context, request: PreviewRequest) {
|
||||
PREVIEW_GEN.fetch_add(1, Ordering::Relaxed);
|
||||
ctx.data_mut(|d| d.insert_temp(egui::Id::unique(FROM_PLOT), FromPlot { params, info }));
|
||||
ctx.data_mut(|d| d.insert_temp(egui::Id::unique(FROM_PLOT), request));
|
||||
app.ui.dialog = Some("preview".into());
|
||||
}
|
||||
|
||||
/// Render the plot preview of the current layout (or model), or of the Plot dialog's settings,
|
||||
/// as a texture.
|
||||
fn render(app: &mut CadApp, ctx: &egui::Context) -> Result<(TextureHandle, String), String> {
|
||||
if let Some(f) = ctx.data(|d| d.get_temp::<FromPlot>(egui::Id::unique(FROM_PLOT))) {
|
||||
let r = app.session.execute("plot", &f.params).map_err(|e| e.to_string())?;
|
||||
let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?;
|
||||
let tex = preview_texture(ctx, &png)?;
|
||||
return Ok((tex, f.info));
|
||||
}
|
||||
let r = app.session.execute("preview", &json!({ "width": 1600 })).map_err(|e| e.to_string())?;
|
||||
let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?;
|
||||
let tex = preview_texture(ctx, &png)?;
|
||||
let mut info = format!("{} · {}", r["layout"].as_str().unwrap_or(""), r["paper"].as_str().unwrap_or(""));
|
||||
if r["landscape"].as_bool() == Some(true) {
|
||||
info.push_str(" · landscape");
|
||||
}
|
||||
Ok((tex, info))
|
||||
/// The preview the Plot dialog asked for, if this preview is one.
|
||||
fn from_plot(ctx: &egui::Context) -> Option<PreviewRequest> {
|
||||
ctx.data(|d| d.get_temp::<PreviewRequest>(egui::Id::unique(FROM_PLOT)))
|
||||
}
|
||||
|
||||
fn preview_texture(ctx: &egui::Context, png: &[u8]) -> Result<TextureHandle, String> {
|
||||
/// Whether a preview the Plot dialog asked for is of another drawing than the one shown now (the
|
||||
/// user switched drawings, or entered or left the Block Editor): it is not plotted with the
|
||||
/// drawing shown, and Print... is off.
|
||||
fn stale(app: &CadApp, request: Option<&PreviewRequest>) -> bool {
|
||||
request.is_some_and(|r| r.drawing != crate::managers::plot_drawing(app))
|
||||
}
|
||||
|
||||
/// Plot `params` (a PNG) and load it as a texture called `name`.
|
||||
fn plot_texture(app: &mut CadApp, ctx: &egui::Context, params: &Value, name: &str) -> Result<TextureHandle, String> {
|
||||
let r = app.session.execute("plot", params).map_err(|e| e.to_string())?;
|
||||
let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?;
|
||||
preview_texture(ctx, &png, name)
|
||||
}
|
||||
|
||||
fn preview_texture(ctx: &egui::Context, png: &[u8], name: &str) -> Result<TextureHandle, String> {
|
||||
if !png.starts_with(b"\x89PNG\r\n\x1a\n") {
|
||||
return Err("the preview is not a PNG".into());
|
||||
}
|
||||
let img = cadcraft_io::raster::decode(png).map_err(|e| e.to_string())?;
|
||||
let size = [img.width() as usize, img.height() as usize];
|
||||
Ok(ctx.load_texture("plot-preview", egui::ColorImage::from_rgba_unmultiplied(size, img.rgba()), egui::TextureOptions::LINEAR))
|
||||
Ok(ctx.load_texture(name, egui::ColorImage::from_rgba_unmultiplied(size, img.rgba()), egui::TextureOptions::LINEAR))
|
||||
}
|
||||
|
||||
/// The Plot Preview window: the sheet as it plots, with Print and Close.
|
||||
/// Render the plot preview of the tab being shown, or of the Plot dialog's settings, as it plots
|
||||
/// (page setup, plot style table, lineweights): the whole sheet at about 1600 pixels.
|
||||
fn render(app: &mut CadApp, ctx: &egui::Context) -> Result<Shown, String> {
|
||||
let request = match from_plot(ctx) {
|
||||
Some(r) if stale(app, Some(&r)) => {
|
||||
return Err(
|
||||
crate::tl!("This preview is of another drawing than the one shown now. Close it and preview again from the Plot dialog.").to_string()
|
||||
);
|
||||
}
|
||||
Some(r) => r,
|
||||
None => crate::managers::current_preview(app)?,
|
||||
};
|
||||
let base = plot_texture(app, ctx, &request.params, "plot-preview")?;
|
||||
// The sheet's size as plotted comes with the request: a preview of one of several sheets
|
||||
// leaves the size to the layout's page setup, so its parameters don't hold it.
|
||||
Ok(Shown { base, info: request.info, sheet_mm: request.sheet_mm, params: request.params })
|
||||
}
|
||||
|
||||
/// Draw the part `crop` of the sheet again at the resolution of the screen, where the whole sheet is
|
||||
/// `sheet_width` points wide.
|
||||
fn render_detail(app: &mut CadApp, ctx: &egui::Context, shown: &Shown, crop: [f32; 4], sheet_width: f32) -> Result<Detail, String> {
|
||||
// One image pixel per screen pixel: the sheet's pixel width over its width in inches.
|
||||
let pixels = f64::from(sheet_width) * f64::from(ctx.pixels_per_point());
|
||||
let dpi = (pixels / (f64::from(shown.sheet_mm.x) / 25.4)).clamp(50.0, 2400.0);
|
||||
let mut params = shown.params.clone();
|
||||
if let Some(o) = params.as_object_mut() {
|
||||
o.insert("resolution".into(), json!(dpi));
|
||||
o.insert("crop".into(), json!(crop));
|
||||
}
|
||||
let tex = plot_texture(app, ctx, ¶ms, "plot-preview-detail")?;
|
||||
Ok(Detail { tex, crop, sheet_width })
|
||||
}
|
||||
|
||||
/// The Plot Preview window: the sheet as it plots, with Print and Close. The mouse wheel zooms
|
||||
/// about the pointer, dragging pans and a double click shows the whole sheet again; the part in
|
||||
/// view is drawn again at the screen's resolution once the view rests.
|
||||
pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
|
||||
let id = egui::Id::unique("cc_plot_preview");
|
||||
let generation = PREVIEW_GEN.load(Ordering::Relaxed);
|
||||
let cached = ctx.data(|d| d.get_temp::<Preview>(id)).filter(|p| p.generation == generation);
|
||||
let preview = match cached {
|
||||
let now = ctx.input(|i| i.time);
|
||||
let document = (app.session.doc_epoch, app.session.state().ok().map(|s| (s.uid, s.revision)));
|
||||
let cached = ctx.data(|d| d.get_temp::<Preview>(id)).filter(|p| p.generation == generation && p.document == document);
|
||||
let mut pv = match cached {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
let p = Preview { generation, shown: render(app, ctx) };
|
||||
ctx.data_mut(|d| d.insert_temp(id, p.clone()));
|
||||
p
|
||||
}
|
||||
None => Preview {
|
||||
generation,
|
||||
document,
|
||||
shown: render(app, ctx),
|
||||
view: PanZoom::default(),
|
||||
detail: None,
|
||||
changed: now,
|
||||
drawn: Rect::NOTHING,
|
||||
tried: None,
|
||||
},
|
||||
};
|
||||
let (mut close, mut print) = (false, false);
|
||||
egui::Window::new("Plot Preview").open(open).collapsible(false).resizable(false).show(ctx, |ui| {
|
||||
match &preview.shown {
|
||||
Ok((tex, info)) => {
|
||||
ui.label(info);
|
||||
let size = tex.size_vec2();
|
||||
let k = (760.0 / size.x).min(540.0 / size.y).min(1.0);
|
||||
ui.image((tex.id(), size * k));
|
||||
let stale_request = stale(app, from_plot(ctx).as_ref());
|
||||
// What to draw in detail after the window: the part and the sheet's width on screen.
|
||||
let mut want: Option<([f32; 4], f32)> = None;
|
||||
egui::Window::new("Plot Preview").open(open).collapsible(false).resizable(true).default_size(vec2(900.0, 680.0)).show(ctx, |ui| {
|
||||
match &pv.shown {
|
||||
Ok(shown) => {
|
||||
let image = shown.base.size_vec2();
|
||||
let mut view = pv.view;
|
||||
let (mut zoom_out, mut fit, mut zoom_in) = (false, false, false);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(&shown.info);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.label(format!("{:.0}%", view.zoom * 100.0));
|
||||
fit = ui.small_button("Fit").on_hover_text("The whole sheet (or double-click)").clicked();
|
||||
zoom_in = ui.small_button("+").on_hover_text("Zoom in (or the mouse wheel)").clicked();
|
||||
zoom_out = ui.small_button("−").on_hover_text("Zoom out").clicked();
|
||||
});
|
||||
});
|
||||
let size = vec2(ui.available_width().max(160.0), (ui.available_height() - 36.0).max(160.0));
|
||||
let (area, resp) = ui.allocate_exact_size(size, Sense::click_and_drag());
|
||||
let name = crate::tl!("Sheet preview (arrow keys move the view, + and − zoom)");
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, name));
|
||||
if resp.clicked() || resp.drag_started() {
|
||||
resp.request_focus();
|
||||
}
|
||||
// With the keyboard: Tab reaches the sheet, the arrow keys move the view over it
|
||||
// (Right shows more of its right side) and + and − zoom; Tab leaves it again.
|
||||
if resp.has_focus() {
|
||||
let arrows = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, tab: false, escape: false };
|
||||
ui.memory_mut(|m| m.set_focus_lock_filter(resp.id, arrows));
|
||||
let step = area.width().min(area.height()) * 0.1;
|
||||
ui.input(|i| {
|
||||
let pressed = |k: egui::Key| i.key_pressed(k);
|
||||
if pressed(egui::Key::ArrowLeft) {
|
||||
view.pan.x += step;
|
||||
}
|
||||
if pressed(egui::Key::ArrowRight) {
|
||||
view.pan.x -= step;
|
||||
}
|
||||
if pressed(egui::Key::ArrowUp) {
|
||||
view.pan.y += step;
|
||||
}
|
||||
if pressed(egui::Key::ArrowDown) {
|
||||
view.pan.y -= step;
|
||||
}
|
||||
zoom_in |= pressed(egui::Key::Plus) || pressed(egui::Key::Equals);
|
||||
zoom_out |= pressed(egui::Key::Minus);
|
||||
});
|
||||
}
|
||||
let hover = ui.input(|i| i.pointer.hover_pos()).filter(|p| area.contains(*p));
|
||||
if resp.hovered() {
|
||||
let (scroll, pinch) = ui.input(|i| (i.smooth_scroll_delta.y, i.zoom_delta()));
|
||||
if let Some(at) = hover {
|
||||
view.zoom_at(area, image, at, (scroll * 0.002).exp() * pinch);
|
||||
}
|
||||
}
|
||||
if resp.dragged() {
|
||||
view.pan += resp.drag_delta();
|
||||
}
|
||||
if resp.double_clicked() || fit {
|
||||
view = PanZoom::default();
|
||||
}
|
||||
if zoom_in {
|
||||
view.zoom_at(area, image, area.center(), 1.5);
|
||||
}
|
||||
if zoom_out {
|
||||
view.zoom_at(area, image, area.center(), 1.0 / 1.5);
|
||||
}
|
||||
view.clamp(area, image);
|
||||
if resp.dragged() || resp.hovered() {
|
||||
ui.ctx().set_cursor_icon(if resp.dragged() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab });
|
||||
}
|
||||
let sheet = view.image_rect(area, image);
|
||||
let painter = ui.painter_at(area);
|
||||
painter.rect_filled(area, 0.0, egui::Color32::from_gray(70));
|
||||
let full = Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0));
|
||||
painter.image(shown.base.id(), sheet, full, egui::Color32::WHITE);
|
||||
if let Some(d) = pv.detail.as_ref().filter(|d| d.matches(sheet.width())) {
|
||||
let [x0, y0, x1, y1] = d.crop;
|
||||
let (w, h) = (sheet.width(), sheet.height());
|
||||
let part = Rect::from_min_max(sheet.min + vec2(x0 * w, y0 * h), sheet.min + vec2(x1 * w, y1 * h));
|
||||
painter.image(d.tex.id(), part, full, egui::Color32::WHITE);
|
||||
}
|
||||
painter.rect_stroke(sheet, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(120)), egui::StrokeKind::Outside);
|
||||
if resp.has_focus() {
|
||||
let t = crate::theme::Tokens::get();
|
||||
painter.rect_stroke(area, 0.0, egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
// A change of the view or of the size the sheet is drawn at (the window was resized)
|
||||
// restarts the wait, so the detail is not drawn again at every step of a resize.
|
||||
if view != pv.view || sheet != pv.drawn {
|
||||
pv.changed = now;
|
||||
pv.view = view;
|
||||
pv.drawn = sheet;
|
||||
}
|
||||
// Drawn in detail when the sheet is shown larger than its image, once the view rests.
|
||||
let larger = sheet.width() * ui.ctx().pixels_per_point() > image.x * 1.1;
|
||||
if let Some(crop) = visible_crop(area, sheet).filter(|_| larger) {
|
||||
let covered = pv.detail.as_ref().is_some_and(|d| d.matches(sheet.width()) && covers(d.crop, crop));
|
||||
let key = (crop.map(|v| (v * 1000.0) as i32), sheet.width() as i32);
|
||||
if !covered && pv.tried != Some(key) {
|
||||
if now - pv.changed >= SETTLE {
|
||||
want = Some((with_margin(crop), sheet.width()));
|
||||
pv.tried = Some(key);
|
||||
} else {
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(SETTLE));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pv.detail = None;
|
||||
// Fit discarded the texture; the same zoom must be able to request it again.
|
||||
pv.tried = None;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
ui.label(e);
|
||||
@@ -252,26 +514,36 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
print = ui.button("Print...").clicked();
|
||||
print = ui.add_enabled(!stale_request, egui::Button::new("Print...")).clicked();
|
||||
close = ui.button("Close").clicked();
|
||||
});
|
||||
});
|
||||
if let (Some((crop, width)), Ok(shown)) = (want, pv.shown.as_ref()) {
|
||||
// A failure keeps the sheet as it is, and the part already drawn in detail, and is not
|
||||
// tried again for this view.
|
||||
if let Ok(detail) = render_detail(app, ctx, shown, crop, width) {
|
||||
pv.detail = Some(detail);
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
ctx.data_mut(|d| d.insert_temp(id, pv));
|
||||
if crate::framework::escape_pressed(ctx) {
|
||||
close = true;
|
||||
}
|
||||
if close || print {
|
||||
*open = false;
|
||||
}
|
||||
let from_plot = ctx.data(|d| d.get_temp::<FromPlot>(egui::Id::unique(FROM_PLOT))).is_some();
|
||||
let from_plot = from_plot(ctx).is_some();
|
||||
if !*open {
|
||||
ctx.data_mut(|d| {
|
||||
d.remove::<Preview>(id);
|
||||
d.remove::<FromPlot>(egui::Id::unique(FROM_PLOT));
|
||||
d.remove::<PreviewRequest>(egui::Id::unique(FROM_PLOT));
|
||||
});
|
||||
}
|
||||
if from_plot && !*open {
|
||||
// Back to the Plot dialog with its settings; Print... plots them.
|
||||
crate::managers::set_flag(ctx, crate::managers::PLOT_NOW, print);
|
||||
// Back to the Plot dialog with its settings; Print... plots them (the dialog checks they
|
||||
// are still its settings for the drawing shown).
|
||||
crate::managers::set_flag(ctx, crate::managers::PLOT_NOW, print && !stale_request);
|
||||
app.ui.dialog = Some("plot".into());
|
||||
} else if print {
|
||||
app.start("plot");
|
||||
@@ -311,9 +583,9 @@ mod tests {
|
||||
let ctx = egui::Context::default();
|
||||
let mut png = Vec::new();
|
||||
cadcraft_render::raster::write_rgba_png(&mut png, 1, 1, &[10, 20, 30, 255]).unwrap();
|
||||
let texture = super::preview_texture(&ctx, &png).unwrap();
|
||||
let texture = super::preview_texture(&ctx, &png, "test-preview").unwrap();
|
||||
assert_eq!(texture.size(), [1, 1]);
|
||||
assert!(super::preview_texture(&ctx, b"not a PNG").is_err());
|
||||
assert!(super::preview_texture(&ctx, b"not a PNG", "test-preview").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -343,6 +615,129 @@ mod tests {
|
||||
assert!(e.contains("not available yet"), "{e}");
|
||||
}
|
||||
|
||||
use egui::{Rect, Vec2, pos2, vec2};
|
||||
|
||||
use super::{MAX_ZOOM, PanZoom, covers, visible_crop, with_margin};
|
||||
|
||||
/// The preview area the zoom tests use.
|
||||
fn area() -> Rect {
|
||||
Rect::from_min_size(pos2(10.0, 20.0), vec2(800.0, 600.0))
|
||||
}
|
||||
|
||||
const IMAGE: Vec2 = vec2(1600.0, 1000.0);
|
||||
|
||||
/// The sheet fits the area and is centred until zoomed.
|
||||
#[test]
|
||||
fn the_sheet_fits_the_area_and_is_centred_until_zoomed() {
|
||||
let r = PanZoom::default().image_rect(area(), IMAGE);
|
||||
assert!((r.width() - 800.0).abs() < 1e-3 && (r.height() - 500.0).abs() < 1e-3, "fits by width: {r:?}");
|
||||
assert!((r.center() - area().center()).length() < 1e-3);
|
||||
}
|
||||
|
||||
/// Zooming keeps the image point under the pointer in place.
|
||||
#[test]
|
||||
fn zoom_keeps_the_point_under_the_pointer() {
|
||||
let mut v = PanZoom::default();
|
||||
let at = pos2(430.0, 330.0);
|
||||
let r = v.image_rect(area(), IMAGE);
|
||||
let u = ((at.x - r.min.x) / r.width(), (at.y - r.min.y) / r.height());
|
||||
v.zoom_at(area(), IMAGE, at, 3.0);
|
||||
assert!((v.zoom - 3.0).abs() < 1e-5);
|
||||
let r = v.image_rect(area(), IMAGE);
|
||||
let now = pos2(r.min.x + u.0 * r.width(), r.min.y + u.1 * r.height());
|
||||
assert!((now - at).length() < 0.01, "the point under the pointer stayed: {now:?} vs {at:?}");
|
||||
// And back out: the whole sheet again, centred.
|
||||
v.zoom_at(area(), IMAGE, at, 1.0 / 3.0);
|
||||
assert_eq!(v, PanZoom::default());
|
||||
}
|
||||
|
||||
/// The zoom is limited and the sheet stays over the area.
|
||||
#[test]
|
||||
fn zoom_is_limited_and_the_sheet_stays_over_the_area() {
|
||||
let mut v = PanZoom::default();
|
||||
v.zoom_at(area(), IMAGE, area().center(), 1e6);
|
||||
assert_eq!(v.zoom, MAX_ZOOM);
|
||||
v.zoom_at(area(), IMAGE, area().center(), 1e-6);
|
||||
assert_eq!(v.zoom, 1.0, "no further out than the whole sheet");
|
||||
// Dragged far away, the sheet still covers the area along the axes where it is larger.
|
||||
v.zoom_at(area(), IMAGE, area().center(), 4.0);
|
||||
v.pan = vec2(1e6, -1e6);
|
||||
v.clamp(area(), IMAGE);
|
||||
let r = v.image_rect(area(), IMAGE);
|
||||
assert!(
|
||||
r.min.x <= area().min.x + 1e-3 && r.max.x >= area().max.x - 1e-3 && r.min.y <= area().min.y + 1e-3 && r.max.y >= area().max.y - 1e-3,
|
||||
"{r:?}"
|
||||
);
|
||||
// Nonsense values change nothing or reset.
|
||||
let before = v;
|
||||
v.zoom_at(area(), IMAGE, area().center(), f32::NAN);
|
||||
v.zoom_at(area(), IMAGE, area().center(), -2.0);
|
||||
assert_eq!(v, before);
|
||||
v.pan = vec2(f32::NAN, 0.0);
|
||||
v.zoom = f32::INFINITY;
|
||||
v.clamp(area(), IMAGE);
|
||||
assert!(v.zoom == 1.0 && v.pan == Vec2::ZERO);
|
||||
}
|
||||
|
||||
/// The part in view is what is drawn again in detail.
|
||||
#[test]
|
||||
fn the_visible_part_is_what_is_drawn_again_in_detail() {
|
||||
// Whole sheet in view: all of it.
|
||||
let whole = PanZoom::default().image_rect(area(), IMAGE);
|
||||
assert_eq!(visible_crop(area(), whole), Some([0.0, 0.0, 1.0, 1.0]));
|
||||
// Zoomed 4x on the centre: the middle eighth... of each side.
|
||||
let mut v = PanZoom::default();
|
||||
v.zoom_at(area(), IMAGE, area().center(), 4.0);
|
||||
let c = visible_crop(area(), v.image_rect(area(), IMAGE)).unwrap();
|
||||
assert!((c[0] - 0.375).abs() < 1e-4 && (c[2] - 0.625).abs() < 1e-4, "{c:?}");
|
||||
assert!(c[1] > 0.0 && c[3] < 1.0 && c[1] < c[3]);
|
||||
// The detail drawn covers it with a margin all round, within the sheet.
|
||||
let d = with_margin(c);
|
||||
assert!(covers(d, c) && !covers(c, d));
|
||||
assert!(d.iter().all(|v| (0.0..=1.0).contains(v)));
|
||||
assert_eq!(with_margin([0.0, 0.0, 1.0, 1.0]), [0.0, 0.0, 1.0, 1.0], "the margin stays inside the sheet");
|
||||
// Nothing of the sheet in the area: no part.
|
||||
let away = Rect::from_min_size(pos2(5000.0, 5000.0), vec2(100.0, 100.0));
|
||||
assert_eq!(visible_crop(area(), away), None);
|
||||
}
|
||||
|
||||
/// The red-looking pixels of a plotted PNG, and its size.
|
||||
fn red_pixels(png: &[u8]) -> (usize, u32, u32) {
|
||||
let img = image::load_from_memory_with_format(png, image::ImageFormat::Png).unwrap().to_rgba8();
|
||||
let red = img.pixels().filter(|p| p.0[0] > 180 && p.0[1] < 90 && p.0[2] < 90).count();
|
||||
(red, img.width(), img.height())
|
||||
}
|
||||
|
||||
/// The preview draws the page setup's plot style table, and `None` overrides it.
|
||||
#[test]
|
||||
fn the_preview_draws_the_plot_style_table_of_the_page_setup() {
|
||||
let (mut app, _) = app();
|
||||
app.run("color", json!({ "color": 1 })).unwrap();
|
||||
app.run("line", json!({ "points": [[0, 0], [100, 60]] })).unwrap();
|
||||
app.run("mview", json!({ "layout": "Layout1" })).unwrap();
|
||||
app.run("layout.set", json!({ "name": "Layout1" })).unwrap();
|
||||
// The real plotter is called directly: the plot hook is global to the test process, which
|
||||
// other tests replace.
|
||||
let plot = |app: &CadApp, params: &serde_json::Value| {
|
||||
cadcraft_io::plotter::plot(app.session.doc().unwrap(), &cadcraft_doc::Space::Paper("Layout1".into()), params).unwrap()
|
||||
};
|
||||
let crate::managers::PreviewRequest { params, info, .. } = crate::managers::current_preview(&app).unwrap();
|
||||
assert!(info.starts_with("Layout1"), "{info}");
|
||||
let (plain, w, h) = red_pixels(&plot(&app, ¶ms));
|
||||
assert!(plain > 50, "without a table the red line is drawn red ({plain} red pixels)");
|
||||
// The page setup's table is what the preview shows, as it is what plots.
|
||||
app.run("pagesetup", json!({ "layout": "Layout1", "plotStyleTable": "monochrome.ctb" })).unwrap();
|
||||
let mut params = crate::managers::current_preview(&app).unwrap().params;
|
||||
assert_eq!(red_pixels(&plot(&app, ¶ms)).0, 0, "monochrome.ctb prints it black");
|
||||
// The Plot dialog's "None" is sent as such, so it overrides the layout's own table.
|
||||
params["plotStyleTable"] = json!("None");
|
||||
assert!(red_pixels(&plot(&app, ¶ms)).0 > 50, "None overrides the page setup's table");
|
||||
// A crop is that part of the sheet, at the same scale.
|
||||
params["crop"] = json!([0.25, 0.25, 0.75, 0.75]);
|
||||
let (_, cw, ch) = red_pixels(&plot(&app, ¶ms));
|
||||
assert!((i64::from(cw) - i64::from(w) / 2).abs() <= 1 && (i64::from(ch) - i64::from(h) / 2).abs() <= 1, "{cw}x{ch} of {w}x{h}");
|
||||
}
|
||||
|
||||
type Done = Box<dyn FnOnce(Option<String>) + Send>;
|
||||
|
||||
/// An app whose host shows its dialogs without waiting (macOS, #1527): the dialogs asked
|
||||
@@ -518,4 +913,33 @@ mod tests {
|
||||
assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("line"), "LINE was not cancelled");
|
||||
assert!(status(&app).starts_with("APPLOAD: another command started"), "{:?}", app.status);
|
||||
}
|
||||
|
||||
/// A preview the Plot dialog asked for in one drawing is not plotted with another drawing
|
||||
/// shown since, and its Print... sends nothing back to the Plot dialog (#2171 review).
|
||||
#[test]
|
||||
fn a_plot_preview_is_bound_to_its_drawing() {
|
||||
let (mut app, _) = app();
|
||||
let ctx = egui::Context::default();
|
||||
crate::framework::install_headless(&ctx);
|
||||
let request = crate::managers::PreviewRequest {
|
||||
params: json!({ "layout": "Model", "output": "png", "resolution": 50 }),
|
||||
info: "Model · A4".into(),
|
||||
sheet_mm: egui::vec2(297.0, 210.0),
|
||||
drawing: crate::managers::plot_drawing(&app),
|
||||
};
|
||||
super::preview_plot(&mut app, &ctx, request);
|
||||
app.run("new", json!({})).unwrap();
|
||||
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))), ..Default::default() };
|
||||
let mut out = ctx.run_ui(raw, |ui| {
|
||||
let mut open = true;
|
||||
super::dialog(&mut app, &ui.ctx().clone(), &mut open);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
let shown = ctx.data(|d| d.get_temp::<super::Preview>(egui::Id::unique("cc_plot_preview"))).and_then(|p| p.shown.err());
|
||||
assert!(
|
||||
shown.as_deref().is_some_and(|e| e.contains("another drawing")),
|
||||
"the other drawing is not plotted with the preview's settings: {shown:?}"
|
||||
);
|
||||
assert!(super::stale(&app, super::from_plot(&ctx).as_ref()), "Print... is off");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,6 +81,13 @@ menu Modify Edita
|
||||
Array Serie
|
||||
Attach Associa
|
||||
Attribute Attributo
|
||||
All layouts Tutti i layout
|
||||
Only this one Solo questo
|
||||
Plot several sheets Stampa più fogli
|
||||
{n} sheets in one PDF, each with its own page setup (change them in the Page Setup Manager): {n} fogli in un solo PDF, ciascuno con la propria impostazione pagina (si modificano nel Gestore impostazioni pagina):
|
||||
{n} sheets {n} fogli
|
||||
Select all Seleziona tutti
|
||||
{n} layouts selected: a change applies to all of them {n} layout selezionati: una modifica vale per tutti
|
||||
Attribute Definition Definizione di attributo
|
||||
Attribute Display Visualizzazione attributi
|
||||
Audit Controlla
|
||||
@@ -1434,6 +1441,71 @@ menu Modify Edita
|
||||
ENTER INVIO
|
||||
Shortcut Menu: always enabled Menu di scelta rapida: sempre attivo
|
||||
Shortcut Menu: enabled when command options are present Menu di scelta rapida: attivo se il comando ha opzioni
|
||||
Limits Limiti
|
||||
{name} (default) {name} (predefinita)
|
||||
Printer/plotter Stampante/plotter
|
||||
PDF on the paper chosen below PDF sul foglio scelto sotto
|
||||
Paper size Formato carta
|
||||
Orientation Orientamento
|
||||
Portrait Verticale
|
||||
Landscape Orizzontale
|
||||
Plot area Area di stampa
|
||||
What to plot Cosa stampare
|
||||
Fit to paper Adatta al foglio
|
||||
Center the plot Centra la stampa
|
||||
Center the plotted model bounds on the printable area Centra i limiti del modello stampato nell'area stampabile
|
||||
Model-space offset placement is not supported by SVG L'SVG non supporta lo scostamento nello spazio modello
|
||||
X offset (mm) Scostamento X (mm)
|
||||
Y offset (mm) Scostamento Y (mm)
|
||||
Distance from the printable area's lower-left corner; values range from −100000 to 100000 mm Distanza dall'angolo inferiore sinistro dell'area stampabile; valori da −100000 a 100000 mm
|
||||
Offsets must be within ±100000 mm Gli scostamenti devono essere entro ±100000 mm
|
||||
Paper units per drawing unit, or a ratio such as 1:50 Unità di carta per unità di disegno, o un rapporto come 1:50
|
||||
Plot object lineweights Stampa gli spessori di linea degli oggetti
|
||||
Plot transparency Stampa la trasparenza
|
||||
Plot objects with their transparency (PLOTTRANSPARENCYOVERRIDE can override it) Stampa gli oggetti con la loro trasparenza (PLOTTRANSPARENCYOVERRIDE può sostituirla)
|
||||
System printer Stampante di sistema
|
||||
File ({kind}) File ({kind})
|
||||
Plot - {layout} Stampa - {layout}
|
||||
Page setup Impostazione pagina
|
||||
Every layout, in tab order (not the Model tab) Tutti i layout, nell'ordine delle schede (non la scheda Modello)
|
||||
Sheets Fogli
|
||||
Number of copies Numero di copie
|
||||
Where Destinazione
|
||||
Plot to file Stampa su file
|
||||
Also save the printed PDF in a file you choose after OK Salva anche il PDF stampato in un file scelto dopo OK
|
||||
This device writes a file: OK asks where Questo dispositivo scrive un file: OK chiede dove
|
||||
Looking for printers… Ricerca delle stampanti…
|
||||
Refresh printers Aggiorna stampanti
|
||||
Ask the system for its printers again (a printer just added or switched on) Chiede di nuovo al sistema le sue stampanti (una stampante appena aggiunta o accesa)
|
||||
First corner Primo angolo
|
||||
Opposite corner Angolo opposto
|
||||
Window < Finestra <
|
||||
Pick the window's corners in the drawing Indica gli angoli della finestra nel disegno
|
||||
Choose Window to set the corners Scegli Finestra per impostare gli angoli
|
||||
Layouts plot the whole sheet I layout stampano l'intero foglio
|
||||
Plot offset Scostamento di stampa
|
||||
Origin: printable area Origine: area stampabile
|
||||
Plot scale Scala di stampa
|
||||
Open the Plot Style Manager; Plot comes back when it closes Apre il Gestore stili di stampa; la finestra Stampa torna quando si chiude
|
||||
Plot options Opzioni di stampa
|
||||
Plot with plot styles Stampa con gli stili di stampa
|
||||
Off: plot the objects' own colours and lineweights, keeping the table chosen above Disattivato: stampa i colori e gli spessori propri degli oggetti, mantenendo la tabella scelta sopra
|
||||
Plot stamp on Timbro di stampa
|
||||
A line at the sheet's lower-left corner: drawing, layout, date and time (UTC), device, paper and scale Una riga nell'angolo inferiore sinistro del foglio: disegno, layout, data e ora (UTC), dispositivo, carta e scala
|
||||
SVG plots have no plot stamp; choose a PDF or PNG device Le stampe SVG non hanno il timbro di stampa; scegli un dispositivo PDF o PNG
|
||||
Save changes to layout Salva le modifiche nel layout
|
||||
OK also saves these settings in the layout's page setup OK salva anche queste impostazioni nell'impostazione pagina del layout
|
||||
Drawing orientation Orientamento del disegno
|
||||
The sheet as these settings plot it Il foglio come lo stampano queste impostazioni
|
||||
Apply to Layout Applica al layout
|
||||
Save these settings in the layout's page setup Salva queste impostazioni nell'impostazione pagina del layout
|
||||
Sent {what} to {printer} (job {job}) and saved it to {path} {what} inviato a {printer} (lavoro {job}) e salvato in {path}
|
||||
Sent {what} to {printer} (job {job}) {what} inviato a {printer} (lavoro {job})
|
||||
Plotted {what} to {path} {what} stampato in {path}
|
||||
Plotted {what} ({bytes} bytes; there is no file dialog here) {what} stampato ({bytes} byte; qui non c'è una finestra per i file)
|
||||
landscape orizzontale
|
||||
portrait verticale
|
||||
Sheet {w} × {h} mm, unprintable margins left {l}, bottom {b}, right {r}, top {t} mm Foglio {w} × {h} mm, margini non stampabili sinistro {l}, inferiore {b}, destro {r}, superiore {t} mm
|
||||
Check for updates when CADCraft starts Controlla gli aggiornamenti all'avvio di CADCraft
|
||||
Turned off, CADCraft never offers an update on its own; Help ▸ Check for Updates… still looks. Se disattivato, CADCraft non propone mai un aggiornamento da solo; Aiuto ▸ Verifica aggiornamenti… continua a controllare.
|
||||
|
||||
@@ -1443,3 +1515,5 @@ menu Modify Edita
|
||||
Block name: Nome blocco:
|
||||
Tag: {tag} Etichetta: {tag}
|
||||
Values typed at the command line work too Anche i valori digitati nella riga di comando vengono accettati
|
||||
Sheet preview (arrow keys move the view, + and − zoom) Anteprima del foglio (i tasti freccia spostano la vista, + e − ingrandiscono e riducono)
|
||||
This preview is of another drawing than the one shown now. Close it and preview again from the Plot dialog. Questa anteprima è di un disegno diverso da quello mostrato ora. Chiudila e ripeti l'anteprima dalla finestra Stampa.
|
||||
|
||||
|
@@ -166,6 +166,7 @@ fn missing_commands_menus_tools_and_snap_labels(language: &str) -> Vec<String> {
|
||||
sources.into_iter().filter(|s| !s.is_empty() && !catalog.contains_key(&("", *s))).map(str::to_string).collect()
|
||||
}
|
||||
|
||||
/// The `tl!` and `tf!` literals of the checked UI files that `language`'s catalog lacks.
|
||||
fn missing_marked_ui_literals(language: &str) -> BTreeSet<String> {
|
||||
let catalog = catalog(language).unwrap();
|
||||
let modules = [
|
||||
@@ -192,6 +193,7 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet<String> {
|
||||
"options/dialog",
|
||||
"finddlg",
|
||||
"textdlg",
|
||||
"managers",
|
||||
];
|
||||
let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
|
||||
let mut files = Vec::new();
|
||||
|
||||
@@ -1468,6 +1468,76 @@
|
||||
ENTER Клавіша Enter
|
||||
Shortcut Menu: always enabled Контекстне меню: завжди
|
||||
Shortcut Menu: enabled when command options are present Контекстне меню: коли команда має параметри
|
||||
Limits Граничні розміри
|
||||
{name} (default) {name} (типовий)
|
||||
Printer/plotter Принтер/плотер
|
||||
PDF on the paper chosen below PDF на папері, вибраному нижче
|
||||
Paper size Розмір паперу
|
||||
Orientation Орієнтація
|
||||
Portrait Книжкова
|
||||
Landscape Альбомна
|
||||
Plot area Область друку
|
||||
What to plot Що друкувати
|
||||
Fit to paper Вписати в папір
|
||||
Center the plot Центрувати друк
|
||||
Center the plotted model bounds on the printable area Центрувати межі друкованої моделі в області друку
|
||||
Model-space offset placement is not supported by SVG SVG не підтримує зміщення в просторі моделі
|
||||
X offset (mm) Зміщення X (мм)
|
||||
Y offset (mm) Зміщення Y (мм)
|
||||
Distance from the printable area's lower-left corner; values range from −100000 to 100000 mm Відстань від лівого нижнього кута області друку; значення від −100000 до 100000 мм
|
||||
Offsets must be within ±100000 mm Зміщення мають бути в межах ±100000 мм
|
||||
Paper units per drawing unit, or a ratio such as 1:50 Одиниць паперу на одиницю креслення або співвідношення, наприклад 1:50
|
||||
Plot object lineweights Друкувати ваги ліній об'єктів
|
||||
Plot transparency Друкувати прозорість
|
||||
Plot objects with their transparency (PLOTTRANSPARENCYOVERRIDE can override it) Друкувати об'єкти з їхньою прозорістю (PLOTTRANSPARENCYOVERRIDE може це змінити)
|
||||
System printer Системний принтер
|
||||
File ({kind}) Файл ({kind})
|
||||
Plot - {layout} Друк креслення - {layout}
|
||||
Page setup Параметри аркуша
|
||||
Plot several sheets Друкувати кілька аркушів
|
||||
All layouts Усі аркуші
|
||||
Every layout, in tab order (not the Model tab) Усі аркуші в порядку вкладок (без вкладки «Модель»)
|
||||
Only this one Лише цей
|
||||
Sheets Аркуші
|
||||
{n} sheets in one PDF, each with its own page setup (change them in the Page Setup Manager): {n} аркушів в одному PDF, кожен зі своїми параметрами (змініть їх у диспетчері параметрів аркушів):
|
||||
Number of copies Кількість копій
|
||||
Where Куди
|
||||
Plot to file Друк у файл
|
||||
Also save the printed PDF in a file you choose after OK Також зберегти надрукований PDF у файл, вибраний після «Гаразд»
|
||||
This device writes a file: OK asks where Цей пристрій записує файл: «Гаразд» запитає, куди
|
||||
Looking for printers… Пошук принтерів…
|
||||
Refresh printers Оновити принтери
|
||||
Ask the system for its printers again (a printer just added or switched on) Знову запитати в системи її принтери (щойно доданий або увімкнений принтер)
|
||||
First corner Перший кут
|
||||
Opposite corner Протилежний кут
|
||||
Window < Вікно <
|
||||
Pick the window's corners in the drawing Вкажіть кути вікна на кресленні
|
||||
Choose Window to set the corners Виберіть «Вікно», щоб задати кути
|
||||
Layouts plot the whole sheet Аркуші друкуються повністю
|
||||
Plot offset Зміщення друку
|
||||
Origin: printable area Початок: область друку
|
||||
Plot scale Масштаб друку
|
||||
Open the Plot Style Manager; Plot comes back when it closes Відкрити диспетчер стилів друку; після його закриття повернеться вікно друку
|
||||
Plot options Параметри друку
|
||||
Plot with plot styles Друкувати зі стилями друку
|
||||
Off: plot the objects' own colours and lineweights, keeping the table chosen above Вимкнено: друкувати власні кольори й ваги ліній об'єктів, зберігши вибрану вище таблицю
|
||||
Plot stamp on Штамп друку
|
||||
A line at the sheet's lower-left corner: drawing, layout, date and time (UTC), device, paper and scale Рядок у лівому нижньому куті аркуша: креслення, аркуш, дата й час (UTC), пристрій, папір і масштаб
|
||||
SVG plots have no plot stamp; choose a PDF or PNG device SVG-друк не має штампа друку; виберіть пристрій PDF або PNG
|
||||
Save changes to layout Зберегти зміни в аркуші
|
||||
OK also saves these settings in the layout's page setup «Гаразд» також зберігає ці налаштування в параметрах аркуша
|
||||
Drawing orientation Орієнтація креслення
|
||||
The sheet as these settings plot it Аркуш так, як його надрукують ці налаштування
|
||||
Apply to Layout Застосувати до аркуша
|
||||
Save these settings in the layout's page setup Зберегти ці налаштування в параметрах аркуша
|
||||
{n} sheets {n} аркушів
|
||||
{n} layouts selected: a change applies to all of them Вибрано аркушів: {n}; зміна застосується до всіх
|
||||
Sent {what} to {printer} (job {job}) and saved it to {path} {what} надіслано на {printer} (завдання {job}) і збережено в {path}
|
||||
Sent {what} to {printer} (job {job}) {what} надіслано на {printer} (завдання {job})
|
||||
Plotted {what} to {path} {what} надруковано в {path}
|
||||
Plotted {what} ({bytes} bytes; there is no file dialog here) {what} надруковано ({bytes} байт; тут немає вікна вибору файлу)
|
||||
landscape альбомна
|
||||
portrait книжкова
|
||||
Check for updates when CADCraft starts Перевіряти оновлення під час запуску CADCraft
|
||||
Turned off, CADCraft never offers an update on its own; Help ▸ Check for Updates… still looks. Якщо вимкнено, CADCraft ніколи сам не пропонує оновлення; Довідка ▸ Перевірити оновлення… усе одно перевіряє.
|
||||
|
||||
@@ -1593,7 +1663,6 @@
|
||||
Alt round Округлення альтернативних одиниць
|
||||
Alt prefix Префікс альтернативних одиниць
|
||||
Alt suffix Суфікс альтернативних одиниць
|
||||
Limits Граничні розміри
|
||||
Upper tolerance Верхнє відхилення
|
||||
Lower tolerance Нижнє відхилення
|
||||
Tolerance precision Точність допуску
|
||||
@@ -1662,7 +1731,10 @@
|
||||
Alt prefix and suffix Префікс і суфікс альтернативних одиниць
|
||||
Alt zero suppression Приховування нулів альтернативних одиниць
|
||||
Tolerance zero suppression Приховування нулів допусків
|
||||
Sheet {w} × {h} mm, unprintable margins left {l}, bottom {b}, right {r}, top {t} mm Аркуш {w} × {h} мм, поля без друку: ліве {l}, нижнє {b}, праве {r}, верхнє {t} мм
|
||||
Edit Attributes Редагування атрибутів
|
||||
Block name: Ім’я блока:
|
||||
Tag: {tag} Мітка: {tag}
|
||||
Values typed at the command line work too Значення, введені в командному рядку, теж приймаються
|
||||
Sheet preview (arrow keys move the view, + and − zoom) Попередній перегляд аркуша (стрілки зсувають вигляд, + і − масштабують)
|
||||
This preview is of another drawing than the one shown now. Close it and preview again from the Plot dialog. Цей попередній перегляд належить іншому кресленню, ніж показане зараз. Закрийте його й перегляньте знову з діалогу «Друк креслення».
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1404 and column 24.
|
+1406
-242
File diff suppressed because it is too large
Load Diff
@@ -33,12 +33,17 @@ const LINEWEIGHTS: [f64; 12] = [0.0, 0.09, 0.13, 0.18, 0.25, 0.3, 0.35, 0.5, 0.7
|
||||
/// A command to run after the dialog is drawn.
|
||||
type Action = Option<(&'static str, Value)>;
|
||||
|
||||
/// The Plot Style Manager; opened from the Plot dialog's "Edit…", closing it goes back to Plot.
|
||||
pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
|
||||
let action = window(app, ctx, open);
|
||||
if let Some((cmd, p)) = action {
|
||||
// Errors are echoed on the command line by `run`.
|
||||
let _ = app.run(cmd, p);
|
||||
}
|
||||
// Opened from the Plot dialog's "Edit…": closing goes back to Plot.
|
||||
if !*open {
|
||||
crate::managers::return_to_plot(app, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
/// Plot Style Manager window; returns the command (`stylesmanager` or `pagesetup`) to run after drawing.
|
||||
|
||||
@@ -5,6 +5,9 @@ use std::rc::Rc;
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_ui_egui::{CadApp, Services, menus};
|
||||
use egui::{PointerButton, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::json;
|
||||
|
||||
/// An app whose file pickers count their calls and cancel.
|
||||
@@ -99,6 +102,7 @@ fn typed_json_form_runs_the_command() {
|
||||
assert_eq!(app.session.settings.gridmajor, 7);
|
||||
}
|
||||
|
||||
/// PLOT and PRINT from the menu or typed open the Plot dialog; the JSON form plots without it.
|
||||
#[test]
|
||||
fn print_opens_the_plot_dialog_but_json_plot_never_does() {
|
||||
let (mut app, picks) = app();
|
||||
@@ -114,3 +118,28 @@ fn print_opens_the_plot_dialog_but_json_plot_never_does() {
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(picks.get(), 0);
|
||||
}
|
||||
|
||||
/// Cancel in the Plot dialog leaves the drawing as it was and asks for no file.
|
||||
#[test]
|
||||
fn canceling_plot_dialog_preserves_drawing_and_does_not_open_picker() {
|
||||
let (mut app, picks) = app();
|
||||
menus::activate(&mut app, "plot");
|
||||
let drawing = app.session.doc().unwrap().clone();
|
||||
let mut harness =
|
||||
Harness::builder().with_context_setup(cadcraft_ui_egui::framework::install_headless).with_size(vec2(1280.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(&ui.ctx().clone());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
harness.run_steps(4);
|
||||
assert_eq!(harness.state().ui.dialog.as_deref(), Some("plot"));
|
||||
assert_eq!(harness.state().session.doc().unwrap(), &drawing);
|
||||
|
||||
harness.get_by_label("Cancel").click_button(PointerButton::Primary);
|
||||
harness.run_steps(3);
|
||||
assert!(harness.state().ui.dialog.is_none());
|
||||
assert_eq!(harness.state().session.doc().unwrap(), &drawing);
|
||||
assert_eq!(picks.get(), 0);
|
||||
}
|
||||
|
||||
@@ -37,10 +37,12 @@ mod offset_clicks;
|
||||
mod options_dialog;
|
||||
mod options_right_click;
|
||||
mod page_setup_paper_units;
|
||||
mod pagesetup_multi;
|
||||
mod parameters_rename;
|
||||
mod pdf_import_dialog;
|
||||
mod pickdrag;
|
||||
mod press_first_clicks;
|
||||
mod preview_zoom;
|
||||
mod properties_described;
|
||||
mod properties_units;
|
||||
mod rapid_clicks;
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
//! The Page Setup Manager with several layouts picked: choosing the value the layout shown
|
||||
//! already has still applies it to the others, which is how mixed layouts are made to match.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_ui_egui::{CadApp, Services, menus};
|
||||
use egui::vec2;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::json;
|
||||
|
||||
/// An app in a window, as the other integration tests build it.
|
||||
fn harness(app: CadApp) -> Harness<'static, CadApp> {
|
||||
let mut h = Harness::builder().with_context_setup(cadcraft_ui_egui::framework::install_headless).with_size(vec2(1280.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(&ui.ctx().clone());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
h
|
||||
}
|
||||
|
||||
/// Whether layout `layout` is landscape.
|
||||
fn landscape(app: &CadApp, layout: &str) -> bool {
|
||||
app.session.doc().unwrap().layout(layout).unwrap().page.landscape
|
||||
}
|
||||
|
||||
/// Choosing the value the shown layout has makes the other picked layouts match.
|
||||
#[test]
|
||||
fn picking_the_value_shown_makes_the_other_picked_layouts_match() {
|
||||
let mut app = CadApp::new(Session::default(), Services::default());
|
||||
app.ui.start_tab = false;
|
||||
app.ui.in_window_menu = false;
|
||||
// Layout1 is shown and landscape; Layout2 is portrait.
|
||||
app.run("pagesetup", json!({ "layout": "Layout1", "landscape": true })).unwrap();
|
||||
app.run("pagesetup", json!({ "layout": "Layout2", "landscape": false })).unwrap();
|
||||
app.run("layout.set", json!({ "name": "Layout1" })).unwrap();
|
||||
let mut h = harness(app);
|
||||
menus::activate(h.state_mut(), "pagesetup");
|
||||
h.run_steps(5);
|
||||
|
||||
// With one layout picked, choosing what it already has changes nothing.
|
||||
h.get_by_label("Landscape").click();
|
||||
h.run_steps(3);
|
||||
assert!(!landscape(h.state(), "Layout2"), "one layout picked: the other is left alone");
|
||||
|
||||
// With both picked, the same click is a change for both.
|
||||
h.get_by_label("Select all").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Landscape").click();
|
||||
h.run_steps(3);
|
||||
assert!(landscape(h.state(), "Layout1") && landscape(h.state(), "Layout2"), "both layouts are landscape now");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_selection_does_not_follow_the_user_into_another_drawing() {
|
||||
let mut app = CadApp::new(Session::default(), Services::default());
|
||||
app.ui.start_tab = false;
|
||||
app.ui.in_window_menu = false;
|
||||
let mut h = harness(app);
|
||||
menus::activate(h.state_mut(), "pagesetup");
|
||||
h.run_steps(4);
|
||||
h.get_by_label("Select all").click();
|
||||
h.run_steps(3);
|
||||
h.state_mut().session.open_drawing(cadcraft_engine::doc::Drawing::new_metric(), "other.dxf", None);
|
||||
h.state_mut().run("pagesetup", json!({ "layout": "Layout1", "landscape": false })).unwrap();
|
||||
h.state_mut().run("pagesetup", json!({ "layout": "Layout2", "landscape": false })).unwrap();
|
||||
h.run_steps(4);
|
||||
h.get_by_label("Landscape").click();
|
||||
h.run_steps(3);
|
||||
assert!(landscape(h.state(), "Layout1"));
|
||||
assert!(!landscape(h.state(), "Layout2"), "the second drawing never had multiple layouts selected");
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//! The Plot Preview window draws the sheet once, and zooming in on it draws the part in view again
|
||||
//! at the screen's resolution (a `crop` of the sheet) once the view rests.
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
use cadcraft_doc::{Drawing, Space};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{IoHooks, set_io};
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use egui::{Event, Modifiers, MouseWheelUnit, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The options of every `plot` the preview made.
|
||||
static PLOTS: Mutex<Vec<Value>> = Mutex::new(Vec::new());
|
||||
|
||||
/// A plot hook that records the options it is given.
|
||||
fn recording_plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>, String> {
|
||||
if let Ok(mut plots) = PLOTS.lock() {
|
||||
plots.push(opts.clone());
|
||||
}
|
||||
cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The PNG plots so far: other tests in this process also plot (to PDF) through the global hook.
|
||||
fn plots() -> Vec<Value> {
|
||||
PLOTS.lock().map(|p| p.iter().filter(|o| o["output"] == "png").cloned().collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Zooming in draws the part in view again at the screen's resolution.
|
||||
#[test]
|
||||
fn zooming_in_draws_the_part_in_view_at_the_screens_resolution() {
|
||||
set_io(IoHooks { read: |_, _| Err("no".into()), write: |_, _| Err("no".into()), plot: Some(recording_plot) });
|
||||
// The hooks are set once per process: when another test of this binary set them first (a
|
||||
// plain `cargo test`; nextest runs each test alone), the preview's plots can't be watched.
|
||||
let ours = recording_plot as fn(&Drawing, &Space, &Value) -> Result<Vec<u8>, String>;
|
||||
if cadcraft_engine::cmd::file::io().and_then(|h| h.plot).is_none_or(|f| !std::ptr::fn_addr_eq(f, ours)) {
|
||||
eprintln!("another test installed the file hooks first; skipped");
|
||||
return;
|
||||
}
|
||||
let mut app = CadApp::new(Session::default(), Services::default());
|
||||
app.ui.start_tab = false;
|
||||
app.ui.in_window_menu = false;
|
||||
app.run("line", json!({ "points": [[0, 0], [100, 60]] })).unwrap();
|
||||
app.run("mview", json!({ "layout": "Layout1" })).unwrap();
|
||||
app.run("layout.set", json!({ "name": "Layout1" })).unwrap();
|
||||
let mut h = Harness::builder().with_context_setup(cadcraft_ui_egui::framework::install_headless).with_size(vec2(1280.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(&ui.ctx().clone());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
|
||||
PLOTS.lock().unwrap().clear();
|
||||
h.state_mut().start("preview");
|
||||
h.run_steps(5);
|
||||
let first = plots();
|
||||
assert_eq!(first.len(), 1, "the whole sheet is drawn once: {first:?}");
|
||||
assert!(first[0].get("crop").is_none());
|
||||
assert_eq!(first[0]["output"], "png");
|
||||
|
||||
// Scroll up over the preview: zoom in. Rendered again only once the view rests.
|
||||
let over = egui::pos2(450.0, 380.0);
|
||||
h.hover_at(over);
|
||||
h.run_steps(2);
|
||||
h.event(Event::MouseWheel {
|
||||
unit: MouseWheelUnit::Point,
|
||||
delta: vec2(0.0, 1000.0),
|
||||
modifiers: Modifiers::NONE,
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
});
|
||||
h.run_steps(12);
|
||||
let after = plots();
|
||||
assert!(after.len() >= 2, "the part in view is drawn again: {} plots", after.len());
|
||||
let detail = after.last().unwrap();
|
||||
let crop: Vec<f64> = detail["crop"].as_array().expect("a crop").iter().filter_map(Value::as_f64).collect();
|
||||
assert_eq!(crop.len(), 4);
|
||||
assert!(crop[2] - crop[0] < 1.0 && crop[3] - crop[1] < 1.0, "a part of the sheet, not all of it: {crop:?}");
|
||||
assert!(detail["resolution"].as_f64().unwrap() > first[0]["resolution"].as_f64().unwrap(), "at a higher resolution than the whole sheet");
|
||||
|
||||
// Zooming back out to the whole sheet needs no further drawing.
|
||||
let n = plots().len();
|
||||
h.event(Event::MouseWheel {
|
||||
unit: MouseWheelUnit::Point,
|
||||
delta: vec2(0.0, -2000.0),
|
||||
modifiers: Modifiers::NONE,
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
});
|
||||
h.run_steps(12);
|
||||
assert_eq!(plots().len(), n, "the whole sheet is shown from its first image");
|
||||
|
||||
// With the keyboard (#2171 review): the sheet takes the focus, + zooms in and the arrow keys
|
||||
// move the view over it (Right shows more of its right side).
|
||||
h.get_by_label("Sheet preview (arrow keys move the view, + and − zoom)").focus();
|
||||
h.run_steps(2);
|
||||
for _ in 0..4 {
|
||||
h.key_press(egui::Key::Plus);
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.run_steps(12);
|
||||
let crop_of = |o: &Value| -> Vec<f64> { o["crop"].as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default() };
|
||||
let zoomed = plots().last().map(crop_of).unwrap_or_default();
|
||||
assert_eq!(zoomed.len(), 4, "+ zoomed in far enough to draw the part in view in detail");
|
||||
// Past the margin the detail was drawn with, so the part in view is drawn again.
|
||||
for _ in 0..6 {
|
||||
h.key_press(egui::Key::ArrowRight);
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.run_steps(12);
|
||||
let moved = plots().last().map(crop_of).unwrap_or_default();
|
||||
assert!(moved.len() == 4 && moved[0] > zoomed[0], "the view moved right over the sheet: {zoomed:?} → {moved:?}");
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//! The base and detail in Plot Preview must represent the same document revision.
|
||||
use cadcraft_engine::{
|
||||
Session,
|
||||
cmd::file::{IoHooks, set_io},
|
||||
};
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use serde_json::json;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
static RENDERS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
#[test]
|
||||
fn preview_rebuilds_after_a_drawing_switch_and_content_edit() {
|
||||
set_io(IoHooks {
|
||||
read: |_, _| Err("no reader".into()),
|
||||
write: |_, _| Err("no writer".into()),
|
||||
plot: Some(|_, _, _| {
|
||||
RENDERS.fetch_add(1, Ordering::SeqCst);
|
||||
let image = image::RgbaImage::from_pixel(1600, 1000, image::Rgba([255, 255, 255, 255]));
|
||||
let mut data = std::io::Cursor::new(Vec::new());
|
||||
image::DynamicImage::ImageRgba8(image).write_to(&mut data, image::ImageFormat::Png).unwrap();
|
||||
Ok(data.into_inner())
|
||||
}),
|
||||
});
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
app.start("preview");
|
||||
let ctx = egui::Context::default();
|
||||
// The UI runtime the app's panels need, as the other tests that run the app's UI install it.
|
||||
cadcraft_ui_egui::framework::install_headless(&ctx);
|
||||
let frame = |app: &mut CadApp| {
|
||||
let mut output = ctx.run_ui(
|
||||
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))), ..Default::default() },
|
||||
|ui| app.ui(ui),
|
||||
);
|
||||
output.textures_delta.clear();
|
||||
};
|
||||
frame(&mut app);
|
||||
frame(&mut app);
|
||||
let initial = RENDERS.load(Ordering::SeqCst);
|
||||
app.run("new", json!({})).unwrap();
|
||||
frame(&mut app);
|
||||
assert_eq!(RENDERS.load(Ordering::SeqCst), initial + 1, "switch invalidates the base");
|
||||
app.run("line", json!({ "points": [[0,0],[10,0]] })).unwrap();
|
||||
frame(&mut app);
|
||||
assert_eq!(RENDERS.load(Ordering::SeqCst), initial + 2, "content edits invalidate the base too");
|
||||
}
|
||||
@@ -34,6 +34,33 @@ resolve case-insensitively and ignore spaces, hyphens and parentheses (`B5 (JIS)
|
||||
`B4`/`B5` keep meaning the ISO sizes, so a drawing or caller that used them doesn't change; a plot
|
||||
that means JIS B4/B5 says `B4 (JIS)`/`B5 (JIS)`. A drawing keeps the sheet size it stored.
|
||||
|
||||
The computer's printers come next, listed in the background (a dialog never waits for them):
|
||||
|
||||
- macOS and Linux: the CUPS destinations (`lpstat -e`), each with its PPD's papers and printable
|
||||
areas. A queue without a PPD file the user can read (a driverless IPP printer, or a PPD only
|
||||
root can read) takes its papers from `lpoptions -p NAME -l`, with the 4.23 mm margins IPP
|
||||
printers commonly report. With a remote CUPS server (`CUPS_SERVER`, `client.conf`; `lpstat -H`
|
||||
names it) every queue's papers come from `lpoptions`, which asks that server, never from the
|
||||
local PPD files. Queues are asked at once; one that hasn't answered in 6 s is left out of that
|
||||
listing. `lpstat -d` names the default printer. A plot is the PDF the PDF
|
||||
plotter writes for the paper, sent unscaled with `lp` (`PageSize` for a PPD paper, `media`
|
||||
otherwise). CUPS commands run in the C locale.
|
||||
- Windows: the spooler's printers with their drivers' papers and printable areas, printed
|
||||
through craft-print at the plot's exact size. The listing waits up to 8 s for driver catalogs.
|
||||
An unfinished query is left out and runs without a retry until it answers. The shared
|
||||
PrintTicket provider handles one call at a time, so a stalled call can delay other catalogs.
|
||||
|
||||
The default printer says "(default)" in the device lists (the Plot and Page Setup dialogs and
|
||||
typed `-PLOTTERMANAGER ?`); `plottermanager` `list` and `get` report it as `default: true`. `plottermanager {action: "refresh"}`
|
||||
(the Plot dialog's Refresh printers) asks the system again instead of using a list up to 5 s
|
||||
old. `plot {device: <printer>, copies?, path?}` prints; with `path` ("Plot to file") the PDF is
|
||||
written there first, and nothing prints when it can't be. `plot {stamp: true | text}` stamps a
|
||||
line at the printable area's lower-left corner (`{drawing}`, `{layout}`, `{device}`, `{paper}`
|
||||
and `{scale}` are filled in, once each: a name holding `{paper}` stays as it is; `{{` is a
|
||||
literal `{`; PDF and PNG plots, not SVG). `plot {layouts: [a, b, …]}` without `device` writes one
|
||||
PDF of those sheets, each with its own page setup, even when the layout shown prints on a
|
||||
system printer; a single `layouts` entry plots like `layout` with that layout's device and paper.
|
||||
|
||||
User devices are files in our own format, kept in the `plotters` folder of the CADCraft
|
||||
settings directory:
|
||||
|
||||
|
||||
Reference in New Issue
Block a user