1use pdfboss_core::content::Op;
15use pdfboss_core::{Dict, Matrix, Name, Object, Point};
16
17use crate::color::Color;
18use crate::error::Result;
19use crate::font::Standard14;
20use crate::image::ImageData;
21
22#[allow(clippy::excessive_precision)] const KAPPA: f32 = 0.552284749831;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27pub enum LineCap {
28 #[default]
30 Butt,
31 Round,
33 Square,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
39pub enum LineJoin {
40 #[default]
42 Miter,
43 Round,
45 Bevel,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub struct ImageHandle(pub(crate) usize);
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct GroupHandle(pub(crate) usize);
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum BlendMode {
62 Normal,
64 Multiply,
66 Screen,
68 Overlay,
70 Darken,
72 Lighten,
74 ColorDodge,
76 ColorBurn,
78 HardLight,
80 SoftLight,
82 Difference,
84 Exclusion,
86}
87
88impl BlendMode {
89 fn pdf_name(self) -> &'static str {
91 match self {
92 BlendMode::Normal => "Normal",
93 BlendMode::Multiply => "Multiply",
94 BlendMode::Screen => "Screen",
95 BlendMode::Overlay => "Overlay",
96 BlendMode::Darken => "Darken",
97 BlendMode::Lighten => "Lighten",
98 BlendMode::ColorDodge => "ColorDodge",
99 BlendMode::ColorBurn => "ColorBurn",
100 BlendMode::HardLight => "HardLight",
101 BlendMode::SoftLight => "SoftLight",
102 BlendMode::Difference => "Difference",
103 BlendMode::Exclusion => "Exclusion",
104 }
105 }
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Default)]
112pub(crate) struct GState {
113 pub(crate) fill_alpha: Option<f32>,
114 pub(crate) stroke_alpha: Option<f32>,
115 pub(crate) blend_mode: Option<BlendMode>,
116}
117
118impl GState {
119 pub(crate) fn ext_gstate_dict(self) -> Dict {
121 let mut dict = Dict::new();
122 if let Some(alpha) = self.fill_alpha {
123 dict.insert(name("ca"), Object::Real(f64::from(alpha)));
124 }
125 if let Some(alpha) = self.stroke_alpha {
126 dict.insert(name("CA"), Object::Real(f64::from(alpha)));
127 }
128 if let Some(mode) = self.blend_mode {
129 dict.insert(name("BM"), Object::Name(name(mode.pdf_name())));
130 }
131 dict
132 }
133}
134
135fn name(text: &str) -> Name {
137 Name(text.to_string())
138}
139
140#[derive(Debug)]
142pub struct CanvasParts {
143 pub ops: Vec<Op>,
145 pub fonts: Vec<Standard14>,
147 pub images: Vec<ImageData>,
149 pub(crate) groups: Vec<(CanvasParts, [f32; 4])>,
152 pub(crate) gstates: Vec<GState>,
155}
156
157#[derive(Debug, Default)]
159pub struct Canvas {
160 ops: Vec<Op>,
161 fonts: Vec<Standard14>,
162 images: Vec<ImageData>,
163 groups: Vec<(CanvasParts, [f32; 4])>,
164 gstates: Vec<GState>,
165}
166
167impl Canvas {
168 pub fn new() -> Canvas {
170 Canvas::default()
171 }
172
173 pub fn save(&mut self) {
175 self.ops.push(Op::Save);
176 }
177
178 pub fn restore(&mut self) {
180 self.ops.push(Op::Restore);
181 }
182
183 pub fn transform(&mut self, m: Matrix) {
185 self.ops.push(Op::Concat(m));
186 }
187
188 pub fn set_line_width(&mut self, width: f32) {
190 self.ops.push(Op::SetLineWidth(width));
191 }
192
193 pub fn set_line_cap(&mut self, cap: LineCap) {
195 self.ops.push(Op::SetLineCap(cap as i32));
196 }
197
198 pub fn set_line_join(&mut self, join: LineJoin) {
200 self.ops.push(Op::SetLineJoin(join as i32));
201 }
202
203 pub fn set_miter_limit(&mut self, limit: f32) {
205 self.ops.push(Op::SetMiterLimit(limit));
206 }
207
208 pub fn set_dash(&mut self, pattern: &[f32], phase: f32) {
210 self.ops.push(Op::SetDash(pattern.to_vec(), phase));
211 }
212
213 pub fn set_fill(&mut self, color: Color) {
215 self.ops.push(color.fill_op());
216 }
217
218 pub fn set_stroke(&mut self, color: Color) {
220 self.ops.push(color.stroke_op());
221 }
222
223 pub fn move_to(&mut self, x: f32, y: f32) {
225 self.ops.push(Op::MoveTo(x, y));
226 }
227
228 pub fn line_to(&mut self, x: f32, y: f32) {
230 self.ops.push(Op::LineTo(x, y));
231 }
232
233 #[allow(clippy::too_many_arguments)] pub fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32) {
236 self.ops.push(Op::CurveTo(x1, y1, x2, y2, x3, y3));
237 }
238
239 pub fn close(&mut self) {
241 self.ops.push(Op::ClosePath);
242 }
243
244 pub fn rect(&mut self, x: f32, y: f32, width: f32, height: f32) {
246 self.ops.push(Op::Rect(x, y, width, height));
247 }
248
249 pub fn circle(&mut self, cx: f32, cy: f32, r: f32) {
252 self.ellipse(cx, cy, r, r);
253 }
254
255 pub fn ellipse(&mut self, cx: f32, cy: f32, rx: f32, ry: f32) {
258 let ox = KAPPA * rx;
259 let oy = KAPPA * ry;
260 self.ops.push(Op::MoveTo(cx + rx, cy));
261 self.ops
262 .push(Op::CurveTo(cx + rx, cy + oy, cx + ox, cy + ry, cx, cy + ry));
263 self.ops
264 .push(Op::CurveTo(cx - ox, cy + ry, cx - rx, cy + oy, cx - rx, cy));
265 self.ops
266 .push(Op::CurveTo(cx - rx, cy - oy, cx - ox, cy - ry, cx, cy - ry));
267 self.ops
268 .push(Op::CurveTo(cx + ox, cy - ry, cx + rx, cy - oy, cx + rx, cy));
269 self.ops.push(Op::ClosePath);
270 }
271
272 pub fn polygon(&mut self, points: &[Point]) {
275 if points.len() < 3 {
276 return;
277 }
278 self.ops.push(Op::MoveTo(points[0].x, points[0].y));
279 for point in &points[1..] {
280 self.ops.push(Op::LineTo(point.x, point.y));
281 }
282 self.ops.push(Op::ClosePath);
283 }
284
285 pub fn fill(&mut self) {
287 self.ops.push(Op::Fill);
288 }
289
290 pub fn fill_even_odd(&mut self) {
292 self.ops.push(Op::FillEvenOdd);
293 }
294
295 pub fn stroke(&mut self) {
297 self.ops.push(Op::Stroke);
298 }
299
300 pub fn close_stroke(&mut self) {
302 self.ops.push(Op::CloseStroke);
303 }
304
305 pub fn fill_stroke(&mut self) {
307 self.ops.push(Op::FillStroke);
308 }
309
310 pub fn clip(&mut self) {
314 self.ops.push(Op::ClipNonZero);
315 self.ops.push(Op::EndPath);
316 }
317
318 pub fn clip_even_odd(&mut self) {
322 self.ops.push(Op::ClipEvenOdd);
323 self.ops.push(Op::EndPath);
324 }
325
326 pub fn end_path(&mut self) {
328 self.ops.push(Op::EndPath);
329 }
330
331 pub fn text(&mut self, text: &str, x: f32, y: f32, font: Standard14, size: f32) -> Result<()> {
335 let encoded = font.encode(text)?;
336 let index = match self.fonts.iter().position(|face| *face == font) {
337 Some(index) => index,
338 None => {
339 self.fonts.push(font);
340 self.fonts.len() - 1
341 }
342 };
343 self.ops.push(Op::BeginText);
344 self.ops
345 .push(Op::SetFont(Name(format!("F{}", index + 1)), size));
346 self.ops.push(Op::TextMove(x, y));
347 self.ops.push(Op::ShowText(encoded));
348 self.ops.push(Op::EndText);
349 Ok(())
350 }
351
352 pub fn add_image(&mut self, image: ImageData) -> ImageHandle {
354 let handle = ImageHandle(self.images.len());
355 self.images.push(image);
356 handle
357 }
358
359 pub fn draw_image(&mut self, image: ImageHandle, x: f32, y: f32, width: f32, height: f32) {
362 self.ops.push(Op::Save);
363 self.ops.push(Op::Concat(Matrix {
364 a: width,
365 b: 0.0,
366 c: 0.0,
367 d: height,
368 e: x,
369 f: y,
370 }));
371 self.ops
372 .push(Op::XObject(Name(format!("Im{}", image.0 + 1))));
373 self.ops.push(Op::Restore);
374 }
375
376 pub fn group(&mut self, canvas: Canvas, bbox: [f32; 4]) -> GroupHandle {
380 let handle = GroupHandle(self.groups.len());
381 self.groups.push((canvas.into_parts(), bbox));
382 handle
383 }
384
385 pub fn draw_group(&mut self, group: GroupHandle, matrix: Matrix) {
388 self.ops.push(Op::Save);
389 self.ops.push(Op::Concat(matrix));
390 self.ops
391 .push(Op::XObject(Name(format!("Gp{}", group.0 + 1))));
392 self.ops.push(Op::Restore);
393 }
394
395 pub fn set_fill_alpha(&mut self, alpha: f32) {
397 self.push_gstate(GState {
398 fill_alpha: Some(alpha),
399 ..GState::default()
400 });
401 }
402
403 pub fn set_stroke_alpha(&mut self, alpha: f32) {
405 self.push_gstate(GState {
406 stroke_alpha: Some(alpha),
407 ..GState::default()
408 });
409 }
410
411 pub fn set_blend_mode(&mut self, mode: BlendMode) {
413 self.push_gstate(GState {
414 blend_mode: Some(mode),
415 ..GState::default()
416 });
417 }
418
419 fn push_gstate(&mut self, state: GState) {
422 let index = match self.gstates.iter().position(|seen| *seen == state) {
423 Some(index) => index,
424 None => {
425 self.gstates.push(state);
426 self.gstates.len() - 1
427 }
428 };
429 self.ops
430 .push(Op::SetExtGState(Name(format!("Gs{}", index + 1))));
431 }
432
433 pub fn op(&mut self, op: Op) {
437 self.ops.push(op);
438 }
439
440 pub fn ops(&self) -> &[Op] {
442 &self.ops
443 }
444
445 pub(crate) fn into_parts(self) -> CanvasParts {
447 CanvasParts {
448 ops: self.ops,
449 fonts: self.fonts,
450 images: self.images,
451 groups: self.groups,
452 gstates: self.gstates,
453 }
454 }
455}
456
457#[cfg(test)]
458mod tests {
459 use pdfboss_core::content::parse_content;
460 use pdfboss_core::Name;
461
462 use super::*;
463 use crate::content::serialize_ops;
464 use crate::error::Error;
465
466 fn name(text: &str) -> Name {
467 Name(text.into())
468 }
469
470 #[test]
472 fn state_ops_push_single_operators() {
473 let mut canvas = Canvas::new();
474 canvas.save();
475 canvas.restore();
476 canvas.transform(Matrix {
477 a: 1.0,
478 b: 2.0,
479 c: 3.0,
480 d: 4.0,
481 e: 5.0,
482 f: 6.0,
483 });
484 canvas.set_line_width(2.5);
485 canvas.set_miter_limit(4.0);
486 canvas.set_dash(&[3.0, 1.0], 0.5);
487 assert_eq!(
488 canvas.ops(),
489 [
490 Op::Save,
491 Op::Restore,
492 Op::Concat(Matrix {
493 a: 1.0,
494 b: 2.0,
495 c: 3.0,
496 d: 4.0,
497 e: 5.0,
498 f: 6.0,
499 }),
500 Op::SetLineWidth(2.5),
501 Op::SetMiterLimit(4.0),
502 Op::SetDash(vec![3.0, 1.0], 0.5),
503 ]
504 );
505 }
506
507 #[test]
508 fn line_cap_and_join_map_declaration_order() {
509 let mut canvas = Canvas::new();
510 canvas.set_line_cap(LineCap::Butt);
511 canvas.set_line_cap(LineCap::Round);
512 canvas.set_line_cap(LineCap::Square);
513 canvas.set_line_join(LineJoin::Miter);
514 canvas.set_line_join(LineJoin::Round);
515 canvas.set_line_join(LineJoin::Bevel);
516 assert_eq!(
517 canvas.ops(),
518 [
519 Op::SetLineCap(0),
520 Op::SetLineCap(1),
521 Op::SetLineCap(2),
522 Op::SetLineJoin(0),
523 Op::SetLineJoin(1),
524 Op::SetLineJoin(2),
525 ]
526 );
527 }
528
529 #[test]
530 fn fill_and_stroke_colors() {
531 let mut canvas = Canvas::new();
532 canvas.set_fill(Color::Gray(0.5));
533 canvas.set_fill(Color::Rgb(0.1, 0.2, 0.3));
534 canvas.set_fill(Color::Cmyk(0.1, 0.2, 0.3, 0.4));
535 canvas.set_stroke(Color::Gray(0.5));
536 canvas.set_stroke(Color::Rgb(0.1, 0.2, 0.3));
537 canvas.set_stroke(Color::Cmyk(0.1, 0.2, 0.3, 0.4));
538 assert_eq!(
539 canvas.ops(),
540 [
541 Op::SetFillGray(0.5),
542 Op::SetFillRGB(0.1, 0.2, 0.3),
543 Op::SetFillCMYK(0.1, 0.2, 0.3, 0.4),
544 Op::SetStrokeGray(0.5),
545 Op::SetStrokeRGB(0.1, 0.2, 0.3),
546 Op::SetStrokeCMYK(0.1, 0.2, 0.3, 0.4),
547 ]
548 );
549 }
550
551 #[test]
552 fn path_construction_ops() {
553 let mut canvas = Canvas::new();
554 canvas.move_to(1.0, 2.0);
555 canvas.line_to(3.0, 4.0);
556 canvas.curve_to(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);
557 canvas.close();
558 canvas.rect(10.0, 20.0, 30.0, 40.0);
559 assert_eq!(
560 canvas.ops(),
561 [
562 Op::MoveTo(1.0, 2.0),
563 Op::LineTo(3.0, 4.0),
564 Op::CurveTo(1.0, 2.0, 3.0, 4.0, 5.0, 6.0),
565 Op::ClosePath,
566 Op::Rect(10.0, 20.0, 30.0, 40.0),
567 ]
568 );
569 }
570
571 #[test]
572 fn circle_appends_four_arcs_and_close() {
573 let mut canvas = Canvas::new();
574 canvas.circle(0.0, 0.0, 1.0);
575 assert_eq!(
576 canvas.ops(),
577 [
578 Op::MoveTo(1.0, 0.0),
579 Op::CurveTo(1.0, KAPPA, KAPPA, 1.0, 0.0, 1.0),
580 Op::CurveTo(-KAPPA, 1.0, -1.0, KAPPA, -1.0, 0.0),
581 Op::CurveTo(-1.0, -KAPPA, -KAPPA, -1.0, 0.0, -1.0),
582 Op::CurveTo(KAPPA, -1.0, 1.0, -KAPPA, 1.0, 0.0),
583 Op::ClosePath,
584 ]
585 );
586 }
587
588 #[test]
589 fn ellipse_appends_four_arcs_and_close() {
590 let (cx, cy, rx, ry) = (10.0f32, 20.0f32, 4.0f32, 2.0f32);
591 let ox = KAPPA * rx;
592 let oy = KAPPA * ry;
593 let mut canvas = Canvas::new();
594 canvas.ellipse(cx, cy, rx, ry);
595 assert_eq!(
596 canvas.ops(),
597 [
598 Op::MoveTo(cx + rx, cy),
599 Op::CurveTo(cx + rx, cy + oy, cx + ox, cy + ry, cx, cy + ry),
600 Op::CurveTo(cx - ox, cy + ry, cx - rx, cy + oy, cx - rx, cy),
601 Op::CurveTo(cx - rx, cy - oy, cx - ox, cy - ry, cx, cy - ry),
602 Op::CurveTo(cx + ox, cy - ry, cx + rx, cy - oy, cx + rx, cy),
603 Op::ClosePath,
604 ]
605 );
606 }
607
608 #[test]
609 fn polygon_appends_closed_path() {
610 let mut canvas = Canvas::new();
611 canvas.polygon(&[
612 Point::new(0.0, 0.0),
613 Point::new(10.0, 0.0),
614 Point::new(5.0, 8.0),
615 ]);
616 assert_eq!(
617 canvas.ops(),
618 [
619 Op::MoveTo(0.0, 0.0),
620 Op::LineTo(10.0, 0.0),
621 Op::LineTo(5.0, 8.0),
622 Op::ClosePath,
623 ]
624 );
625 }
626
627 #[test]
628 fn polygon_under_three_points_is_no_op() {
629 let mut canvas = Canvas::new();
630 canvas.polygon(&[]);
631 canvas.polygon(&[Point::new(1.0, 2.0)]);
632 canvas.polygon(&[Point::new(1.0, 2.0), Point::new(3.0, 4.0)]);
633 assert_eq!(canvas.ops(), []);
634 }
635
636 #[test]
637 fn paint_verbs_push_single_operators() {
638 let mut canvas = Canvas::new();
639 canvas.fill();
640 canvas.fill_even_odd();
641 canvas.stroke();
642 canvas.close_stroke();
643 canvas.fill_stroke();
644 canvas.end_path();
645 assert_eq!(
646 canvas.ops(),
647 [
648 Op::Fill,
649 Op::FillEvenOdd,
650 Op::Stroke,
651 Op::CloseStroke,
652 Op::FillStroke,
653 Op::EndPath,
654 ]
655 );
656 }
657
658 #[test]
659 fn clip_pairs_consume_the_path() {
660 let mut canvas = Canvas::new();
661 canvas.clip();
662 canvas.clip_even_odd();
663 assert_eq!(
664 canvas.ops(),
665 [Op::ClipNonZero, Op::EndPath, Op::ClipEvenOdd, Op::EndPath,]
666 );
667 }
668
669 #[test]
671 fn text_pushes_five_op_sequence() {
672 let mut canvas = Canvas::new();
673 canvas
674 .text("Hi", 72.0, 720.0, Standard14::Helvetica, 12.0)
675 .unwrap();
676 assert_eq!(
677 canvas.ops(),
678 [
679 Op::BeginText,
680 Op::SetFont(name("F1"), 12.0),
681 Op::TextMove(72.0, 720.0),
682 Op::ShowText(b"Hi".to_vec()),
683 Op::EndText,
684 ]
685 );
686 let parts = canvas.into_parts();
687 assert_eq!(parts.fonts, [Standard14::Helvetica]);
688 }
689
690 #[test]
691 fn texts_in_the_same_font_share_f1() {
692 let mut canvas = Canvas::new();
693 canvas
694 .text("one", 0.0, 0.0, Standard14::TimesRoman, 10.0)
695 .unwrap();
696 canvas
697 .text("two", 0.0, 20.0, Standard14::TimesRoman, 10.0)
698 .unwrap();
699 let font_names: Vec<&Op> = canvas
700 .ops()
701 .iter()
702 .filter(|op| matches!(op, Op::SetFont(..)))
703 .collect();
704 assert_eq!(
705 font_names,
706 [
707 &Op::SetFont(name("F1"), 10.0),
708 &Op::SetFont(name("F1"), 10.0),
709 ]
710 );
711 assert_eq!(canvas.into_parts().fonts, [Standard14::TimesRoman]);
712 }
713
714 #[test]
715 fn second_face_gets_f2() {
716 let mut canvas = Canvas::new();
717 canvas
718 .text("one", 0.0, 0.0, Standard14::Helvetica, 10.0)
719 .unwrap();
720 canvas
721 .text("two", 0.0, 20.0, Standard14::CourierBold, 10.0)
722 .unwrap();
723 canvas
724 .text("three", 0.0, 40.0, Standard14::Helvetica, 10.0)
725 .unwrap();
726 let font_names: Vec<&Op> = canvas
727 .ops()
728 .iter()
729 .filter(|op| matches!(op, Op::SetFont(..)))
730 .collect();
731 assert_eq!(
732 font_names,
733 [
734 &Op::SetFont(name("F1"), 10.0),
735 &Op::SetFont(name("F2"), 10.0),
736 &Op::SetFont(name("F1"), 10.0),
737 ]
738 );
739 assert_eq!(
740 canvas.into_parts().fonts,
741 [Standard14::Helvetica, Standard14::CourierBold]
742 );
743 }
744
745 #[test]
746 fn text_error_leaves_canvas_untouched() {
747 let mut canvas = Canvas::new();
748 canvas.save();
749 let result = canvas.text("\u{2318}", 0.0, 0.0, Standard14::Helvetica, 12.0);
750 assert!(matches!(
751 result,
752 Err(Error::Unencodable { ch: '\u{2318}', .. })
753 ));
754 assert_eq!(canvas.ops(), [Op::Save]);
755 assert!(canvas.into_parts().fonts.is_empty());
756 }
757
758 #[test]
759 fn draw_image_emits_save_concat_xobject_restore() {
760 let mut canvas = Canvas::new();
761 let first = canvas.add_image(ImageData::gray8(1, 1, vec![0]).unwrap());
762 let second = canvas.add_image(ImageData::gray8(1, 1, vec![255]).unwrap());
763 canvas.draw_image(first, 10.0, 20.0, 100.0, 50.0);
764 canvas.draw_image(second, 0.0, 0.0, 5.0, 5.0);
765 assert_eq!(
766 canvas.ops(),
767 [
768 Op::Save,
769 Op::Concat(Matrix {
770 a: 100.0,
771 b: 0.0,
772 c: 0.0,
773 d: 50.0,
774 e: 10.0,
775 f: 20.0,
776 }),
777 Op::XObject(name("Im1")),
778 Op::Restore,
779 Op::Save,
780 Op::Concat(Matrix {
781 a: 5.0,
782 b: 0.0,
783 c: 0.0,
784 d: 5.0,
785 e: 0.0,
786 f: 0.0,
787 }),
788 Op::XObject(name("Im2")),
789 Op::Restore,
790 ]
791 );
792 assert_eq!(canvas.into_parts().images.len(), 2);
793 }
794
795 #[test]
796 fn group_registers_subcanvas_parts_and_bbox() {
797 let mut sub = Canvas::new();
798 sub.rect(1.0, 2.0, 3.0, 4.0);
799 sub.fill();
800 let mut canvas = Canvas::new();
801 let handle = canvas.group(sub, [0.0, 0.0, 50.0, 20.0]);
802 assert_eq!(handle, GroupHandle(0));
803 let parts = canvas.into_parts();
804 assert_eq!(parts.groups.len(), 1);
805 let (group_parts, bbox) = &parts.groups[0];
806 assert_eq!(*bbox, [0.0, 0.0, 50.0, 20.0]);
807 assert_eq!(group_parts.ops, [Op::Rect(1.0, 2.0, 3.0, 4.0), Op::Fill]);
808 }
809
810 #[test]
811 fn second_group_gets_index_one() {
812 let mut canvas = Canvas::new();
813 let first = canvas.group(Canvas::new(), [0.0, 0.0, 1.0, 1.0]);
814 let second = canvas.group(Canvas::new(), [0.0, 0.0, 1.0, 1.0]);
815 assert_eq!(first, GroupHandle(0));
816 assert_eq!(second, GroupHandle(1));
817 }
818
819 #[test]
820 fn draw_group_emits_save_cm_xobject_restore_and_round_trips() {
821 let mut canvas = Canvas::new();
822 let handle = canvas.group(Canvas::new(), [0.0, 0.0, 10.0, 10.0]);
823 let matrix = Matrix {
824 a: 1.0,
825 b: 0.0,
826 c: 0.0,
827 d: 1.0,
828 e: 72.0,
829 f: 144.0,
830 };
831 canvas.draw_group(handle, matrix);
832 assert_eq!(
833 canvas.ops(),
834 [
835 Op::Save,
836 Op::Concat(matrix),
837 Op::XObject(name("Gp1")),
838 Op::Restore,
839 ]
840 );
841 let bytes = serialize_ops(canvas.ops());
842 let parsed = parse_content(&bytes).unwrap();
843 assert_eq!(parsed, canvas.ops());
844 }
845
846 #[test]
847 fn two_draws_of_one_group_reference_the_same_resource_name() {
848 let mut canvas = Canvas::new();
849 let handle = canvas.group(Canvas::new(), [0.0, 0.0, 10.0, 10.0]);
850 canvas.draw_group(handle, Matrix::identity());
851 canvas.draw_group(handle, Matrix::translate(5.0, 5.0));
852 let names: Vec<&Op> = canvas
853 .ops()
854 .iter()
855 .filter(|op| matches!(op, Op::XObject(_)))
856 .collect();
857 assert_eq!(
858 names,
859 [&Op::XObject(name("Gp1")), &Op::XObject(name("Gp1"))]
860 );
861 }
862
863 #[test]
864 fn second_registered_group_gets_gp2() {
865 let mut canvas = Canvas::new();
866 let first = canvas.group(Canvas::new(), [0.0, 0.0, 1.0, 1.0]);
867 let second = canvas.group(Canvas::new(), [0.0, 0.0, 1.0, 1.0]);
868 canvas.draw_group(first, Matrix::identity());
869 canvas.draw_group(second, Matrix::identity());
870 let names: Vec<&Op> = canvas
871 .ops()
872 .iter()
873 .filter(|op| matches!(op, Op::XObject(_)))
874 .collect();
875 assert_eq!(
876 names,
877 [&Op::XObject(name("Gp1")), &Op::XObject(name("Gp2"))]
878 );
879 }
880
881 #[test]
882 fn nested_groups_recurse() {
883 let mut innermost = Canvas::new();
884 innermost.fill();
885 let mut outer = Canvas::new();
886 let inner_handle = outer.group(innermost, [0.0, 0.0, 1.0, 1.0]);
887 outer.draw_group(inner_handle, Matrix::identity());
888 let mut canvas = Canvas::new();
889 let outer_handle = canvas.group(outer, [0.0, 0.0, 2.0, 2.0]);
890 canvas.draw_group(outer_handle, Matrix::identity());
891 let parts = canvas.into_parts();
892 let (outer_parts, _) = &parts.groups[0];
893 assert_eq!(outer_parts.groups.len(), 1);
894 let (inner_parts, _) = &outer_parts.groups[0];
895 assert_eq!(inner_parts.ops, [Op::Fill]);
896 }
897
898 #[test]
899 fn set_fill_alpha_pushes_gs_referencing_gs1() {
900 let mut canvas = Canvas::new();
901 canvas.set_fill_alpha(0.5);
902 assert_eq!(canvas.ops(), [Op::SetExtGState(name("Gs1"))]);
903 let parts = canvas.into_parts();
904 assert_eq!(parts.gstates.len(), 1);
905 assert_eq!(parts.gstates[0].fill_alpha, Some(0.5));
906 assert_eq!(parts.gstates[0].stroke_alpha, None);
907 assert_eq!(parts.gstates[0].blend_mode, None);
908 }
909
910 #[test]
911 fn set_stroke_alpha_and_blend_mode_get_distinct_resources() {
912 let mut canvas = Canvas::new();
913 canvas.set_fill_alpha(0.5);
914 canvas.set_stroke_alpha(0.5);
915 canvas.set_blend_mode(BlendMode::Multiply);
916 assert_eq!(
917 canvas.ops(),
918 [
919 Op::SetExtGState(name("Gs1")),
920 Op::SetExtGState(name("Gs2")),
921 Op::SetExtGState(name("Gs3")),
922 ]
923 );
924 assert_eq!(canvas.into_parts().gstates.len(), 3);
925 }
926
927 #[test]
928 fn identical_setter_calls_dedupe_to_one_resource() {
929 let mut canvas = Canvas::new();
930 canvas.set_fill_alpha(0.5);
931 canvas.set_fill_alpha(0.5);
932 assert_eq!(
933 canvas.ops(),
934 [Op::SetExtGState(name("Gs1")), Op::SetExtGState(name("Gs1"))]
935 );
936 assert_eq!(canvas.into_parts().gstates.len(), 1);
937 }
938
939 #[test]
940 fn gstate_setters_round_trip() {
941 let mut canvas = Canvas::new();
942 canvas.set_fill_alpha(0.25);
943 canvas.set_stroke_alpha(0.75);
944 canvas.set_blend_mode(BlendMode::Screen);
945 let bytes = serialize_ops(canvas.ops());
946 let parsed = parse_content(&bytes).unwrap();
947 assert_eq!(parsed, canvas.ops());
948 }
949}