exprim 0.4.1

A concurrent, memory-bounded PDF reader and renderer: parse, extract text, and rasterize pages on an immutable document snapshot
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! The headless backend: writes sheets to disk and records the job it was
//! given. It is the CI backend and how every layout test asserts without a
//! printer attached.

use std::path::{Path, PathBuf};
use std::sync::Mutex;

use super::{
    DeviceCapabilities, JobId, JobStatus, PrinterId, PrinterInfo, SpoolJob, SpoolPayload, Spooler,
};
use crate::print::compose::SheetRaster;
use crate::print::paper::Margins;
use crate::print::{ComposeOptions, PrintError, PrintOptions};

/// The synthetic queue name the file backend reports.
pub const FILE_PRINTER: &str = "file";

/// What a `FileSpooler` recorded about one submission.
#[derive(Debug, Clone, PartialEq)]
pub struct RecordedJob {
    /// The id the backend returned for the job.
    pub id: JobId,
    /// The queue the job named.
    pub printer: PrinterId,
    /// The job title.
    pub title: String,
    /// Files written for this job, in sheet order.
    pub files: Vec<PathBuf>,
    /// True when the job took the pass-through path.
    pub pass_through: bool,
    /// The options the caller handed the backend, so a test can assert what
    /// actually reached the spooler.
    pub options: PrintOptions,
    /// The composition settings used, or `None` for a pass-through job.
    pub compose: Option<ComposeOptions>,
}

/// Writes each sheet to `dir` as PNG.
///
/// File names are `sheet-0001.png`, `sheet-0002.png`, … The counter is per
/// spooler rather than per job, so a second submission into the same
/// directory continues the sequence instead of overwriting the first.
/// Pass-through jobs write `document-0001.pdf`, numbered by job.
#[derive(Debug)]
pub struct FileSpooler {
    dir: PathBuf,
    jobs: Mutex<Vec<RecordedJob>>,
    /// Sheets written so far, so names never collide across submissions.
    sheets_written: Mutex<u32>,
}

impl FileSpooler {
    /// A spooler that writes into `dir`.
    #[must_use]
    pub fn new(dir: impl Into<PathBuf>) -> Self {
        Self {
            dir: dir.into(),
            jobs: Mutex::new(Vec::new()),
            sheets_written: Mutex::new(0),
        }
    }

    /// The directory jobs are written to.
    #[must_use]
    pub fn dir(&self) -> &Path {
        &self.dir
    }

    /// Every job submitted so far, oldest first.
    #[must_use]
    pub fn recorded(&self) -> Vec<RecordedJob> {
        lock(&self.jobs).clone()
    }

    /// The most recent submission, if any.
    #[must_use]
    pub fn last_job(&self) -> Option<RecordedJob> {
        lock(&self.jobs).last().cloned()
    }

    /// Write already-composed rasters, exactly as [`Spooler::submit`] would.
    ///
    /// This is the seam the tests use: it exercises the whole backend —
    /// naming, PNG encoding, recording — without needing a `RenderSession`
    /// or the composition stage.
    pub fn submit_rasters(
        &self,
        printer: &PrinterId,
        title: &str,
        options: &PrintOptions,
        compose: ComposeOptions,
        rasters: &[SheetRaster],
    ) -> Result<JobId, PrintError> {
        self.submit_raster_stream(printer, title, options, compose, rasters.iter().map(Ok))
    }

    /// Write sheets as `rasters` yields them: each is written to disk and
    /// dropped before the next one is pulled, so a lazy iterator that
    /// composes on demand keeps at most one composed sheet alive. This is how
    /// [`Spooler::submit`] spools a `Sheets` payload; composing every sheet
    /// first held the whole job in memory (26 MB per A4 sheet at 300 DPI).
    ///
    /// When an item is an error, or a sheet cannot be written, the files
    /// already written for this job are removed (best effort), nothing is
    /// recorded, and the sheet counter is rolled back when no other job has
    /// advanced it meanwhile, so the next job's names are unaffected.
    pub fn submit_raster_stream<R, I>(
        &self,
        printer: &PrinterId,
        title: &str,
        options: &PrintOptions,
        compose: ComposeOptions,
        rasters: I,
    ) -> Result<JobId, PrintError>
    where
        R: std::borrow::Borrow<SheetRaster>,
        I: IntoIterator<Item = Result<R, PrintError>>,
    {
        self.spool(printer, title, options, compose, rasters, |path, raster| {
            write_sheet_png(path, raster.borrow())
        })
    }

    /// Compose and write `sheets` as [`Spooler::submit`] does: each sheet is
    /// composed band by band straight into its PNG encoder, so not even one
    /// whole composed sheet is held (see [`write_composed_sheet_png`]).
    fn submit_composed(
        &self,
        printer: &PrinterId,
        title: &str,
        options: &PrintOptions,
        session: &crate::reader::RenderSession,
        sheets: &[crate::print::Sheet],
        compose: ComposeOptions,
    ) -> Result<JobId, PrintError> {
        // A sheet that is too large fails before it takes a sheet number or
        // a file, as it did when the whole sheet was composed first.
        let items = sheets
            .iter()
            .map(|sheet| crate::print::compose::sheet_pixel_size(sheet, &compose).map(|_| sheet));
        self.spool(printer, title, options, compose, items, |path, sheet| {
            write_composed_sheet_png(path, session, sheet, &compose)
        })
    }

    /// Write one file per item, numbering, recording and cleaning up after a
    /// failure as [`FileSpooler::submit_raster_stream`] documents.
    fn spool<S>(
        &self,
        printer: &PrinterId,
        title: &str,
        options: &PrintOptions,
        compose: ComposeOptions,
        items: impl IntoIterator<Item = Result<S, PrintError>>,
        mut write: impl FnMut(&Path, S) -> Result<(), PrintError>,
    ) -> Result<JobId, PrintError> {
        std::fs::create_dir_all(&self.dir)?;
        let mut files = Vec::new();
        let mut numbers = Vec::new();
        let write_all = || -> Result<(), PrintError> {
            for item in items {
                let item = item?;
                let number = self.next_sheet_number();
                let path = self.dir.join(sheet_name(number));
                // Recorded before writing, so a partly written file is
                // removed on failure too.
                numbers.push(number);
                files.push(path.clone());
                write(&path, item)?;
            }
            Ok(())
        };
        if let Err(error) = write_all() {
            self.discard_sheets(&files, &numbers);
            return Err(error);
        }
        Ok(self.record(printer, title, options, files, false, Some(compose)))
    }

    /// Consume one number from the sheet counter.
    fn next_sheet_number(&self) -> u32 {
        let mut count = lock(&self.sheets_written);
        *count += 1;
        *count
    }

    /// Undo a failed job's sheets: remove its files and, when its numbers
    /// are still the counter's latest (no other job interleaved), give them
    /// back.
    fn discard_sheets(&self, files: &[PathBuf], numbers: &[u32]) {
        for path in files {
            let _ = std::fs::remove_file(path);
        }
        let (Some(&first), Some(&last)) = (numbers.first(), numbers.last()) else {
            return;
        };
        let mut count = lock(&self.sheets_written);
        let contiguous = (last - first) as usize + 1 == numbers.len();
        if contiguous && *count == last {
            *count = first - 1;
        }
    }

    fn record(
        &self,
        printer: &PrinterId,
        title: &str,
        options: &PrintOptions,
        files: Vec<PathBuf>,
        pass_through: bool,
        compose: Option<ComposeOptions>,
    ) -> JobId {
        let mut jobs = lock(&self.jobs);
        let id = JobId(format!("{FILE_PRINTER}-{}", jobs.len() + 1));
        jobs.push(RecordedJob {
            id: id.clone(),
            printer: printer.clone(),
            title: title.to_string(),
            files,
            pass_through,
            options: options.clone(),
            compose,
        });
        id
    }

    fn job_count(&self) -> usize {
        lock(&self.jobs).len()
    }
}

impl Spooler for FileSpooler {
    fn printers(&self) -> Result<Vec<PrinterInfo>, PrintError> {
        Ok(vec![PrinterInfo {
            id: PrinterId::new(FILE_PRINTER),
            description: Some(format!("File spooler ({})", self.dir.display())),
            location: Some(self.dir.display().to_string()),
            is_default: true,
            accepting_jobs: true,
        }])
    }

    /// A directory has no unprintable border and no driver to disagree with,
    /// so the capabilities are the permissive ones: zero hardware margins,
    /// duplex and colour available, and PDF accepted (pass-through here just
    /// copies the bytes).
    fn capabilities(&self, _printer: &PrinterId) -> Result<DeviceCapabilities, PrintError> {
        Ok(DeviceCapabilities {
            hardware_margins: Margins::ZERO,
            supports_duplex: true,
            supports_color: true,
            resolution_dpi: Some(ComposeOptions::default().dpi),
            accepts_pdf: true,
        })
    }

    fn submit(&self, job: SpoolJob<'_>) -> Result<JobId, PrintError> {
        match job.payload {
            SpoolPayload::PassThroughPdf(bytes) => {
                std::fs::create_dir_all(&self.dir)?;
                let path = self
                    .dir
                    .join(format!("document-{:04}.pdf", self.job_count() + 1));
                std::fs::write(&path, bytes)?;
                Ok(self.record(
                    &job.printer,
                    &job.title,
                    job.options,
                    vec![path],
                    true,
                    None,
                ))
            }
            SpoolPayload::Sheets {
                session,
                sheets,
                compose,
            } => {
                // Composed lazily, one sheet at a time (B12), and each sheet
                // streamed band by band into its encoder.
                self.submit_composed(
                    &job.printer,
                    &job.title,
                    job.options,
                    session,
                    sheets,
                    compose,
                )
            }
        }
    }

    /// A file is written by the time `submit` returns, so there is nothing
    /// left to wait for.
    fn status(&self, _job: &JobId) -> Result<JobStatus, PrintError> {
        Ok(JobStatus::Completed)
    }

    /// Nothing to cancel: the job completed synchronously.
    fn cancel(&self, _job: &JobId) -> Result<(), PrintError> {
        Ok(())
    }
}

/// The file name of sheet `number`.
fn sheet_name(number: u32) -> String {
    format!("sheet-{number:04}.png")
}

/// Encode `raster` as an 8-bit PNG at `path`.
///
/// Shared with the CUPS backend, which stages composed sheets as PNG for the
/// `lp` filter chain.
pub fn write_sheet_png(path: &Path, raster: &SheetRaster) -> Result<(), PrintError> {
    let color = match raster.channels {
        1 => png::ColorType::Grayscale,
        3 => png::ColorType::Rgb,
        4 => png::ColorType::Rgba,
        other => {
            return Err(PrintError::Spool(format!(
                "cannot encode a {other}-channel sheet raster as PNG"
            )));
        }
    };
    let expected = u64::from(raster.width) * u64::from(raster.height) * u64::from(raster.channels);
    if expected != raster.pixels.len() as u64 {
        return Err(PrintError::Spool(format!(
            "sheet raster is {} bytes, expected {expected} for {}x{}x{}",
            raster.pixels.len(),
            raster.width,
            raster.height,
            raster.channels
        )));
    }

    let file = std::fs::File::create(path)?;
    let mut encoder = png::Encoder::new(std::io::BufWriter::new(file), raster.width, raster.height);
    encoder.set_color(color);
    encoder.set_depth(png::BitDepth::Eight);
    let mut writer = encoder.write_header().map_err(png_error)?;
    writer.write_image_data(&raster.pixels).map_err(png_error)?;
    writer.finish().map_err(png_error)?;
    Ok(())
}

/// IDAT chunk size when a sheet is streamed into its PNG: the encoder's one
/// buffer of compressed output.
const STREAMED_IDAT_BYTES: usize = 1 << 20;

/// Compose `sheet` and encode it as an 8-bit PNG at `path` without ever
/// holding the composed sheet: each band goes into the encoder as soon as it
/// is composed. At 600 dpi a Letter colour sheet is 101 MB that
/// [`write_sheet_png`] needs whole.
///
/// The decoded pixels are exactly those of
/// [`compose_sheet`](crate::print::compose::compose_sheet) written with
/// [`write_sheet_png`], but the encoded file is not byte-identical to that
/// one: the stream writer cuts IDAT chunks of [`STREAMED_IDAT_BYTES`] instead
/// of writing one, and ends the zlib stream after a sync flush. Shared with
/// the CUPS backend.
pub(crate) fn write_composed_sheet_png(
    path: &Path,
    session: &crate::reader::RenderSession,
    sheet: &crate::print::Sheet,
    compose: &ComposeOptions,
) -> Result<(), PrintError> {
    use std::io::Write as _;

    let (width, height) = crate::print::compose::sheet_pixel_size(sheet, compose)?;
    let color = if compose.channels() == 1 {
        png::ColorType::Grayscale
    } else {
        png::ColorType::Rgb
    };
    let file = std::fs::File::create(path)?;
    let mut encoder = png::Encoder::new(std::io::BufWriter::new(file), width, height);
    encoder.set_color(color);
    encoder.set_depth(png::BitDepth::Eight);
    let mut writer = encoder.write_header().map_err(png_error)?;
    let mut stream = writer
        .stream_writer_with_size(STREAMED_IDAT_BYTES)
        .map_err(png_error)?;
    crate::print::compose::compose_sheet_banded(session, sheet, compose, |band| {
        stream.write_all(&band.pixels).map_err(PrintError::from)
    })?;
    stream.finish().map_err(png_error)?;
    writer.finish().map_err(png_error)?;
    Ok(())
}

fn png_error(error: png::EncodingError) -> PrintError {
    match error {
        png::EncodingError::IoError(io) => PrintError::Io(io),
        other => PrintError::Spool(format!("png encoding failed: {other}")),
    }
}

/// Take a lock, ignoring poisoning: the spooler's state is a plain record and
/// a panic elsewhere does not make it invalid.
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    mutex
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}