Skip to main content

plat/
print.rs

1// print -- printing, the OS-independent part: paper sizes, page layout, rows over white, the
2// job as a one-page PDF  [src/plat/print.s, src/img/pdfwrite.s; docs/modules/PRINT.md]
3//
4//   print(job) -> 0 printed / ERR_CANCEL / ERR_UNSUPPORTED / ERR_IO / ERR_NOMEM / ERR_DIMS
5//        the OS part: win_print.rs (PrintDlgExW + GDI), linux_print.rs (portal Print + PDF)
6//   page_init(paper, flags) -> PPage         the paper PAPER_* in pt (PJF_LANDSCAPE swaps
7//                                            width / height), no unprintable edge
8//   layout(job, page) -> Place               the image rectangle and the printable area on
9//                                            the page (pt, from the top-left)
10//   row_white(dst, src, n, mode)             n pixels (B, G, R, A) -> n * 3 bytes composited
11//                                            over white (PRW_* mode bits)
12//   print_pdf(job, page) -> PDF bytes / ERR_*  the job laid out on page as a one-page PDF
13//                                            (job.page_w / page_h set)
14//   print_dpi(unit, dpu) -> f64              pixels per inch from a resolution in unit (0 none
15//                                            -> 96, 1 inch, 2 cm)
16//   pdf_write_image(src, opt) -> PDF bytes / ERR_*   one image on one PDF page (pdfwrite.s)
17//   set_print_deflate(f)                     the zlib compressor of the PDF streams
18//   PrintDoc (E9): a job of several pages
19//        PrintDoc::begin(&job, pages) -> Result<PrintDoc, ERR_*>   the system's print dialog
20//            (printer, paper, orientation, copies; a page range when pages > 0) where there
21//            is one; job gives the title, paper, PJF_LANDSCAPE, margin, scale, dpi (its src
22//            is not used)
23//        d.page() -> PPage, d.copies(), d.wants(n)   the chosen page in pt, copies, whether
24//            page n (from 1) is in the chosen range
25//        d.add_image(&src) -> 0 / ERR_*   one page: the image laid out as layout() places it
26//        d.pdf_native(), d.add_pdf(bytes)  the platform prints a PDF as it is (Linux)
27//        d.end() -> 0 printed / ERR_*, d.abort()
28//        Windows: PrintDlgExW + GDI, a StartPage per page (win_print.rs); Linux: the
29//        portal's dialog, the pages as one PDF of several pages for Print (linux_print.rs);
30//        test variant everywhere: jfgui_PRINT_TO=FILE (Windows: through the printer
31//        jfgui_PRINT_PRINTER; elsewhere our PDF into FILE); else ERR_UNSUPPORTED
32//
33// Deviation (plat-shared): plat must not depend on the image crates, so pdfwrite.s is ported
34// here and the one thing it took from img -- zlib_deflate -- comes through a hook.  An app
35// sets it to img_core::deflate::zlib_deflate (then the PDF is byte-identical to the
36// assembly's); without a hook the streams are zlib "stored" blocks (a valid, uncompressed
37// PDF).  The source is a PrintSrc (rows of B, G, R, A bytes; the gfx::Surface fields)
38// instead of a SURFACE pointer.
39
40use alloc::string::String;
41use alloc::vec::Vec;
42use core::fmt::Write;
43use core::sync::atomic::{AtomicUsize, Ordering};
44
45use rt::fx::{cvtd64, maxsd, minsd};
46
47// ---- results (the ERR_* of jfgui.inc / plugin.inc that plat returns)
48pub const ERR_NOMEM: i32 = -8;
49pub const ERR_UNSUPPORTED: i32 = -9;
50pub const ERR_DIMS: i32 = -12;
51pub const ERR_IO: i32 = -13;
52pub const ERR_CANCEL: i32 = -14;
53pub const ERR_LIMIT: i32 = -15;
54
55// ---- the source formats (FMT_* of jfgui.inc)
56pub const PRINT_XRGB: u8 = 0; // alpha byte ignored
57pub const PRINT_PARGB: u8 = 1; // premultiplied
58pub const PRINT_ARGB: u8 = 3; // straight
59
60// ---- PrintJob::flags
61pub const PJF_LANDSCAPE: u32 = 1; // Querformat
62pub const PJF_CENTER: u32 = 2; // centre in the printable area (else its top-left corner)
63pub const PJF_SMASK: u32 = 4; // PDF only: straight colours + alpha as /SMask (no white)
64// ---- PrintJob::scale
65pub const PJS_FIT: u32 = 0; // as large as the printable area allows (aspect kept)
66pub const PJS_DPI: u32 = 1; // original size: pixels / DPI inches
67pub const PJS_PERCENT: u32 = 2; // PrintJob::percent of the original size
68// ---- paper
69pub const PAPER_A4: u32 = 0;
70pub const PAPER_LETTER: u32 = 1;
71pub const PAPER_A5: u32 = 2;
72pub const PAPER_LEGAL: u32 = 3;
73pub const PAPER_A3: u32 = 4;
74pub const PAPER_N: u32 = 5;
75// ---- row_white modes
76pub const PRW_BGR: u32 = 1; // B, G, R byte order (GDI DIB) instead of R, G, B (PDF)
77pub const PRW_PREMUL: u32 = 2; // source is premultiplied
78pub const PRW_COPY: u32 = 4; // straight colours unchanged (no white; PDF with SMask)
79pub const PRW_OPAQUE: u32 = 8; // alpha ignored (XRGB)
80
81const TITLE_MAX: usize = 256; // code points of /Title
82const PDF_LEVEL_DEF: i32 = 6;
83
84/// the pixels of a print job: rows of 32-bit B, G, R, A (the fields of gfx::Surface)
85#[derive(Clone, Copy)]
86pub struct PrintSrc<'a> {
87    pub px: &'a [u8],
88    pub w: i32,
89    pub h: i32,
90    pub stride: i32,
91    pub fmt: u8, // PRINT_ARGB (straight), PRINT_PARGB or PRINT_XRGB
92}
93
94/// one print job (PRINTJOB)
95#[derive(Clone, Copy)]
96pub struct PrintJob<'a> {
97    pub src: Option<PrintSrc<'a>>,
98    pub title: &'a str, // document name (spooler job, PDF /Title); "" = "Bild" (no PDF /Title)
99    pub dpi_x: f64,     // image pixels per inch (<= 0: 96)
100    pub dpi_y: f64,     // (<= 0: dpi_x)
101    pub flags: u32,     // PJF_*
102    pub scale: u32,     // PJS_*
103    pub percent: u32,   // PJS_PERCENT: 1..10000 % of the size by DPI
104    pub margin: u32,    // on every side, 1/100 mm (the printer's unprintable edge wins when larger)
105    pub paper: u32,     // PAPER_* suggested to the dialog / used without one
106    // out
107    pub copies: u32,  // copies (informative, 0 = unknown)
108    pub page_w: f64,  // page size in pt the job was laid out on
109    pub page_h: f64,
110}
111
112impl<'a> PrintJob<'a> {
113    pub fn new(src: Option<PrintSrc<'a>>, title: &'a str) -> PrintJob<'a> {
114        PrintJob {
115            src,
116            title,
117            dpi_x: 96.0,
118            dpi_y: 96.0,
119            flags: 0,
120            scale: PJS_FIT,
121            percent: 100,
122            margin: 0,
123            paper: PAPER_A4,
124            copies: 0,
125            page_w: 0.0,
126            page_h: 0.0,
127        }
128    }
129}
130
131/// the page (PPAGE, pt = 1/72 inch)
132#[derive(Clone, Copy, Default, Debug)]
133pub struct PPage {
134    pub w: f64, // page size (orientation applied)
135    pub h: f64,
136    pub l: f64, // unprintable edge left / top / right / bottom
137    pub t: f64,
138    pub r: f64,
139    pub b: f64,
140    pub token: u32, // print system cookie (portal token)
141    pub flags: u32, // PJF_LANDSCAPE as chosen in the dialog
142}
143
144/// where the image goes (PLACE, pt from the page's top-left)
145#[derive(Clone, Copy, Default, Debug)]
146pub struct Place {
147    pub x: f64, // image rectangle
148    pub y: f64,
149    pub w: f64,
150    pub h: f64,
151    pub ax: f64, // printable area (margins applied); the image is clipped to it
152    pub ay: f64,
153    pub aw: f64,
154    pub ah: f64,
155}
156
157/// PDFOPT of pdf_write_image
158#[derive(Clone, Copy, Default)]
159pub struct PdfOpt<'a> {
160    pub page_w: f64, // MediaBox in pt
161    pub page_h: f64,
162    pub x: f64, // image rectangle, pt from the page's top-left
163    pub y: f64,
164    pub w: f64,
165    pub h: f64,
166    pub cx: f64, // clip rectangle (cw <= 0: no clip)
167    pub cy: f64,
168    pub cw: f64,
169    pub ch: f64,
170    pub title: &'a str, // /Title ("" = none)
171    pub flags: u32,     // PJF_SMASK
172    pub level: i32,     // deflate level (<= 0: 6)
173}
174
175// PAPER_* portrait width, height in pt (mm * 72 / 25.4)
176static PAPER_PT: [[f64; 2]; 5] = [
177    [595.2755905511812, 841.8897637795276], // A4 210 x 297 mm
178    [612.0, 792.0],                         // Letter 8.5 x 11 in
179    [419.5275590551181, 595.2755905511812], // A5 148 x 210 mm
180    [612.0, 1008.0],                        // Legal 8.5 x 14 in
181    [841.8897637795276, 1190.551181102362], // A3 297 x 420 mm
182];
183const MM100_PT: f64 = 0.028346456692913385; // 1/100 mm in pt (72 / 2540)
184
185/// the paper in pt, PJF_LANDSCAPE swaps; no unprintable edge  [print_page_init]
186pub fn page_init(paper: u32, flags: u32) -> PPage {
187    let p = PAPER_PT[if paper >= PAPER_N { 0 } else { paper as usize }];
188    let (w, h) = if flags & PJF_LANDSCAPE != 0 { (p[1], p[0]) } else { (p[0], p[1]) };
189    PPage { w, h, l: 0.0, t: 0.0, r: 0.0, b: 0.0, token: 0, flags: flags & PJF_LANDSCAPE }
190}
191
192/// pixels per inch from a document resolution: unit 0 none -> 96, 1 inch, 2 cm (* 2.54);
193/// dpu <= 0 -> 96  [print_dpi]
194pub fn print_dpi(unit: u32, dpu: f64) -> f64 {
195    if unit < 1 || !(dpu > 0.0) {
196        return 96.0;
197    }
198    if unit == 2 { dpu * 2.54 } else { dpu }
199}
200
201/// the image rectangle and the printable area on the page  [print_layout]
202pub fn layout(job: &PrintJob, page: &PPage) -> Place {
203    let dx = if job.dpi_x > 0.0 { job.dpi_x } else { 96.0 };
204    let dy = if job.dpi_y > 0.0 { job.dpi_y } else { dx };
205    let (pw, ph) = job.src.map_or((1, 1), |s| (s.w, s.h));
206    let mut iw = pw as f64 * 72.0 / dx; // image size in pt
207    let mut ih = ph as f64 * 72.0 / dy;
208    let m = job.margin as f64 * MM100_PT;
209    let mut pl = Place::default();
210    pl.ax = maxsd(page.l, m);
211    pl.aw = maxsd(page.w - maxsd(page.r, m) - pl.ax, 1.0);
212    pl.ay = maxsd(page.t, m);
213    pl.ah = maxsd(page.h - maxsd(page.b, m) - pl.ay, 1.0);
214    if job.scale != PJS_DPI {
215        let s = if job.scale == PJS_PERCENT {
216            job.percent.clamp(1, 10000) as f64 / 100.0
217        } else {
218            minsd(pl.aw / iw, pl.ah / ih)
219        };
220        iw *= s;
221        ih *= s;
222    }
223    pl.w = iw;
224    pl.h = ih;
225    pl.x = pl.ax;
226    pl.y = pl.ay;
227    if job.flags & PJF_CENTER != 0 {
228        pl.x += (pl.aw - iw) * 0.5;
229        pl.y += (pl.ah - ih) * 0.5;
230    }
231    pl
232}
233
234/// n pixels of src (B, G, R, A) -> n * 3 bytes of dst (R, G, B; PRW_BGR: B, G, R).  Straight:
235/// c * a / 255 + 255 - a (rounded); PRW_PREMUL: c + 255 - a; PRW_COPY / PRW_OPAQUE: c
236/// [print_row_white]
237pub fn row_white(dst: &mut [u8], src: &[u8], n: usize, mode: u32) {
238    for (d, s) in dst.chunks_exact_mut(3).zip(src.chunks_exact(4)).take(n) {
239        let (b, g, r) = (s[0] as u32, s[1] as u32, s[2] as u32);
240        let a = s[3] as u32;
241        let (b, g, r) = if mode & (PRW_OPAQUE | PRW_COPY) != 0 {
242            (b, g, r)
243        } else if mode & PRW_PREMUL != 0 {
244            let k = 255 - a;
245            ((b + k).min(255), (g + k).min(255), (r + k).min(255))
246        } else {
247            let w = (255 - a) * 255 + 128;
248            let st = |c: u32| {
249                let t = c * a + w;
250                (t + (t >> 8)) >> 8
251            };
252            (st(b), st(g), st(r))
253        };
254        if mode & PRW_BGR != 0 {
255            d[0] = b as u8;
256            d[1] = g as u8;
257            d[2] = r as u8;
258        } else {
259            d[0] = r as u8;
260            d[1] = g as u8;
261            d[2] = b as u8;
262        }
263    }
264}
265
266/// the job laid out on page as a one-page PDF (job.page_w / page_h set)  [print_pdf]
267pub fn print_pdf(job: &mut PrintJob, page: &PPage) -> Result<Vec<u8>, i32> {
268    let src = job.src.ok_or(ERR_DIMS)?;
269    let pl = layout(job, page);
270    job.page_w = page.w;
271    job.page_h = page.h;
272    let opt = PdfOpt {
273        page_w: page.w,
274        page_h: page.h,
275        x: pl.x,
276        y: pl.y,
277        w: pl.w,
278        h: pl.h,
279        cx: pl.ax, // clip = printable area
280        cy: pl.ay,
281        cw: pl.aw,
282        ch: pl.ah,
283        title: job.title,
284        flags: job.flags & PJF_SMASK,
285        level: 0,
286    };
287    pdf_write_image(&src, &opt)
288}
289
290// ---------------------------------------------------------------- the zlib hook
291
292/// a zlib compressor: (data, level) -> zlib stream (img_core::deflate::zlib_deflate)
293pub type DeflateFn = fn(&[u8], i32) -> Vec<u8>;
294
295static DEFLATE: AtomicUsize = AtomicUsize::new(0);
296
297/// the compressor of the PDF streams (None: zlib stored blocks, no compression)
298pub fn set_print_deflate(f: Option<DeflateFn>) {
299    DEFLATE.store(f.map_or(0, |f| f as usize), Ordering::SeqCst);
300}
301
302fn deflate(data: &[u8], level: i32) -> Vec<u8> {
303    let p = DEFLATE.load(Ordering::SeqCst);
304    if p != 0 {
305        // SAFETY: only set_print_deflate stores here, always a DeflateFn.
306        let f: DeflateFn = unsafe { core::mem::transmute::<usize, DeflateFn>(p) };
307        return f(data, level);
308    }
309    // zlib with stored blocks: header 78 01, blocks of at most 65535 bytes, Adler-32
310    let mut out = Vec::with_capacity(data.len() + data.len() / 65535 * 5 + 16);
311    out.extend_from_slice(&[0x78, 0x01]);
312    let mut chunks = data.chunks(65535).peekable();
313    if chunks.peek().is_none() {
314        out.extend_from_slice(&[1, 0, 0, 0xFF, 0xFF]);
315    }
316    while let Some(c) = chunks.next() {
317        out.push(chunks.peek().is_none() as u8);
318        out.extend_from_slice(&(c.len() as u16).to_le_bytes());
319        out.extend_from_slice(&(!(c.len() as u16)).to_le_bytes());
320        out.extend_from_slice(c);
321    }
322    let (mut a, mut b) = (1u32, 0u32);
323    for &x in data {
324        a = (a + x as u32) % 65521;
325        b = (b + a) % 65521;
326    }
327    out.extend_from_slice(&(b << 16 | a).to_be_bytes());
328    out
329}
330
331// ---------------------------------------------------------------- the PDF writer  [pdfwrite.s]
332
333// " a b" with 3 decimals each: millipoints rounded (cvtsd2si), "-" for negative  [pw_num]
334fn pw_num(o: &mut String, v: f64) {
335    let m = cvtd64(v * 1000.0);
336    if m < 0 {
337        o.push('-');
338    }
339    let u = m.unsigned_abs();
340    let _ = write!(o, "{}.{:03}", u / 1000, u % 1000);
341}
342
343fn pw_nums(o: &mut String, a: f64, b: f64) {
344    o.push(' ');
345    pw_num(o, a);
346    o.push(' ');
347    pw_num(o, b);
348}
349
350/// " /Title <FEFF....>": UTF-16BE hex, at most TITLE_MAX code points  [pw_title]
351fn pw_title(o: &mut String, s: &str) {
352    o.push_str(" /Title <FEFF");
353    for c in s.chars().take_while(|&c| c != '\0').take(TITLE_MAX) {
354        let mut buf = [0u16; 2];
355        for u in c.encode_utf16(&mut buf) {
356            let _ = write!(o, "{:04X}", u);
357        }
358    }
359    o.push('>');
360}
361
362// the image streams of a PDF page: RGB (deflated; over white unless PJF_SMASK keeps straight
363// colours) and the alpha plane of the soft mask (PJF_SMASK and a straight source) -- the
364// checks of pdf_write_image
365fn pdf_image_data(src: &PrintSrc, flags: u32, level: i32) -> Result<(Vec<u8>, Option<Vec<u8>>), i32> {
366    let (w, h) = (src.w, src.h);
367    if w <= 0 || h <= 0 || src.px.is_empty() {
368        return Err(ERR_DIMS);
369    }
370    let mut mode = match src.fmt {
371        PRINT_ARGB => 0,
372        PRINT_PARGB => PRW_PREMUL,
373        PRINT_XRGB => PRW_OPAQUE,
374        _ => return Err(ERR_UNSUPPORTED),
375    };
376    if src.fmt == PRINT_ARGB && flags & PJF_SMASK != 0 {
377        mode = PRW_COPY;
378    }
379    let level = if level <= 0 { PDF_LEVEL_DEF } else { level };
380    let (wu, hu) = (w as usize, h as usize);
381    // w and h size the buffers below: the rows must lie inside px
382    if src.stride < w.saturating_mul(4) {
383        return Err(ERR_DIMS);
384    }
385    let covered = wu.checked_mul(4).and_then(|rw| (hu - 1).checked_mul(src.stride as usize)?.checked_add(rw));
386    if covered.is_none_or(|n| n > src.px.len()) {
387        return Err(ERR_DIMS);
388    }
389    let stride = src.stride as isize;
390    let row_of = |y: usize| -> &[u8] {
391        let o = (y as isize * stride) as usize;
392        src.px.get(o..o + wu * 4).unwrap_or(&[])
393    };
394    // RGB rows
395    let rb = wu * 3;
396    let mut raw = alloc::vec![0u8; rb * hu];
397    for y in 0..hu {
398        row_white(&mut raw[y * rb..(y + 1) * rb], row_of(y), wu, mode);
399    }
400    let rgb = deflate(&raw, level);
401    drop(raw);
402    // alpha plane for the soft mask
403    let alpha = if mode == PRW_COPY {
404        let mut a = Vec::with_capacity(wu * hu);
405        for y in 0..hu {
406            let r = row_of(y);
407            for x in 0..wu {
408                a.push(r.get(x * 4 + 3).copied().unwrap_or(0));
409            }
410        }
411        Some(deflate(&a, level))
412    } else {
413        None
414    };
415    Ok((rgb, alpha))
416}
417
418// the content stream of a page: the clip (cw > 0) and the image Im1 at its rectangle
419fn pdf_content(opt: &PdfOpt) -> String {
420    let mut c = String::from("q\n");
421    if opt.cw > 0.0 {
422        pw_nums(&mut c, opt.cx, opt.page_h - opt.cy - opt.ch); // bottom of the clip in PDF space
423        pw_nums(&mut c, opt.cw, opt.ch);
424        c.push_str(" re W n\n");
425    }
426    pw_nums(&mut c, opt.w, 0.0);
427    pw_nums(&mut c, 0.0, opt.h);
428    pw_nums(&mut c, opt.x, opt.page_h - opt.y - opt.h);
429    c.push_str(" cm\n/Im1 Do\nQ\n");
430    c
431}
432
433// "N 0 obj\n<< /Type /XObject /Subtype /Image ..>>\nstream\n" + data + "\nendstream\nendobj\n"
434fn pdf_image_obj(f: &mut Vec<u8>, n: usize, w: i32, h: i32, rgb: &[u8], smask: Option<usize>) {
435    let mut s = String::new();
436    let _ = write!(s, "{n} 0 obj\n<< /Type /XObject /Subtype /Image /Width {w} /Height {h}");
437    s.push_str(" /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode");
438    if let Some(m) = smask {
439        let _ = write!(s, " /SMask {m} 0 R");
440    }
441    let _ = write!(s, " /Length {} >>\nstream\n", rgb.len());
442    f.extend_from_slice(s.as_bytes());
443    f.extend_from_slice(rgb);
444    f.extend_from_slice(b"\nendstream\nendobj\n");
445}
446
447// the soft mask object N (alpha, DeviceGray)
448fn pdf_mask_obj(f: &mut Vec<u8>, n: usize, w: i32, h: i32, a: &[u8]) {
449    let mut s = String::new();
450    let _ = write!(s, "{n} 0 obj\n<< /Type /XObject /Subtype /Image /Width {w} /Height {h}");
451    let _ = write!(s, " /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", a.len());
452    f.extend_from_slice(s.as_bytes());
453    f.extend_from_slice(a);
454    f.extend_from_slice(b"\nendstream\nendobj\n");
455}
456
457/// one image on one PDF 1.4 page: objects 1 Catalog, 2 Pages, 3 Page, 4 Contents, 5 Image
458/// (/DeviceRGB 8 bit /FlateDecode, composited over white -- with PJF_SMASK and a straight
459/// source: straight colours), 6 Info, [7 /SMask alpha]; classic xref  [pdf_write_image]
460pub fn pdf_write_image(src: &PrintSrc, opt: &PdfOpt) -> Result<Vec<u8>, i32> {
461    let (w, h) = (src.w, src.h);
462    let (rgb, alpha) = pdf_image_data(src, opt.flags, opt.level)?;
463    let nobj = if alpha.is_some() { 7 } else { 6 };
464    let mut off = [0usize; 8];
465    let mut f: Vec<u8> = Vec::with_capacity(rgb.len() + alpha.as_ref().map_or(0, |a| a.len()) + 4096);
466    let mut s = String::new();
467    f.extend_from_slice(b"%PDF-1.4\n%\xE2\xE3\xCF\xD3\n");
468    off[1] = f.len();
469    f.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
470    off[2] = f.len();
471    f.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
472    // 3 Page
473    off[3] = f.len();
474    s.push_str("3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0");
475    pw_nums(&mut s, opt.page_w, opt.page_h);
476    s.push_str("] /Resources << /XObject << /Im1 5 0 R >> /ProcSet [/PDF /ImageC] >> /Contents 4 0 R >>\nendobj\n");
477    f.extend_from_slice(s.as_bytes());
478    // 4 Contents
479    let c = pdf_content(opt);
480    off[4] = f.len();
481    s.clear();
482    let _ = write!(s, "4 0 obj\n<< /Length {} >>\nstream\n", c.len());
483    f.extend_from_slice(s.as_bytes());
484    f.extend_from_slice(c.as_bytes());
485    f.extend_from_slice(b"\nendstream\nendobj\n");
486    // 5 Image
487    off[5] = f.len();
488    pdf_image_obj(&mut f, 5, w, h, &rgb, (nobj == 7).then_some(7));
489    // 6 Info
490    off[6] = f.len();
491    s.clear();
492    s.push_str("6 0 obj\n<< /Producer (jfguiLib)");
493    if !opt.title.is_empty() && !opt.title.starts_with('\0') {
494        pw_title(&mut s, opt.title);
495    }
496    s.push_str(" >>\nendobj\n");
497    f.extend_from_slice(s.as_bytes());
498    // 7 SMask
499    if let Some(a) = &alpha {
500        off[7] = f.len();
501        pdf_mask_obj(&mut f, 7, w, h, a);
502    }
503    // xref, trailer
504    let startxref = f.len();
505    s.clear();
506    let _ = write!(s, "xref\n0 {}\n0000000000 65535 f \n", nobj + 1);
507    for o in &off[1..=nobj] {
508        let _ = write!(s, "{o:010} 00000 n \n");
509    }
510    let _ = write!(s, "trailer\n<< /Size {} /Root 1 0 R /Info 6 0 R >>\nstartxref\n{startxref}\n", nobj + 1);
511    s.push_str("%%EOF\n");
512    f.extend_from_slice(s.as_bytes());
513    Ok(f)
514}
515
516// ---------------------------------------------------------------- jobs of several pages (E9)
517
518// a PDF of several pages built page by page: 1 Catalog, 2 Pages, 3 Info, then per page Page,
519// Contents, Image [, SMask]; the image streams are kept deflated until finish
520#[derive(Default)]
521pub(crate) struct PdfPages {
522    // the objects from 4 on, each "N 0 obj .. endobj\n"
523    objs: Vec<Vec<u8>>,
524    pages: Vec<usize>,
525}
526
527impl PdfPages {
528    // one page of page_w x page_h pt with the image placed as opt says
529    fn add(&mut self, src: &PrintSrc, opt: &PdfOpt) -> Result<(), i32> {
530        let (rgb, alpha) = pdf_image_data(src, opt.flags, opt.level)?;
531        let n = 4 + self.objs.len(); // Page n, Contents n+1, Image n+2, SMask n+3
532        let mut s = String::new();
533        let _ = write!(s, "{n} 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0");
534        pw_nums(&mut s, opt.page_w, opt.page_h);
535        let _ = write!(s, "] /Resources << /XObject << /Im1 {} 0 R >> /ProcSet [/PDF /ImageC] >> /Contents {} 0 R >>\nendobj\n", n + 2, n + 1);
536        self.objs.push(s.into_bytes());
537        let c = pdf_content(opt);
538        let mut o = Vec::with_capacity(c.len() + 64);
539        let mut s = String::new();
540        let _ = write!(s, "{} 0 obj\n<< /Length {} >>\nstream\n", n + 1, c.len());
541        o.extend_from_slice(s.as_bytes());
542        o.extend_from_slice(c.as_bytes());
543        o.extend_from_slice(b"\nendstream\nendobj\n");
544        self.objs.push(o);
545        let mut o = Vec::with_capacity(rgb.len() + 200);
546        pdf_image_obj(&mut o, n + 2, src.w, src.h, &rgb, alpha.as_ref().map(|_| n + 3));
547        self.objs.push(o);
548        if let Some(a) = &alpha {
549            let mut o = Vec::with_capacity(a.len() + 200);
550            pdf_mask_obj(&mut o, n + 3, src.w, src.h, a);
551            self.objs.push(o);
552        }
553        self.pages.push(n);
554        Ok(())
555    }
556
557    // the whole file
558    fn finish(&self, title: &str) -> Vec<u8> {
559        let total: usize = self.objs.iter().map(|o| o.len()).sum();
560        let mut f: Vec<u8> = Vec::with_capacity(total + 1024 + self.pages.len() * 16);
561        let mut off = Vec::with_capacity(self.objs.len() + 4);
562        f.extend_from_slice(b"%PDF-1.4\n%\xE2\xE3\xCF\xD3\n");
563        off.push(f.len());
564        f.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
565        off.push(f.len());
566        let mut s = String::from("2 0 obj\n<< /Type /Pages /Kids [");
567        for (k, p) in self.pages.iter().enumerate() {
568            let _ = write!(s, "{}{p} 0 R", if k > 0 { " " } else { "" });
569        }
570        let _ = write!(s, "] /Count {} >>\nendobj\n", self.pages.len());
571        f.extend_from_slice(s.as_bytes());
572        off.push(f.len());
573        s.clear();
574        s.push_str("3 0 obj\n<< /Producer (jfguiLib)");
575        if !title.is_empty() && !title.starts_with('\0') {
576            pw_title(&mut s, title);
577        }
578        s.push_str(" >>\nendobj\n");
579        f.extend_from_slice(s.as_bytes());
580        for o in &self.objs {
581            off.push(f.len());
582            f.extend_from_slice(o);
583        }
584        let startxref = f.len();
585        s.clear();
586        let _ = write!(s, "xref\n0 {}\n0000000000 65535 f \n", off.len() + 1);
587        for o in &off {
588            let _ = write!(s, "{o:010} 00000 n \n");
589        }
590        let _ = write!(s, "trailer\n<< /Size {} /Root 1 0 R /Info 3 0 R >>\nstartxref\n{startxref}\n%%EOF\n", off.len() + 1);
591        f.extend_from_slice(s.as_bytes());
592        f
593    }
594}
595
596// the platform's part of a PrintDoc (win_print.rs: the printer DC and its geometry; Linux /
597// tests: the PDF and where it goes)
598#[derive(Default)]
599pub(crate) struct DocSys {
600    #[cfg_attr(not(windows), allow(dead_code))]
601    pub hdc: isize,
602    #[cfg_attr(not(windows), allow(dead_code))]
603    pub dpi: [f64; 2],
604    #[cfg_attr(not(windows), allow(dead_code))]
605    pub off: [i32; 2],
606    #[cfg_attr(not(windows), allow(dead_code))]
607    pub started: bool,
608    // the PDF being built (platforms that print PDF documents, the test variant)
609    pub pdf: Option<PdfPages>,
610    // add_pdf's document
611    pub raw: Option<Vec<u8>>,
612    // the test variant's file (jfgui_PRINT_TO)
613    pub to: Option<String>,
614    // PrintDlgExW's page ranges (from, to; empty: every page)
615    pub ranges: Vec<(u32, u32)>,
616}
617
618/// a print job of several pages (see the file header; E9)
619pub struct PrintDoc {
620    pub(crate) title: String,
621    pub(crate) dpi_x: f64,
622    pub(crate) dpi_y: f64,
623    pub(crate) flags: u32,
624    pub(crate) scale: u32,
625    pub(crate) percent: u32,
626    pub(crate) margin: u32,
627    pub(crate) paper: u32,
628    #[cfg_attr(not(windows), allow(dead_code))] // (the dialog's page range: Windows)
629    pub(crate) pages: u32,
630    pub(crate) page: PPage,
631    pub(crate) copies: u32,
632    pub(crate) added: u32,
633    pub(crate) sys: DocSys,
634}
635
636impl PrintDoc {
637    /// start a job: the system's print dialog where the platform has one (printer, paper,
638    /// orientation, copies; with pages > 0 a page range of 1..=pages), never one in the test
639    /// variant (jfgui_PRINT_TO).  job: the title (spooler, PDF /Title; "" = "Dokument"), paper,
640    /// PJF_LANDSCAPE / PJF_CENTER / PJF_SMASK, margin, scale, percent, dpi -- its src is not
641    /// used.  Err: ERR_CANCEL (the dialog was cancelled), ERR_UNSUPPORTED (no printing here,
642    /// no window, the manifest forbids it), ERR_IO
643    pub fn begin(job: &PrintJob, pages: u32) -> Result<PrintDoc, i32> {
644        if !crate::policy::print_allowed() {
645            return Err(ERR_UNSUPPORTED);
646        }
647        let title = if job.title.is_empty() || job.title.starts_with('\0') { "Dokument" } else { job.title };
648        let mut d = PrintDoc {
649            title: String::from(title),
650            dpi_x: job.dpi_x,
651            dpi_y: job.dpi_y,
652            flags: job.flags,
653            scale: job.scale,
654            percent: job.percent,
655            margin: job.margin,
656            paper: job.paper,
657            pages,
658            page: page_init(job.paper, job.flags),
659            copies: 0,
660            added: 0,
661            sys: DocSys::default(),
662        };
663        let r = crate::doc_begin(&mut d);
664        if r != 0 {
665            return Err(r);
666        }
667        Ok(d)
668    }
669
670    /// the page the job prints on (pt; the printer's unprintable edges; the orientation the
671    /// dialog chose in flags): lay the pages out for it
672    pub fn page(&self) -> PPage {
673        self.page
674    }
675
676    /// the copies the dialog chose (informative: the printer makes them; 1 in the test variant)
677    pub fn copies(&self) -> u32 {
678        self.copies
679    }
680
681    /// page n (from 1) is in the range the dialog chose (always without a range)
682    pub fn wants(&self, n: u32) -> bool {
683        self.sys.ranges.is_empty() || self.sys.ranges.iter().any(|&(a, b)| n >= a && n <= b)
684    }
685
686    /// the pages added so far
687    pub fn added(&self) -> u32 {
688        self.added
689    }
690
691    /// the platform prints a PDF document as it is (add_pdf): Linux's portal and the test
692    /// variant there; Windows and the others: images only
693    pub fn pdf_native(&self) -> bool {
694        self.sys.pdf.is_some()
695    }
696
697    // the job's settings with src for layout()
698    fn job_of<'a>(&'a self, src: &PrintSrc<'a>) -> PrintJob<'a> {
699        PrintJob {
700            src: Some(*src),
701            title: &self.title,
702            dpi_x: self.dpi_x,
703            dpi_y: self.dpi_y,
704            flags: self.flags,
705            scale: self.scale,
706            percent: self.percent,
707            margin: self.margin,
708            paper: self.paper,
709            copies: 0,
710            page_w: self.page.w,
711            page_h: self.page.h,
712        }
713    }
714
715    /// one page: the image laid out on the page as layout() places it (the job's scale, dpi,
716    /// margin, PJF_CENTER; clipped to the printable area) -> 0 / ERR_DIMS / ERR_UNSUPPORTED (a
717    /// format or after add_pdf) / ERR_IO / ERR_NOMEM
718    pub fn add_image(&mut self, src: &PrintSrc) -> i32 {
719        if src.w <= 0 || src.h <= 0 || src.px.is_empty() {
720            return ERR_DIMS;
721        }
722        if self.sys.raw.is_some() {
723            return ERR_UNSUPPORTED;
724        }
725        let pl = layout(&self.job_of(src), &self.page);
726        let r = if let Some(pdf) = self.sys.pdf.as_mut() {
727            let opt = PdfOpt {
728                page_w: self.page.w,
729                page_h: self.page.h,
730                x: pl.x,
731                y: pl.y,
732                w: pl.w,
733                h: pl.h,
734                cx: pl.ax,
735                cy: pl.ay,
736                cw: pl.aw,
737                ch: pl.ah,
738                title: "",
739                flags: self.flags & PJF_SMASK,
740                level: 0,
741            };
742            pdf.add(src, &opt).err().unwrap_or(0)
743        } else {
744            crate::doc_image(self, src, &pl)
745        };
746        if r == 0 {
747            self.added += 1;
748        }
749        r
750    }
751
752    /// the whole job as a PDF of the app's own, printed as it is (only where pdf_native(),
753    /// before any add_image) -> 0 / ERR_UNSUPPORTED
754    pub fn add_pdf(&mut self, pdf: &[u8]) -> i32 {
755        if !self.pdf_native() || self.added > 0 || self.sys.raw.is_some() || !pdf.starts_with(b"%PDF-") {
756            return ERR_UNSUPPORTED;
757        }
758        self.sys.raw = Some(Vec::from(pdf));
759        self.added = 1;
760        0
761    }
762
763    /// finish: the job goes to the printer -> 0 printed / ERR_CANCEL (the portal's job was
764    /// cancelled) / ERR_DIMS (no page) / ERR_IO
765    pub fn end(mut self) -> i32 {
766        if self.added == 0 {
767            crate::doc_abort(&mut self);
768            return ERR_DIMS;
769        }
770        crate::doc_end(&mut self)
771    }
772
773    /// drop the job (nothing is printed)
774    pub fn abort(mut self) {
775        crate::doc_abort(&mut self);
776    }
777
778    // (platforms) the PDF of the pages or add_pdf's document
779    pub(crate) fn pdf_bytes(&self) -> Option<Vec<u8>> {
780        if let Some(r) = &self.sys.raw {
781            return Some(r.clone());
782        }
783        self.sys.pdf.as_ref().map(|p| p.finish(&self.title))
784    }
785}
786
787// (platforms without a print system of their own) begin: the test variant writes our PDF
788// into jfgui_PRINT_TO, else ERR_UNSUPPORTED
789#[allow(dead_code)]
790pub(crate) fn doc_begin_pdf_only(d: &mut PrintDoc) -> i32 {
791    match crate::env("jfgui_PRINT_TO").filter(|v| !v.is_empty()) {
792        Some(to) => {
793            d.sys.to = Some(to);
794            d.sys.pdf = Some(PdfPages::default());
795            d.copies = 1;
796            0
797        }
798        None => ERR_UNSUPPORTED,
799    }
800}
801
802// (platforms) end of a PDF job of the test variant: the PDF into its file
803#[allow(dead_code)]
804pub(crate) fn doc_end_pdf_file(d: &mut PrintDoc) -> i32 {
805    let (Some(to), Some(pdf)) = (d.sys.to.clone(), d.pdf_bytes()) else { return ERR_UNSUPPORTED };
806    if crate::write_file_raw(&to, &pdf) { 0 } else { ERR_IO }
807}