mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-04 22:49:54 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7eb22b31f6 | ||
|
|
b0d0543bbf | ||
|
|
e50f6ff5a3 | ||
|
|
49688e479a | ||
|
|
2441ec4905 | ||
|
|
7a7a568d9a | ||
|
|
57d2fbc541 | ||
|
|
428b75079b |
@@ -0,0 +1,60 @@
|
||||
function Remove-CaptureLocalPort {
|
||||
param([Parameter(Mandatory)][string]$Name)
|
||||
|
||||
if ($Name -notmatch '^[A-Za-z]:\\') {
|
||||
throw 'A capture port must have an absolute local file path as its name.'
|
||||
}
|
||||
# Remove-PrinterPort interprets backslashes as part of a printer/server name.
|
||||
# Pass the full path as data to the local monitor instead.
|
||||
if (-not ('CraftCaptureLocalPort' -as [type])) {
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
public static class CraftCaptureLocalPort
|
||||
{
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct PrinterDefaults
|
||||
{
|
||||
public IntPtr DataType;
|
||||
public IntPtr DevMode;
|
||||
public uint DesiredAccess;
|
||||
}
|
||||
|
||||
[DllImport("winspool.drv", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern bool OpenPrinter(string name, out IntPtr printer, ref PrinterDefaults defaults);
|
||||
|
||||
[DllImport("winspool.drv", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern bool XcvData(IntPtr printer, string command, byte[] input, uint inputBytes,
|
||||
IntPtr output, uint outputBytes, out uint bytesNeeded, out uint status);
|
||||
|
||||
[DllImport("winspool.drv")]
|
||||
private static extern bool ClosePrinter(IntPtr printer);
|
||||
|
||||
public static void Remove(string name)
|
||||
{
|
||||
const uint ServerAccessAdminister = 1;
|
||||
var defaults = new PrinterDefaults { DesiredAccess = ServerAccessAdminister };
|
||||
if (!OpenPrinter(",XcvMonitor Local Port", out var printer, ref defaults))
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
|
||||
try
|
||||
{
|
||||
byte[] input = Encoding.Unicode.GetBytes(name + "\0");
|
||||
if (!XcvData(printer, "DeletePort", input, (uint)input.Length, IntPtr.Zero, 0, out _, out uint status))
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
if (status != 0)
|
||||
throw new Win32Exception((int)status);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ClosePrinter(printer);
|
||||
}
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
[CraftCaptureLocalPort]::Remove($Name)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. ./.github/print-probe/windows-local-port.ps1
|
||||
Start-Service Spooler
|
||||
$driver = 'Microsoft Print To PDF'
|
||||
if (!(Get-PrinterDriver -Name $driver -ErrorAction SilentlyContinue)) { Add-PrinterDriver -Name $driver }
|
||||
$out = New-Item -ItemType Directory -Path queue-paper-evidence
|
||||
$port = Join-Path $out.FullName 'incoming.pdf'
|
||||
$queue = "WordCraft QA file $env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT"
|
||||
$binary = Join-Path $env:CARGO_TARGET_DIR 'debug/examples/queue_paper_qa.exe'
|
||||
Add-PrinterPort -Name $port
|
||||
try {
|
||||
Add-Printer -Name $queue -DriverName $driver -PortName $port
|
||||
try {
|
||||
Set-PrintConfiguration -PrinterName $queue -PaperSize Letter
|
||||
foreach ($case in 'no-scaling','a4-form') {
|
||||
& $binary $queue $case | Tee-Object -FilePath (Join-Path $out.FullName "$case.json")
|
||||
if ($LASTEXITCODE) { throw "WordCraft print command failed for $case" }
|
||||
$deadline = [DateTime]::UtcNow.AddSeconds(50)
|
||||
$complete = $false
|
||||
while ([DateTime]::UtcNow -lt $deadline) {
|
||||
try {
|
||||
$bytes = [IO.File]::ReadAllBytes($port)
|
||||
$n = [Math]::Min(40, $bytes.Length)
|
||||
if ($n -gt 0 -and [Text.Encoding]::ASCII.GetString($bytes, $bytes.Length - $n, $n).TrimEnd().EndsWith('%%EOF')) {
|
||||
Move-Item -LiteralPath $port -Destination (Join-Path $out.FullName "$case.pdf")
|
||||
$complete = $true
|
||||
break
|
||||
}
|
||||
} catch [IO.IOException] {}
|
||||
Start-Sleep -Milliseconds 250
|
||||
}
|
||||
if (!$complete) { throw "No complete PDF was captured for $case" }
|
||||
}
|
||||
} finally { Remove-Printer -Name $queue }
|
||||
} finally { Remove-CaptureLocalPort -Name $port }
|
||||
@@ -0,0 +1,38 @@
|
||||
ZGlmZiAtLWdpdCBhL2NyYXRlcy91aS1jb250cmFjdC9zcmMvcnVudGltZS93aW5kb3dzL2hvc3Qu
|
||||
cnMgYi9jcmF0ZXMvdWktY29udHJhY3Qvc3JjL3J1bnRpbWUvd2luZG93cy9ob3N0LnJzCmluZGV4
|
||||
IGYwMDg2OTU4Mi4uNjU0YjQzMTE5IDEwMDY0NAotLS0gYS9jcmF0ZXMvdWktY29udHJhY3Qvc3Jj
|
||||
L3J1bnRpbWUvd2luZG93cy9ob3N0LnJzCisrKyBiL2NyYXRlcy91aS1jb250cmFjdC9zcmMvcnVu
|
||||
dGltZS93aW5kb3dzL2hvc3QucnMKQEAgLTM1NCw2ICszNTQsMTggQEAgaW1wbCBXaW5kb3dIb3N0
|
||||
IHsKICAgICAgICAgUGVyVmlld3BvcnQ6OjxSZWNvcmQ+Ojp3aXRoKCZzZWxmLmN0eCwgVmlld3Bv
|
||||
cnRJZDo6Uk9PVCwgfHJlY29yZHwgcmVjb3JkLm5hdGl2ZS5jbG9uZSgpKT8ucmF3X2hhbmRsZSgp
|
||||
CiAgICAgfQogCisgICAgLy8vIFRoZSBXaW4zMiBIV05EIG9mIHRoZSBnaXZlbiB2aWV3cG9ydCdz
|
||||
IHdpbmRvdywgZm9yIG93bmluZyBhIG5hdGl2ZSBkaWFsb2cuIFJldHVybnMKKyAgICAvLy8gYE5v
|
||||
bmVgIGlmIHRoZSB2aWV3cG9ydCBoYXMgbm8gbmF0aXZlIHdpbmRvdyBoYW5kbGUuCisgICAgcHVi
|
||||
IGZuIG5hdGl2ZV93aW5kb3dfaGFuZGxlKCZzZWxmLCB2aWV3cG9ydDogVmlld3BvcnRJZCkgLT4g
|
||||
T3B0aW9uPHN0ZDo6bnVtOjpOb25aZXJvSXNpemU+IHsKKyAgICAgICAgaWYgdmlld3BvcnQgPT0g
|
||||
Vmlld3BvcnRJZDo6Uk9PVCB7CisgICAgICAgICAgICByZXR1cm4gc2VsZi5tYWluX3dpbmRvd19o
|
||||
YW5kbGUoKTsKKyAgICAgICAgfQorICAgICAgICBpZiAhc2VsZi5pc19vcGVuKHZpZXdwb3J0KSB7
|
||||
CisgICAgICAgICAgICByZXR1cm4gTm9uZTsKKyAgICAgICAgfQorICAgICAgICBzdXBlcjo6bmF0
|
||||
aXZlOjpuYXRpdmVfb2YoJnNlbGYuY3R4LCB2aWV3cG9ydCk/LnJhd19oYW5kbGUoKQorICAgIH0K
|
||||
KwogICAgIC8vLyBNb3ZlcyB0aGUgc3lzdGVtIHBvaW50ZXIgdG8gYHRvYCBpbiBkZXNrdG9wIHBv
|
||||
aW50czsgZmFsc2Ugd2hlcmUgdGhlIHBsYXRmb3JtIGNhbm5vdC4KICAgICBwdWIgZm4gd2FycF9w
|
||||
b2ludGVyKCZzZWxmLCB0bzogUG9zMikgLT4gYm9vbCB7CiAgICAgICAgIGxldCBzeXN0ZW0gPSBz
|
||||
aGFyZWQoJnNlbGYuY3R4LCB8c2hhcmVkfCBzaGFyZWQuc3lzdGVtLmNsb25lKCkpOwpkaWZmIC0t
|
||||
Z2l0IGEvY3JhdGVzL3VpLWNvbnRyYWN0L3NyYy9ydW50aW1lL3dpbmRvd3MvbmF0aXZlLnJzIGIv
|
||||
Y3JhdGVzL3VpLWNvbnRyYWN0L3NyYy9ydW50aW1lL3dpbmRvd3MvbmF0aXZlLnJzCmluZGV4IDkz
|
||||
MTM2ODE2OS4uNWVlZmQyNDgzIDEwMDY0NAotLS0gYS9jcmF0ZXMvdWktY29udHJhY3Qvc3JjL3J1
|
||||
bnRpbWUvd2luZG93cy9uYXRpdmUucnMKKysrIGIvY3JhdGVzL3VpLWNvbnRyYWN0L3NyYy9ydW50
|
||||
aW1lL3dpbmRvd3MvbmF0aXZlLnJzCkBAIC0yMTUsNyArMjE1LDcgQEAgZm4gc2V0X29wYWNpdHko
|
||||
Y3R4OiAmQ29udGV4dCwgdmlld3BvcnQ6IFZpZXdwb3J0SWQsIG9wYWNpdHk6IGYzMikgLT4gYm9v
|
||||
bCB7CiAvLy8gVGhlIE9TIHdpbmRvdyBvZiBgdmlld3BvcnRgLCBmb3VuZCBvbmNlIGl0cyB3aW5k
|
||||
b3cgZXhpc3RzOiBieSBpdHMgdGl0bGUgYW1vbmcgdGhlIHRocmVhZCdzIHdpbmRvd3MsIHdoZW4g
|
||||
ZXhhY3RseQogLy8vIG9uZSBzdGFydHMgYXQgdGhlIHJlcG9ydGVkIGNsaWVudCBvcmlnaW4uIEEg
|
||||
ZmFpbGVkIHNlYXJjaCByZXBlYXRzIGV2ZXJ5IGBTRUFSQ0hfRVZFUllgIHBhc3Nlcy4gVGhlIHJv
|
||||
b3Qgd2luZG93J3MgaXMKIC8vLyBzZXQgYnkgW2Byb3V0ZV9yb290YF0uCi1mbiBuYXRpdmVfb2Yo
|
||||
Y3R4OiAmQ29udGV4dCwgdmlld3BvcnQ6IFZpZXdwb3J0SWQpIC0+IE9wdGlvbjxOYXRpdmVXaW5k
|
||||
b3c+IHsKK3B1YihzdXBlcikgZm4gbmF0aXZlX29mKGN0eDogJkNvbnRleHQsIHZpZXdwb3J0OiBW
|
||||
aWV3cG9ydElkKSAtPiBPcHRpb248TmF0aXZlV2luZG93PiB7CiAgICAgbGV0IHBhc3MgPSBwYXNz
|
||||
OjpwYXNzX25yKGN0eCwgdmlld3BvcnQpOwogICAgIGxldCAoa25vd24sIHRpdGxlLCBzZWFyY2hl
|
||||
ZCwgZmFjdHMpID0KICAgICAgICAgUGVyVmlld3BvcnQ6OjxSZWNvcmQ+Ojp3aXRoKGN0eCwgdmll
|
||||
d3BvcnQsIHxyZWNvcmR8IChyZWNvcmQubmF0aXZlLmNsb25lKCksIHJlY29yZC50aXRsZS5jbG9u
|
||||
ZSgpLCByZWNvcmQuc2VhcmNoZWQsIHJlY29yZC5mYWN0cykpOwo=
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,108 @@
|
||||
name: Verify WordCraft queue-specific paper
|
||||
on:
|
||||
push:
|
||||
branches: [verify/wordcraft-queue-paper-4859]
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
CARGO_PROFILE_DEV_DEBUG: '0'
|
||||
CARGO_PROFILE_TEST_DEBUG: '0'
|
||||
CARGO_INCREMENTAL: '0'
|
||||
WORDCRAFT_FRAMEWORK: d73e274a01408ef433a291a667e6014937d72165
|
||||
jobs:
|
||||
paper:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: ${{ contains(github.event.head_commit.message, '[same-size-linux]') && fromJSON('["ubuntu-24.04"]') || fromJSON('["windows-2025","ubuntu-24.04"]') }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 90
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@58848078cd09e3ca182891a8b76ee979f1eb6e1c
|
||||
with:
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
- uses: storytold/craft-common-actions/actions/install-apt-packages@58848078cd09e3ca182891a8b76ee979f1eb6e1c
|
||||
if: runner.os == 'Linux'
|
||||
with:
|
||||
packages: pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
|
||||
- name: Choose an isolated build directory on Windows
|
||||
if: runner.os == 'Windows'
|
||||
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
|
||||
"CARGO_TARGET_DIR=$(Join-Path $disk.Root "wordcraft-paper-$env:GITHUB_RUN_ID")" >> $env:GITHUB_ENV
|
||||
- name: Apply native window ownership and paper catalogs to the locked library revision
|
||||
id: overlay
|
||||
shell: python
|
||||
run: |
|
||||
import base64, json, os, pathlib, subprocess
|
||||
host = next(line[6:] for line in subprocess.check_output(['rustc', '-vV'], text=True).splitlines() if line.startswith('host: '))
|
||||
os.environ['CARGO_HOME'] = str(pathlib.Path(os.environ['RUNNER_TEMP']) / 'wordcraft-paper-cargo')
|
||||
graph = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--format-version', '1', '--filter-platform', host]))
|
||||
package, = (p for p in graph['packages'] if p['name'] == 'craft-print')
|
||||
crate = pathlib.Path(package['manifest_path']).parent
|
||||
framework = pathlib.Path(subprocess.check_output(['git', 'rev-parse', '--show-toplevel'], cwd=crate, text=True).strip())
|
||||
head = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=framework, text=True).strip()
|
||||
assert head == os.environ['WORDCRAFT_FRAMEWORK'], head
|
||||
for file in sorted(pathlib.Path('.github/qa').glob('*.patch.b64')):
|
||||
patch = base64.b64decode(file.read_bytes())
|
||||
subprocess.run(['git', 'apply', '--check'], cwd=framework, input=patch, check=True)
|
||||
subprocess.run(['git', 'apply'], cwd=framework, input=patch, check=True)
|
||||
subprocess.run(['git', 'diff', '--exit-code', '--', 'Cargo.toml', 'Cargo.lock'], check=True)
|
||||
with open(os.environ['GITHUB_ENV'], 'a', encoding='utf-8') as env:
|
||||
print('CARGO_HOME=' + os.environ['CARGO_HOME'], file=env)
|
||||
- name: Capture the no-scaling and discovered A4 form jobs
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
run: |
|
||||
cargo build --locked -p wordcraft-ui-egui --example queue_paper_qa
|
||||
if ($LASTEXITCODE) { exit $LASTEXITCODE }
|
||||
./.github/print-probe/wordcraft-paper-capture.ps1
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
|
||||
if: always() && runner.os == 'Windows'
|
||||
with:
|
||||
name: wordcraft-queue-paper
|
||||
path: queue-paper-evidence/
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
- name: Run document geometry and native print integration tests
|
||||
if: "!cancelled() && steps.overlay.outcome == 'success' && !contains(github.event.head_commit.message, '[same-size-linux]')"
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cargo test --locked -p wordcraft-engine --lib print::
|
||||
cargo test --locked -p wordcraft-ui-egui --test it native_print::
|
||||
cargo test --locked -p wordcraft-ui-egui --lib printer_properties_
|
||||
- name: Verify that same-size CUPS forms preserve different keys
|
||||
if: contains(github.event.head_commit.message, '[same-size-linux]')
|
||||
run: cargo test --locked -p wordcraft-ui-egui --test it queue_form_keeps_its_media_with_the_job_and_clears_on_queue_change
|
||||
- name: Compile the real host and native window ownership
|
||||
if: "!cancelled() && steps.overlay.outcome == 'success' && runner.os == 'Windows'"
|
||||
run: cargo check --locked -p wordcraft
|
||||
inspect:
|
||||
needs: paper
|
||||
if: "!cancelled() && !contains(github.event.head_commit.message, '[same-size-linux]')"
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0
|
||||
with:
|
||||
name: wordcraft-queue-paper
|
||||
path: queue-paper-evidence
|
||||
- uses: storytold/craft-common-actions/actions/install-apt-packages@58848078cd09e3ca182891a8b76ee979f1eb6e1c
|
||||
with:
|
||||
packages: poppler-utils
|
||||
- name: Inspect the PDF dimensions and identify the submitted sheet
|
||||
run: |
|
||||
set -euo pipefail
|
||||
pdfinfo queue-paper-evidence/no-scaling.pdf | tee "$RUNNER_TEMP/no-scaling.info"
|
||||
pdfinfo queue-paper-evidence/a4-form.pdf | tee "$RUNNER_TEMP/a4.info"
|
||||
grep -Eq '^Page size: +612 x 792 pts' "$RUNNER_TEMP/no-scaling.info"
|
||||
grep -Eq '^Page size: +595\.2[0-9]+ x 841\.8[0-9]+ pts' "$RUNNER_TEMP/a4.info"
|
||||
for case in no-scaling a4-form; do
|
||||
pdftoppm -r 72 -singlefile "queue-paper-evidence/$case.pdf" "$RUNNER_TEMP/$case"
|
||||
python3 -c 'from pathlib import Path; import sys; raw=Path(sys.argv[1]).read_bytes().split(b"\n", 3); assert raw[0] == b"P6" and raw[-1].count(0) > 250, "page must contain visible ink"' "$RUNNER_TEMP/$case.ppm"
|
||||
done
|
||||
@@ -107,6 +107,7 @@ impl App {
|
||||
embed::before_ui(ui.ctx(), frame);
|
||||
}
|
||||
self.app.ui(ui);
|
||||
self.app.show_print_properties(ui.ctx());
|
||||
self.panels.pump_with(self.app.dialog_host_mut(), frame);
|
||||
}
|
||||
|
||||
@@ -243,6 +244,13 @@ fn services(spool: Spool, intake: FileIntake, nightly: bool) -> Services {
|
||||
let make_default_app: Option<MakeDefault> = None;
|
||||
Services {
|
||||
print: Some(spool),
|
||||
#[cfg(any(windows, unix))]
|
||||
print_papers: Some(wordcraft_ui_egui::native_print_papers),
|
||||
#[cfg(windows)]
|
||||
print_properties: Some(Box::new(|job, ctx, viewport| {
|
||||
let owner = WindowHost::of(ctx).native_window_handle(viewport).ok_or("the print window has no native owner")?;
|
||||
craft::print::driver_settings_dialog(job, Some(owner.get())).map_err(|error| error.to_string())
|
||||
})),
|
||||
templates_dir: wordcraft_control_key::settings_dir().map(|d| d.join("Templates")),
|
||||
make_default_app,
|
||||
intake: Some(intake),
|
||||
|
||||
@@ -131,7 +131,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.pure(),
|
||||
CommandSpec::new("file.printPdf", "Print to PDF", "File › Print", crate::print::print_pdf_to_file)
|
||||
.params(
|
||||
r#"{"path": string, "pagesPerSheet"?: 1 | 2 | 4 | 6 | 9 | 16 | "booklet" | "bookletReverse", "range"?: "all" | "current" | "selection" (the pages the selection touches) | "custom", "pages"?: "1-3,5" (implies custom), "parity"?: "all" | "odd" | "even", "copies"?: 1-999, "collate"?: bool (default true), "paper"?: "none" | "Letter" | "Legal" | "A4" | … (a Layout › Size name: scale every page to this paper, centred; the document keeps its size), "compress"?: bool (default true: compress the PDF's content streams; false writes the same pages uncompressed, which is larger)"#,
|
||||
r#"{"path": string, "pagesPerSheet"?: 1 | 2 | 4 | 6 | 9 | 16 | "booklet" | "bookletReverse", "range"?: "all" | "current" | "selection" (the pages the selection touches) | "custom", "pages"?: "1-3,5" (implies custom), "parity"?: "all" | "odd" | "even", "copies"?: 1-999, "collate"?: bool (default true), "paper"?: "none" | Layout › Size name | [width,height] in points (scale every page to this paper, centred; the document keeps its size), "compress"?: bool (default true: compress the PDF's content streams; false writes the same pages uncompressed, which is larger)"#,
|
||||
)
|
||||
.pure(),
|
||||
CommandSpec::new("file.print", "Print", "File", |s, _| {
|
||||
|
||||
@@ -148,6 +148,19 @@ pub fn paper(v: &Value) -> Result<Option<(&'static str, f32, f32)>, CmdError> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Physical output dimensions from a system queue's form or a standard document paper.
|
||||
fn paper_size(v: &Value) -> Result<Option<(f32, f32)>, CmdError> {
|
||||
if let Some(Value::Array(size)) = v.get("paper") {
|
||||
let invalid = || CmdError::Params("paper must be [width, height] in points, both from 1 to 14400".into());
|
||||
let side = |value: &Value| value.as_f64().filter(|n| (1.0..=14_400.0).contains(n)).map(|n| n as f32).ok_or_else(invalid);
|
||||
return match size.as_slice() {
|
||||
[width, height] => Ok(Some((side(width)?, side(height)?))),
|
||||
_ => Err(invalid()),
|
||||
};
|
||||
}
|
||||
Ok(paper(v)?.map(|(_, width, height)| (width, height)))
|
||||
}
|
||||
|
||||
/// Validate the physical sheet layout without touching document page setup.
|
||||
pub fn imposition(v: &Value) -> Result<wordcraft_pdf::imposition::Imposition, CmdError> {
|
||||
match v.get("pagesPerSheet") {
|
||||
@@ -164,7 +177,7 @@ pub fn imposition(v: &Value) -> Result<wordcraft_pdf::imposition::Imposition, Cm
|
||||
|
||||
/// Resolve physical paper orientation for imposed jobs; ordinary export keeps its existing policy.
|
||||
fn imposed_paper(v: &Value, lay: &DocLayout, pages: &[usize]) -> Result<Option<(f32, f32)>, CmdError> {
|
||||
let paper = paper(v)?.map(|(_, w, h)| (w, h));
|
||||
let paper = paper_size(v)?;
|
||||
if imposition(v)? == Imposition::Single {
|
||||
return Ok(paper);
|
||||
}
|
||||
@@ -361,11 +374,13 @@ mod tests {
|
||||
let (bytes, _) = s.print_pdf(&json!({"range": "current", "paper": name})).unwrap();
|
||||
assert_eq!(media(&bytes), vec![want], "{name}");
|
||||
}
|
||||
let (custom, _) = s.print_pdf(&json!({"range": "current", "paper": [421.0, 639.0]})).unwrap();
|
||||
assert_eq!(media(&custom), vec![(421.0, 639.0)]);
|
||||
for none in [json!(null), json!(""), json!("none"), json!("Document")] {
|
||||
let (bytes, _) = s.print_pdf(&json!({"range": "current", "paper": none})).unwrap();
|
||||
assert_eq!(media(&bytes), media(&own));
|
||||
}
|
||||
for bad in [json!("Quarto"), json!(5), json!({"w": 1}), json!("x".repeat(10_000))] {
|
||||
for bad in [json!("Quarto"), json!(5), json!({"w": 1}), json!("x".repeat(10_000)), json!([421.0]), json!([0, 639]), json!([421, 14401])] {
|
||||
assert!(s.print_pdf(&json!({"paper": bad})).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!((s.doc.last_section.page_w, s.doc.last_section.page_h, s.rev()), (w, h, rev), "the document is unchanged");
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Print two WordCraft jobs to the disposable Windows file queue created by the QA harness.
|
||||
|
||||
#[cfg(windows)]
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
use craft::print::spool::Spool;
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use wordcraft_ui_egui::{
|
||||
Services, WordApp,
|
||||
printing::{Feedback, Printer},
|
||||
};
|
||||
if let Some(code) = craft::print::spool::isolated::helper_main() {
|
||||
std::process::exit(code);
|
||||
}
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
let [queue, case] = args.as_slice() else { return Err("expected a disposable queue name and case".into()) };
|
||||
if !queue.starts_with("WordCraft QA file ") {
|
||||
return Err("this test only uses the disposable Windows file queue".into());
|
||||
}
|
||||
let services = Services {
|
||||
print: Some(Spool::new(Arc::new(craft::host::InlineJobs))),
|
||||
print_papers: Some(wordcraft_ui_egui::native_print_papers),
|
||||
..Default::default()
|
||||
};
|
||||
let mut doc = wordcraft_doc::Document::from_text("WordCraft printer form acceptance");
|
||||
doc.last_section.page_w = 612.0;
|
||||
doc.last_section.page_h = 792.0;
|
||||
let session = wordcraft_engine::Session::new(doc);
|
||||
let mut app = WordApp::new(session, services);
|
||||
let size = |app: &WordApp| (app.session.doc.last_section.page_w, app.session.doc.last_section.page_h);
|
||||
let document = size(&app);
|
||||
assert!((document.0 - 612.0).abs() < 1.0 && (document.1 - 792.0).abs() < 1.0, "{document:?}");
|
||||
app.printing.printers.push(Printer::new(queue).is_default(true));
|
||||
app.run("ui.printSettings", json!({"printer": queue}))?;
|
||||
let paper = match case.as_str() {
|
||||
"no-scaling" => json!("none"),
|
||||
"a4-form" => {
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
let page = app.run("ui.printPage", json!({}))?;
|
||||
let forms = page["printerPapers"].as_array().ok_or("no printer paper response")?;
|
||||
if let Some(form) = forms.iter().find(|f| {
|
||||
let w = f["size"][0].as_f64().unwrap_or_default();
|
||||
let h = f["size"][1].as_f64().unwrap_or_default();
|
||||
(w - 595.276).abs() < 1.0 && (h - 841.89).abs() < 1.0
|
||||
}) {
|
||||
break form["id"].clone();
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Err(format!("the virtual driver did not list A4: {forms:?}").into());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
_ => return Err("unknown acceptance case".into()),
|
||||
};
|
||||
let settings = app.run("ui.printPage", json!({"paper": paper}))?;
|
||||
let job = app.run("ui.printSubmit", json!({"paper": paper}))?;
|
||||
app.printing.poll(&egui::Context::default());
|
||||
assert_eq!(size(&app), document);
|
||||
let Some(Feedback::Submitted(receipt)) = &app.printing.message else {
|
||||
return Err(format!("spooler did not accept the job: {:?}", app.printing.message).into());
|
||||
};
|
||||
println!("{}", json!({"case": case, "paper": paper, "document": document, "settings": settings, "receipt": receipt, "job": job}));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn main() {}
|
||||
@@ -111,6 +111,7 @@ impl WordApp {
|
||||
fonts_frames: 0,
|
||||
clipboard_published: false,
|
||||
printing: Default::default(),
|
||||
pending_print_properties: None,
|
||||
print_feedback_seen: None,
|
||||
print_gen: 0,
|
||||
updates_rt: updates_ui::Runtime::default(),
|
||||
|
||||
@@ -823,7 +823,16 @@ impl WordApp {
|
||||
// Native printing submits the selected queue on a worker; the browser owns its dialog.
|
||||
"ui.printSettings" => {
|
||||
let discover = self.services.print.as_ref().map(craft::print::spool::Spool::discoverer);
|
||||
return Some(printing::settings(&mut self.printing, p, discover.as_ref()));
|
||||
let result = printing::settings(&mut self.printing, p, discover.as_ref()).map(|mut status| {
|
||||
self.print.driver_properties.select_queue(printing::printer_name(&self.printing.settings));
|
||||
printing::update_papers(self, p.get("refresh").and_then(Value::as_bool) == Some(true), None);
|
||||
if let Some(error) = self.properties_error() {
|
||||
status["ready"] = json!(false);
|
||||
status["detail"] = json!(error);
|
||||
}
|
||||
status
|
||||
});
|
||||
return Some(result);
|
||||
}
|
||||
"ui.printPage" => return Some(printing::print_page(self, p)),
|
||||
"ui.print" | "ui.printSubmit" => return Some(self.print_to_system(p)),
|
||||
|
||||
@@ -499,7 +499,13 @@ impl WordApp {
|
||||
/// settings choose.
|
||||
pub(crate) fn print_pdf_dialog(&mut self) {
|
||||
let name = format!("{}.pdf", self.title_stem());
|
||||
let settings = self.ui.print.params();
|
||||
let settings = match self.print.pdf_params(crate::printing::printer_name(&self.printing.settings)) {
|
||||
Ok(settings) => settings,
|
||||
Err(error) => {
|
||||
self.status(error);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let req = PickRequest::save("export").file_name(name).suggested_extension("pdf").filter(tl!("PDF"), &["pdf"]);
|
||||
let _ = self.ask_file(req, AfterPick::PrintPdf { settings });
|
||||
}
|
||||
|
||||
@@ -112,7 +112,9 @@ mod state;
|
||||
pub(crate) use app::works_without_document;
|
||||
// PLAN: assumed shell-w13 leaves `HostSaveFn` and `Inbox` out of `services` (sh.A14 removes `host_save` and `inbox`).
|
||||
pub use app::fonts::ui_fonts;
|
||||
pub use services::Services;
|
||||
#[cfg(any(windows, unix))]
|
||||
pub use printing::native_print_papers;
|
||||
pub use services::{PrintPaper, Services};
|
||||
pub use state::{AutoSaveBlock, keeps_everything};
|
||||
|
||||
/// A status-bar message and when it stops showing.
|
||||
@@ -415,6 +417,7 @@ pub struct WordApp {
|
||||
/// Only a successfully published copy may reuse this window's private fragment.
|
||||
pub clipboard_published: bool,
|
||||
pub printing: printing::State,
|
||||
pending_print_properties: Option<printing::PropertiesRequest>,
|
||||
print_feedback_seen: Option<printing::Feedback>,
|
||||
/// Which job message is current: bumped when a job starts and whenever the message changes,
|
||||
/// so a window can tell a new result from one it already said even when the text is the same.
|
||||
|
||||
@@ -42,8 +42,7 @@ pub struct PrintSettings {
|
||||
pub preview: usize,
|
||||
/// `auto`, `portrait` or `landscape`.
|
||||
pub orientation: String,
|
||||
/// Scale to paper size (#2108): `none` prints the document's page sizes, a Layout › Size
|
||||
/// name scales every page onto that paper. The document itself is unchanged.
|
||||
/// Scale to paper size (#2108): `none`, a Layout › Size name, or a form from the selected queue.
|
||||
pub paper: String,
|
||||
/// Physical grid size or booklet binding, independent of document page setup.
|
||||
pub pages_per_sheet: String,
|
||||
@@ -96,6 +95,9 @@ impl PrintSettings {
|
||||
pub struct PrintPage {
|
||||
/// What gets printed.
|
||||
pub settings: PrintSettings,
|
||||
pub(crate) papers: crate::printing::QueuePapers,
|
||||
/// Settings accepted in the selected queue's driver for this print draft.
|
||||
pub(crate) driver_properties: crate::printing::DriverProperties,
|
||||
/// The generation (`WordApp::print_gen`) of the job result this window has already said, in
|
||||
/// its status bar or on this page: a result of the same text from a later job is another one.
|
||||
pub(crate) said: Option<u64>,
|
||||
@@ -118,11 +120,27 @@ impl PrintPage {
|
||||
pub(crate) fn fit_view() -> PreviewView {
|
||||
PreviewView::fitting().zoom_range(Self::ZOOM)
|
||||
}
|
||||
|
||||
/// The current draft with a selected printer form resolved to its physical dimensions.
|
||||
pub(crate) fn pdf_params(&self, queue: &str) -> Result<Value, String> {
|
||||
let mut params = self.settings.params();
|
||||
self.papers.resolve(&mut params, queue)?;
|
||||
Ok(params)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PrintPage {
|
||||
fn default() -> Self {
|
||||
PrintPage { settings: PrintSettings::default(), said: None, hidden: None, opened_in: None, view: PrintPage::fit_view(), layout: None }
|
||||
PrintPage {
|
||||
settings: PrintSettings::default(),
|
||||
papers: Default::default(),
|
||||
driver_properties: Default::default(),
|
||||
said: None,
|
||||
hidden: None,
|
||||
opened_in: None,
|
||||
view: PrintPage::fit_view(),
|
||||
layout: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,6 +250,7 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
|
||||
let opened = cx.appeared() && app.print.opened_in != Some(frame);
|
||||
if opened {
|
||||
app.print.opened_in = Some(frame);
|
||||
app.print.driver_properties.discard_accepted_settings();
|
||||
}
|
||||
let result = |m: &Option<crate::printing::Feedback>| {
|
||||
matches!(
|
||||
@@ -253,7 +272,7 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
|
||||
// Shown here, so the next opening needn't repeat it.
|
||||
app.print.said = result(&message).then_some(generation);
|
||||
}
|
||||
let ready = !chooses || app.printing.ready();
|
||||
let ready = !chooses || (app.printing.ready() && app.properties_error().is_none());
|
||||
// The row takes the page, so the preview beside the settings column fills the room left (production: the
|
||||
// preview takes the page's height beside a 380 pt column).
|
||||
Row::new().fill().gap(Gap::Section).show(ui, |ui, _| {
|
||||
@@ -278,7 +297,7 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
|
||||
pub(crate) fn print_requested(app: &mut WordApp, _ctx: &egui::Context) {
|
||||
let chooses = app.services.print.as_ref().is_some_and(|spool| spool.chooses_printer());
|
||||
let can_print = app.services.print.is_some();
|
||||
if can_print && (!chooses || app.printing.ready()) {
|
||||
if can_print && (!chooses || (app.printing.ready() && app.properties_error().is_none())) {
|
||||
let params = app.print.settings.params();
|
||||
let _ = app.run("ui.print", params);
|
||||
}
|
||||
@@ -297,6 +316,18 @@ fn settings(app: &mut WordApp, ui: &mut Ui, lay: &Arc<DocLayout>, hide_message:
|
||||
if let Some(discover) = app.services.print.as_ref().map(|spool| spool.discoverer()) {
|
||||
app.printing.run(ui, &discover);
|
||||
}
|
||||
if app.services.print_properties.is_some() {
|
||||
let queue = crate::printing::printer_name(&app.printing.settings);
|
||||
app.print.driver_properties.select_queue(queue);
|
||||
if clicked(
|
||||
&Button::new(tl!("Printer Properties…")).enabled(app.printing.ready() && !queue.is_empty()).id_salt("printer-properties").show(ui),
|
||||
) {
|
||||
crate::printing::request_properties(app, ui.ctx());
|
||||
}
|
||||
if let Some(error) = app.properties_error() {
|
||||
Text::new(error.to_owned()).tone(Tone::Bad).show(ui);
|
||||
}
|
||||
}
|
||||
if let Some(message) = app.printing.message.as_ref().filter(|_| !hide_message) {
|
||||
Text::new(crate::printing::feedback(message, |label| crate::i18n::t(label).to_owned())).show(ui);
|
||||
}
|
||||
@@ -310,6 +341,7 @@ fn settings(app: &mut WordApp, ui: &mut Ui, lay: &Arc<DocLayout>, hide_message:
|
||||
} else {
|
||||
Text::new(tl!("Save a copy in another format. Printing goes through a PDF you can print from any viewer.")).show(ui);
|
||||
}
|
||||
crate::printing::update_papers(app, false, Some(ui.ctx()));
|
||||
if clicked(&Button::new(tl!("Save these pages as PDF…")).id_salt("save-pdf").sizing(Sizing::FillWidth).show(ui)) {
|
||||
app.print_pdf_dialog();
|
||||
}
|
||||
@@ -363,8 +395,16 @@ fn settings(app: &mut WordApp, ui: &mut Ui, lay: &Arc<DocLayout>, hide_message:
|
||||
Text::new(tl!("Booklets: duplex on the short edge. Blank pages are added at the end.")).show(ui);
|
||||
}
|
||||
// Word: Pages per sheet › Scale to paper size. Only the printout changes.
|
||||
let papers: Vec<(&str, &str)> =
|
||||
std::iter::once((NO_SCALING, "No Scaling")).chain(wordcraft_geom::PAPER_SIZES.iter().map(|(n, _, _)| (*n, *n))).collect();
|
||||
let mut papers = vec![(NO_SCALING, "No Scaling")];
|
||||
let current_paper = sheet.paper.clone();
|
||||
if print.papers.forms.is_empty() {
|
||||
papers.extend(wordcraft_geom::PAPER_SIZES.iter().map(|(name, _, _)| (*name, *name)));
|
||||
} else {
|
||||
if let Some((name, _, _)) = wordcraft_geom::paper_by_name(¤t_paper) {
|
||||
papers.push((current_paper.as_str(), name));
|
||||
}
|
||||
papers.extend(print.papers.forms.iter().map(|(id, form)| (id.as_str(), form.name.as_str())));
|
||||
}
|
||||
choice(ui, tl!("Scale to paper size"), "print_paper", &mut sheet.paper, &papers);
|
||||
|
||||
match wordcraft_engine::print::plan(&app.print.settings.params(), total, current) {
|
||||
|
||||
@@ -95,7 +95,13 @@ impl ThumbSource<usize> for SheetSource<'_> {
|
||||
/// The preview (#1156): the sheet fills the pane, a bar below pages through the sheets and zooms; zoomed in,
|
||||
/// the sheet pans.
|
||||
pub(super) fn show(app: &mut WordApp, ui: &mut Ui, lay: &Arc<DocLayout>) {
|
||||
let params = app.print.settings.params();
|
||||
let params = match app.print.pdf_params(crate::printing::printer_name(&app.printing.settings)) {
|
||||
Ok(params) => params,
|
||||
Err(error) => {
|
||||
Text::new(error).show(ui);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let sheets = match wordcraft_engine::print::sheets(¶ms, lay, app.session.current_pages(lay)) {
|
||||
Ok(sheets) => sheets,
|
||||
Err(error) => {
|
||||
|
||||
+138
-10
@@ -4,20 +4,25 @@ use serde_json::{Value, json};
|
||||
|
||||
use crate::print_page::{NO_SCALING, ORIENTATIONS, PAGES_PER_SHEET, PARITIES, PrintPage, RANGES};
|
||||
|
||||
mod papers;
|
||||
#[cfg(any(windows, unix))]
|
||||
pub use papers::native_print_papers;
|
||||
pub(crate) use papers::{QueuePapers, update as update_papers};
|
||||
|
||||
/// Metadata for the app-owned commands. Inspecting it never discovers printers or submits.
|
||||
pub fn commands(app: &crate::WordApp) -> Vec<Value> {
|
||||
let enabled = match &app.services.print {
|
||||
Some(spool) if spool.chooses_printer() => app.printing.ready(),
|
||||
Some(spool) if spool.chooses_printer() => app.printing.ready() && app.properties_error().is_none(),
|
||||
Some(_) => true,
|
||||
None => false,
|
||||
};
|
||||
let submit_params = "pagesPerSheet?: 1|2|4|6|9|16|booklet|bookletReverse; range?: all|current|selection|custom; pages?: string (1-3,5); parity?: all|odd|even; copies?: integer 1..999; collate?: bool; orientation?: auto|portrait|landscape; paper?: none|Letter|Legal|A4|… (Layout › Size names: Scale to paper size, every page scaled onto that paper and centred; the document is unchanged). Native uses the selected printer, duplex and grayscale from ui.printSettings; omitted copies/collation use current settings. Browser printing opens its dialog. Submits only when explicitly executed.";
|
||||
let submit_params = "pagesPerSheet?: 1|2|4|6|9|16|booklet|bookletReverse; range?: all|current|selection|custom; pages?: string (1-3,5); parity?: all|odd|even; copies?: integer 1..999; collate?: bool; orientation?: auto|portrait|landscape; paper?: none|Layout › Size name|form ID from ui.printPage. Scales the output and keeps the document’s size. Native uses the selected printer, duplex and grayscale from ui.printSettings; omitted copies/collation use current settings. Browser printing opens its dialog. Submits only when explicitly executed.";
|
||||
vec![
|
||||
json!({"id":"ui.printSettings", "label":"Print settings", "location":"File › Print", "shortcut":null,
|
||||
"params":"printer?: discovered name; copies?: integer 1..999; duplex?: printerDefault|off|longEdge|shortEdge|null; grayscale?: bool; refresh?: bool. Empty params inspect printer/copies/duplex/grayscale, printers, busy/discovering/ready and status/detail. Updates are atomic; refresh discovers only on native hosts. Never submits or opens a dialog.",
|
||||
"enabled":true}),
|
||||
json!({"id":"ui.printPage", "label":"Print page settings", "location":"File › Print", "shortcut":null,
|
||||
"params":"range?: all|current|selection|custom; pages?: string (1-3,5); parity?: all|odd|even; orientation?: auto|portrait|landscape; pagesPerSheet?: 1|2|4|6|9|16|booklet|bookletReverse; paper?: none|Layout › Size name; preview?: sheet index (0-based); zoom?: number 0.1..5 or null (fit). Empty params inspect. Updates are atomic. Never prints or opens a dialog.",
|
||||
"params":"range?: all|current|selection|custom; pages?: string (1-3,5); parity?: all|odd|even; orientation?: auto|portrait|landscape; pagesPerSheet?: 1|2|4|6|9|16|booklet|bookletReverse; paper?: none|Layout › Size name|form ID from printerPapers; preview?: sheet index (0-based); zoom?: number 0.1..5 or null (fit). Empty params inspect, including the selected printer’s available forms. Updates are atomic. Never prints or opens a dialog.",
|
||||
"enabled":true}),
|
||||
json!({"id":"ui.printSubmit", "label":"Submit print job", "location":"File › Print", "shortcut":null, "params":submit_params, "enabled":enabled}),
|
||||
json!({"id":"ui.print", "label":"Print (alias of ui.printSubmit)", "location":"File › Print", "shortcut":null, "params":submit_params, "enabled":enabled}),
|
||||
@@ -102,13 +107,14 @@ fn one_of<'a>(object: &'a serde_json::Map<String, Value>, key: &str, ids: impl I
|
||||
|
||||
// PLAN(shell-w6): ui.printPage arm in app/commands.rs beside ui.printSettings: `"ui.printPage" => printing::print_page(self, ¶ms)`.
|
||||
/// `ui.printPage`: read the Print page's settings, or validate an explicit update before changing any.
|
||||
/// Never prints, opens a dialog or starts discovery.
|
||||
/// Never prints or opens a dialog. Paper discovery runs on a separate worker.
|
||||
pub(crate) fn print_page(app: &mut crate::WordApp, params: &Value) -> Result<Value, String> {
|
||||
let object = params.as_object().ok_or("print page settings must be an object")?;
|
||||
const KEYS: [&str; 8] = ["range", "pages", "parity", "orientation", "pagesPerSheet", "paper", "preview", "zoom"];
|
||||
if object.keys().any(|key| !KEYS.contains(&key.as_str())) {
|
||||
return Err("unknown print page setting; use range, pages, parity, orientation, pagesPerSheet, paper, preview or zoom".into());
|
||||
}
|
||||
update_papers(app, false, None);
|
||||
let mut next = app.print.settings.clone();
|
||||
let mut view = app.print.view.clone();
|
||||
if let Some(range) = one_of(object, "range", RANGES.iter().map(|(id, _)| *id))? {
|
||||
@@ -128,9 +134,12 @@ pub(crate) fn print_page(app: &mut crate::WordApp, params: &Value) -> Result<Val
|
||||
}
|
||||
}
|
||||
if let Some(value) = object.get("paper") {
|
||||
let queue = printer_name(&app.printing.settings);
|
||||
match value.as_str() {
|
||||
Some(paper) if paper == NO_SCALING || wordcraft_geom::paper_by_name(paper).is_some() => next.paper = paper.to_owned(),
|
||||
_ => return Err("paper must be none or a Layout › Size name".into()),
|
||||
Some(paper) if paper == NO_SCALING || wordcraft_geom::paper_by_name(paper).is_some() || app.print.papers.form(queue, paper).is_some() => {
|
||||
next.paper = paper.to_owned();
|
||||
}
|
||||
_ => return Err("paper must be none, a Layout › Size name or a form from the selected printer".into()),
|
||||
}
|
||||
}
|
||||
if let Some(value) = object.get("pages") {
|
||||
@@ -158,6 +167,7 @@ pub(crate) fn print_page(app: &mut crate::WordApp, params: &Value) -> Result<Val
|
||||
Ok(json!({
|
||||
"range": settings.range, "pages": settings.pages, "parity": settings.parity, "orientation": settings.orientation,
|
||||
"pagesPerSheet": settings.pages_per_sheet, "paper": settings.paper, "preview": settings.preview,
|
||||
"printerPapers": app.print.papers.forms.iter().map(|(id, form)| json!({"id": id, "name": form.name, "size": form.size})).collect::<Vec<_>>(),
|
||||
"zoom": if app.print.view.fit { Value::Null } else { json!(app.print.view.transform.scale) },
|
||||
}))
|
||||
}
|
||||
@@ -236,6 +246,108 @@ pub(crate) fn printer_name(settings: &Settings) -> &str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Driver data belongs to this window's print draft and must never enter command JSON.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct DriverProperties {
|
||||
settings: Option<(u64, craft::print::DriverSettings)>,
|
||||
feedback: Option<(u64, String, String)>,
|
||||
}
|
||||
|
||||
impl DriverProperties {
|
||||
pub(crate) fn discard_accepted_settings(&mut self) {
|
||||
self.settings = None;
|
||||
}
|
||||
|
||||
pub(crate) fn select_queue(&mut self, queue: &str) {
|
||||
self.settings = self.settings.take().filter(|(_, settings)| settings.printer() == queue);
|
||||
self.feedback = self.feedback.take().filter(|(_, printer, _)| printer == queue);
|
||||
}
|
||||
|
||||
fn take_for(self, document: u64, queue: Option<&str>) -> Option<craft::print::DriverSettings> {
|
||||
self.settings.filter(|(doc, settings)| *doc == document && queue == Some(settings.printer())).map(|(_, settings)| settings)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct PropertiesRequest {
|
||||
window: u64,
|
||||
document: u64,
|
||||
viewport: egui::ViewportId,
|
||||
queue: String,
|
||||
}
|
||||
|
||||
pub(crate) fn request_properties(app: &mut crate::WordApp, ctx: &egui::Context) {
|
||||
let queue = printer_name(&app.printing.settings);
|
||||
if queue.is_empty() || !app.printing.ready() || app.services.print_properties.is_none() {
|
||||
return;
|
||||
}
|
||||
app.pending_print_properties = Some(PropertiesRequest {
|
||||
window: app.windows.shown(),
|
||||
document: app.session.document_id(),
|
||||
viewport: craft::ui::runtime::windows::WindowHost::of(ctx).current(),
|
||||
queue: queue.to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
impl crate::WordApp {
|
||||
pub(crate) fn properties_error(&self) -> Option<&str> {
|
||||
let (document, printer, message) = self.print.driver_properties.feedback.as_ref()?;
|
||||
(*document == self.session.document_id() && printer == printer_name(&self.printing.settings)).then_some(message.as_str())
|
||||
}
|
||||
|
||||
/// Lets the host present a requested Windows dialog after the frame. The viewport and
|
||||
/// document that asked keep their own draft, even if another window was drawn last.
|
||||
pub fn show_print_properties(&mut self, ctx: &egui::Context) {
|
||||
let Some(request) = self.pending_print_properties.take() else { return };
|
||||
let previous = self.windows.shown();
|
||||
if self.enter_window(request.window) {
|
||||
self.open_print_properties(ctx, request);
|
||||
self.enter_window(previous);
|
||||
}
|
||||
}
|
||||
|
||||
fn open_print_properties(&mut self, ctx: &egui::Context, request: PropertiesRequest) {
|
||||
if !self.ui.backstage
|
||||
|| self.ui.backstage_page != "print"
|
||||
|| self.session.document_id() != request.document
|
||||
|| !self.printing.ready()
|
||||
|| printer_name(&self.printing.settings) != request.queue
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(open) = self.services.print_properties.as_ref() else { return };
|
||||
let mut job = job_of(&self.printing.settings, self.print.settings.collate, Vec::new());
|
||||
job.driver_settings = self
|
||||
.print
|
||||
.driver_properties
|
||||
.settings
|
||||
.as_ref()
|
||||
.filter(|(doc, settings)| *doc == request.document && settings.printer() == request.queue)
|
||||
.map(|(_, settings)| settings.clone());
|
||||
let result = open(&mut job, ctx, request.viewport).and_then(|accepted| {
|
||||
if !accepted {
|
||||
return Ok(None);
|
||||
}
|
||||
job.driver_settings
|
||||
.filter(|settings| settings.printer() == request.queue)
|
||||
.map(Some)
|
||||
.ok_or_else(|| tl!("The driver did not return settings for the selected printer.").to_owned())
|
||||
});
|
||||
match result {
|
||||
Ok(Some(settings)) => {
|
||||
self.print.driver_properties.settings = Some((request.document, settings));
|
||||
self.print.driver_properties.feedback = None;
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
let message = crate::i18n::fmt(tl!("Could not open printer properties: {error}"), &[("error", &error)]);
|
||||
self.print.driver_properties.feedback = Some((request.document, request.queue, message.clone()));
|
||||
self.status(message);
|
||||
}
|
||||
}
|
||||
ctx.request_repaint_of(request.viewport);
|
||||
}
|
||||
}
|
||||
|
||||
/// The spooler's job for `settings`: the app's choices, shrink-to-fit paper and the options list.
|
||||
// PLAN: assumed `craft::print` is reachable from ui-egui (the Job is built here, as apps/wordcraft/src/print.rs did).
|
||||
fn job_of(settings: &Settings, collate: bool, options: Vec<(String, String)>) -> craft::print::Job {
|
||||
@@ -268,14 +380,21 @@ pub fn submit(app: &mut crate::WordApp, params: &Value) -> Result<Value, String>
|
||||
return Ok(json!({"saveAsPdf": true}));
|
||||
}
|
||||
let chooses = spool.chooses_printer();
|
||||
if chooses && let Some(error) = app.properties_error() {
|
||||
return Err(error.to_owned());
|
||||
}
|
||||
if chooses && !app.printing.ready() {
|
||||
return Err("Select an available printer in File > Print before submitting.".into());
|
||||
}
|
||||
if app.printing.busy() {
|
||||
return Err("A print job is already being submitted.".into());
|
||||
}
|
||||
update_papers(app, false, None);
|
||||
let mut pdf_params = params.clone();
|
||||
let mut settings = app.printing.settings.clone();
|
||||
let queue_form = app.print.papers.resolve(&mut pdf_params, printer_name(&settings))?;
|
||||
let exact = queue_form.is_some_and(|form| form.media.is_none());
|
||||
let queue_media = queue_form.and_then(|form| form.media.clone());
|
||||
let collate =
|
||||
params.get("collate").map(|value| value.as_bool().ok_or("collate must be a boolean")).transpose()?.unwrap_or(app.print.settings.collate);
|
||||
if chooses {
|
||||
@@ -312,7 +431,7 @@ pub fn submit(app: &mut crate::WordApp, params: &Value) -> Result<Value, String>
|
||||
let is_landscape = if mode != wordcraft_engine::print::Imposition::Single {
|
||||
let markup = wordcraft_engine::cmd::file::export_options(&app.session, &pdf_params).markup;
|
||||
let lay = app.session.export_layout_with(markup);
|
||||
wordcraft_engine::print::sheets(params, &lay, app.session.current_pages(&lay))
|
||||
wordcraft_engine::print::sheets(&pdf_params, &lay, app.session.current_pages(&lay))
|
||||
.map_err(|e| e.to_string())?
|
||||
.first()
|
||||
.is_some_and(|s| s.width > s.height)
|
||||
@@ -325,8 +444,9 @@ pub fn submit(app: &mut crate::WordApp, params: &Value) -> Result<Value, String>
|
||||
lay.pages.first().is_some_and(|p| p.w > p.h)
|
||||
};
|
||||
// Scale to paper size: ask the printer for that paper too, so it takes it from the right tray.
|
||||
if let Some(media) = wordcraft_engine::print::paper(params).ok().flatten().and_then(|(name, _, _)| pwg_media(name)) {
|
||||
print_options.push(("media".into(), media.into()));
|
||||
let standard_media = || wordcraft_engine::print::paper(params).ok().flatten().and_then(|(name, _, _)| pwg_media(name)).map(str::to_owned);
|
||||
if let Some(media) = queue_media.or_else(standard_media) {
|
||||
print_options.push(("media".into(), media));
|
||||
}
|
||||
if is_landscape {
|
||||
print_options.push(("orientation-requested".into(), "4".into()));
|
||||
@@ -334,7 +454,15 @@ pub fn submit(app: &mut crate::WordApp, params: &Value) -> Result<Value, String>
|
||||
} else {
|
||||
print_options.push(("orientation-requested".into(), "3".into()));
|
||||
}
|
||||
let receiver = spool.submit(bytes, job_of(&settings, collate, print_options));
|
||||
let mut job = job_of(&settings, collate, print_options);
|
||||
if exact {
|
||||
job.scaling = craft::print::Scaling::Exact;
|
||||
}
|
||||
let properties = std::mem::take(&mut app.print.driver_properties);
|
||||
if app.ui.backstage && app.ui.backstage_page == "print" {
|
||||
job.driver_settings = properties.take_for(app.session.document_id(), job.printer.as_deref());
|
||||
}
|
||||
let receiver = spool.submit(bytes, job);
|
||||
app.printing.begin(receiver).map_err(|_| "A print job is already being submitted.".to_owned())?;
|
||||
app.print_feedback_seen = None;
|
||||
app.print_gen = app.print_gen.wrapping_add(1);
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
use std::sync::mpsc::{self, Receiver, TryRecvError};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{PrintPaper, WordApp, print_page::NO_SCALING};
|
||||
|
||||
/// A selection key belongs to one generation of one queue's catalog.
|
||||
pub(super) fn is_key(key: &str) -> bool {
|
||||
key.starts_with("queue:")
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct QueuePapers {
|
||||
queue: String,
|
||||
generation: u64,
|
||||
requested: bool,
|
||||
pending: Option<(u64, Receiver<Vec<PrintPaper>>)>,
|
||||
pub(crate) forms: Vec<(String, PrintPaper)>,
|
||||
}
|
||||
|
||||
impl QueuePapers {
|
||||
/// Resolve a driver form using the active queue and the last catalog it returned.
|
||||
pub(crate) fn form(&self, queue: &str, key: &str) -> Option<&PrintPaper> {
|
||||
(self.queue == queue).then_some(())?;
|
||||
self.forms.iter().find(|(id, _)| id == key).map(|(_, form)| form)
|
||||
}
|
||||
|
||||
/// Use the same physical sheet dimensions in the preview, export and spool PDF.
|
||||
pub(crate) fn resolve(&self, params: &mut Value, queue: &str) -> Result<Option<&PrintPaper>, String> {
|
||||
let Some(key) = params.get("paper").and_then(Value::as_str).filter(|key| is_key(key)) else { return Ok(None) };
|
||||
let form = self.form(queue, key).ok_or_else(|| tl!("Choose a paper size from the selected printer.").to_owned())?;
|
||||
params["paper"] = json!([form.size.0, form.size.1]);
|
||||
Ok(Some(form))
|
||||
}
|
||||
|
||||
fn update(&mut self, queue: &str, refresh: bool, provider: Option<fn(&str) -> Vec<PrintPaper>>, ctx: Option<&egui::Context>) -> bool {
|
||||
let reset = self.queue != queue || refresh;
|
||||
if reset {
|
||||
self.queue = queue.to_owned();
|
||||
self.generation = self.generation.wrapping_add(1);
|
||||
self.requested = false;
|
||||
self.forms.clear();
|
||||
}
|
||||
if let Some((generation, receiver)) = &self.pending {
|
||||
match receiver.try_recv() {
|
||||
Ok(forms) => {
|
||||
if *generation == self.generation {
|
||||
self.forms = forms
|
||||
.into_iter()
|
||||
.filter(|form| [form.size.0, form.size.1].iter().all(|n| (1.0..=14_400.0).contains(n)))
|
||||
.enumerate()
|
||||
.map(|(index, form)| (format!("queue:{generation}:{}:{index}", self.queue), form))
|
||||
.collect();
|
||||
}
|
||||
self.pending = None;
|
||||
}
|
||||
Err(TryRecvError::Disconnected) => self.pending = None,
|
||||
Err(TryRecvError::Empty) => {}
|
||||
}
|
||||
}
|
||||
if !self.requested
|
||||
&& self.pending.is_none()
|
||||
&& !queue.is_empty()
|
||||
&& let Some(provider) = provider
|
||||
{
|
||||
self.requested = true;
|
||||
let (send, receive) = mpsc::channel();
|
||||
let queue = queue.to_owned();
|
||||
let ctx = ctx.cloned();
|
||||
if std::thread::Builder::new()
|
||||
.name("printer-paper".to_owned())
|
||||
.spawn(move || {
|
||||
let _ = send.send(provider(&queue));
|
||||
if let Some(ctx) = ctx {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
{
|
||||
self.pending = Some((self.generation, receive));
|
||||
}
|
||||
}
|
||||
reset
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn update(app: &mut WordApp, refresh: bool, ctx: Option<&egui::Context>) {
|
||||
let queue = super::printer_name(&app.printing.settings);
|
||||
if app.print.papers.update(queue, refresh, app.services.print_papers, ctx) && is_key(&app.print.settings.paper) {
|
||||
app.print.settings.paper = NO_SCALING.into();
|
||||
}
|
||||
if app.print.papers.pending.is_some()
|
||||
&& let Some(ctx) = ctx
|
||||
{
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn native_print_papers(queue: &str) -> Vec<PrintPaper> {
|
||||
let mut forms: Vec<PrintPaper> = Vec::new();
|
||||
for form in craft::print::printer_papers(queue) {
|
||||
let (w, h) = (form.width as f32, form.height as f32);
|
||||
let size = (w.min(h), w.max(h));
|
||||
// The Windows API selects a form by size. Same-size driver choices belong in Properties.
|
||||
if !forms.iter().any(|form| (form.size.0 - size.0).abs() < 0.1 && (form.size.1 - size.1).abs() < 0.1) {
|
||||
forms.push(PrintPaper { name: form.name, size, media: None });
|
||||
}
|
||||
}
|
||||
forms
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub fn native_print_papers(queue: &str) -> Vec<PrintPaper> {
|
||||
craft::print::cups::media_catalog(queue)
|
||||
.sizes
|
||||
.into_iter()
|
||||
.map(|form| PrintPaper { name: form.label, size: (form.width as f32, form.height as f32), media: Some(form.key) })
|
||||
.collect()
|
||||
}
|
||||
@@ -1,3 +1,13 @@
|
||||
/// Shows the selected printer's driver dialog, owned by the requesting viewport.
|
||||
pub type PrintProperties = Box<dyn Fn(&mut craft::print::Job, &egui::Context, egui::ViewportId) -> Result<bool, String>>;
|
||||
|
||||
/// A physical form advertised by a system queue. CUPS also supplies its exact submission key.
|
||||
pub struct PrintPaper {
|
||||
pub name: String,
|
||||
pub size: (f32, f32),
|
||||
pub media: Option<String>,
|
||||
}
|
||||
|
||||
/// Platform services injected by the host. Files, the clipboard, animations and preferences
|
||||
/// reach the app through the framework's host, not through here.
|
||||
#[derive(Default)]
|
||||
@@ -5,6 +15,10 @@ pub struct Services {
|
||||
/// Printing: the print job layer over the host's jobs (desktop printers, the browser's print
|
||||
/// dialog on the web).
|
||||
pub print: Option<craft::print::spool::Spool>,
|
||||
/// Windows: per-job printer properties. The host resolves the viewport's native owner.
|
||||
pub print_properties: Option<PrintProperties>,
|
||||
/// Reads the selected queue's forms on a worker. Browser hosts leave this unset.
|
||||
pub print_papers: Option<fn(&str) -> Vec<PrintPaper>>,
|
||||
/// Web: told whether the document has unsaved changes after each pass, for the browser's
|
||||
/// leave-page guard (`beforeunload` runs between frames and can't ask the app).
|
||||
pub on_dirty: Option<Box<dyn Fn(bool)>>,
|
||||
|
||||
@@ -30,6 +30,7 @@ enum Reply {
|
||||
struct Recorder {
|
||||
reply: Arc<Mutex<Reply>>,
|
||||
sent: Arc<Mutex<Vec<Vec<u8>>>>,
|
||||
job_options: Arc<Mutex<Vec<craft::print::Job>>>,
|
||||
cancels: Arc<AtomicUsize>,
|
||||
held: Arc<Mutex<Vec<mpsc::Sender<()>>>>,
|
||||
never_sent: bool,
|
||||
@@ -42,6 +43,7 @@ impl Recorder {
|
||||
Recorder {
|
||||
reply: Arc::new(Mutex::new(reply)),
|
||||
sent: Arc::default(),
|
||||
job_options: Arc::default(),
|
||||
cancels: Arc::default(),
|
||||
held: Arc::default(),
|
||||
never_sent: true,
|
||||
@@ -101,8 +103,9 @@ impl SpoolBackend for Recorder {
|
||||
)
|
||||
}
|
||||
|
||||
fn prepare(&self, pdf: Vec<u8>, _job: craft::print::Job) -> Pending {
|
||||
fn prepare(&self, pdf: Vec<u8>, job: craft::print::Job) -> Pending {
|
||||
self.sent.lock().unwrap().push(pdf);
|
||||
self.job_options.lock().unwrap().push(job);
|
||||
let reply = self.reply.lock().unwrap().clone();
|
||||
let (keep, wait) = mpsc::channel::<()>();
|
||||
if matches!(reply, Reply::Hold) {
|
||||
@@ -537,6 +540,105 @@ fn print_page_harness(message: Option<Feedback>, rec: &Recorder) -> egui_kittest
|
||||
h
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printer_properties_open_for_the_selected_queue_and_apply_to_one_submission() {
|
||||
let rec = Recorder::new(Reply::Sent).with_printers(["Test queue", "Second queue"]);
|
||||
let mut h = print_page_harness(None, &rec);
|
||||
let opened = Arc::new(AtomicUsize::new(0));
|
||||
let seen = opened.clone();
|
||||
h.state_mut().services.print_properties = Some(Box::new(move |job, _, owner| {
|
||||
assert_eq!(owner, egui::ViewportId::ROOT);
|
||||
assert_eq!(job.printer.as_deref(), Some("Test queue"));
|
||||
let mut bytes = vec![0; 160];
|
||||
bytes[68..70].copy_from_slice(&156u16.to_le_bytes());
|
||||
bytes[70..72].copy_from_slice(&4u16.to_le_bytes());
|
||||
bytes[156..].copy_from_slice(&[1, 2, 3, 4]);
|
||||
let native = craft::print::rgb::DevMode::from_bytes(bytes).unwrap();
|
||||
job.driver_settings = Some(craft::print::DriverSettings::new("Test queue", native));
|
||||
seen.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(true)
|
||||
}));
|
||||
let ctx = h.ctx.clone();
|
||||
let open = || By::new().role(egui::accesskit::Role::Button).label("Printer Properties…");
|
||||
h.state_mut().run("file.print", json!({})).unwrap();
|
||||
h.run_steps(3);
|
||||
h.query(open()).expect("the selected printer has a Properties button").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(opened.load(Ordering::SeqCst), 0, "the host owns the native dialog");
|
||||
h.state_mut().show_print_properties(&ctx);
|
||||
assert_eq!(opened.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(rec.sent_count(), 0, "opening Properties does not print");
|
||||
|
||||
h.state_mut().run("ui.printSubmit", json!({})).unwrap();
|
||||
h.state_mut().poll_printing(&ctx);
|
||||
h.state_mut().run("file.print", json!({})).unwrap();
|
||||
h.run_steps(3);
|
||||
h.state_mut().run("ui.printSubmit", json!({})).unwrap();
|
||||
h.state_mut().poll_printing(&ctx);
|
||||
h.state_mut().run("file.print", json!({})).unwrap();
|
||||
h.run_steps(3);
|
||||
h.query(open()).expect("the selected printer has a Properties button").click();
|
||||
h.run_steps(3);
|
||||
h.state_mut().show_print_properties(&ctx);
|
||||
h.state_mut().run("ui.printSettings", json!({"printer": "Second queue"})).unwrap();
|
||||
h.state_mut().run("ui.printSubmit", json!({})).unwrap();
|
||||
h.state_mut().poll_printing(&ctx);
|
||||
h.state_mut().run("ui.printSettings", json!({"printer": "Test queue"})).unwrap();
|
||||
h.state_mut().run("ui.printSubmit", json!({})).unwrap();
|
||||
|
||||
let jobs = rec.job_options.lock().unwrap();
|
||||
let [first, second, third, fourth] = jobs.as_slice() else { panic!("expected four jobs") };
|
||||
let properties = first.driver_settings.as_ref().expect("the first job carries the accepted properties");
|
||||
assert_eq!(properties.printer(), "Test queue");
|
||||
assert!(properties.dev_mode().to_hex().ends_with("01020304"), "the private driver fields reach the job");
|
||||
assert_eq!(second.printer.as_deref(), Some("Test queue"));
|
||||
assert!(second.driver_settings.is_none(), "the settings were for one submission");
|
||||
assert_eq!(third.printer.as_deref(), Some("Second queue"));
|
||||
assert!(third.driver_settings.is_none(), "properties do not follow a printer change");
|
||||
assert!(fourth.driver_settings.is_none(), "switching back does not recover the former properties");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printer_properties_failure_blocks_print_until_the_driver_returns_matching_settings() {
|
||||
let rec = Recorder::new(Reply::Sent).with_printers(["Test queue", "Second queue"]);
|
||||
let mut h = print_page_harness(None, &rec);
|
||||
h.state_mut().run("file.print", json!({})).unwrap();
|
||||
h.run_steps(3);
|
||||
let ctx = h.ctx.clone();
|
||||
let attempts = AtomicUsize::new(0);
|
||||
h.state_mut().services.print_properties = Some(Box::new(move |job, _, _| match attempts.fetch_add(1, Ordering::SeqCst) {
|
||||
0 => Err("driver unavailable".into()),
|
||||
1 => Ok(false),
|
||||
2 => Ok(true),
|
||||
attempt => {
|
||||
let mut bytes = vec![0; 156];
|
||||
bytes[68..70].copy_from_slice(&156u16.to_le_bytes());
|
||||
let native = craft::print::rgb::DevMode::from_bytes(bytes).unwrap();
|
||||
let queue = if attempt == 3 { "Second queue" } else { "Test queue" };
|
||||
job.driver_settings = Some(craft::print::DriverSettings::new(queue, native));
|
||||
Ok(true)
|
||||
}
|
||||
}));
|
||||
for attempt in 0..5 {
|
||||
crate::printing::request_properties(h.state_mut(), &ctx);
|
||||
h.state_mut().show_print_properties(&ctx);
|
||||
if attempt < 4 {
|
||||
if attempt == 0 {
|
||||
leave_and_reopen_print(&mut h);
|
||||
}
|
||||
let settings = h.state_mut().run("ui.printSettings", json!({})).unwrap();
|
||||
assert_eq!(settings["ready"], false);
|
||||
assert!(h.state_mut().run("ui.printSubmit", json!({})).is_err());
|
||||
crate::print_page::print_requested(h.state_mut(), &ctx);
|
||||
assert_eq!(rec.sent_count(), 0);
|
||||
}
|
||||
}
|
||||
assert_eq!(h.state_mut().run("ui.printSettings", json!({})).unwrap()["ready"], true);
|
||||
h.state_mut().run("ui.printSubmit", json!({})).unwrap();
|
||||
assert_eq!(rec.sent_count(), 1);
|
||||
assert_eq!(rec.job_options.lock().unwrap()[0].driver_settings.as_ref().unwrap().printer(), "Test queue");
|
||||
}
|
||||
|
||||
/// A job message that arrives without the app's own `print_feedback` acting on it (a submitted job
|
||||
/// would close the Print page); what the window has said is set by the test.
|
||||
fn set_print_message(h: &mut egui_kittest::Harness<'_, WordApp>, message: Option<Feedback>) {
|
||||
|
||||
@@ -153,6 +153,7 @@ impl WordApp {
|
||||
search_cache: _,
|
||||
fonts_frames: _,
|
||||
printing: _,
|
||||
pending_print_properties: _,
|
||||
print_feedback_seen: _,
|
||||
print_gen: _,
|
||||
font_generation: _,
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::sync::{Arc, Mutex};
|
||||
use wordcraft_engine::Session;
|
||||
use wordcraft_ui_egui::control::handle;
|
||||
use wordcraft_ui_egui::printing::{Feedback, Printer};
|
||||
use wordcraft_ui_egui::{Services, WordApp};
|
||||
use wordcraft_ui_egui::{PrintPaper, Services, WordApp};
|
||||
|
||||
/// What the status bar says, as `ui.inspect` reports it; empty once the message has expired.
|
||||
fn status_text(app: &mut WordApp) -> String {
|
||||
@@ -375,6 +375,66 @@ fn native_print_scales_to_the_chosen_paper() {
|
||||
assert_eq!((app.session.doc.last_section.page_w, app.session.doc.last_section.page_h), page, "the document is unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queue_form_keeps_its_media_with_the_job_and_clears_on_queue_change() {
|
||||
let fake = Fake::accepting();
|
||||
let mut app = app_over(&fake);
|
||||
app.services.print_papers = Some(|queue| match queue {
|
||||
"Queue" => vec![
|
||||
PrintPaper { name: "Plain stock".into(), size: (421.0, 639.0), media: Some("plain_vendor_421x639".into()) },
|
||||
PrintPaper { name: "Borderless stock".into(), size: (421.0, 639.0), media: Some("borderless_vendor_421x639".into()) },
|
||||
],
|
||||
"Another queue" => vec![PrintPaper { name: "Special form".into(), size: (425.0, 650.0), media: None }],
|
||||
_ => Vec::new(),
|
||||
});
|
||||
app.run("text.insert", json!({"text": "The document keeps its own paper"})).unwrap();
|
||||
let paper = (app.session.doc.last_section.page_w, app.session.doc.last_section.page_h);
|
||||
choose_queue(&mut app, json!({}));
|
||||
let wait_for_form = |app: &mut WordApp| {
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
loop {
|
||||
let result = page_of(app);
|
||||
if let Some(id) = result["printerPapers"][0]["id"].as_str() {
|
||||
return id.to_owned();
|
||||
}
|
||||
assert!(std::time::Instant::now() < deadline, "the mock queue returned a form");
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
};
|
||||
let first = wait_for_form(&mut app);
|
||||
app.run("ui.printPage", json!({"paper": first})).unwrap();
|
||||
app.run("ui.printSubmit", json!({"paper": first})).unwrap();
|
||||
assert!(String::from_utf8_lossy(&fake.last_pdf()).contains("/MediaBox[0 0 421 639]"));
|
||||
assert!(fake.last_options().contains(&("media".into(), "plain_vendor_421x639".into())));
|
||||
app.printing.poll(&egui::Context::default());
|
||||
app.poll_printing(&egui::Context::default());
|
||||
|
||||
let catalog = page_of(&mut app);
|
||||
assert_eq!(catalog["printerPapers"][1]["name"], "Borderless stock");
|
||||
let borderless = catalog["printerPapers"][1]["id"].as_str().unwrap();
|
||||
assert_ne!(borderless, first);
|
||||
app.run("ui.printSubmit", json!({"paper": borderless})).unwrap();
|
||||
assert!(String::from_utf8_lossy(&fake.last_pdf()).contains("/MediaBox[0 0 421 639]"));
|
||||
assert!(fake.last_options().contains(&("media".into(), "borderless_vendor_421x639".into())));
|
||||
app.printing.poll(&egui::Context::default());
|
||||
app.poll_printing(&egui::Context::default());
|
||||
|
||||
app.printing.printers.push(Printer::new("Another queue"));
|
||||
app.run("ui.printSettings", json!({"printer": "Another queue"})).unwrap();
|
||||
assert_eq!(page_of(&mut app)["paper"], "none");
|
||||
let second = wait_for_form(&mut app);
|
||||
assert_ne!(first, second);
|
||||
assert!(app.run("ui.printSubmit", json!({"paper": first})).is_err());
|
||||
assert_eq!(fake.jobs(), 2, "a form from the previous queue cannot submit");
|
||||
app.run("ui.printSubmit", json!({"paper": second})).unwrap();
|
||||
let sent = fake.sent.lock().unwrap();
|
||||
let (bytes, job) = sent.last().unwrap();
|
||||
assert!(String::from_utf8_lossy(bytes).contains("/MediaBox[0 0 425 650]"));
|
||||
assert!(matches!(job.scaling, print::Scaling::Exact));
|
||||
assert!(job.options.iter().all(|(name, _)| name != "media"), "geometry selects the Windows form");
|
||||
assert_eq!((app.session.doc.last_section.page_w, app.session.doc.last_section.page_h), paper);
|
||||
}
|
||||
|
||||
/// Native copies stay in the spooler; booklet pairing and padding happen once in its PDF.
|
||||
#[test]
|
||||
fn native_booklet_uses_landscape_sheets_without_multiplying_copies() {
|
||||
|
||||
@@ -12,7 +12,7 @@ pens, microphones (Dictate) and speakers (Read Aloud), and displays.
|
||||
|
||||
| Hardware | Word | WordCraft macOS | Windows | Linux / BSD | Web | Parity | Hours |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| Printers: native print dialog, printer choice, copies, duplex, page ranges, tray, scaling | ✅ (`WordPDE.plugin` print-dialog extension on Mac) | 🟡 Direct CUPS printing; printer, copies, collation, duplex, ranges, grayscale, scale to paper size, N-up and booklets; on every desktop the PDF sent to the printer leaves out link annotations, which the spooler can't fit to the paper; Save these pages as PDF keeps them (#4734) | 🟡 Direct spooler printing; printer, copies, collation, duplex, ranges, grayscale, scale to paper size, N-up and booklets; on every desktop the PDF sent to the printer leaves out link annotations, which the spooler can't fit to the paper; Save these pages as PDF keeps them (#4734) | 🟡 Direct spooler printing; printer, copies, collation, duplex, ranges, grayscale, scale to paper size, N-up and booklets; on every desktop the PDF sent to the printer leaves out link annotations, which the spooler can't fit to the paper; Save these pages as PDF keeps them (#4734) | ✅ browser print dialog (#209) | 35% | 5–8 |
|
||||
| Printers: native print dialog, printer choice, copies, duplex, page ranges, tray, scaling | ✅ (`WordPDE.plugin` print-dialog extension on Mac) | 🟡 Direct CUPS printing; printer, copies, collation, duplex, ranges, grayscale, scale to paper size, N-up and booklets; on every desktop the PDF sent to the printer leaves out link annotations, which the spooler can't fit to the paper; Save these pages as PDF keeps them (#4734) | 🟡 Direct spooler printing and per-job printer-driver properties (#7665); printer, copies, collation, duplex, ranges, grayscale, scale to paper size, N-up and booklets; on every desktop the PDF sent to the printer leaves out link annotations, which the spooler can't fit to the paper; Save these pages as PDF keeps them (#4734) | 🟡 Direct spooler printing; printer, copies, collation, duplex, ranges, grayscale, scale to paper size, N-up and booklets; on every desktop the PDF sent to the printer leaves out link annotations, which the spooler can't fit to the paper; Save these pages as PDF keeps them (#4734) | ✅ browser print dialog (#209) | 35% | 5–8 |
|
||||
| GPU rendering, HiDPI/Retina, pixel-aligned text | ✅ | ✅ wgpu + vello_cpu rasteriser, whole-pixel text (#110, #165) | ✅ DirectX 12 default (#50), OpenGL when DirectX 12 has no GPU driver (#316) or on 32-bit; startup crash on Intel UHD (#170) | ✅ (soft text on KDE at some zooms, #140) | ✅ | 80% | 3–5 (bugs) |
|
||||
| Pen / stylus: ink, pressure, eraser, ink to shape/math | ✅ (Draw tab, `InkRender.bundle`) | 🟡 ink, stroke eraser, Ink to Shape incl. one- and two-stroke arrows with open or closed heads (#307, #395); pressure and Ink to Math missing | 🟡 same | 🟡 same | 🟡 same | 50% | (Draw tab, 15–25) |
|
||||
| Multiple monitors, per-monitor DPI, remembered window position, a window that fits its screen | ✅ | ✅ (#38, #76, #1215) | ✅ (winit DPI fix pending, #155) | ✅ | — | 85% | 1 |
|
||||
|
||||
Reference in New Issue
Block a user