zenith-render 0.0.7

Zenith CPU PNG (tiny-skia) and vector PDF rendering backends.
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! Unit tests for the vector PDF backend.

use zenith_core::{AssetKind, AssetProvider, BytesAssetProvider, FontProvider, default_provider};
use zenith_scene::{
    Color, FilterSpec, FitMode, GradientPaint, GradientStop, Paint, Rect, Scene, SceneCommand,
    SceneGlyph,
};

use super::render_pdf;

/// A font + asset provider pair for tests. The default provider carries the
/// bundled Noto faces; the asset provider is empty unless a test registers one.
fn providers() -> (impl FontProvider, impl AssetProvider) {
    (default_provider(), BytesAssetProvider::new())
}

/// Resolve a bundled font id so glyph-run tests reference a real face.
fn a_font_id(fonts: &dyn FontProvider) -> String {
    fonts
        .all_faces()
        .first()
        .map(|f| f.id.clone())
        .expect("bundled fonts must be present")
}

fn render(scene: &Scene) -> Vec<u8> {
    let (fonts, assets) = providers();
    render_pdf(scene, &fonts, &assets)
}

#[test]
fn pdf_starts_and_ends_with_markers() {
    let mut scene = Scene::new(100.0, 80.0);
    scene.commands.push(SceneCommand::FillRect {
        x: 0.0,
        y: 0.0,
        w: 100.0,
        h: 80.0,
        paint: Paint::solid(Color::srgb(10, 20, 30, 255)),
    });
    let bytes = render(&scene);
    assert!(!bytes.is_empty(), "PDF must be non-empty");
    assert!(
        bytes.starts_with(b"%PDF-"),
        "PDF must start with %PDF- marker"
    );
    let tail_start = bytes.len().saturating_sub(8);
    let tail = &bytes[tail_start..];
    assert!(
        tail.windows(5).any(|w| w == b"%%EOF"),
        "PDF must end with %%EOF; tail was {:?}",
        String::from_utf8_lossy(tail)
    );
}

#[test]
fn render_is_byte_identical_across_runs() {
    let fonts = default_provider();
    let font_id = a_font_id(&fonts);
    let mut scene = Scene::new(120.0, 60.0);
    scene.commands.push(SceneCommand::FillRect {
        x: 0.0,
        y: 0.0,
        w: 120.0,
        h: 60.0,
        paint: Paint::solid(Color::srgb(240, 240, 240, 255)),
    });
    scene.commands.push(SceneCommand::DrawGlyphRun {
        x: 10.0,
        y: 40.0,
        font_id,
        font_size: 24.0,
        color: Color::srgb(0, 0, 0, 255),
        stroke_color: None,
        stroke_width: None,
        link: None,
        selectable: true,
        glyphs: vec![
            SceneGlyph {
                glyph_id: 5,
                dx: 0.0,
                dy: 0.0,
                text: String::new(),
            },
            SceneGlyph {
                glyph_id: 8,
                dx: 14.0,
                dy: 0.0,
                text: String::new(),
            },
        ],
    });
    let a = render(&scene);
    let b = render(&scene);
    assert_eq!(a, b, "two renders of the same scene must be byte-identical");
}

#[test]
fn cmyk_color_emits_device_cmyk_operator() {
    let mut scene = Scene::new(50.0, 50.0);
    scene.commands.push(SceneCommand::FillRect {
        x: 0.0,
        y: 0.0,
        w: 50.0,
        h: 50.0,
        paint: Paint::solid(Color::cmyk(59.0, 85.0, 0.0, 7.0, 97, 36, 237)),
    });
    let bytes = render(&scene);
    let text = String::from_utf8_lossy(&bytes);
    assert!(
        text.contains(" k\n") || text.contains(" k "),
        "CMYK fill must emit a DeviceCMYK `k` operator"
    );
}

#[test]
fn srgb_color_emits_device_rgb_operator() {
    let mut scene = Scene::new(50.0, 50.0);
    scene.commands.push(SceneCommand::FillRect {
        x: 0.0,
        y: 0.0,
        w: 50.0,
        h: 50.0,
        paint: Paint::solid(Color::srgb(200, 100, 50, 255)),
    });
    let bytes = render(&scene);
    let text = String::from_utf8_lossy(&bytes);
    assert!(
        text.contains(" rg\n") || text.contains(" rg "),
        "sRGB fill must emit a DeviceRGB `rg` operator"
    );
    assert!(
        !text.contains(" k\n"),
        "sRGB-only scene must not emit a DeviceCMYK `k` operator"
    );
}

#[test]
fn bleed_scene_has_distinct_trim_box() {
    // Media box larger than the trim box (bleed of 5 on each side).
    let mut scene = Scene::new(110.0, 90.0);
    scene.trim = Some(Rect {
        x: 5.0,
        y: 5.0,
        w: 100.0,
        h: 80.0,
    });
    scene.commands.push(SceneCommand::FillRect {
        x: 0.0,
        y: 0.0,
        w: 110.0,
        h: 90.0,
        paint: Paint::solid(Color::srgb(0, 0, 0, 255)),
    });
    let bytes = render(&scene);
    let text = String::from_utf8_lossy(&bytes);
    assert!(text.contains("/TrimBox"), "page must carry a /TrimBox");
    assert!(text.contains("/BleedBox"), "page must carry a /BleedBox");
    assert!(text.contains("/CropBox"), "page must carry a /CropBox");
    // The trim box, converted to PDF coords, is [5 5 105 85] — not the media
    // box [0 0 110 90].
    assert!(
        text.contains("/TrimBox [5 5 105 85]"),
        "TrimBox must differ from MediaBox; got document:\n{}",
        &text[..text.len().min(1200)]
    );
}

#[test]
fn non_bleed_scene_has_equal_boxes() {
    let mut scene = Scene::new(64.0, 48.0);
    scene.commands.push(SceneCommand::FillRect {
        x: 0.0,
        y: 0.0,
        w: 64.0,
        h: 48.0,
        paint: Paint::solid(Color::srgb(1, 2, 3, 255)),
    });
    let bytes = render(&scene);
    let text = String::from_utf8_lossy(&bytes);
    assert!(text.contains("/MediaBox [0 0 64 48]"));
    assert!(text.contains("/TrimBox [0 0 64 48]"));
    assert!(text.contains("/BleedBox [0 0 64 48]"));
    assert!(text.contains("/CropBox [0 0 64 48]"));
}

#[test]
fn glyph_run_emits_path_fill_ops() {
    let fonts = default_provider();
    let font_id = a_font_id(&fonts);
    let mut scene = Scene::new(200.0, 60.0);
    scene.commands.push(SceneCommand::DrawGlyphRun {
        x: 10.0,
        y: 40.0,
        font_id,
        font_size: 32.0,
        color: Color::srgb(0, 0, 0, 255),
        stroke_color: None,
        stroke_width: None,
        link: None,
        // selectable=false → the outline-fallback path under test.
        selectable: false,
        glyphs: vec![SceneGlyph {
            glyph_id: 36, // 'A' in many fonts; any outlined glyph works
            dx: 0.0,
            dy: 0.0,
            text: String::new(),
        }],
    });
    let bytes = render(&scene);
    let text = String::from_utf8_lossy(&bytes);
    // A non-selectable run is drawn as filled outlines: the content stream must
    // contain a curve op (`c`) and a nonzero fill (`f`), and NO embedded font.
    assert!(
        !text.contains("/Type0"),
        "non-selectable run must not embed a Type0 font"
    );
    assert!(
        text.contains(" c\n"),
        "glyph outline must emit cubic-curve `c` ops"
    );
    assert!(
        text.contains("\nf\n") || text.contains(" f\n"),
        "glyph run must emit a fill `f` op"
    );
}

#[test]
fn svg_asset_emits_vector_paths_and_shading_not_raster() {
    // A logo-shaped SVG: one gradient-filled polygon + one solid polygon. The
    // PDF backend must translate it to VECTOR ops — a nonzero fill `f` for the
    // solid polygon and an axial shading `/sh0 sh` for the gradient one — and
    // must NOT embed the SVG as a rasterized image XObject.
    const LOGO_SVG: &[u8] = b"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'>\
        <defs><linearGradient id='g' gradientUnits='userSpaceOnUse' x1='0' y1='0' x2='100' y2='100'>\
        <stop offset='0' stop-color='#24b6dd'/><stop offset='1' stop-color='#0860a0'/>\
        </linearGradient></defs>\
        <polygon points='0,0 100,0 0,100' fill='url(#g)'/>\
        <polygon points='100,0 100,100 0,100' fill='#051b3e'/></svg>";

    let fonts = default_provider();
    let mut assets = BytesAssetProvider::new();
    assets.register("asset.logo", AssetKind::Svg, std::sync::Arc::from(LOGO_SVG));

    let mut scene = Scene::new(200.0, 200.0);
    scene.commands.push(SceneCommand::DrawImage {
        x: 20.0,
        y: 20.0,
        w: 160.0,
        h: 160.0,
        asset_id: "asset.logo".to_string(),
        fit: FitMode::Contain,
        pos_x: 50.0,
        pos_y: 50.0,
        opacity: 1.0,
        clip_shape: None,
        src_rect: None,
    });

    let bytes = render_pdf(&scene, &fonts, &assets);
    let text = String::from_utf8_lossy(&bytes);
    assert!(
        text.contains("\nf\n") || text.contains(" f\n"),
        "SVG solid polygon must emit a nonzero fill `f` op"
    );
    assert!(
        text.contains("/sh0 sh"),
        "SVG linear gradient must emit an axial shading `/sh0 sh`"
    );
    assert!(
        !text.contains("/Subtype /Image"),
        "SVG must be vector, not a rasterized image XObject"
    );
}

#[test]
fn gradient_scene_renders_shading() {
    let mut scene = Scene::new(100.0, 100.0);
    scene.commands.push(SceneCommand::FillRect {
        x: 0.0,
        y: 0.0,
        w: 100.0,
        h: 100.0,
        paint: Paint::Gradient(GradientPaint {
            angle_deg: 90.0,
            stops: vec![
                GradientStop {
                    offset: 0.0,
                    color: Color::srgb(255, 0, 0, 255),
                },
                GradientStop {
                    offset: 0.5,
                    color: Color::srgb(0, 255, 0, 255),
                },
                GradientStop {
                    offset: 1.0,
                    color: Color::srgb(0, 0, 255, 255),
                },
            ],
            radial: false,
            center_x: None,
            center_y: None,
            radius_frac: None,
        }),
    });
    let bytes = render(&scene);
    let text = String::from_utf8_lossy(&bytes);
    assert!(
        text.contains("/ShadingType 2"),
        "linear gradient must emit an axial (Type 2) shading"
    );
    assert!(
        text.contains("/FunctionType 3"),
        "a 3-stop gradient must use a Type 3 stitching function"
    );
    assert!(text.contains(" sh\n"), "shading must be painted with `sh`");
}

/// A plain opaque FillRect with NO filter bracket renders via the vector path and
/// embeds zero image XObjects — the page carries no `/Subtype /Image`.
#[test]
fn unfiltered_fill_rect_embeds_no_image() {
    let mut scene = Scene::new(60.0, 40.0);
    scene.commands.push(SceneCommand::FillRect {
        x: 10.0,
        y: 10.0,
        w: 30.0,
        h: 20.0,
        paint: Paint::solid(Color::srgb(200, 60, 40, 255)),
    });
    let bytes = render(&scene);
    let text = String::from_utf8_lossy(&bytes);
    assert!(
        !text.contains("/Subtype /Image"),
        "an unfiltered fill rect must not embed any image XObject"
    );
}

/// The SAME rect wrapped in a `BeginFilter{Grayscale 1.0}` / `EndFilter` bracket
/// is rasterized and embedded as an image XObject — proving the filtered region
/// is no longer a no-op (it produces ≥1 image where the vector path produces 0).
#[test]
fn filtered_fill_rect_embeds_image_xobject() {
    let mut scene = Scene::new(60.0, 40.0);
    scene.commands.push(SceneCommand::BeginFilter {
        filters: vec![FilterSpec::Grayscale(1.0)],
    });
    scene.commands.push(SceneCommand::FillRect {
        x: 10.0,
        y: 10.0,
        w: 30.0,
        h: 20.0,
        paint: Paint::solid(Color::srgb(200, 60, 40, 255)),
    });
    scene.commands.push(SceneCommand::EndFilter);

    let bytes = render(&scene);
    let text = String::from_utf8_lossy(&bytes);
    assert!(
        text.contains("/Subtype /Image"),
        "a filtered fill rect must rasterize+embed an image XObject"
    );
    // The XObject is referenced from the page Resources under the `im0` name.
    assert!(
        text.contains("/im0"),
        "the embedded filter image must be named im0 in page resources"
    );
}

/// Rasterize-and-embed must stay deterministic: two renders of a filtered scene
/// are byte-identical (no time, no randomness, fixed deflate level + rounding).
#[test]
fn filtered_region_render_is_byte_identical() {
    let mut scene = Scene::new(80.0, 50.0);
    scene.commands.push(SceneCommand::BeginFilter {
        filters: vec![FilterSpec::Sepia(1.0)],
    });
    scene.commands.push(SceneCommand::FillRect {
        x: 5.0,
        y: 5.0,
        w: 40.0,
        h: 30.0,
        paint: Paint::solid(Color::srgb(20, 140, 200, 255)),
    });
    scene.commands.push(SceneCommand::EndFilter);

    let a = render(&scene);
    let b = render(&scene);
    assert_eq!(
        a, b,
        "two renders of a filtered scene must be byte-identical"
    );
}

#[test]
fn multi_page_pdf_has_one_page_object_per_scene() {
    use super::render_pdf_multi;
    let (fonts, assets) = providers();

    let mut p1 = Scene::new(100.0, 80.0);
    p1.commands.push(SceneCommand::FillRect {
        x: 0.0,
        y: 0.0,
        w: 100.0,
        h: 80.0,
        paint: Paint::solid(Color::srgb(10, 20, 30, 255)),
    });
    let mut p2 = Scene::new(120.0, 60.0);
    p2.commands.push(SceneCommand::FillRect {
        x: 0.0,
        y: 0.0,
        w: 120.0,
        h: 60.0,
        paint: Paint::solid(Color::srgb(200, 100, 50, 255)),
    });

    let bytes = render_pdf_multi(&[p1, p2], &fonts, &assets);
    let text = String::from_utf8_lossy(&bytes);

    // The page tree must report two kids, and each page its own MediaBox.
    assert!(
        text.contains("/Count 2"),
        "two-scene PDF must declare /Count 2"
    );
    let mediaboxes = text.matches("/MediaBox").count();
    assert_eq!(mediaboxes, 2, "each page must carry its own MediaBox");
    // Distinct page sizes confirm both scenes were written, not one twice.
    assert!(
        text.contains("/MediaBox [0 0 100 80]"),
        "page 1 box missing"
    );
    assert!(
        text.contains("/MediaBox [0 0 120 60]"),
        "page 2 box missing"
    );
}

#[test]
fn single_scene_multi_is_byte_identical_to_render_pdf() {
    use super::render_pdf_multi;
    let (fonts, assets) = providers();
    let mut scene = Scene::new(64.0, 48.0);
    scene.commands.push(SceneCommand::FillRect {
        x: 0.0,
        y: 0.0,
        w: 64.0,
        h: 48.0,
        paint: Paint::solid(Color::srgb(1, 2, 3, 255)),
    });
    let via_wrapper = render_pdf(&scene, &fonts, &assets);
    let via_multi = render_pdf_multi(std::slice::from_ref(&scene), &fonts, &assets);
    assert_eq!(
        via_wrapper, via_multi,
        "single-scene multi-page path must be byte-identical to render_pdf"
    );
}

/// A selectable run (the default) emits a real embedded `Type0` font with a
/// `ToUnicode` CMap and text-showing operators, not filled outlines.
#[test]
fn selectable_glyph_run_emits_embedded_text() {
    let fonts = default_provider();
    let font_id = a_font_id(&fonts);
    let mut scene = Scene::new(200.0, 60.0);
    scene.commands.push(SceneCommand::DrawGlyphRun {
        x: 10.0,
        y: 40.0,
        font_id,
        font_size: 32.0,
        color: Color::srgb(0, 0, 0, 255),
        stroke_color: None,
        stroke_width: None,
        link: None,
        selectable: true,
        glyphs: vec![SceneGlyph {
            glyph_id: 36,
            dx: 0.0,
            dy: 0.0,
            text: "A".to_owned(),
        }],
    });
    let bytes = render(&scene);
    let text = String::from_utf8_lossy(&bytes);
    assert!(
        text.contains("/Type0"),
        "selectable run must embed a Type0 font"
    );
    assert!(
        text.contains("/CIDFontType2"),
        "selectable run must embed a CIDFontType2 descendant"
    );
    assert!(
        text.contains("/ToUnicode"),
        "selectable run must carry a ToUnicode CMap for extraction"
    );
    // The ToUnicode CMap maps the glyph's CID to U+0041 ('A').
    assert!(
        text.contains("beginbfchar"),
        "ToUnicode CMap must contain a bfchar block"
    );
}

/// A selectable run carrying a link emits a clickable `/Link` annotation with a
/// `/URI` action over the run's bounds.
#[test]
fn selectable_link_run_emits_link_annotation() {
    let fonts = default_provider();
    let font_id = a_font_id(&fonts);
    let mut scene = Scene::new(200.0, 60.0);
    scene.commands.push(SceneCommand::DrawGlyphRun {
        x: 10.0,
        y: 40.0,
        font_id,
        font_size: 32.0,
        color: Color::srgb(0, 0, 0, 255),
        stroke_color: None,
        stroke_width: None,
        link: Some("https://zenith.example/".to_owned()),
        selectable: true,
        glyphs: vec![SceneGlyph {
            glyph_id: 36,
            dx: 0.0,
            dy: 0.0,
            text: "A".to_owned(),
        }],
    });
    let bytes = render(&scene);
    let text = String::from_utf8_lossy(&bytes);
    assert!(
        text.contains("/Link"),
        "a linked run must emit a /Link annotation"
    );
    assert!(
        text.contains("/URI"),
        "the link annotation must carry a /URI action"
    );
    assert!(
        text.contains("https://zenith.example/"),
        "the link URL must appear in the annotation"
    );
}

/// A `selectable=false` run carrying a link is drawn as outlines and emits no
/// embedded text — and therefore no link annotation either.
#[test]
fn non_selectable_run_has_no_font_or_link() {
    let fonts = default_provider();
    let font_id = a_font_id(&fonts);
    let mut scene = Scene::new(200.0, 60.0);
    scene.commands.push(SceneCommand::DrawGlyphRun {
        x: 10.0,
        y: 40.0,
        font_id,
        font_size: 32.0,
        color: Color::srgb(0, 0, 0, 255),
        stroke_color: None,
        stroke_width: None,
        link: Some("https://zenith.example/".to_owned()),
        selectable: false,
        glyphs: vec![SceneGlyph {
            glyph_id: 36,
            dx: 0.0,
            dy: 0.0,
            text: "A".to_owned(),
        }],
    });
    let bytes = render(&scene);
    let text = String::from_utf8_lossy(&bytes);
    assert!(
        !text.contains("/Type0"),
        "non-selectable run must not embed a font"
    );
    assert!(
        !text.contains("/Link"),
        "non-selectable run must not emit a link annotation"
    );
}

/// A scene with no glyph runs embeds no fonts and is byte-identical regardless of
/// the subset option — the additive invariant for documents without text.
#[test]
fn textless_scene_identical_under_subset_options() {
    use super::{PdfOptions, render_pdf_with};
    let (fonts, assets) = providers();
    let mut scene = Scene::new(40.0, 40.0);
    scene.commands.push(SceneCommand::FillRect {
        x: 0.0,
        y: 0.0,
        w: 40.0,
        h: 40.0,
        paint: Paint::solid(Color::srgb(9, 9, 9, 255)),
    });
    let subset = render_pdf_with(&scene, &fonts, &assets, PdfOptions { subset: true });
    let full = render_pdf_with(&scene, &fonts, &assets, PdfOptions { subset: false });
    let plain = render(&scene);
    assert_eq!(
        subset, full,
        "textless scene must not depend on the subset option"
    );
    assert_eq!(
        subset, plain,
        "textless scene must match the default render"
    );
    assert!(
        !String::from_utf8_lossy(&subset).contains("/Type0"),
        "a textless scene must embed no fonts"
    );
}