1#![deny(clippy::float_arithmetic)]
27
28use std::num::NonZeroU32;
29use std::ops::Range;
30use std::sync::Arc;
31
32use f_office_fonts::FontId;
33use f_office_units::binary32::Binary32;
34use f_office_units::{Length, div_round, div_round_i128};
35
36mod color_effect;
37#[cfg(feature = "decode")]
38mod decode;
39#[cfg(feature = "files")]
40pub mod files;
41pub mod image_header;
42mod image_store;
43mod page_sizes;
44pub mod paper_forms;
45mod sink;
46pub mod stroke;
47#[cfg(feature = "testing")]
48pub mod testing;
49
50pub use color_effect::{ColorEffect, ImageColor};
51pub use image_store::{
52 DEFAULT_IMAGE_BYTES_CACHE, ImageData, ImageId, ImageKey, ImageLoader, ImageRef, LruBytesCache,
53 next_store_id,
54};
55
56#[cfg(feature = "decode")]
57pub use decode::{converts_inks, decode, decode_file, without_profile};
58pub use page_sizes::{GivenSize, PageSizes};
59pub use sink::{PageSink, Painted};
60
61#[derive(Clone, Debug, Default, PartialEq, Eq)]
63pub struct DisplayList {
64 pages: Vec<Page>,
66}
67
68#[derive(Clone, Debug, PartialEq, Eq)]
70pub struct Page {
71 width: Length,
73 height: Length,
75 orientation: Orientation,
78 items: Vec<Item>,
80}
81
82#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
87pub enum Orientation {
88 #[default]
90 Portrait,
91 Landscape,
93}
94
95impl DisplayList {
96 #[must_use]
99 pub const fn new(pages: Vec<Page>) -> Self {
100 Self { pages }
101 }
102
103 #[must_use]
105 pub const fn pages(&self) -> &[Page] {
106 self.pages.as_slice()
107 }
108
109 #[must_use]
112 pub fn into_pages(self) -> Vec<Page> {
113 self.pages
114 }
115}
116
117impl Page {
118 #[must_use]
122 pub const fn new(
123 width: Length,
124 height: Length,
125 orientation: Orientation,
126 items: Vec<Item>,
127 ) -> Self {
128 Self {
129 width,
130 height,
131 orientation,
132 items,
133 }
134 }
135
136 #[must_use]
138 pub const fn orientation(&self) -> Orientation {
139 self.orientation
140 }
141
142 #[must_use]
144 pub const fn width(&self) -> Length {
145 self.width
146 }
147
148 #[must_use]
150 pub const fn height(&self) -> Length {
151 self.height
152 }
153
154 #[must_use]
156 pub const fn items(&self) -> &[Item] {
157 self.items.as_slice()
158 }
159
160 #[must_use]
165 pub fn map_items(self, change: impl FnOnce(Vec<Item>) -> Vec<Item>) -> Self {
166 Self {
167 items: change(self.items),
168 ..self
169 }
170 }
171}
172
173#[derive(Clone, Debug, PartialEq, Eq)]
175pub enum Item {
176 Glyphs(GlyphRun),
178 Rect(Rect),
180 Path(PathItem),
182 Gradient(GradientItem),
184 Image(ImageItem),
186 Group(Group),
192}
193
194#[derive(Clone, Debug, PartialEq, Eq)]
197pub struct Group {
198 pub items: Vec<Item>,
200 pub clip: Option<GroupClip>,
203 pub places: GroupPlaces,
205}
206
207#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
210pub enum GroupPlaces {
211 #[default]
215 Own,
216 Page,
219 Cell,
224 Points,
229 Stroked {
237 width: Length,
239 },
240}
241
242impl Group {
243 #[must_use]
245 pub fn new(items: Vec<Item>) -> Self {
246 Self {
247 items,
248 clip: None,
249 places: GroupPlaces::Own,
250 }
251 }
252
253 #[must_use]
255 pub fn of_page(items: Vec<Item>, clip: GroupClip) -> Self {
256 Self {
257 items,
258 clip: Some(clip),
259 places: GroupPlaces::Page,
260 }
261 }
262
263 #[must_use]
266 pub fn of_cell(items: Vec<Item>, clip: GroupClip) -> Self {
267 Self {
268 items,
269 clip: Some(clip),
270 places: GroupPlaces::Cell,
271 }
272 }
273
274 fn placed_items(&mut self) -> &mut [Item] {
277 match self.places {
278 GroupPlaces::Page
279 | GroupPlaces::Cell
280 | GroupPlaces::Points
281 | GroupPlaces::Stroked { .. } => &mut self.items,
282 GroupPlaces::Own => &mut [],
283 }
284 }
285
286 fn points_mut(&mut self) -> impl Iterator<Item = &mut Point> {
289 let clip = self.clip.iter_mut().flat_map(|clip| &mut clip.commands);
290 let items = self.items.iter_mut().flat_map(|item| -> Vec<&mut Point> {
291 match item {
292 Item::Path(path) => path
293 .commands
294 .iter_mut()
295 .flat_map(PathCommand::points_mut)
296 .collect(),
297 Item::Gradient(GradientItem {
298 commands,
299 start,
300 end,
301 ..
302 }) => commands
303 .iter_mut()
304 .flat_map(PathCommand::points_mut)
305 .chain([start, end])
306 .collect(),
307 _ => Vec::new(),
308 }
309 });
310 clip.flat_map(PathCommand::points_mut).chain(items)
311 }
312
313 #[must_use]
315 pub fn shows_nothing(&self) -> bool {
316 self.clip.as_ref().is_some_and(|clip| !clip.has_area())
317 }
318}
319
320#[derive(Clone, Debug, PartialEq, Eq)]
324pub struct GroupClip {
325 pub commands: Vec<PathCommand>,
327 pub fill_rule: FillRule,
329}
330
331impl GroupClip {
332 #[must_use]
335 pub fn rect(x: Length, y: Length, width: Length, height: Length) -> Self {
336 let corner = |x, y| PathCommand::LineTo(Point { x, y });
337 Self {
338 commands: vec![
339 PathCommand::MoveTo(Point { x, y }),
340 corner(x + width, y),
341 corner(x + width, y + height),
342 corner(x, y + height),
343 PathCommand::Close,
344 ],
345 fill_rule: FillRule::NonZero,
346 }
347 }
348
349 #[must_use]
352 pub fn has_area(&self) -> bool {
353 let spread = |of: fn(Point) -> Length| {
354 let mut values = self.commands.iter().flat_map(PathCommand::points).map(of);
355 let first = values.next();
356 first.is_some_and(|first| values.any(|value| value != first))
357 };
358 spread(|point| point.x) && spread(|point| point.y)
359 }
360}
361
362impl Item {
363 pub fn map_places(
370 &mut self,
371 mut place: impl FnMut(Point) -> Point,
372 mut length: impl FnMut(Length) -> Length,
373 ) {
374 self.map_places_with(&mut place, &mut length);
375 }
376
377 #[must_use]
382 pub fn first_place(&self) -> Option<Point> {
383 let first_point =
384 |commands: &[PathCommand]| commands.iter().flat_map(PathCommand::points).next();
385 match self {
386 Self::Glyphs(run) => run.glyphs.first().map(|glyph| Point {
387 x: glyph.x,
388 y: glyph.y,
389 }),
390 Self::Rect(rect) => Some(Point {
391 x: rect.x,
392 y: rect.y,
393 }),
394 Self::Path(path) => first_point(&path.commands),
395 Self::Gradient(gradient) => first_point(&gradient.commands),
396 Self::Image(image) => Some(Point {
397 x: image.x,
398 y: image.y,
399 }),
400 Self::Group(group) => group.items.iter().find_map(Self::first_place).or_else(|| {
401 group
402 .clip
403 .as_ref()
404 .and_then(|clip| first_point(&clip.commands))
405 }),
406 }
407 }
408
409 fn map_places_with(
410 &mut self,
411 place: &mut dyn FnMut(Point) -> Point,
412 length: &mut dyn FnMut(Length) -> Length,
413 ) {
414 match self {
415 Self::Glyphs(run) => {
416 run.size = length(run.size);
417 for glyph in &mut run.glyphs {
418 Point {
419 x: glyph.x,
420 y: glyph.y,
421 } = place(Point {
422 x: glyph.x,
423 y: glyph.y,
424 });
425 }
426 if let Some(outline) = &mut run.outline {
427 outline.width = length(outline.width);
428 }
429 }
430 Self::Rect(rect) => {
431 Point {
432 x: rect.x,
433 y: rect.y,
434 } = place(Point {
435 x: rect.x,
436 y: rect.y,
437 });
438 rect.width = length(rect.width);
439 rect.height = length(rect.height);
440 }
441 Self::Path(path) => map_points(&mut path.commands, place),
442 Self::Gradient(gradient) => {
443 map_points(&mut gradient.commands, place);
444 gradient.start = place(gradient.start);
445 gradient.end = place(gradient.end);
446 }
447 Self::Image(image) => {
448 Point {
449 x: image.x,
450 y: image.y,
451 } = place(Point {
452 x: image.x,
453 y: image.y,
454 });
455 image.width = length(image.width);
456 image.height = length(image.height);
457 if let Some(clip) = &mut image.clip {
458 clip.map_places_with(place, length);
459 }
460 }
461 Self::Group(group) => {
462 for item in &mut group.items {
463 item.map_places_with(place, length);
464 }
465 if let Some(clip) = &mut group.clip {
466 map_points(&mut clip.commands, place);
467 }
468 }
469 }
470 }
471}
472
473fn map_points(commands: &mut [PathCommand], place: &mut dyn FnMut(Point) -> Point) {
475 for point in commands.iter_mut().flat_map(PathCommand::points_mut) {
476 *point = place(*point);
477 }
478}
479
480impl Clip {
481 fn map_places_with(
482 &mut self,
483 place: &mut dyn FnMut(Point) -> Point,
484 length: &mut dyn FnMut(Length) -> Length,
485 ) {
486 Point {
487 x: self.x,
488 y: self.y,
489 } = place(Point {
490 x: self.x,
491 y: self.y,
492 });
493 self.width = length(self.width);
494 self.height = length(self.height);
495 }
496}
497
498#[derive(Clone, Debug, PartialEq, Eq)]
500pub struct GlyphRun {
501 pub font: FontId,
503 pub size: Length,
505 pub color: Rgb,
507 pub text: String,
509 pub glyphs: Vec<Glyph>,
511 pub outline: Option<Outline>,
513 pub filled: bool,
517 pub effect: bool,
520 pub turn: Option<Turn>,
525}
526
527impl GlyphRun {
528 #[must_use]
532 pub fn glyph_range(&self, glyph: &Glyph) -> Option<Range<usize>> {
533 let start = usize::try_from(glyph.text_start).ok()?;
534 let end = usize::try_from(glyph.text_end).ok()?;
535 self.text.get(start..end).map(|_| start..end)
536 }
537
538 #[must_use]
540 pub fn glyph_text(&self, glyph: &Glyph) -> Option<&str> {
541 self.text.get(self.glyph_range(glyph)?)
542 }
543}
544
545#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
547pub struct Outline {
548 pub width: Length,
550 pub color: Rgb,
552 pub join: Join,
554}
555
556#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
558pub enum Join {
559 Round,
561 Miter,
564}
565
566#[derive(Clone, Debug, PartialEq, Eq)]
568pub struct Glyph {
569 pub id: u32,
571 pub x: Length,
573 pub y: Length,
575 pub text_start: u32,
577 pub text_end: u32,
579}
580
581#[derive(Clone, Debug, PartialEq, Eq)]
583pub struct Rect {
584 pub x: Length,
586 pub y: Length,
588 pub width: Length,
590 pub height: Length,
592 pub color: Rgb,
594}
595
596#[derive(Clone, Debug, PartialEq, Eq)]
602pub struct PathItem {
603 pub commands: Vec<PathCommand>,
605 pub color: Rgb,
607 pub fill_rule: FillRule,
609}
610
611#[derive(Clone, Debug, PartialEq, Eq)]
618#[non_exhaustive]
619pub struct GradientItem {
620 pub commands: Vec<PathCommand>,
622 pub fill_rule: FillRule,
624 pub start: Point,
626 pub end: Point,
628 pub stops: Vec<GradientStop>,
631}
632
633impl GradientItem {
634 #[must_use]
637 pub fn new(
638 commands: Vec<PathCommand>,
639 fill_rule: FillRule,
640 axis: (Point, Point),
641 stops: Vec<GradientStop>,
642 ) -> Self {
643 Self {
644 commands,
645 fill_rule,
646 start: axis.0,
647 end: axis.1,
648 stops,
649 }
650 }
651
652 #[must_use]
658 pub fn color_at(&self, place: i64) -> Rgb {
659 let (Some(first), Some(last)) = (self.stops.first(), self.stops.last()) else {
660 return Rgb::BLACK;
661 };
662 if place < i64::from(first.place) {
663 return first.color;
664 }
665 let after = self
666 .stops
667 .partition_point(|stop| i64::from(stop.place) <= place);
668 let (Some(before), Some(next)) = (
669 after.checked_sub(1).and_then(|at| self.stops.get(at)),
670 self.stops.get(after),
671 ) else {
672 return last.color;
673 };
674 let span = i64::from(next.place) - i64::from(before.place);
675 let along = place - i64::from(before.place);
676 let mix = |from: u8, to: u8| {
677 let from = i64::from(from);
678 let value = from + div_round(along * (i64::from(to) - from), span);
679 u8::try_from(value.clamp(0, 255)).unwrap_or(u8::MAX)
680 };
681 Rgb {
682 r: mix(before.color.r, next.color.r),
683 g: mix(before.color.g, next.color.g),
684 b: mix(before.color.b, next.color.b),
685 }
686 }
687}
688
689#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
691#[non_exhaustive]
692pub struct GradientStop {
693 pub place: u32,
696 pub color: Rgb,
698}
699
700impl GradientStop {
701 pub const START: u32 = 0;
703 pub const END: u32 = 1_000_000;
705
706 #[must_use]
708 pub const fn new(place: u32, color: Rgb) -> Self {
709 Self { place, color }
710 }
711}
712
713#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
716pub enum PathCommand {
717 MoveTo(Point),
719 LineTo(Point),
721 QuadTo(Point, Point),
723 CubicTo(Point, Point, Point),
725 Close,
727}
728
729impl PathCommand {
730 pub fn points_mut(&mut self) -> impl Iterator<Item = &mut Point> {
733 let points = match self {
734 Self::MoveTo(a) | Self::LineTo(a) => [Some(a), None, None],
735 Self::QuadTo(a, b) => [Some(a), Some(b), None],
736 Self::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
737 Self::Close => [None, None, None],
738 };
739 points.into_iter().flatten()
740 }
741
742 pub fn points(&self) -> impl Iterator<Item = Point> {
744 let points = match *self {
745 Self::MoveTo(a) | Self::LineTo(a) => [Some(a), None, None],
746 Self::QuadTo(a, b) => [Some(a), Some(b), None],
747 Self::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
748 Self::Close => [None, None, None],
749 };
750 points.into_iter().flatten()
751 }
752}
753
754pub const THINNEST_FILL: Length = Length::from_units(100);
759
760#[must_use]
763pub const fn fill_shows(across: Length, down: Length) -> bool {
764 across.units().abs() > THINNEST_FILL.units() && down.units().abs() > THINNEST_FILL.units()
765}
766
767#[must_use]
770pub fn path_shows(commands: &[PathCommand]) -> bool {
771 let drawn = fill_commands(commands);
772 let mut points = drawn.iter().flat_map(PathCommand::points);
773 let Some(first) = points.next() else {
774 return false;
775 };
776 let (low, high) = points.fold((first, first), |(low, high), p| {
777 (
778 Point {
779 x: low.x.min(p.x),
780 y: low.y.min(p.y),
781 },
782 Point {
783 x: high.x.max(p.x),
784 y: high.y.max(p.y),
785 },
786 )
787 });
788 fill_shows(high.x - low.x, high.y - low.y)
789}
790
791#[must_use]
798pub fn fill_commands(commands: &[PathCommand]) -> Vec<PathCommand> {
799 let mut current: Option<Point> = None;
800 let mut start: Option<Point> = None;
801 commands
802 .iter()
803 .filter_map(|&command| match command {
804 PathCommand::MoveTo(p) => {
805 (current, start) = (Some(p), Some(p));
806 Some(command)
807 }
808 PathCommand::LineTo(p) => {
809 let empty = current == Some(p);
810 current = Some(p);
811 (!empty).then_some(command)
812 }
813 PathCommand::CubicTo(_, _, p) => {
814 current = Some(p);
815 Some(command)
816 }
817 PathCommand::QuadTo(control, end) => {
818 let from = current.unwrap_or(control);
819 current = Some(end);
820 let [_, first, second, _] = stroke::quad_as_cubic(from, control, end);
821 Some(PathCommand::CubicTo(first, second, end))
822 }
823 PathCommand::Close => {
824 current = start;
825 Some(command)
826 }
827 })
828 .collect()
829}
830
831#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
833pub struct Point {
834 pub x: Length,
836 pub y: Length,
838}
839
840#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
842pub enum FillRule {
843 #[default]
846 NonZero,
847 EvenOdd,
849}
850
851#[derive(Clone, Debug, PartialEq, Eq)]
858pub struct ImageItem {
859 pub x: Length,
861 pub y: Length,
863 pub width: Length,
865 pub height: Length,
867 pub clip: Option<Clip>,
869 pub turn: Option<Turn>,
872 pub image: Image,
874}
875
876#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
881pub struct Turn {
882 pub xx: i32,
884 pub yx: i32,
886 pub xy: i32,
888 pub yy: i32,
890}
891
892impl Turn {
893 pub const SCALE: i32 = 1_000_000;
895}
896
897impl ImageItem {
898 #[must_use]
902 pub fn shown(&self) -> Option<Clip> {
903 let clip = self.clip?;
904 let end = |start: Length, length: Length| start.units().checked_add(length.units());
905 let left = clip.x.max(self.x).units();
906 let top = clip.y.max(self.y).units();
907 let right = end(clip.x, clip.width)?.min(end(self.x, self.width)?);
908 let bottom = end(clip.y, clip.height)?.min(end(self.y, self.height)?);
909 (left < right && top < bottom).then(|| Clip {
910 x: Length::from_units(left),
911 y: Length::from_units(top),
912 width: Length::from_units(right - left),
913 height: Length::from_units(bottom - top),
914 })
915 }
916}
917
918#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
920pub struct Clip {
921 pub x: Length,
923 pub y: Length,
925 pub width: Length,
927 pub height: Length,
929}
930
931#[derive(Clone, Debug, PartialEq, Eq, Hash)]
934pub struct Image {
935 pub format: ImageFormat,
937 pub data: ImageData,
939 pub opacity: Opacity,
941 pub color: ImageColor,
943 pub inks: InkConversion,
945}
946
947#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
950pub struct Opacity(i64);
951
952impl Opacity {
953 pub const FULL: Self = Self(f_office_units::scale::DRAWING_WHOLE);
955
956 #[must_use]
959 pub const fn clamped(share: i64) -> Self {
960 let whole = f_office_units::scale::DRAWING_WHOLE;
961 Self(if share < 0 {
962 0
963 } else if share > whole {
964 whole
965 } else {
966 share
967 })
968 }
969
970 #[must_use]
973 pub const fn times(self, other: Self) -> Self {
974 Self(div_round(
975 self.0 * other.0,
976 f_office_units::scale::DRAWING_WHOLE,
977 ))
978 }
979
980 #[must_use]
982 pub const fn share(self) -> i64 {
983 self.0
984 }
985}
986
987impl Image {
988 #[must_use]
990 pub fn new(data: impl Into<Arc<[u8]>>) -> Self {
991 let data = data.into();
992 Self {
993 format: ImageFormat::detect(&data),
994 data: ImageData::Inline(data),
995 opacity: Opacity::FULL,
996 color: ImageColor::Original,
997 inks: InkConversion::EmbeddedProfile,
998 }
999 }
1000
1001 #[must_use]
1003 pub const fn from_ref(format: ImageFormat, image_ref: ImageRef) -> Self {
1004 Self {
1005 format,
1006 data: ImageData::Lazy(image_ref),
1007 opacity: Opacity::FULL,
1008 color: ImageColor::Original,
1009 inks: InkConversion::EmbeddedProfile,
1010 }
1011 }
1012
1013 #[must_use]
1016 pub fn load_bytes(&self) -> Option<Arc<[u8]>> {
1017 self.data.bytes()
1018 }
1019
1020 #[must_use]
1022 pub fn load_bytes_with_format(&self) -> Option<(Arc<[u8]>, ImageFormat)> {
1023 self.data.bytes_with_format(self.format)
1024 }
1025
1026 #[must_use]
1029 pub fn load_prefix(&self, max_bytes: usize) -> Option<Arc<[u8]>> {
1030 self.data.prefix(max_bytes)
1031 }
1032
1033 #[must_use]
1035 pub fn cache_key(&self) -> ImageKey {
1036 self.data.key()
1037 }
1038}
1039
1040#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1044pub enum InkConversion {
1045 #[default]
1049 EmbeddedProfile,
1050 InkTable,
1053}
1054
1055pub const MAX_DECODED_BYTES: u64 = 256 << 20;
1062
1063pub const MAX_DECODED_BYTES_TO_WRITE_AGAIN: u64 = 512 << 20;
1069
1070#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1072pub enum ImageFormat {
1073 Png,
1075 Jpeg,
1077 Gif,
1079 Bmp,
1081 Tiff,
1083 Emf,
1085 Wmf,
1087 EffectPicture,
1092 Unknown,
1094}
1095
1096#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1098#[non_exhaustive]
1099pub enum ImageFault {
1100 Format,
1102 Data,
1104 Limit,
1108}
1109
1110impl std::fmt::Display for ImageFault {
1111 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1112 f.write_str(match self {
1113 Self::Format => "the output draws no image of this format",
1114 Self::Data => "its data does not decode",
1115 Self::Limit => "it is larger than the output's limits",
1116 })
1117 }
1118}
1119
1120impl std::fmt::Display for ImageFormat {
1121 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1122 f.write_str(match self {
1123 Self::Png => "PNG",
1124 Self::Jpeg => "JPEG",
1125 Self::Gif => "GIF",
1126 Self::Bmp => "BMP",
1127 Self::Tiff => "TIFF",
1128 Self::Emf => "EMF",
1129 Self::Wmf => "WMF",
1130 Self::EffectPicture => "effect picture",
1131 Self::Unknown => "unknown",
1132 })
1133 }
1134}
1135
1136impl ImageFormat {
1137 #[must_use]
1139 pub fn detect(data: &[u8]) -> Self {
1140 const EMR_HEADER: [u8; 4] = [1, 0, 0, 0];
1142 const EMF_SIGNATURE: &[u8] = b" EMF";
1144 let starts = |signature: &[u8]| data.starts_with(signature);
1145 if starts(b"\x89PNG\r\n\x1a\n") {
1146 Self::Png
1147 } else if starts(&[0xFF, 0xD8, 0xFF]) {
1148 Self::Jpeg
1149 } else if starts(b"GIF87a") || starts(b"GIF89a") {
1150 Self::Gif
1151 } else if starts(b"BM") {
1152 Self::Bmp
1153 } else if starts(b"II*\0") || starts(b"MM\0*") {
1154 Self::Tiff
1155 } else if starts(&EMR_HEADER) && data.get(40..44) == Some(EMF_SIGNATURE) {
1156 Self::Emf
1157 } else if is_wmf(data) {
1158 Self::Wmf
1159 } else {
1160 Self::Unknown
1161 }
1162 }
1163}
1164
1165fn is_wmf(data: &[u8]) -> bool {
1168 data.starts_with(&[0xD7, 0xCD, 0xC6, 0x9A])
1169 || data.starts_with(&[1, 0, 9, 0])
1170 || data.starts_with(&[2, 0, 9, 0])
1171}
1172
1173#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1175pub struct Rgb {
1176 pub r: u8,
1178 pub g: u8,
1180 pub b: u8,
1182}
1183
1184impl Rgb {
1185 pub const BLACK: Self = Self { r: 0, g: 0, b: 0 };
1187
1188 pub const WHITE: Self = Self {
1190 r: u8::MAX,
1191 g: u8::MAX,
1192 b: u8::MAX,
1193 };
1194
1195 #[must_use]
1200 pub fn from_hex(text: &str) -> Option<Self> {
1201 let digits = text.as_bytes();
1202 if digits.len() != 6 || !digits.iter().all(u8::is_ascii_hexdigit) {
1203 return None;
1204 }
1205 let value = u32::from_str_radix(text, 16).ok()?;
1206 let [_, r, g, b] = value.to_be_bytes();
1207 Some(Self { r, g, b })
1208 }
1209}
1210
1211#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1214pub enum Offset {
1215 #[default]
1217 None,
1218 Share {
1221 share: i64,
1223 bias: i64,
1225 step: i64,
1227 },
1228 Page {
1234 steps: Fraction,
1236 parts: i64,
1238 per_inch: i64,
1240 product: OffsetProduct,
1242 },
1243}
1244
1245#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1249pub enum OffsetProduct {
1250 #[default]
1252 Exact,
1253 Binary32 {
1260 dots_per_inch: i64,
1262 },
1263}
1264
1265#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1270pub enum WriterOffset {
1271 EveryPage(Offset),
1273 Sizes(&'static PageSizes),
1276}
1277
1278impl WriterOffset {
1279 pub const NONE: Self = Self::EveryPage(Offset::None);
1281
1282 #[must_use]
1286 pub fn on_page(self, width: i64, height: i64, orientation: Orientation) -> (Offset, Offset) {
1287 match self {
1288 Self::Sizes(sizes) => sizes.offsets(width, height, orientation),
1289 Self::EveryPage(offset) => (offset, offset),
1290 }
1291 }
1292}
1293
1294pub const STEP_PARTS: i64 = 100_000;
1297
1298impl Offset {
1299 #[must_use]
1302 pub fn of(self, x: i64, side: i64) -> i64 {
1303 self.of_in(x, side, 1)
1304 }
1305
1306 #[must_use]
1314 pub(crate) fn written_place(self, x: i64, side: i64) -> i64 {
1315 if let Self::Page {
1316 steps,
1317 parts,
1318 per_inch,
1319 product: OffsetProduct::Binary32 { dots_per_inch },
1320 } = self
1321 && let Some(place) =
1322 binary32_written_place(x, side, (steps, parts, per_inch), dots_per_inch)
1323 {
1324 return place;
1325 }
1326 x + self.of(x, side)
1327 }
1328
1329 #[must_use]
1333 pub fn of_in(self, x: i64, side: i64, fraction: i64) -> i64 {
1334 let fraction = i128::from(fraction.max(1));
1335 match self {
1336 Self::None => 0,
1337 Self::Share { share, bias, step } => {
1338 if share <= 0 || step <= 0 {
1339 return 0;
1340 }
1341 let steps = div_round_i128(
1342 i128::from(x) + i128::from(bias) * i128::from(share),
1343 i128::from(step) * i128::from(share),
1344 );
1345 i64::try_from(steps * i128::from(step) * fraction).unwrap_or(0)
1346 }
1347 Self::Page {
1348 steps,
1349 parts,
1350 per_inch,
1351 product,
1352 } => {
1353 if side <= 0 || parts <= 0 || per_inch <= 0 || steps.1 <= 0 {
1354 return 0;
1355 }
1356 if let OffsetProduct::Binary32 { dots_per_inch } = product {
1357 return binary32_page_offset(
1358 x,
1359 side,
1360 (steps, parts, per_inch),
1361 (dots_per_inch, fraction),
1362 )
1363 .unwrap_or(0);
1364 }
1365 let parts = i128::from(parts);
1367 let product = div_round_i128(
1368 i128::from(x) * i128::from(steps.0) * parts,
1369 i128::from(steps.1) * i128::from(side),
1370 );
1371 let n = div_round_i128(product, parts);
1372 let inch = i128::from(Length::UNITS_PER_INCH);
1373 i64::try_from(div_round_i128(n * inch * fraction, i128::from(per_inch)))
1374 .unwrap_or(0)
1375 }
1376 }
1377 }
1378}
1379
1380fn binary32_page_offset(
1385 x: i64,
1386 side: i64,
1387 (steps, parts, per_inch): (Fraction, i64, i64),
1388 (dots_per_inch, fraction): (i64, i128),
1389) -> Option<i64> {
1390 if dots_per_inch <= 0 {
1391 return None;
1392 }
1393 let inch = i128::from(Length::UNITS_PER_INCH);
1394 let dpi = i128::from(dots_per_inch);
1395 let dots = i64::try_from(div_round_i128(i128::from(side) * dpi, inch)).ok()?;
1396 let place = i64::try_from(div_round_i128(i128::from(x) * dpi, inch)).ok()?;
1397 let entry = page_entry(dots, (steps, parts, per_inch), dpi)?;
1398 let written_parts = i128::from(entry.times(place).whole(false));
1400 let written = div_round_i128(written_parts, parts.into());
1401 let difference = written
1404 .checked_mul(dpi)?
1405 .checked_sub(i128::from(place).checked_mul(per_inch.into())?)?;
1406 i64::try_from(div_round_i128(
1407 difference.checked_mul(inch)?.checked_mul(fraction)?,
1408 i128::from(per_inch).checked_mul(dpi)?,
1409 ))
1410 .ok()
1411}
1412
1413fn binary32_written_place(
1418 x: i64,
1419 side: i64,
1420 (steps, parts, per_inch): (Fraction, i64, i64),
1421 dots_per_inch: i64,
1422) -> Option<i64> {
1423 if dots_per_inch <= 0 || parts <= 0 || per_inch <= 0 {
1424 return None;
1425 }
1426 let inch = i128::from(Length::UNITS_PER_INCH);
1427 let dpi = i128::from(dots_per_inch);
1428 let dots = i64::try_from(div_round_i128(i128::from(side) * dpi, inch)).ok()?;
1429 let entry = page_entry(dots, (steps, parts, per_inch), dpi)?;
1430 let (mantissa, exponent) = (i128::from(entry.mantissa()), entry.exponent());
1432 let mut numerator = mantissa.checked_mul(i128::from(x))?.checked_mul(dpi)?;
1433 let mut denominator = inch;
1434 let shift = exponent.unsigned_abs();
1435 if exponent >= 0 {
1436 numerator = numerator.checked_mul(1_i128.checked_shl(shift)?)?;
1437 } else {
1438 denominator = denominator.checked_mul(1_i128.checked_shl(shift)?)?;
1439 }
1440 let product = Binary32::nearest(numerator, denominator);
1441 let written_parts = i128::from(product.whole(false));
1442 let written = div_round_i128(written_parts, parts.into());
1443 i64::try_from(div_round_i128(
1444 written.checked_mul(inch)?,
1445 i128::from(per_inch),
1446 ))
1447 .ok()
1448}
1449
1450fn page_entry(
1454 dots: i64,
1455 (steps, parts, per_inch): (Fraction, i64, i64),
1456 dpi: i128,
1457) -> Option<Binary32> {
1458 if dots <= 0 {
1459 return None;
1460 }
1461 let (gain, over) = (i128::from(steps.0), i128::from(steps.1));
1463 let numerator = i128::from(per_inch)
1464 .checked_mul(dots.into())?
1465 .checked_mul(over)?
1466 .checked_add(gain.checked_mul(dpi)?)?
1467 .checked_mul(parts.into())?;
1468 let denominator = dpi.checked_mul(dots.into())?.checked_mul(over)?;
1469 Some(Binary32::nearest(numerator, denominator))
1470}
1471
1472fn offset_rect(rect: &mut Rect, across: Offset, width: Length) {
1475 let right = rect.x.units() + rect.width.units();
1476 let left = rect.x.units() + across.of(rect.x.units(), width.units());
1477 let right = right + across.of(right, width.units());
1478 rect.x = Length::from_units(left);
1479 rect.width = Length::from_units(right - left);
1480}
1481
1482pub type Fraction = (i64, i64);
1484
1485pub const STRETCH_HEIGHTS: usize = 16;
1488
1489#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1494pub struct Writer {
1495 page_step: i64,
1496 vertical_stretch: i64,
1497 glyph_stretch_step: Option<Length>,
1498 stretch_offset: Fraction,
1499 stretch_factors: [(i64, Fraction); STRETCH_HEIGHTS],
1500 stretch_heights: usize,
1501 digits: Option<NonZeroU32>,
1502 least_decimals: u32,
1503 rectangle_steps: Option<NonZeroU32>,
1504 baseline_steps: Option<NonZeroU32>,
1505 picture_digits: Option<NonZeroU32>,
1506 horizontal_offset: WriterOffset,
1507 vertical_offset: WriterOffset,
1508 jpeg_quality: Option<JpegQuality>,
1509 jpeg_share: Option<JpegShare>,
1510 jpeg_sample: Option<JpegSample>,
1511 picture_density: Option<PictureDensity>,
1512 palette_density: Option<PaletteDensity>,
1513 picture_crop: PictureCrop,
1514 alpha_mix: AlphaMix,
1515 linear_limit: LinearLimit,
1516}
1517
1518#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1521pub enum AlphaMix {
1522 Plain,
1524 Weighted,
1529}
1530
1531#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1534pub enum PictureCrop {
1535 WholeFileUnderClip,
1537 VisiblePart,
1543 VisiblePartAtScale,
1550}
1551
1552impl PictureCrop {
1553 #[must_use]
1555 pub const fn keeps_visible_part(self) -> bool {
1556 !matches!(self, Self::WholeFileUnderClip)
1557 }
1558}
1559
1560#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1563pub struct JpegQuality(u8);
1564
1565impl JpegQuality {
1566 #[must_use]
1568 pub const fn new(quality: u8) -> Option<Self> {
1569 if quality >= 1 && quality <= 100 {
1570 Some(Self(quality))
1571 } else {
1572 None
1573 }
1574 }
1575
1576 #[must_use]
1578 pub const fn get(self) -> u8 {
1579 self.0
1580 }
1581}
1582
1583#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1586pub struct JpegShare(u16);
1587
1588impl JpegShare {
1589 #[must_use]
1591 pub const fn new(thousandths: u16) -> Option<Self> {
1592 if thousandths >= 1 && thousandths <= 1000 {
1593 Some(Self(thousandths))
1594 } else {
1595 None
1596 }
1597 }
1598
1599 #[must_use]
1601 pub const fn thousandths(self) -> u16 {
1602 self.0
1603 }
1604
1605 #[must_use]
1608 pub fn takes(self, jpeg: usize, flate: usize) -> bool {
1609 let (Ok(jpeg), Ok(flate)) = (u128::try_from(jpeg), u128::try_from(flate)) else {
1610 return false;
1611 };
1612 jpeg * 1000 < u128::from(self.0) * flate
1613 }
1614}
1615
1616#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1624pub struct JpegSample {
1625 share: u16,
1626 floor: u32,
1627 whole: u16,
1628}
1629
1630impl JpegSample {
1631 pub const STRIPS: usize = 16;
1633 pub const ROWS: usize = 8;
1635
1636 #[must_use]
1639 pub const fn new(share: u16, floor: u32, whole: u16) -> Option<Self> {
1640 if share >= 1 && share <= 1000 && whole >= 1 && whole <= 1000 && floor >= 1 {
1641 Some(Self {
1642 share,
1643 floor,
1644 whole,
1645 })
1646 } else {
1647 None
1648 }
1649 }
1650
1651 pub fn strips(height: usize) -> impl Iterator<Item = std::ops::Range<usize>> {
1656 (0..Self::STRIPS).map(move |k| {
1657 let start = k.saturating_mul(height) / Self::STRIPS;
1658 start..start.saturating_add(Self::ROWS).min(height)
1659 })
1660 }
1661
1662 #[must_use]
1665 pub fn takes(self, sample: usize, height: usize, (flate, raw): (usize, usize)) -> bool {
1666 let (Ok(sample), Ok(height), Ok(flate), Ok(raw), Ok(rows)) = (
1667 u128::try_from(sample),
1668 u128::try_from(height),
1669 u128::try_from(flate),
1670 u128::try_from(raw),
1671 u128::try_from(Self::STRIPS * Self::ROWS),
1672 ) else {
1673 return false;
1674 };
1675 let estimate = sample * height;
1676 flate * 1000 >= u128::from(self.whole) * raw
1677 || (estimate * 1000 >= u128::from(self.share) * flate * rows
1678 && estimate >= u128::from(self.floor) * rows)
1679 }
1680}
1681
1682#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1686pub struct PictureDensity {
1687 pub limit_ppi: NonZeroU32,
1689 pub ppi: NonZeroU32,
1691}
1692
1693#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1698pub enum PaletteClass {
1699 OneBit,
1701 FourBitColor,
1703 EightBitColor,
1705}
1706
1707#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1714pub struct PaletteDensity {
1715 pub one_bit_limit_ppi: NonZeroU32,
1717 pub one_bit_ppi: NonZeroU32,
1720 pub four_bits_limit_ppi: NonZeroU32,
1723 pub eight_bits_limit_ppi: NonZeroU32,
1726}
1727
1728#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1730pub enum Resampler {
1731 Filter(LinearLimit),
1734 CentrePixel,
1736}
1737
1738#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1741pub enum LinearLimit {
1742 Pixels(NonZeroU32),
1744 Side(NonZeroU32),
1746}
1747
1748impl LinearLimit {
1749 #[must_use]
1752 pub fn takes_linear(self, (width, height): (usize, usize)) -> bool {
1753 let most = |count: NonZeroU32| usize::try_from(count.get()).unwrap_or(usize::MAX);
1754 match self {
1755 Self::Pixels(count) => width.saturating_mul(height) <= most(count),
1756 Self::Side(count) => width.max(height) <= most(count),
1757 }
1758 }
1759}
1760
1761const DEFAULT_LINEAR_LIMIT: LinearLimit = match NonZeroU32::new(1 << 17) {
1763 Some(count) => LinearLimit::Pixels(count),
1764 None => LinearLimit::Pixels(NonZeroU32::MIN),
1765};
1766
1767impl Writer {
1768 #[must_use]
1771 pub const fn new(page_step: Length) -> Option<Self> {
1772 if page_step.units() > 0 {
1773 Some(Self {
1774 page_step: page_step.units(),
1775 vertical_stretch: 0,
1776 glyph_stretch_step: None,
1777 stretch_offset: (0, 1),
1778 stretch_factors: [(0, (1, 1)); STRETCH_HEIGHTS],
1779 stretch_heights: 0,
1780 digits: None,
1781 least_decimals: 0,
1782 rectangle_steps: None,
1783 baseline_steps: None,
1784 picture_digits: None,
1785 horizontal_offset: WriterOffset::NONE,
1786 vertical_offset: WriterOffset::NONE,
1787 jpeg_quality: None,
1788 jpeg_share: None,
1789 jpeg_sample: None,
1790 picture_density: None,
1791 palette_density: None,
1792 picture_crop: PictureCrop::WholeFileUnderClip,
1793 alpha_mix: AlphaMix::Plain,
1794 linear_limit: DEFAULT_LINEAR_LIMIT,
1795 })
1796 } else {
1797 None
1798 }
1799 }
1800
1801 #[must_use]
1806 pub const fn with_jpeg_quality(self, quality: Option<JpegQuality>) -> Self {
1807 Self {
1808 jpeg_quality: quality,
1809 ..self
1810 }
1811 }
1812
1813 #[must_use]
1816 pub const fn jpeg_quality(&self) -> Option<JpegQuality> {
1817 self.jpeg_quality
1818 }
1819
1820 #[must_use]
1825 pub const fn with_jpeg_share(self, share: Option<JpegShare>) -> Self {
1826 Self {
1827 jpeg_share: share,
1828 ..self
1829 }
1830 }
1831
1832 #[must_use]
1835 pub const fn jpeg_share(&self) -> Option<JpegShare> {
1836 self.jpeg_share
1837 }
1838
1839 #[must_use]
1843 pub const fn with_jpeg_sample(self, sample: Option<JpegSample>) -> Self {
1844 Self {
1845 jpeg_sample: sample,
1846 ..self
1847 }
1848 }
1849
1850 #[must_use]
1853 pub const fn jpeg_sample(&self) -> Option<JpegSample> {
1854 self.jpeg_sample
1855 }
1856
1857 #[must_use]
1862 pub const fn with_picture_density(self, density: Option<PictureDensity>) -> Self {
1863 Self {
1864 picture_density: density,
1865 ..self
1866 }
1867 }
1868
1869 #[must_use]
1874 pub const fn with_palette_density(self, density: Option<PaletteDensity>) -> Self {
1875 Self {
1876 palette_density: density,
1877 ..self
1878 }
1879 }
1880
1881 #[must_use]
1883 pub const fn with_picture_crop(self, crop: PictureCrop) -> Self {
1884 Self {
1885 picture_crop: crop,
1886 ..self
1887 }
1888 }
1889
1890 #[must_use]
1893 pub const fn picture_crop(&self) -> PictureCrop {
1894 self.picture_crop
1895 }
1896
1897 #[must_use]
1900 pub const fn with_alpha_mix(self, mix: AlphaMix) -> Self {
1901 Self {
1902 alpha_mix: mix,
1903 ..self
1904 }
1905 }
1906
1907 #[must_use]
1911 pub const fn alpha_mix(&self) -> AlphaMix {
1912 self.alpha_mix
1913 }
1914
1915 #[must_use]
1919 pub const fn with_linear_limit(self, limit: LinearLimit) -> Self {
1920 Self {
1921 linear_limit: limit,
1922 ..self
1923 }
1924 }
1925
1926 #[must_use]
1929 pub const fn digits(&self) -> Option<NonZeroU32> {
1930 self.digits
1931 }
1932
1933 #[must_use]
1936 pub const fn least_decimals(&self) -> u32 {
1937 self.least_decimals
1938 }
1939
1940 #[must_use]
1943 pub const fn rectangle_steps(&self) -> Option<NonZeroU32> {
1944 self.rectangle_steps
1945 }
1946
1947 #[must_use]
1950 pub const fn baseline_steps(&self) -> Option<NonZeroU32> {
1951 self.baseline_steps
1952 }
1953
1954 #[must_use]
1966 pub fn resampled_size(
1967 &self,
1968 pixels: (usize, usize),
1969 size: (Length, Length),
1970 palette: Option<PaletteClass>,
1971 ) -> Option<((usize, usize), Resampler)> {
1972 let density = self.picture_density?;
1973 let filter = Resampler::Filter(self.linear_limit);
1974 let (limit_ppi, ppi, resampler) = match (self.palette_density, palette) {
1975 (Some(palettes), Some(PaletteClass::OneBit)) => (
1976 palettes.one_bit_limit_ppi,
1977 palettes.one_bit_ppi,
1978 Resampler::CentrePixel,
1979 ),
1980 (Some(palettes), Some(PaletteClass::FourBitColor)) => {
1981 (palettes.four_bits_limit_ppi, density.ppi, filter)
1982 }
1983 (Some(palettes), Some(PaletteClass::EightBitColor)) => {
1984 (palettes.eight_bits_limit_ppi, density.ppi, filter)
1985 }
1986 _ => (density.limit_ppi, density.ppi, filter),
1987 };
1988 let inch = i128::from(Length::UNITS_PER_INCH);
1989 let written = |count: usize, length: Length| {
1993 let units = i128::from(length.units());
1994 let pixels = i128::try_from(count).unwrap_or(i128::MAX);
1995 if pixels * inch < i128::from(limit_ppi.get()) * units {
1996 return count;
1997 }
1998 let most = (i128::from(ppi.get()) * units - 1) / inch;
1999 usize::try_from(most).map_or(count, |most| most.min(count))
2000 };
2001 let (width, height) = size;
2002 if width.units() <= 0 || height.units() <= 0 {
2003 return None;
2004 }
2005 let new = (written(pixels.0, width), written(pixels.1, height));
2006 (new != pixels && new.0 > 0 && new.1 > 0).then_some((new, resampler))
2007 }
2008
2009 #[must_use]
2013 pub const fn with_vertical_stretch(self, steps: i64) -> Self {
2014 Self {
2015 vertical_stretch: steps,
2016 ..self
2017 }
2018 }
2019
2020 #[must_use]
2025 pub const fn with_glyph_stretch_step(self, step: Option<Length>) -> Option<Self> {
2026 match step {
2027 Some(step) if step.units() <= 0 => None,
2028 Some(step) => Some(Self {
2029 glyph_stretch_step: Some(step),
2030 ..self
2031 }),
2032 None => Some(Self {
2033 glyph_stretch_step: None,
2034 ..self
2035 }),
2036 }
2037 }
2038
2039 #[must_use]
2046 pub fn with_stretch_factors(
2047 self,
2048 offset: Fraction,
2049 factors: &[(Length, Fraction)],
2050 ) -> Option<Self> {
2051 if factors.len() > STRETCH_HEIGHTS
2052 || offset.1 <= 0
2053 || factors.iter().any(|(_, factor)| factor.1 <= 0)
2054 {
2055 return None;
2056 }
2057 let mut table = [(0, (1, 1)); STRETCH_HEIGHTS];
2058 for (slot, (height, factor)) in table.iter_mut().zip(factors) {
2059 *slot = (height.units(), *factor);
2060 }
2061 Some(Self {
2062 stretch_offset: offset,
2063 stretch_factors: table,
2064 stretch_heights: factors.len(),
2065 ..self
2066 })
2067 }
2068
2069 fn stretch_factor(&self, height: Length) -> (Fraction, Fraction) {
2073 self.stretch_factors
2074 .iter()
2075 .take(self.stretch_heights)
2076 .find(|(written, _)| *written == height.units())
2077 .map_or(((1, 1), (0, 1)), |(_, factor)| {
2078 (*factor, self.stretch_offset)
2079 })
2080 }
2081
2082 #[must_use]
2087 pub const fn with_digits(self, digits: Option<NonZeroU32>) -> Self {
2088 Self { digits, ..self }
2089 }
2090
2091 #[must_use]
2097 pub const fn with_least_decimals(self, decimals: u32) -> Self {
2098 Self {
2099 least_decimals: decimals,
2100 ..self
2101 }
2102 }
2103
2104 #[must_use]
2111 pub const fn with_rectangle_steps(self, per_inch: Option<NonZeroU32>) -> Self {
2112 Self {
2113 rectangle_steps: per_inch,
2114 ..self
2115 }
2116 }
2117
2118 #[must_use]
2124 pub const fn with_baseline_steps(self, per_inch: Option<NonZeroU32>) -> Self {
2125 Self {
2126 baseline_steps: per_inch,
2127 ..self
2128 }
2129 }
2130
2131 #[must_use]
2136 pub const fn with_picture_digits(self, digits: Option<NonZeroU32>) -> Self {
2137 Self {
2138 picture_digits: digits,
2139 ..self
2140 }
2141 }
2142
2143 pub fn place_pictures(&self, list: &mut DisplayList) {
2149 let Some(digits) = self.picture_digits else {
2150 return;
2151 };
2152 for page in &mut list.pages {
2153 for item in &mut page.items {
2154 if let Item::Image(image) = item
2155 && image.turn.is_none()
2156 {
2157 (image.x, image.y, image.width, image.height) = written_box(
2158 page.height,
2159 (image.x, image.y, image.width, image.height),
2160 (digits.get(), 0),
2161 );
2162 }
2163 }
2164 }
2165 }
2166
2167 #[must_use]
2171 pub const fn with_horizontal_offset(self, offset: WriterOffset) -> Self {
2172 Self {
2173 horizontal_offset: offset,
2174 ..self
2175 }
2176 }
2177
2178 #[must_use]
2182 pub const fn with_vertical_offset(self, offset: WriterOffset) -> Self {
2183 Self {
2184 vertical_offset: offset,
2185 ..self
2186 }
2187 }
2188
2189 fn page_offsets(
2193 &self,
2194 width: Length,
2195 height: Length,
2196 orientation: Orientation,
2197 ) -> (Offset, Offset) {
2198 let (width, height) = (width.units(), height.units());
2199 (
2200 self.horizontal_offset.on_page(width, height, orientation).0,
2201 self.vertical_offset.on_page(width, height, orientation).1,
2202 )
2203 }
2204
2205 #[cfg(feature = "development")]
2208 #[must_use]
2209 pub fn development_page_offsets(
2210 &self,
2211 width: Length,
2212 height: Length,
2213 orientation: Orientation,
2214 ) -> (Offset, Offset) {
2215 self.page_offsets(width, height, orientation)
2216 }
2217
2218 #[must_use]
2222 pub const fn page_side(&self, length: Length) -> Length {
2223 let step = self.page_step;
2224 Length::from_units(div_round(length.units(), step) * step)
2225 }
2226
2227 pub fn finish(&self, list: &mut DisplayList) {
2233 for page in &mut list.pages {
2234 page.width = self.page_side(page.width);
2235 page.height = self.page_side(page.height);
2236 let extra = self.vertical_stretch * self.page_step;
2237 if extra != 0 && page.height.units() > 0 {
2238 let (factor, offset) = self.stretch_factor(page.height);
2239 let stretch = Stretch {
2240 taller: page.height.units() + extra,
2241 height: page.height.units(),
2242 glyph_step: self.glyph_stretch_step,
2243 factor,
2244 offset,
2245 };
2246 for item in &mut page.items {
2247 stretch.item(item);
2248 }
2249 }
2250 self.offset_items(page);
2251 if let Some(digits) = self.digits {
2252 let digits = (digits.get(), self.least_decimals);
2253 for item in &mut page.items {
2254 self.write_digits(page.height, digits, item);
2255 }
2256 }
2257 stroke_items(&mut page.items);
2258 }
2259 }
2260
2261 fn offset_items(&self, page: &mut Page) {
2267 let (width, height) = (page.width, page.height);
2268 let (across, down_offset) = self.page_offsets(width, height, page.orientation);
2269 let down =
2270 |y: Length| Length::from_units(y.units() + down_offset.of(y.units(), height.units()));
2271 let place = |point: &mut Point| {
2272 let x = point.x.units();
2273 point.x = Length::from_units(x + across.of(x, width.units()));
2274 point.y = down(point.y);
2275 };
2276 offset_all(&mut page.items, &|item| match item {
2277 Item::Rect(rect) => {
2278 offset_rect(rect, across, width);
2279 let bottom = Length::from_units(rect.y.units() + rect.height.units());
2280 let top = down(rect.y);
2281 let bottom = down(bottom);
2282 rect.y = top;
2283 rect.height = Length::from_units(bottom.units() - top.units());
2284 }
2285 Item::Glyphs(run) => {
2286 for glyph in &mut run.glyphs {
2287 glyph.y = down(glyph.y);
2288 }
2289 }
2290 Item::Group(group) if group.places == GroupPlaces::Cell => {
2291 let clip = group.clip.iter_mut().flat_map(|clip| &mut clip.commands);
2292 clip.flat_map(PathCommand::points_mut).for_each(place);
2293 }
2294 Item::Group(group) if group.places == GroupPlaces::Points => {
2295 group.points_mut().for_each(place);
2296 }
2297 Item::Group(group) if matches!(group.places, GroupPlaces::Stroked { .. }) => {
2298 place_edges(&mut group.items, (across, down_offset), (width, height));
2299 }
2300 Item::Path(_) | Item::Gradient(_) | Item::Image(_) | Item::Group(_) => {}
2301 });
2302 }
2303
2304 fn write_digits(&self, height: Length, digits: (u32, u32), item: &mut Item) {
2307 match item {
2308 Item::Glyphs(run) => {
2309 for glyph in &mut run.glyphs {
2310 glyph.y = match self.baseline_steps {
2311 Some(per_inch) => {
2312 counted_y(height, glyph.y, digits, i64::from(per_inch.get()))
2313 }
2314 None => written_y(height, glyph.y, digits),
2315 };
2316 }
2317 }
2318 Item::Rect(rect) => {
2319 let exact = (rect.x, rect.y, rect.width, rect.height);
2320 (rect.x, rect.y, rect.width, rect.height) = self
2321 .rectangle_steps
2322 .and_then(|steps| held_box(height, exact, (digits, i64::from(steps.get()))))
2323 .unwrap_or_else(|| written_box(height, exact, digits));
2324 }
2325 Item::Group(group) => {
2326 if group.places == GroupPlaces::Points {
2327 for point in group.points_mut() {
2328 *point = written_point(height, *point, digits);
2329 }
2330 }
2331 for item in group.placed_items() {
2332 self.write_digits(height, digits, item);
2333 }
2334 }
2335 Item::Path(_) | Item::Gradient(_) | Item::Image(_) => {}
2336 }
2337 }
2338}
2339
2340fn offset_all(items: &mut [Item], place: &dyn Fn(&mut Item)) {
2344 for item in items {
2345 if let Item::Group(group) = item
2346 && !matches!(group.places, GroupPlaces::Stroked { .. })
2347 {
2348 offset_all(group.placed_items(), place);
2349 }
2350 place(item);
2351 }
2352}
2353
2354fn place_edges(
2358 items: &mut [Item],
2359 (across, down): (Offset, Offset),
2360 (width, height): (Length, Length),
2361) {
2362 for item in items {
2363 let Item::Rect(rect) = item else {
2364 continue;
2365 };
2366 let (left, top) = (rect.x.units(), rect.y.units());
2367 let (right, bottom) = (left + rect.width.units(), top + rect.height.units());
2368 let (left, right) = (
2369 across.written_place(left, width.units()),
2370 across.written_place(right, width.units()),
2371 );
2372 let (top, bottom) = (
2373 down.written_place(top, height.units()),
2374 down.written_place(bottom, height.units()),
2375 );
2376 rect.x = Length::from_units(left);
2377 rect.y = Length::from_units(top);
2378 rect.width = Length::from_units(right - left);
2379 rect.height = Length::from_units(bottom - top);
2380 }
2381}
2382
2383fn stroke_items(items: &mut [Item]) {
2387 for item in items {
2388 let Item::Group(group) = item else {
2389 continue;
2390 };
2391 if let GroupPlaces::Stroked { width } = group.places {
2392 let half = Length::from_units(div_round(width.units(), 2));
2393 group.items = std::mem::take(&mut group.items)
2394 .into_iter()
2395 .flat_map(|item| match item {
2396 Item::Rect(rect) => {
2397 let outline = stroke_outline(&rect, half);
2398 vec![Item::Rect(rect), Item::Path(outline)]
2399 }
2400 other => vec![other],
2401 })
2402 .collect();
2403 }
2404 stroke_items(&mut group.items);
2405 }
2406}
2407
2408const QUARTER_ARC_ARM: i64 = 552_284_750;
2411
2412fn stroke_outline(rect: &Rect, half: Length) -> PathItem {
2419 let (left, top) = (rect.x, rect.y);
2420 let (right, bottom) = (rect.x + rect.width, rect.y + rect.height);
2421 let (outer_left, outer_top) = (left - half, top - half);
2422 let (outer_right, outer_bottom) = (right + half, bottom + half);
2423 let start = Point {
2424 x: left,
2425 y: outer_bottom,
2426 };
2427 let sides = [
2430 [
2431 (right, outer_bottom),
2432 (outer_right, outer_bottom),
2433 (outer_right, bottom),
2434 ],
2435 [
2436 (outer_right, top),
2437 (outer_right, outer_top),
2438 (right, outer_top),
2439 ],
2440 [
2441 (left, outer_top),
2442 (outer_left, outer_top),
2443 (outer_left, top),
2444 ],
2445 [
2446 (outer_left, bottom),
2447 (outer_left, outer_bottom),
2448 (left, outer_bottom),
2449 ],
2450 ];
2451 let mut commands = vec![PathCommand::MoveTo(start)];
2452 for [(end_x, end_y), (corner_x, corner_y), (next_x, next_y)] in sides {
2453 let end = Point { x: end_x, y: end_y };
2454 commands.push(PathCommand::LineTo(end));
2455 commands.push(quarter_arc(
2456 end,
2457 Point {
2458 x: corner_x,
2459 y: corner_y,
2460 },
2461 Point {
2462 x: next_x,
2463 y: next_y,
2464 },
2465 ));
2466 }
2467 commands.push(PathCommand::Close);
2468 if rect.width > half + half && rect.height > half + half {
2469 let inner = [
2470 (left, bottom - half),
2471 (left + half, bottom),
2472 (left + half, top),
2473 (left, top + half),
2474 (right, top + half),
2475 (right - half, top),
2476 (right - half, bottom),
2477 (right, bottom - half),
2478 (left, bottom - half),
2479 ];
2480 for (index, (x, y)) in inner.into_iter().enumerate() {
2481 let point = Point { x, y };
2482 commands.push(if index == 0 {
2483 PathCommand::MoveTo(point)
2484 } else {
2485 PathCommand::LineTo(point)
2486 });
2487 }
2488 commands.push(PathCommand::Close);
2489 }
2490 PathItem {
2491 commands,
2492 color: rect.color,
2493 fill_rule: FillRule::NonZero,
2494 }
2495}
2496
2497fn quarter_arc(from: Point, corner: Point, to: Point) -> PathCommand {
2501 let arm = |distance: Length| {
2502 Length::from_units(div_round(
2503 distance.units().saturating_mul(QUARTER_ARC_ARM),
2504 1_000_000_000,
2505 ))
2506 };
2507 let toward = |point: Point| Point {
2508 x: point.x + arm(corner.x - point.x),
2509 y: point.y + arm(corner.y - point.y),
2510 };
2511 PathCommand::CubicTo(toward(from), toward(to), to)
2512}
2513
2514fn fraction(number: Binary32) -> (i128, u32) {
2517 let (mantissa, exponent) = (i128::from(number.mantissa()), number.exponent());
2518 match u32::try_from(exponent) {
2519 Ok(up) => (mantissa << up, 0),
2520 Err(_) => (mantissa, exponent.unsigned_abs()),
2521 }
2522}
2523
2524fn single_less(a: Binary32, b: Binary32) -> Option<Binary32> {
2527 let ((a, a_shift), (b, b_shift)) = (fraction(a), fraction(b));
2528 let shift = a_shift.max(b_shift);
2529 let exact = (a << (shift - a_shift)) - (b << (shift - b_shift));
2530 single(exact, 1_i128 << shift)
2531}
2532
2533fn held(units: i64, per_inch: i64) -> Option<Binary32> {
2537 let inch = i128::from(Length::UNITS_PER_INCH);
2538 let per_inch = i128::from(per_inch);
2539 let steps = div_round_i128(i128::from(units) * per_inch, inch);
2540 if steps == 0 {
2541 return Some(Binary32::ZERO);
2542 }
2543 let (step, shift) = fraction(single(72, per_inch)?);
2544 single(steps * step, 1_i128 << shift)
2545}
2546
2547fn held_box(
2556 height: Length,
2557 (x, y, width, tall): (Length, Length, Length, Length),
2558 (digits, per_inch): (Digits, i64),
2559) -> Option<(Length, Length, Length, Length)> {
2560 let point = i128::from(Length::UNITS_PER_POINT);
2561 let written = |number: Binary32| {
2562 let (significand, shift) = fraction(number);
2563 decimal(
2564 significand,
2565 shift,
2566 significant_decimals(significand, shift, digits),
2567 )
2568 };
2569 let edge = |units: i64| held(units, per_inch);
2570 let (left, right) = (edge(x.units())?, edge(x.units() + width.units())?);
2571 let (top, bottom) = (edge(y.units())?, edge(y.units() + tall.units())?);
2572 let foot = written(single_less(
2573 single(i128::from(height.units()), point)?,
2574 bottom,
2575 )?);
2576 let (left, across) = (written(left), written(single_less(right, left)?));
2577 let down = written(single_less(bottom, top)?);
2578 let (left_units, right_units) = (
2579 decimal_units(left)?,
2580 decimal_units(decimal_sum(left, across))?,
2581 );
2582 let bottom_units = height.units() - decimal_units(foot)?;
2583 let top_units = height.units() - decimal_units(decimal_sum(foot, down))?;
2584 Some((
2585 Length::from_units(left_units),
2586 Length::from_units(top_units),
2587 Length::from_units(right_units - left_units),
2588 Length::from_units(bottom_units - top_units),
2589 ))
2590}
2591
2592fn written_point(height: Length, point: Point, digits: Digits) -> Point {
2598 let unit = i128::from(Length::UNITS_PER_POINT);
2599 let x = single(i128::from(point.x.units()), unit)
2600 .map(fraction)
2601 .and_then(|(significand, shift)| printed(significand, shift, digits))
2602 .map_or(point.x, Length::from_units);
2603 Point {
2604 x,
2605 y: written_y(height, point.y, digits),
2606 }
2607}
2608
2609type Digits = (u32, u32);
2612
2613fn written_y(height: Length, y: Length, digits: Digits) -> Length {
2619 let point = i128::from(Length::UNITS_PER_POINT);
2620 let difference = match (
2623 single(i128::from(height.units()), point),
2624 single(i128::from(y.units()), point),
2625 ) {
2626 (Some(top), Some(low)) => single_less(top, low),
2627 _ => single(i128::from(height.units() - y.units()), point),
2628 };
2629 let Some((significand, shift)) = difference.map(fraction) else {
2630 return y;
2631 };
2632 printed(significand, shift, digits)
2633 .map_or(y, |units| Length::from_units(height.units() - units))
2634}
2635
2636fn counted_y(height: Length, y: Length, digits: Digits, per_inch: i64) -> Length {
2647 let point = i128::from(Length::UNITS_PER_POINT);
2648 let inch = i128::from(Length::UNITS_PER_INCH);
2649 let per_inch = i128::from(per_inch);
2650 let scaled = i128::from(y.units()) * per_inch;
2651 if scaled % inch != 0 {
2652 return written_y(height, y, digits);
2653 }
2654 let count = scaled / inch;
2655 let points = single(count, per_inch)
2656 .map(fraction)
2657 .and_then(|(significand, shift)| single(significand * 72, 1_i128 << shift));
2658 let difference = single(i128::from(height.units()), point)
2659 .zip(points)
2660 .and_then(|(top, low)| single_less(top, low));
2661 let Some((significand, shift)) = difference.map(fraction) else {
2662 return written_y(height, y, digits);
2663 };
2664 printed(significand, shift, digits)
2665 .map_or(y, |units| Length::from_units(height.units() - units))
2666}
2667
2668fn written_box(
2673 height: Length,
2674 (x, y, width, tall): (Length, Length, Length, Length),
2675 digits: Digits,
2676) -> (Length, Length, Length, Length) {
2677 let point = i128::from(Length::UNITS_PER_POINT);
2678 let written = |length: Length| {
2679 single(i128::from(length.units()), point)
2680 .map(fraction)
2681 .and_then(|(significand, shift)| printed(significand, shift, digits))
2682 .map_or(length, Length::from_units)
2683 };
2684 let written_tall = written(tall);
2685 let bottom = written_y(height, Length::from_units(y.units() + tall.units()), digits);
2686 (
2687 written(x),
2688 Length::from_units(bottom.units() - written_tall.units()),
2689 written(width),
2690 written_tall,
2691 )
2692}
2693
2694fn printed(significand: i128, shift: u32, (digits, least): Digits) -> Option<i64> {
2699 let whole = (significand >> shift).max(1);
2700 let decimals = digits.saturating_sub(whole.ilog10() + 1).max(least);
2701 decimal_units(decimal(significand, shift, decimals))
2702}
2703
2704fn significant_decimals(significand: i128, shift: u32, (digits, least): Digits) -> u32 {
2709 let whole = significand >> shift;
2710 if whole > 0 {
2711 return digits.saturating_sub(whole.ilog10() + 1).max(least);
2712 }
2713 let mut decimals = digits;
2714 let mut scaled = significand * 10;
2715 while significand > 0 && scaled < 1 << shift {
2716 decimals += 1;
2717 scaled *= 10;
2718 }
2719 decimals
2720}
2721
2722type Decimal = (i128, i128);
2724
2725fn decimal(significand: i128, shift: u32, decimals: u32) -> Decimal {
2728 let scale = i128::from(f_office_units::scale::TENTHS).pow(decimals);
2729 (
2730 (significand * scale * 2 + (1 << shift)) >> (shift + 1),
2731 scale,
2732 )
2733}
2734
2735fn decimal_sum((a, a_scale): Decimal, (b, b_scale): Decimal) -> Decimal {
2737 let scale = a_scale.max(b_scale);
2738 (a * (scale / a_scale) + b * (scale / b_scale), scale)
2739}
2740
2741fn decimal_units((value, scale): Decimal) -> Option<i64> {
2743 let point = i128::from(Length::UNITS_PER_POINT);
2744 i64::try_from(div_round_i128(value * point, scale)).ok()
2745}
2746
2747#[must_use]
2751pub fn single(numerator: i128, denominator: i128) -> Option<Binary32> {
2752 if numerator <= 0 || denominator <= 0 {
2753 return None;
2754 }
2755 let mut exponent =
2757 i32::try_from(numerator.ilog2()).ok()? - i32::try_from(denominator.ilog2()).ok()?;
2758 let below = if exponent >= 0 {
2759 numerator < denominator << exponent
2760 } else {
2761 numerator << -exponent < denominator
2762 };
2763 if below {
2764 exponent -= 1;
2765 }
2766 let shift = u32::try_from(i32::try_from(Binary32::BITS).ok()? - 1 - exponent).ok()?;
2767 if shift > u32::BITS * 2 {
2768 return None;
2769 }
2770 Some(Binary32::nearest(numerator, denominator))
2771}
2772
2773struct Stretch {
2777 taller: i64,
2778 height: i64,
2779 glyph_step: Option<Length>,
2780 factor: Fraction,
2781 offset: Fraction,
2782}
2783
2784impl Stretch {
2785 fn glyph_y(&self, y: Length) -> Length {
2789 let Some(glyph_step) = self.glyph_step else {
2790 return self.y(y);
2791 };
2792 let distance = i128::from(y.units()) * i128::from(self.taller - self.height);
2793 let per_step = i128::from(self.height) * i128::from(glyph_step.units());
2794 let (factor, of) = (i128::from(self.factor.0), i128::from(self.factor.1));
2795 let (offset, by) = (i128::from(self.offset.0), i128::from(self.offset.1));
2796 let whole = of * by * per_step;
2799 let steps = div_round_i128(distance * factor * by + offset * of * per_step, whole);
2800 let moved = i64::try_from(steps * i128::from(glyph_step.units())).unwrap_or(i64::MAX);
2801 Length::from_units(y.units().saturating_add(moved))
2802 }
2803
2804 fn y(&self, y: Length) -> Length {
2806 let product = i128::from(y.units()) * i128::from(self.taller);
2807 let height = i128::from(self.height);
2808 let rounded = div_round_i128(product, height);
2809 Length::from_units(i64::try_from(rounded).unwrap_or(i64::MAX))
2810 }
2811
2812 fn stepped_span(&self, (top, height): (Length, Length)) -> (Length, Length) {
2815 let new_top = self.glyph_y(top);
2816 let bottom = self.glyph_y(Length::from_units(top.units() + height.units()));
2817 (
2818 new_top,
2819 Length::from_units(bottom.units() - new_top.units()),
2820 )
2821 }
2822
2823 fn point(&self, point: &mut Point) {
2824 point.y = self.y(point.y);
2825 }
2826
2827 fn item(&self, item: &mut Item) {
2829 match item {
2830 Item::Glyphs(run) => {
2831 for glyph in &mut run.glyphs {
2832 glyph.y = self.glyph_y(glyph.y);
2833 }
2834 }
2835 Item::Rect(rect) => (rect.y, rect.height) = self.stepped_span((rect.y, rect.height)),
2836 Item::Path(path) => {
2837 for point in path.commands.iter_mut().flat_map(PathCommand::points_mut) {
2838 self.point(point);
2839 }
2840 }
2841 Item::Gradient(gradient) => {
2842 let axis = [&mut gradient.start, &mut gradient.end];
2843 let outline = gradient
2844 .commands
2845 .iter_mut()
2846 .flat_map(PathCommand::points_mut);
2847 for point in outline.chain(axis) {
2848 self.point(point);
2849 }
2850 }
2851 Item::Group(group) => {
2854 if group.places != GroupPlaces::Own {
2855 let clip = group.clip.iter_mut().flat_map(|clip| &mut clip.commands);
2856 for point in clip.flat_map(PathCommand::points_mut) {
2857 self.point(point);
2858 }
2859 }
2860 for item in group.placed_items() {
2861 self.item(item);
2862 }
2863 }
2864 Item::Image(_) => {}
2865 }
2866 }
2867}
2868
2869#[cfg(test)]
2870mod tests {
2871 use std::sync::Arc;
2872
2873 use f_office_units::Length;
2874
2875 use super::{
2876 DEFAULT_LINEAR_LIMIT, DisplayList, Glyph, GlyphRun, Image, ImageFormat, JpegQuality,
2877 LinearLimit, Offset, OffsetProduct, Orientation, Page, PaletteClass, PaletteDensity,
2878 PictureDensity, Resampler, Rgb, Writer, WriterOffset,
2879 };
2880
2881 #[test]
2882 fn takes_the_linear_interpolation_up_to_a_count_or_up_to_a_side() {
2883 let count = |n| std::num::NonZeroU32::new(n).unwrap();
2884 let (pixels, side) = (
2885 LinearLimit::Pixels(count(1 << 17)),
2886 LinearLimit::Side(count(419)),
2887 );
2888 let cases = [
2889 (pixels, (400, 327), true),
2890 (pixels, (400, 328), false),
2891 (pixels, (480, 270), true),
2892 (side, (419, 419), true),
2893 (side, (420, 100), false),
2894 (side, (100, 420), false),
2895 (side, (480, 270), false),
2896 ];
2897 for (limit, size, linear) in cases {
2898 assert_eq!(limit.takes_linear(size), linear, "{limit:?} {size:?}");
2899 }
2900 assert_eq!(DEFAULT_LINEAR_LIMIT, pixels);
2901 }
2902
2903 #[test]
2904 fn answers_with_the_filter_of_its_own_limit() {
2905 let side = LinearLimit::Side(std::num::NonZeroU32::new(419).unwrap());
2906 let density = PictureDensity {
2907 limit_ppi: std::num::NonZeroU32::new(275).unwrap(),
2908 ppi: std::num::NonZeroU32::new(200).unwrap(),
2909 };
2910 let writer = Writer::new(Length::from_units(10))
2911 .unwrap()
2912 .with_picture_density(Some(density))
2913 .with_linear_limit(side);
2914 let inch = Length::from_units(Length::UNITS_PER_INCH);
2915 let answer = writer.resampled_size((600, 600), (inch, inch), None);
2916 assert_eq!(answer, Some(((199, 199), Resampler::Filter(side))));
2917 }
2918
2919 #[test]
2920 fn a_filled_path_draws_quadratic_curves_as_cubic_curves_of_whole_units() {
2921 use super::PathCommand::{Close, CubicTo, LineTo, MoveTo, QuadTo};
2922 let at = |x, y| super::Point {
2923 x: Length::from_units(x),
2924 y: Length::from_units(y),
2925 };
2926 let commands = [
2927 MoveTo(at(0, 0)),
2928 QuadTo(at(30, 10), at(31, 0)),
2929 Close,
2930 QuadTo(at(3, 3), at(6, 0)),
2931 LineTo(at(9, 9)),
2932 ];
2933 let expected = vec![
2936 MoveTo(at(0, 0)),
2937 CubicTo(at(20, 7), at(30, 7), at(31, 0)),
2938 Close,
2939 CubicTo(at(2, 2), at(4, 2), at(6, 0)),
2940 LineTo(at(9, 9)),
2941 ];
2942 assert_eq!(super::fill_commands(&commands), expected);
2943 assert_eq!(
2944 super::fill_commands(&[QuadTo(at(3, 3), at(6, 0))]),
2945 vec![CubicTo(at(3, 3), at(4, 2), at(6, 0))]
2946 );
2947 }
2948
2949 #[test]
2950 fn a_filled_path_leaves_out_lines_to_their_own_start() {
2951 use super::PathCommand::{Close, LineTo, MoveTo};
2952 let at = |x, y| super::Point {
2953 x: Length::from_units(x),
2954 y: Length::from_units(y),
2955 };
2956 let commands = [
2957 MoveTo(at(5, 5)),
2958 LineTo(at(5, 5)),
2959 LineTo(at(9, 5)),
2960 LineTo(at(9, 5)),
2961 LineTo(at(9, 9)),
2962 Close,
2963 LineTo(at(5, 5)),
2964 LineTo(at(7, 7)),
2965 ];
2966 let expected = vec![
2968 MoveTo(at(5, 5)),
2969 LineTo(at(9, 5)),
2970 LineTo(at(9, 9)),
2971 Close,
2972 LineTo(at(7, 7)),
2973 ];
2974 assert_eq!(super::fill_commands(&commands), expected);
2975 }
2976
2977 #[test]
2978 fn a_fill_at_most_the_thinnest_fill_across_paints_nothing() {
2979 use super::PathCommand::{Close, CubicTo, LineTo, MoveTo};
2980 let at = |x, y| super::Point {
2981 x: Length::from_units(x),
2982 y: Length::from_units(y),
2983 };
2984 let bar = |across| {
2985 [
2986 MoveTo(at(0, 0)),
2987 LineTo(at(across, 0)),
2988 LineTo(at(across, 5000)),
2989 LineTo(at(0, 5000)),
2990 Close,
2991 ]
2992 };
2993 assert!(!super::path_shows(&bar(100)));
2994 assert!(super::path_shows(&bar(101)));
2995 assert!(!super::fill_shows(
2996 Length::from_units(5000),
2997 Length::from_units(-100)
2998 ));
2999 assert!(super::fill_shows(
3000 Length::from_units(5000),
3001 Length::from_units(-101)
3002 ));
3003 let bowed = [
3005 MoveTo(at(0, 0)),
3006 CubicTo(at(150, 1000), at(150, 4000), at(0, 5000)),
3007 Close,
3008 ];
3009 assert!(super::path_shows(&bowed));
3010 assert!(!super::path_shows(&[]));
3011 }
3012
3013 fn write_digits(writer: &Writer, height: Length, item: &mut super::Item) {
3016 let digits = (writer.digits().unwrap().get(), writer.least_decimals());
3017 writer.write_digits(height, digits, item);
3018 }
3019
3020 #[test]
3021 fn gives_the_text_of_a_glyph_only_on_whole_characters() {
3022 let run = GlyphRun {
3023 font: f_office_fonts::FontId::from_index(0),
3024 size: Length::ZERO,
3025 color: Rgb::BLACK,
3026 text: "a\u{e9}".to_owned(),
3027 glyphs: Vec::new(),
3028 outline: None,
3029 filled: true,
3030 effect: false,
3031 turn: None,
3032 };
3033 let glyph = |text_start, text_end| Glyph {
3034 id: 0,
3035 x: Length::ZERO,
3036 y: Length::ZERO,
3037 text_start,
3038 text_end,
3039 };
3040 assert_eq!(run.glyph_text(&glyph(0, 1)), Some("a"));
3041 assert_eq!(run.glyph_range(&glyph(1, 3)), Some(1..3));
3042 assert_eq!(run.glyph_text(&glyph(1, 3)), Some("\u{e9}"));
3043 assert_eq!(run.glyph_text(&glyph(1, 1)), Some(""));
3044 for (start, end) in [(1, 2), (2, 3), (1, 0), (0, 4)] {
3046 assert_eq!(run.glyph_range(&glyph(start, end)), None, "{start}..{end}");
3047 assert_eq!(run.glyph_text(&glyph(start, end)), None, "{start}..{end}");
3048 }
3049 }
3050
3051 fn non_zero(count: u32) -> std::num::NonZeroU32 {
3053 std::num::NonZeroU32::new(count).unwrap()
3054 }
3055
3056 fn density(limit_ppi: u32, ppi: u32) -> PictureDensity {
3058 PictureDensity {
3059 limit_ppi: non_zero(limit_ppi),
3060 ppi: non_zero(ppi),
3061 }
3062 }
3063
3064 #[test]
3065 fn reads_six_hexadecimal_digits_only() {
3066 let rgb = |r, g, b| Some(Rgb { r, g, b });
3067 assert_eq!(Rgb::from_hex("FF0080"), rgb(255, 0, 128));
3068 assert_eq!(Rgb::from_hex("1f3864"), rgb(31, 56, 100));
3069 for wrong in [
3070 "+FFFFF", "+F+F+F", "-FFFFF", "FFFFF", "FFFFFFF", "GGGGGG", " FFFFF", "auto",
3071 ] {
3072 assert_eq!(Rgb::from_hex(wrong), None, "{wrong}");
3073 }
3074 }
3075
3076 fn every_kind(at: impl Fn(i64) -> super::Point, by: impl Fn(i64) -> Length) -> super::Item {
3080 use super::{
3081 Clip, FillRule, Glyph, GlyphRun, Group, GroupClip, GroupPlaces, ImageItem, Item, Join,
3082 Outline, PathCommand, PathItem, Rect,
3083 };
3084 let glyph = |n: i64| Glyph {
3085 id: 1,
3086 x: at(n).x,
3087 y: at(n).y,
3088 text_start: 0,
3089 text_end: 1,
3090 };
3091 let run = GlyphRun {
3092 font: f_office_fonts::FontId::from_index(0),
3093 size: by(1),
3094 color: Rgb::BLACK,
3095 text: "a".to_owned(),
3096 glyphs: vec![glyph(1), glyph(2)],
3097 outline: Some(Outline {
3098 width: by(2),
3099 color: Rgb::BLACK,
3100 join: Join::Round,
3101 }),
3102 filled: true,
3103 effect: false,
3104 turn: None,
3105 };
3106 let rect = Rect {
3107 x: at(3).x,
3108 y: at(3).y,
3109 width: by(3),
3110 height: by(4),
3111 color: Rgb::BLACK,
3112 };
3113 let path = PathItem {
3114 commands: vec![
3115 PathCommand::MoveTo(at(4)),
3116 PathCommand::LineTo(at(5)),
3117 PathCommand::QuadTo(at(6), at(7)),
3118 PathCommand::CubicTo(at(8), at(9), at(10)),
3119 PathCommand::Close,
3120 ],
3121 color: Rgb::BLACK,
3122 fill_rule: FillRule::NonZero,
3123 };
3124 let image = ImageItem {
3125 x: at(11).x,
3126 y: at(11).y,
3127 width: by(5),
3128 height: by(6),
3129 clip: Some(Clip {
3130 x: at(12).x,
3131 y: at(12).y,
3132 width: by(7),
3133 height: by(8),
3134 }),
3135 turn: None,
3136 image: Image::new(vec![0]),
3137 };
3138 Item::Group(Group::new(vec![
3139 Item::Glyphs(run),
3140 Item::Group(Group {
3141 items: vec![Item::Rect(rect), Item::Path(path)],
3142 clip: Some(GroupClip {
3143 commands: vec![
3144 PathCommand::MoveTo(at(13)),
3145 PathCommand::LineTo(at(14)),
3146 PathCommand::QuadTo(at(15), at(16)),
3147 PathCommand::Close,
3148 ],
3149 fill_rule: FillRule::EvenOdd,
3150 }),
3151 places: GroupPlaces::Own,
3152 }),
3153 Item::Image(image),
3154 ]))
3155 }
3156
3157 #[test]
3158 fn maps_every_place_and_length_of_an_item_and_of_the_items_of_its_groups() {
3159 use super::Point;
3160 let u = Length::from_units;
3161 let at = |n: i64| Point {
3162 x: u(2 * n - 1),
3163 y: u(2 * n),
3164 };
3165 let mut item = every_kind(at, |n| u(10 * n));
3166 item.map_places(
3168 |p| Point {
3169 x: p.x + u(1),
3170 y: p.y * 2,
3171 },
3172 |v| v * 3,
3173 );
3174 let mapped = |n: i64| Point {
3175 x: u(2 * n),
3176 y: u(4 * n),
3177 };
3178 assert_eq!(item, every_kind(mapped, |n| u(30 * n)));
3179 }
3180
3181 #[test]
3182 fn gives_the_pages_and_the_parts_that_it_was_built_from() {
3183 use super::Point;
3184 let u = Length::from_units;
3185 let at = |n: i64| Point { x: u(n), y: u(n) };
3186 let items = vec![every_kind(at, u), every_kind(at, |n| u(2 * n))];
3187 let landscape = Orientation::Landscape;
3188 let page = Page::new(u(300), u(400), landscape, items.clone());
3189 assert_eq!((page.width(), page.height()), (u(300), u(400)));
3190 assert_eq!(page.orientation(), landscape);
3191 assert_eq!(page.items(), items.as_slice());
3192 let empty = Page::new(u(5), u(6), Orientation::Portrait, Vec::new());
3193 let list = DisplayList::new(vec![page.clone(), empty.clone()]);
3194 assert_eq!(list.pages(), [page.clone(), empty.clone()].as_slice());
3195 assert_eq!(list.into_pages(), vec![page.clone(), empty]);
3196 let fewer = page.map_items(|mut kept| {
3197 kept.truncate(1);
3198 kept
3199 });
3200 assert_eq!(
3201 fewer,
3202 Page::new(u(300), u(400), landscape, items[..1].to_vec())
3203 );
3204 }
3205
3206 #[test]
3207 fn writes_the_page_size_in_whole_steps() {
3208 assert_eq!(Writer::new(Length::ZERO), None);
3209 let step = Length::from_units(Length::UNITS_PER_DOT);
3210 let writer = Writer::new(step).unwrap();
3211 let page = |width, height| Page {
3213 width: Length::from_units(width),
3214 height: Length::from_units(height),
3215 orientation: Orientation::Portrait,
3216 items: Vec::new(),
3217 };
3218 let mut list = DisplayList {
3219 pages: vec![page(15_120_000, 3048 + 6096 * 3)],
3220 };
3221 writer.finish(&mut list);
3222 assert_eq!(list.pages[0].width.units(), 2480 * 6096);
3223 assert_eq!(list.pages[0].height.units(), 4 * 6096);
3224 }
3225
3226 #[test]
3227 fn keeps_the_picture_files_unless_it_has_a_jpeg_quality() {
3228 let writer = Writer::new(Length::from_units(10)).unwrap();
3229 assert_eq!(writer.jpeg_quality(), None);
3230 let quality = JpegQuality::new(75);
3231 assert_eq!(writer.with_jpeg_quality(quality).jpeg_quality(), quality);
3232 assert_eq!(writer.with_jpeg_quality(None), writer);
3233 }
3234
3235 #[test]
3236 fn keeps_an_opacity_between_none_and_a_whole() {
3237 use super::Opacity;
3238 assert_eq!(Opacity::clamped(-5).share(), 0);
3239 assert_eq!(Opacity::clamped(150_000), Opacity::FULL);
3240 assert_eq!(Opacity::FULL.share(), 100_000);
3241 let half = Opacity::clamped(50_000);
3243 assert_eq!(half.times(Opacity::clamped(50_001)).share(), 25_001);
3244 assert_eq!(Opacity::FULL.times(half), half);
3245 }
3246
3247 #[test]
3248 fn takes_a_jpeg_quality_of_1_to_100_only() {
3249 assert_eq!(JpegQuality::new(1).map(JpegQuality::get), Some(1));
3250 assert_eq!(JpegQuality::new(100).map(JpegQuality::get), Some(100));
3251 assert_eq!(JpegQuality::new(0), None);
3252 assert_eq!(JpegQuality::new(101), None);
3253 assert_eq!(JpegQuality::new(255), None);
3254 }
3255
3256 #[test]
3257 fn resamples_pictures_denser_than_the_limit_below_its_density() {
3258 let inches =
3259 |hundredths: i64| Length::from_units(Length::UNITS_PER_INCH * hundredths / 100);
3260 let size = (
3261 inches(150),
3262 Length::from_units(Length::UNITS_PER_POINT * 81),
3263 );
3264 let writer = Writer::new(Length::from_units(10)).unwrap();
3265 assert_eq!(writer.resampled_size((600, 450), size, None), None);
3266 let writer = writer.with_picture_density(Some(density(275, 200)));
3267 let filter = |pixels| Some((pixels, Resampler::Filter(DEFAULT_LINEAR_LIMIT)));
3268 assert_eq!(writer.resampled_size((412, 309), size, None), None);
3270 assert_eq!(
3271 writer.resampled_size((414, 311), size, None),
3272 filter((299, 224))
3273 );
3274 assert_eq!(
3275 writer.resampled_size((600, 450), size, None),
3276 filter((299, 224))
3277 );
3278 let size = (
3280 inches(125),
3281 Length::from_units(Length::UNITS_PER_POINT * 135 / 2),
3282 );
3283 assert_eq!(
3284 writer.resampled_size((500, 375), size, None),
3285 filter((249, 187))
3286 );
3287 assert_eq!(
3289 writer.resampled_size((600, 100), size, None),
3290 filter((249, 100))
3291 );
3292 assert_eq!(
3293 writer.resampled_size((600, 450), (Length::from_units(0), size.1), None),
3294 None
3295 );
3296 }
3297
3298 #[test]
3299 fn resamples_a_palette_of_a_class_by_the_limits_of_its_class() {
3300 let size = (
3302 Length::from_units(Length::UNITS_PER_INCH),
3303 Length::from_units(Length::UNITS_PER_INCH * 3 / 10),
3304 );
3305 let palettes = PaletteDensity {
3306 one_bit_limit_ppi: non_zero(750),
3307 one_bit_ppi: non_zero(600),
3308 four_bits_limit_ppi: non_zero(562),
3309 eight_bits_limit_ppi: non_zero(395),
3310 };
3311 let writer = Writer::new(Length::from_units(10))
3312 .unwrap()
3313 .with_picture_density(Some(density(275, 200)));
3314 let (centre, filter) = (
3315 Resampler::CentrePixel,
3316 Resampler::Filter(DEFAULT_LINEAR_LIMIT),
3317 );
3318 let classes = [
3319 (
3320 Some(PaletteClass::OneBit),
3321 749_usize,
3322 750_usize,
3323 (599, 179),
3324 centre,
3325 ),
3326 (
3327 Some(PaletteClass::FourBitColor),
3328 561,
3329 562,
3330 (199, 59),
3331 filter,
3332 ),
3333 (
3334 Some(PaletteClass::EightBitColor),
3335 394,
3336 395,
3337 (199, 59),
3338 filter,
3339 ),
3340 (None, 274, 275, (199, 59), filter),
3341 ];
3342 let with = writer.with_palette_density(Some(palettes));
3343 for (class, kept, dense, new, resampler) in classes {
3344 let (kept, dense) = ((kept, kept * 3 / 10), (dense, (dense * 3).div_ceil(10)));
3346 assert_eq!(with.resampled_size(kept, size, class), None);
3347 let written = with.resampled_size(dense, size, class);
3348 assert_eq!(written, Some((new, resampler)));
3349 let general = writer.resampled_size(dense, size, class);
3351 assert_eq!(general, Some(((199, 59), filter)));
3352 }
3353 let none = Writer::new(Length::from_units(10))
3355 .unwrap()
3356 .with_palette_density(Some(palettes));
3357 let one_bit = Some(PaletteClass::OneBit);
3358 assert_eq!(none.resampled_size((900, 270), size, one_bit), None);
3359 }
3360
3361 fn half_inch_sizes(
3364 limit_ppi: u32,
3365 ppi: u32,
3366 pixels: &[(usize, usize)],
3367 ) -> Vec<Option<(usize, usize)>> {
3368 let half = Length::from_units(Length::UNITS_PER_POINT * 36);
3369 let writer = Writer::new(Length::from_units(10))
3370 .unwrap()
3371 .with_picture_density(Some(density(limit_ppi, ppi)));
3372 pixels
3373 .iter()
3374 .map(|&pixels| writer.resampled_size(pixels, (half, half), None))
3375 .map(|written| written.map(|(pixels, _)| pixels))
3376 .collect()
3377 }
3378
3379 #[test]
3380 fn resamples_only_the_directions_denser_than_a_limit_of_275_ppi() {
3381 assert_eq!(
3384 half_inch_sizes(275, 200, &[(145, 130), (130, 145), (145, 138), (145, 137)]),
3385 [
3386 Some((99, 130)),
3387 Some((130, 99)),
3388 Some((99, 99)),
3389 Some((99, 137))
3390 ]
3391 );
3392 }
3393
3394 #[test]
3395 fn resamples_only_the_directions_at_a_limit_of_450_ppi_or_denser() {
3396 assert_eq!(
3399 half_inch_sizes(
3400 450,
3401 300,
3402 &[(223, 223), (225, 225), (225, 175), (200, 225), (225, 150)]
3403 ),
3404 [
3405 None,
3406 Some((149, 149)),
3407 Some((149, 175)),
3408 Some((200, 149)),
3409 Some((149, 150))
3410 ]
3411 );
3412 }
3413
3414 fn across(limit_ppi: u32, ppi: u32, pixels: usize, units: i64) -> usize {
3417 let writer = Writer::new(Length::from_units(10))
3418 .unwrap()
3419 .with_picture_density(Some(density(limit_ppi, ppi)));
3420 let size = (
3421 Length::from_units(units),
3422 Length::from_emus(137_160).unwrap(),
3423 );
3424 writer
3425 .resampled_size((pixels, 30), size, None)
3426 .map_or(pixels, |(written, _)| written.0)
3427 }
3428
3429 #[test]
3430 fn tests_and_resamples_the_drawn_size_itself() {
3431 let cases = [
3434 (450, 300, 225, 914_400, 149),
3438 (450, 300, 225, 915_670, 225),
3439 (275, 200, 225, 914_400, 99),
3440 (275, 200, 225, 915_670, 100),
3441 (275, 200, 275, 1_828_800, 199),
3444 (275, 200, 275, 1_828_801, 275),
3445 (450, 300, 211, 573_024, 93),
3449 (450, 300, 211, 573_025, 94),
3450 (275, 200, 211, 932_688, 101),
3451 (275, 200, 211, 932_689, 102),
3452 (450, 300, 211, 857_504, 140),
3453 (450, 300, 211, 857_505, 211),
3454 ];
3455 for (limit, ppi, pixels, units, written) in cases {
3456 assert_eq!(
3457 across(limit, ppi, pixels, units),
3458 written,
3459 "{pixels} on {units}"
3460 );
3461 }
3462 }
3463
3464 #[test]
3465 fn stretches_glyphs_and_rectangles_down_by_the_steps_of_the_page() {
3466 use super::Item;
3467 let page = stretched();
3468 let Item::Glyphs(run) = &page.items[0] else {
3469 panic!("no glyphs")
3470 };
3471 assert_eq!(
3472 (run.glyphs[0].x.units(), run.glyphs[0].y.units()),
3473 (500, 402)
3474 );
3475 assert_eq!(run.size.units(), 120);
3476 let Item::Rect(rect) = &page.items[1] else {
3477 panic!("no rect")
3478 };
3479 let units = [rect.x, rect.y, rect.width, rect.height].map(Length::units);
3480 assert_eq!(units, [100, 201, 300, 402]);
3481 assert_eq!((page.width.units(), page.height.units()), (1000, 2000));
3483 }
3484
3485 #[test]
3486 fn stretches_paths_down_and_leaves_pictures_and_everything_without_a_stretch() {
3487 use super::{Item, PathCommand, Point};
3488 let page = stretched();
3489 let Item::Path(path) = &page.items[2] else {
3490 panic!("no path")
3491 };
3492 let corner = Point {
3493 x: Length::from_units(1000),
3494 y: Length::from_units(2010),
3495 };
3496 assert_eq!(path.commands[0], PathCommand::MoveTo(corner));
3497 assert_eq!(page.items[3], sample_page().items[3]);
3499 let mut plain = DisplayList {
3500 pages: vec![sample_page()],
3501 };
3502 Writer::new(Length::from_units(10))
3503 .unwrap()
3504 .finish(&mut plain);
3505 assert_eq!(plain.pages[0], sample_page());
3506 }
3507
3508 #[test]
3509 fn holds_a_quotient_as_the_nearest_single_precision_number() {
3510 use super::{fraction, single};
3511 let cases = [
3515 ((744_975, 1000), Some((12_205_670, 14))),
3516 ((434_125, 1000), Some((14_225_408, 15))),
3517 ((1, 3), Some((11_184_811, 25))),
3518 ((2, 3), Some((11_184_811, 24))),
3519 ((123_456_789, 25_400), Some((9_954_311, 11))),
3520 ((16_777_217, 2), Some((8_388_608, 0))),
3521 ((16_777_217, 1), None),
3522 ((0, 1), None),
3523 (((1 << 25) - 1, 2), Some((1 << 24, 0))),
3525 ];
3526 for ((numerator, denominator), expected) in cases {
3527 assert_eq!(
3528 single(numerator, denominator).map(fraction),
3529 expected,
3530 "{numerator}/{denominator}"
3531 );
3532 }
3533 }
3534
3535 #[test]
3536 fn writes_a_baseline_from_the_bottom_with_significant_digits() {
3537 use super::written_y;
3538 let point =
3545 |thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
3546 let page = point(792_000);
3547 assert_eq!(written_y(page, point(357_875), (5, 0)), point(357_870));
3548 assert_eq!(written_y(page, point(47_025), (5, 0)), point(47_030));
3549 assert_eq!(written_y(page, point(82_275), (5, 0)), point(82_280));
3550 assert_eq!(written_y(page, point(741_025), (5, 0)), point(741_025));
3551 assert_eq!(written_y(page, point(800_000), (5, 0)), point(800_000));
3552 assert_eq!(written_y(page, point(586_425), (5, 0)), point(586_420));
3553 }
3554
3555 #[test]
3556 fn writes_a_baseline_from_its_count_of_steps() {
3557 use super::{counted_y, written_y};
3558 let point =
3565 |thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
3566 let page = point(792_000);
3567 let counted = |y: i64| counted_y(page, point(y), (5, 2), 2_880);
3568 let written = |y: i64| written_y(page, point(y), (5, 2));
3569 let pairs = [582_925, 273_825].map(|y| (counted(y), written(y)));
3570 assert_eq!(pairs[0], (point(582_930), point(582_920)));
3571 assert_eq!(pairs[1], (point(273_820), point(273_830)));
3572 for same in [587_925, 586_425, 357_875, 744_975, 300_000] {
3573 assert_eq!(counted(same), written(same), "{same}");
3574 }
3575 }
3576
3577 #[test]
3578 fn writes_a_baseline_off_the_steps_from_its_own_points() {
3579 use super::{counted_y, written_y};
3580 let point =
3584 |thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
3585 let page = point(792_000);
3586 let counted = |y: i64| counted_y(page, point(y), (5, 2), 2_880);
3587 let written = |y: i64| written_y(page, point(y), (5, 2));
3588 for y in [0, 800_000, 582_938] {
3589 assert_eq!(counted(y), written(y), "{y}");
3590 }
3591 assert_eq!(counted(582_938), point(582_940));
3592 }
3593
3594 #[test]
3595 fn writes_glyph_baselines_from_their_counts_where_the_writer_holds_steps() {
3596 use super::{Glyph, GlyphRun, Item};
3597 let point =
3598 |thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
3599 let glyphs = || {
3600 Item::Glyphs(GlyphRun {
3601 font: f_office_fonts::FontId::from_index(0),
3602 size: point(11_000),
3603 color: Rgb::BLACK,
3604 text: "a".to_owned(),
3605 glyphs: vec![Glyph {
3606 id: 1,
3607 x: point(72_000),
3608 y: point(582_925),
3609 text_start: 0,
3610 text_end: 1,
3611 }],
3612 outline: None,
3613 filled: true,
3614 effect: false,
3615 turn: None,
3616 })
3617 };
3618 let baseline = |writer: &Writer| {
3619 let mut item = glyphs();
3620 write_digits(writer, point(792_000), &mut item);
3621 let Item::Glyphs(run) = item else {
3622 unreachable!()
3623 };
3624 run.glyphs[0].y
3625 };
3626 let writer = Writer::new(Length::from_units(10))
3627 .unwrap()
3628 .with_digits(Some(non_zero(5)))
3629 .with_least_decimals(2);
3630 let counting = writer.with_baseline_steps(Some(non_zero(2_880)));
3631 assert_eq!(counting.baseline_steps(), Some(non_zero(2_880)));
3632 assert_eq!(writer.baseline_steps(), None);
3633 assert_eq!(baseline(&counting), point(582_930));
3634 assert_eq!(baseline(&writer), point(582_920));
3635 }
3636
3637 #[test]
3638 fn writes_a_baseline_from_1000_pt_with_the_least_decimals() {
3639 use super::written_y;
3640 let point =
3643 |thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
3644 let page = point(1_584_000);
3645 assert_eq!(written_y(page, point(576_120), (5, 0)), point(576_100));
3646 assert_eq!(written_y(page, point(576_120), (5, 2)), point(576_120));
3647 assert_eq!(written_y(page, point(576_400), (5, 2)), point(576_400));
3649 let letter = point(792_000);
3652 assert_eq!(written_y(letter, point(357_875), (5, 2)), point(357_870));
3653 assert_eq!(written_y(letter, point(741_025), (5, 2)), point(741_025));
3654 }
3655
3656 #[test]
3657 fn offsets_a_rectangles_edges_as_a_text_objects_start() {
3658 let writer = Writer::new(Length::from_units(10))
3662 .unwrap()
3663 .with_horizontal_offset(WriterOffset::EveryPage(Offset::Share {
3664 share: 2_400,
3665 bias: 18,
3666 step: 635,
3667 }));
3668 let point = |thousandths: i64| Length::from_units(thousandths * 254 / 10);
3669 let (width, height) = (point(612_000), point(792_000));
3670 let across = |writer: Writer, x: Length| {
3671 Length::from_units(
3672 writer
3673 .page_offsets(width, height, Orientation::Portrait)
3674 .0
3675 .of(x.units(), width.units()),
3676 )
3677 };
3678 assert_eq!(across(writer, point(66_500)), point(25));
3679 assert_eq!(across(writer, point(186_750)), point(75));
3680 assert_eq!(
3681 across(Writer::new(Length::from_units(10)).unwrap(), point(66_500)),
3682 point(0)
3683 );
3684 }
3685
3686 const fn page_form(c: i64, parts: i64) -> Offset {
3689 Offset::Page {
3690 steps: (c, 100_000),
3691 parts,
3692 per_inch: 3_000,
3693 product: OffsetProduct::Exact,
3694 }
3695 }
3696
3697 const fn binary32_page_form(c: i64) -> Offset {
3700 Offset::Page {
3701 steps: (c, 100_000),
3702 parts: 16,
3703 per_inch: 3_000,
3704 product: OffsetProduct::Binary32 { dots_per_inch: 600 },
3705 }
3706 }
3707
3708 #[test]
3709 fn rounds_the_product_of_the_dot_and_the_page_entry_in_binary32() {
3710 let offset = |c, k: i64| binary32_page_form(c).of(k * DOT, LETTER);
3715 assert_eq!(page_form(472_515, 16).of(3_743 * DOT, LETTER), 1_829);
3716 assert_eq!(offset(472_515, 3_743), 2_438);
3717 assert_eq!(offset(472_515, 3_742), 1_829);
3718 for k in [600, 1_585, 1_586, 2_664, 2_665, 3_744] {
3720 assert_eq!(
3721 offset(472_515, k),
3722 page_form(472_515, 16).of(k * DOT, LETTER)
3723 );
3724 }
3725 assert_eq!(
3727 binary32_page_form(472_515).of(3_743 * DOT + 1_000, LETTER),
3728 2_438
3729 );
3730 assert_eq!(binary32_page_form(472_515).of(3_743 * DOT, 0), 0);
3731 }
3732
3733 const DOT: i64 = 3_048;
3736
3737 const LETTER: i64 = 12_240 * 1_270;
3739
3740 #[test]
3741 fn offsets_a_place_by_whole_steps_as_if_the_page_were_larger() {
3742 for k in [600, 646, 692] {
3746 assert_eq!(page_form(472_515, 16).of(k * DOT, LETTER), 610);
3747 }
3748 assert_eq!(page_form(472_515, 16).of(0, LETTER), 0);
3749 assert_eq!(Offset::None.of(1_585 * DOT, LETTER), 0);
3750 }
3751
3752 #[test]
3753 fn rounds_the_product_of_the_page_form_before_the_division() {
3754 assert_eq!(page_form(473_073, 16).of(1_585 * DOT, LETTER), 1_219);
3758 assert_eq!(page_form(473_073, 16).of(1_583 * DOT, LETTER), 610);
3759 assert_eq!(page_form(473_073, 1).of(1_585 * DOT, LETTER), 610);
3760 assert_eq!(page_form(473_073, 0).of(1_585 * DOT, LETTER), 0);
3761 }
3762
3763 #[test]
3764 fn writes_a_rectangle_with_significant_digits() {
3765 use super::Item;
3770 let u = Length::from_units;
3771 let writer = Writer::new(u(10)).unwrap().with_digits(Some(non_zero(5)));
3772 let mut rect = Item::Rect(super::Rect {
3773 x: u(3_023_870),
3774 y: u(16_426_262),
3775 width: u(9_084_361),
3776 height: u(12_700),
3777 color: super::Rgb::BLACK,
3778 });
3779 write_digits(&writer, u(842 * 25_400), &mut rect);
3780 let Item::Rect(rect) = rect else {
3781 unreachable!()
3782 };
3783 assert_eq!(
3784 (
3785 rect.x.units(),
3786 rect.y.units(),
3787 rect.width.units(),
3788 rect.height.units()
3789 ),
3790 (3_023_870, 16_426_180, 9_084_310, 12_700)
3791 );
3792 }
3793
3794 #[test]
3795 fn writes_a_rectangle_from_its_edges_on_the_steps() {
3796 use super::Item;
3802 let u = Length::from_units;
3803 let writer = Writer::new(u(10))
3804 .unwrap()
3805 .with_digits(Some(non_zero(5)))
3806 .with_rectangle_steps(Some(non_zero(3_000)));
3807 let rect = |x, y, width, height| {
3808 Item::Rect(super::Rect {
3809 x: u(x),
3810 y: u(y),
3811 width: u(width),
3812 height: u(height),
3813 color: super::Rgb::BLACK,
3814 })
3815 };
3816 let mut rule = rect(8_029_651, 12_922_301, 12_192, 12_192);
3817 write_digits(&writer, u(792 * 25_400), &mut rule);
3818 let Item::Rect(rule) = rule else {
3819 unreachable!()
3820 };
3821 let edges = |r: &super::Rect| (r.x.units(), r.y.units(), r.width.units(), r.height.units());
3822 assert_eq!(edges(&rule), (8_029_702, 12_922_251, 12_192, 12_191));
3823 let mut wide = rect(-25_400, 12_922_301, 50_800, 12_192);
3826 write_digits(&writer, u(792 * 25_400), &mut wide);
3827 let Item::Rect(wide) = wide else {
3828 unreachable!()
3829 };
3830 assert_eq!(edges(&wide).2, 50_800);
3831 assert_eq!(writer.rectangle_steps(), Some(non_zero(3_000)));
3832 let far = || rect(25_974_446, 12_922_301, 12_192, 12_192);
3836 let written = |writer: Writer| {
3837 let mut item = far();
3838 write_digits(&writer, u(792 * 25_400), &mut item);
3839 let Item::Rect(written) = item else {
3840 unreachable!()
3841 };
3842 edges(&written)
3843 };
3844 let (left, top, _, tall) = written(writer);
3845 assert_eq!((left, top, tall), (25_974_040, 12_922_251, 12_191));
3846 let (left, top, _, tall) = written(writer.with_least_decimals(2));
3847 assert_eq!((left, top, tall), (25_974_548, 12_922_251, 12_191));
3848 }
3849
3850 #[test]
3851 fn writes_an_upright_image_with_significant_digits() {
3852 use super::{ImageItem, Item, Turn};
3856 let u = Length::from_units;
3857 let image = |turn| {
3858 Item::Image(ImageItem {
3859 x: u(1_143_000),
3860 y: u(1_682_799),
3861 width: u(914_400),
3862 height: u(1_219_200),
3863 clip: None,
3864 turn,
3865 image: Image::new(vec![0]),
3866 })
3867 };
3868 let turn = Turn {
3870 xx: 0,
3871 xy: -Turn::SCALE,
3872 yx: Turn::SCALE,
3873 yy: 0,
3874 };
3875 let placed = |writer: Writer| {
3876 let mut list = DisplayList {
3877 pages: vec![Page {
3878 width: u(612 * 25_400),
3879 height: u(792 * 25_400),
3880 orientation: Orientation::Portrait,
3881 items: vec![image(None), image(Some(turn))],
3882 }],
3883 };
3884 writer.finish(&mut list);
3885 writer.place_pictures(&mut list);
3886 list.pages[0]
3887 .items
3888 .iter()
3889 .map(|item| match item {
3890 Item::Image(image) => (image.x, image.y, image.width, image.height),
3891 _ => unreachable!(),
3892 })
3893 .collect::<Vec<_>>()
3894 };
3895 let exact = (u(1_143_000), u(1_682_799), u(914_400), u(1_219_200));
3896 let writer = Writer::new(u(10)).unwrap();
3897 assert_eq!(
3898 placed(writer.with_picture_digits(Some(non_zero(5)))),
3899 [
3900 (u(1_143_000), u(1_682_750), u(914_400), u(1_219_200)),
3901 exact
3902 ]
3903 );
3904 assert_eq!(
3906 placed(writer.with_digits(Some(non_zero(5)))),
3907 [exact, exact]
3908 );
3909 }
3910
3911 #[test]
3912 fn rounds_the_stretch_of_a_glyph_to_whole_steps() {
3913 use super::Item;
3914 let moved = |step: Option<i64>| {
3917 let writer = Writer::new(Length::from_units(10))
3918 .unwrap()
3919 .with_vertical_stretch(1)
3920 .with_glyph_stretch_step(step.map(Length::from_units))
3921 .unwrap();
3922 let mut list = DisplayList {
3923 pages: vec![sample_page()],
3924 };
3925 writer.finish(&mut list);
3926 let (Item::Glyphs(run), Item::Rect(rect)) =
3927 (&list.pages[0].items[0], &list.pages[0].items[1])
3928 else {
3929 panic!("no glyphs or rect")
3930 };
3931 (run.glyphs[0].y.units(), rect.y.units())
3932 };
3933 assert_eq!(moved(None), (402, 201));
3937 assert_eq!(moved(Some(3)), (403, 200));
3938 assert_eq!(moved(Some(5)), (400, 200));
3939 assert_eq!(moved(Some(4)), (404, 200));
3940 }
3941
3942 #[test]
3943 fn refuses_a_glyph_stretch_step_that_is_not_positive() {
3944 let writer = Writer::new(Length::from_units(10)).unwrap();
3945 assert_eq!(writer.with_glyph_stretch_step(Some(Length::ZERO)), None);
3946 assert_eq!(
3947 writer.with_glyph_stretch_step(Some(Length::from_units(-4))),
3948 None
3949 );
3950 assert_eq!(writer.with_glyph_stretch_step(None), Some(writer));
3951 }
3952
3953 fn stepping_writer() -> Writer {
3955 Writer::new(Length::from_units(10))
3956 .unwrap()
3957 .with_vertical_stretch(1)
3958 .with_glyph_stretch_step(Some(Length::from_units(4)))
3959 .unwrap()
3960 }
3961
3962 fn moved(offset: super::Fraction, factors: &[(Length, super::Fraction)]) -> (i64, i64) {
3966 use super::Item;
3967 let mut list = DisplayList {
3968 pages: vec![sample_page()],
3969 };
3970 stepping_writer()
3971 .with_stretch_factors(offset, factors)
3972 .unwrap()
3973 .finish(&mut list);
3974 let (Item::Glyphs(run), Item::Rect(rect)) =
3975 (&list.pages[0].items[0], &list.pages[0].items[1])
3976 else {
3977 panic!("no glyphs or rect")
3978 };
3979 (run.glyphs[0].y.units(), rect.y.units())
3980 }
3981
3982 #[test]
3983 fn counts_the_steps_of_the_stretch_with_the_factor_and_offset_of_the_page_height() {
3984 let u = Length::from_units;
3985 let page = u(2000);
3986 assert_eq!(moved((0, 1), &[]), (404, 200));
3987 assert_eq!(moved((0, 1), &[(page, (99, 100))]), (400, 200));
3989 assert_eq!(moved((1, 100), &[(page, (99, 100))]), (404, 200));
3990 assert_eq!(moved((-1, 100), &[(page, (1, 1))]), (400, 200));
3991 assert_eq!(moved((0, 1), &[(page, (2, 1))]), (404, 204));
3993 assert_eq!(moved((-1, 100), &[(u(3000), (2, 1))]), (404, 200));
3996 }
3997
3998 #[test]
3999 fn holds_no_stretch_factors_without_denominators_or_beyond_its_heights() {
4000 use super::STRETCH_HEIGHTS;
4001 let writer = stepping_writer();
4002 let page = Length::from_units(2000);
4003 assert_eq!(writer.with_stretch_factors((0, 0), &[]), None);
4004 assert_eq!(writer.with_stretch_factors((0, 1), &[(page, (1, 0))]), None);
4005 let many = [(page, (1, 1)); STRETCH_HEIGHTS + 1];
4006 assert_eq!(writer.with_stretch_factors((0, 1), &many), None);
4007 }
4008
4009 #[test]
4010 fn leaves_the_items_of_a_group_where_the_layout_puts_them() {
4011 use super::Item;
4012 let grouped = || {
4016 let mut page = sample_page();
4017 page.items = vec![Item::Group(super::Group::new(page.items))];
4018 page
4019 };
4020 let writer = Writer::new(Length::from_units(10))
4021 .unwrap()
4022 .with_vertical_stretch(1)
4023 .with_glyph_stretch_step(Some(Length::from_units(3)))
4024 .unwrap()
4025 .with_horizontal_offset(WriterOffset::EveryPage(Offset::Share {
4026 share: 2,
4027 bias: 0,
4028 step: 10,
4029 }))
4030 .with_digits(Some(non_zero(5)));
4031 let mut list = DisplayList {
4032 pages: vec![grouped()],
4033 };
4034 writer.finish(&mut list);
4035 assert_eq!(list.pages[0], grouped());
4036 let sample = sample_page();
4037 assert_eq!(list.pages[0].painted(), sample.painted());
4038 }
4039
4040 #[test]
4041 fn places_the_items_of_a_group_of_the_page_as_the_pages_items() {
4042 use super::{Group, GroupClip, Item};
4043 let writer = Writer::new(Length::from_units(10))
4047 .unwrap()
4048 .with_vertical_stretch(1)
4049 .with_glyph_stretch_step(Some(Length::from_units(3)))
4050 .unwrap()
4051 .with_horizontal_offset(WriterOffset::EveryPage(Offset::Share {
4052 share: 2,
4053 bias: 0,
4054 step: 10,
4055 }))
4056 .with_digits(Some(non_zero(5)));
4057 let u = Length::from_units;
4058 let mut plain = DisplayList {
4059 pages: vec![sample_page()],
4060 };
4061 writer.finish(&mut plain);
4062 let mut page = sample_page();
4063 let clip = GroupClip::rect(u(0), u(1000), u(500), u(1000));
4064 page.items = vec![Item::Group(Group::of_page(page.items, clip))];
4065 let mut grouped = DisplayList { pages: vec![page] };
4066 writer.finish(&mut grouped);
4067 let placed = DisplayList {
4068 pages: vec![Page {
4069 items: vec![Item::Group(Group::of_page(
4070 plain.pages[0].items.clone(),
4071 GroupClip::rect(u(0), u(1005), u(500), u(1005)),
4072 ))],
4073 ..plain.pages.remove(0)
4074 }],
4075 };
4076 assert_eq!(grouped, placed);
4077 }
4078
4079 #[test]
4080 fn moves_the_clip_of_a_table_cell_with_the_offsets_of_the_cells_items() {
4081 use super::{Group, GroupClip, Item, Rect, Rgb};
4082 let offset = WriterOffset::EveryPage(Offset::Share {
4086 share: 2,
4087 bias: 0,
4088 step: 10,
4089 });
4090 let writer = Writer::new(Length::from_units(10))
4091 .unwrap()
4092 .with_horizontal_offset(offset)
4093 .with_vertical_offset(offset);
4094 let u = Length::from_units;
4095 let (x, y, width, height) = (u(300), u(900), u(200), u(400));
4096 let fill = Item::Rect(Rect {
4097 x,
4098 y,
4099 width,
4100 height,
4101 color: Rgb::BLACK,
4102 });
4103 let clip = GroupClip::rect(x, y, width, height);
4104 let page = |group: fn(Vec<Item>, GroupClip) -> Group| Page {
4105 width: u(1000),
4106 height: u(2000),
4107 items: vec![Item::Group(group(vec![fill.clone()], clip.clone()))],
4108 ..sample_page()
4109 };
4110 let mut list = DisplayList {
4111 pages: vec![page(Group::of_cell), page(Group::of_page)],
4112 };
4113 writer.finish(&mut list);
4114 let group = |page: &Page| match &page.items[0] {
4115 Item::Group(group) => group.clone(),
4116 _ => unreachable!("the page holds one group"),
4117 };
4118 let cell = group(&list.pages[0]);
4119 let Item::Rect(moved) = &cell.items[0] else {
4120 unreachable!("the group holds one rectangle")
4121 };
4122 assert_ne!((moved.x, moved.y), (x, y));
4123 assert_eq!(
4124 cell.clip,
4125 Some(GroupClip::rect(moved.x, moved.y, moved.width, moved.height))
4126 );
4127 assert_eq!(group(&list.pages[1]).clip, Some(clip));
4128 }
4129
4130 #[test]
4131 fn moves_every_point_of_a_group_of_points_as_a_rectangles_edges() {
4132 use super::{Group, GroupClip, GroupPlaces, Item, PathItem, Rect, Rgb};
4133 let offset = WriterOffset::EveryPage(Offset::Share {
4137 share: 2,
4138 bias: 0,
4139 step: 10,
4140 });
4141 let writer = Writer::new(Length::from_units(10))
4142 .unwrap()
4143 .with_horizontal_offset(offset)
4144 .with_vertical_offset(offset);
4145 let u = Length::from_units;
4146 let (x, y, width, height) = (u(300), u(900), u(200), u(400));
4147 let fill = Item::Rect(Rect {
4148 x,
4149 y,
4150 width,
4151 height,
4152 color: Rgb::BLACK,
4153 });
4154 let outline = |x, y, width, height| GroupClip::rect(x, y, width, height).commands;
4155 let path = Item::Path(PathItem {
4156 commands: outline(x, y, width, height),
4157 color: Rgb::BLACK,
4158 fill_rule: super::FillRule::NonZero,
4159 });
4160 let page = |places| Page {
4161 width: u(1000),
4162 height: u(2000),
4163 items: vec![Item::Group(Group {
4164 items: vec![fill.clone(), path.clone()],
4165 clip: Some(GroupClip::rect(x, y, width, height)),
4166 places,
4167 })],
4168 ..sample_page()
4169 };
4170 let mut list = DisplayList {
4171 pages: vec![page(GroupPlaces::Points), page(GroupPlaces::Page)],
4172 };
4173 writer.finish(&mut list);
4174 let items = |page: &Page| match &page.items[0] {
4175 Item::Group(group) => (group.items.clone(), group.clip.clone()),
4176 _ => unreachable!("the page holds one group"),
4177 };
4178 let (moved, clip) = items(&list.pages[0]);
4179 let [Item::Rect(rect), Item::Path(drawn)] = moved.as_slice() else {
4180 unreachable!("the group holds a rectangle and a path")
4181 };
4182 assert_ne!((rect.x, rect.y), (x, y));
4183 let edges = outline(rect.x, rect.y, rect.width, rect.height);
4184 assert_eq!(drawn.commands, edges);
4185 assert_eq!(clip.map(|clip| clip.commands), Some(edges));
4186 let (kept, _) = items(&list.pages[1]);
4187 assert_eq!(kept[1], path);
4188 }
4189
4190 const LETTER_ACROSS: Offset = Offset::Page {
4193 steps: (472_515, 100_000),
4194 parts: 16,
4195 per_inch: 3_000,
4196 product: super::OffsetProduct::Binary32 { dots_per_inch: 600 },
4197 };
4198
4199 #[test]
4200 fn writes_an_edge_between_two_dots_by_the_entry_at_its_own_place() {
4201 let side = 612 * 25_400;
4205 let between = 4_700 * 3_048 + 122;
4206 assert_eq!(LETTER_ACROSS.written_place(between, side), 14_328_648);
4207 assert_eq!(between + LETTER_ACROSS.of(between, side), 14_328_160);
4208 let dot = 4_800 * 3_048;
4209 assert_eq!(LETTER_ACROSS.written_place(dot, side), 14_632_838);
4210 assert_eq!(dot + LETTER_ACROSS.of(dot, side), 14_632_838);
4211 let share = Offset::Share {
4213 share: 2,
4214 bias: 0,
4215 step: 10,
4216 };
4217 assert_eq!(
4218 share.written_place(between, side),
4219 between + share.of(between, side)
4220 );
4221 }
4222
4223 fn drawn_rectangles(places: super::GroupPlaces) -> Vec<super::Item> {
4227 use super::{Group, Item, Rect};
4228 let u = Length::from_units;
4229 let writer = Writer::new(u(1))
4230 .unwrap()
4231 .with_horizontal_offset(WriterOffset::EveryPage(LETTER_ACROSS));
4232 let rect = Rect {
4233 x: u(4_700 * 3_048 + 122),
4234 y: u(9_000_000),
4235 width: u(3_048),
4236 height: u(50_000),
4237 color: Rgb::BLACK,
4238 };
4239 let wide = Rect {
4240 width: u(4 * 3_048),
4241 ..rect.clone()
4242 };
4243 let mut list = DisplayList {
4244 pages: vec![Page {
4245 width: u(612 * 25_400),
4246 height: u(792 * 25_400),
4247 items: vec![Item::Group(Group {
4248 items: vec![Item::Rect(rect), Item::Rect(wide)],
4249 clip: None,
4250 places,
4251 })],
4252 ..sample_page()
4253 }],
4254 };
4255 writer.finish(&mut list);
4256 match &list.pages[0].items[0] {
4257 Item::Group(group) => group.items.clone(),
4258 _ => unreachable!("the page holds one group"),
4259 }
4260 }
4261
4262 #[test]
4263 fn draws_a_stroked_rectangle_and_then_its_stroke_after_placing_its_edges() {
4264 use super::{FillRule, GroupPlaces, Item, PathCommand, Point};
4265 let u = Length::from_units;
4271 let stroked = drawn_rectangles(GroupPlaces::Stroked { width: u(3_556) });
4272 let [Item::Rect(placed), Item::Path(outline), ..] = stroked.as_slice() else {
4273 unreachable!("each rectangle and then its stroke's outline")
4274 };
4275 assert_eq!(placed.x, u(14_328_648));
4276 assert_eq!(placed.width, u(14_331_696 - 14_328_648));
4277 assert_eq!((placed.y, placed.height), (u(9_000_000), u(50_000)));
4278 assert_eq!(
4279 (outline.color, outline.fill_rule),
4280 (Rgb::BLACK, FillRule::NonZero)
4281 );
4282 let (right, below) = (u(14_331_696), u(9_050_000) + u(1_778));
4283 let at = |x, y| Point { x, y };
4284 assert_eq!(
4287 outline.commands[..3],
4288 [
4289 PathCommand::MoveTo(at(u(14_328_648), below)),
4290 PathCommand::LineTo(at(right, below)),
4291 PathCommand::CubicTo(
4292 at(right + u(982), below),
4293 at(right + u(1_778), u(9_050_000) + u(982)),
4294 at(right + u(1_778), u(9_050_000)),
4295 ),
4296 ]
4297 );
4298 assert_eq!(outline.commands.len(), 10);
4299 let points = drawn_rectangles(GroupPlaces::Points);
4300 let [Item::Rect(nearest), Item::Rect(_)] = points.as_slice() else {
4301 unreachable!("a group of points draws the rectangles alone")
4302 };
4303 assert_eq!(nearest.x, u(14_328_160));
4304 }
4305
4306 #[test]
4307 fn draws_the_inner_outline_of_the_stroke_of_a_rectangle_wider_than_the_stroke() {
4308 use super::{GroupPlaces, Item, PathCommand, Point};
4309 let u = Length::from_units;
4313 let stroked = drawn_rectangles(GroupPlaces::Stroked { width: u(3_556) });
4314 let [_, _, Item::Rect(wide), Item::Path(outline)] = stroked.as_slice() else {
4315 unreachable!("each rectangle and then its stroke's outline")
4316 };
4317 let (left, right, bottom) = (wide.x, wide.x + wide.width, u(9_050_000));
4318 assert_eq!(left, u(14_328_648));
4319 let at = |x, y| Point { x, y };
4320 assert_eq!(
4321 outline.commands[10..13],
4322 [
4323 PathCommand::MoveTo(at(left, bottom - u(1_778))),
4324 PathCommand::LineTo(at(left + u(1_778), bottom)),
4325 PathCommand::LineTo(at(left + u(1_778), u(9_000_000))),
4326 ]
4327 );
4328 assert_eq!(
4329 outline.commands[17],
4330 PathCommand::LineTo(at(right, bottom - u(1_778)))
4331 );
4332 assert_eq!(outline.commands.len(), 20);
4333 }
4334
4335 #[test]
4336 fn writes_every_point_of_a_group_of_points_with_the_writers_digits() {
4337 use super::{Group, GroupPlaces, Item, PathCommand, PathItem, Point, Rgb};
4338 let u = Length::from_units;
4341 let point = Point {
4342 x: u(3_135_800),
4343 y: u(17_783_134),
4344 };
4345 let height = u(792 * 25_400);
4346 let page = Page {
4347 width: u(612 * 25_400),
4348 height,
4349 items: vec![Item::Group(Group {
4350 items: vec![Item::Path(PathItem {
4351 commands: vec![PathCommand::MoveTo(point), PathCommand::Close],
4352 color: Rgb::BLACK,
4353 fill_rule: super::FillRule::NonZero,
4354 })],
4355 clip: None,
4356 places: GroupPlaces::Points,
4357 })],
4358 ..sample_page()
4359 };
4360 let written = |steps: Option<u32>| {
4361 let writer = Writer::new(Length::from_units(1))
4362 .unwrap()
4363 .with_digits(Some(non_zero(5)))
4364 .with_rectangle_steps(steps.map(non_zero));
4365 let mut list = DisplayList {
4366 pages: vec![page.clone()],
4367 };
4368 writer.finish(&mut list);
4369 match &list.pages[0].items[0] {
4370 Item::Group(group) => match &group.items[0] {
4371 Item::Path(path) => path.commands[0].points().next(),
4372 _ => None,
4373 },
4374 _ => None,
4375 }
4376 };
4377 let plain = written(None).unwrap();
4378 assert_eq!(plain.x, u(3_135_884));
4379 assert_eq!(plain.y, super::written_y(height, point.y, (5, 0)));
4380 assert_eq!(written(Some(3_000)), Some(plain));
4383 }
4384
4385 fn stretched() -> Page {
4388 let writer = Writer::new(Length::from_units(10))
4389 .unwrap()
4390 .with_vertical_stretch(1);
4391 let mut list = DisplayList {
4392 pages: vec![sample_page()],
4393 };
4394 writer.finish(&mut list);
4395 list.pages.remove(0)
4396 }
4397
4398 fn sample_page() -> Page {
4400 use super::{Clip, Glyph, GlyphRun, ImageItem, Item, PathCommand, PathItem, Point, Rect};
4401 let u = Length::from_units;
4402 let glyph = Glyph {
4403 id: 1,
4404 x: u(500),
4405 y: u(400),
4406 text_start: 0,
4407 text_end: 1,
4408 };
4409 let items = vec![
4410 Item::Glyphs(GlyphRun {
4411 font: f_office_fonts::FontId::from_index(0),
4412 size: u(120),
4413 color: super::Rgb::default(),
4414 text: "a".to_owned(),
4415 glyphs: vec![glyph],
4416 outline: None,
4417 filled: true,
4418 effect: false,
4419 turn: None,
4420 }),
4421 Item::Rect(Rect {
4422 x: u(100),
4423 y: u(200),
4424 width: u(300),
4425 height: u(400),
4426 color: super::Rgb::default(),
4427 }),
4428 Item::Path(PathItem {
4429 commands: vec![PathCommand::MoveTo(Point {
4430 x: u(1000),
4431 y: u(2000),
4432 })],
4433 color: super::Rgb::default(),
4434 fill_rule: super::FillRule::NonZero,
4435 }),
4436 Item::Image(ImageItem {
4437 x: u(0),
4438 y: u(0),
4439 width: u(1000),
4440 height: u(2000),
4441 clip: Some(Clip {
4442 x: u(100),
4443 y: u(200),
4444 width: u(100),
4445 height: u(200),
4446 }),
4447 turn: None,
4448 image: Image::new(vec![0]),
4449 }),
4450 ];
4451 Page {
4452 width: u(1000),
4453 height: u(2000),
4454 orientation: Orientation::Portrait,
4455 items,
4456 }
4457 }
4458
4459 #[test]
4460 fn detects_formats_from_their_signatures() {
4461 let mut emf = vec![1, 0, 0, 0];
4462 emf.resize(40, 0);
4463 emf.extend_from_slice(b" EMF");
4464 let cases: [(&[u8], ImageFormat); 12] = [
4465 (b"\x89PNG\r\n\x1a\nrest", ImageFormat::Png),
4466 (&[0xFF, 0xD8, 0xFF, 0xE0], ImageFormat::Jpeg),
4467 (b"GIF89a", ImageFormat::Gif),
4468 (b"GIF87a", ImageFormat::Gif),
4469 (b"BM", ImageFormat::Bmp),
4470 (b"II*\0", ImageFormat::Tiff),
4471 (b"MM\0*", ImageFormat::Tiff),
4472 (&emf, ImageFormat::Emf),
4473 (&[0xD7, 0xCD, 0xC6, 0x9A], ImageFormat::Wmf),
4474 (&[1, 0, 9, 0], ImageFormat::Wmf),
4475 (&[2, 0, 9, 0], ImageFormat::Wmf),
4476 (&[1, 0, 0, 0], ImageFormat::Unknown),
4477 ];
4478 for (data, format) in cases {
4479 assert_eq!(ImageFormat::detect(data), format, "{data:?}");
4480 }
4481 assert_eq!(ImageFormat::detect(&emf[..43]), ImageFormat::Unknown);
4482 assert_eq!(ImageFormat::detect(b""), ImageFormat::Unknown);
4483 }
4484
4485 #[test]
4486 fn shares_the_bytes_of_an_image() {
4487 let image = Image::new(vec![0xFF, 0xD8, 0xFF]);
4488 assert_eq!(image.format, ImageFormat::Jpeg);
4489 let copy = image.clone();
4490 assert!(Arc::ptr_eq(
4491 image.data.inline_bytes().unwrap(),
4492 copy.data.inline_bytes().unwrap()
4493 ));
4494 }
4495
4496 #[test]
4497 fn shows_the_part_of_a_clip_that_lies_on_the_image() {
4498 let length = Length::from_units;
4499 let clip = |x, y, width, height| super::Clip {
4500 x: length(x),
4501 y: length(y),
4502 width: length(width),
4503 height: length(height),
4504 };
4505 let item = |clip| super::ImageItem {
4506 x: length(100),
4507 y: length(200),
4508 width: length(80),
4509 height: length(40),
4510 clip,
4511 turn: None,
4512 image: Image::new(vec![0xFF, 0xD8, 0xFF]),
4513 };
4514 assert_eq!(
4516 item(Some(clip(100, 200, 100, 30))).shown(),
4517 Some(clip(100, 200, 80, 30))
4518 );
4519 assert_eq!(
4521 item(Some(clip(90, 190, 100, 60))).shown(),
4522 Some(clip(100, 200, 80, 40))
4523 );
4524 assert_eq!(item(Some(clip(180, 200, 10, 40))).shown(), None);
4525 assert_eq!(item(None).shown(), None);
4526 }
4527
4528 #[test]
4529 fn first_place_is_the_first_place_that_map_places_maps() {
4530 use super::{Group, GroupPlaces, Item, Rect};
4531 let rect = |y| {
4532 Item::Rect(Rect {
4533 x: Length::from_units(1),
4534 y: Length::from_units(y),
4535 width: Length::from_units(2),
4536 height: Length::from_units(3),
4537 color: Rgb::BLACK,
4538 })
4539 };
4540 let group = |items| {
4541 Item::Group(Group {
4542 items,
4543 clip: None,
4544 places: GroupPlaces::Own,
4545 })
4546 };
4547 let empty = group(Vec::new());
4548 let nested = group(vec![empty.clone(), rect(5), rect(7)]);
4549 for item in [rect(4), empty, nested] {
4550 let mut mapped = None;
4551 item.clone().map_places(
4552 |place| {
4553 mapped.get_or_insert(place);
4554 place
4555 },
4556 |length| length,
4557 );
4558 assert_eq!(item.first_place(), mapped);
4559 }
4560 }
4561
4562 fn four_stops() -> super::GradientItem {
4565 use super::{FillRule, GradientItem, GradientStop, Point};
4566 let origin = Point {
4567 x: Length::ZERO,
4568 y: Length::ZERO,
4569 };
4570 let stops = vec![
4571 GradientStop::new(100_000, Rgb::BLACK),
4572 GradientStop::new(
4573 500_000,
4574 Rgb {
4575 r: 201,
4576 g: 10,
4577 b: 0,
4578 },
4579 ),
4580 GradientStop::new(500_000, Rgb { r: 0, g: 0, b: 255 }),
4581 GradientStop::new(GradientStop::END, Rgb::WHITE),
4582 ];
4583 GradientItem::new(Vec::new(), FillRule::NonZero, (origin, origin), stops)
4584 }
4585
4586 #[test]
4587 fn gives_the_color_of_a_gradient_between_its_stops_and_beyond_its_ends() {
4588 let gradient = four_stops();
4589 assert_eq!(gradient.color_at(-5), Rgb::BLACK);
4590 assert_eq!(gradient.color_at(50_000), Rgb::BLACK);
4591 assert_eq!(gradient.color_at(2_000_000), Rgb::WHITE);
4592 assert_eq!(gradient.color_at(300_000), Rgb { r: 101, g: 5, b: 0 });
4594 assert_eq!(
4595 gradient.color_at(750_000),
4596 Rgb {
4597 r: 128,
4598 g: 128,
4599 b: 255
4600 }
4601 );
4602 }
4603
4604 #[test]
4605 fn gives_the_later_color_where_two_stops_meet_and_black_without_stops() {
4606 let gradient = four_stops();
4607 assert_eq!(
4608 gradient.color_at(499_999),
4609 Rgb {
4610 r: 201,
4611 g: 10,
4612 b: 0
4613 }
4614 );
4615 assert_eq!(gradient.color_at(500_000), Rgb { r: 0, g: 0, b: 255 });
4616 let mut empty = gradient;
4617 empty.stops.clear();
4618 assert_eq!(empty.color_at(0), Rgb::BLACK);
4619 }
4620
4621 #[test]
4622 fn moves_the_axis_of_a_gradient_with_its_outline() {
4623 use super::{FillRule, GradientItem, Item, PathCommand, Point};
4624 let at = |x, y| Point {
4625 x: Length::from_units(x),
4626 y: Length::from_units(y),
4627 };
4628 let mut item = Item::Gradient(GradientItem::new(
4629 vec![PathCommand::MoveTo(at(1, 2)), PathCommand::LineTo(at(3, 4))],
4630 FillRule::NonZero,
4631 (at(0, 0), at(10, 0)),
4632 Vec::new(),
4633 ));
4634 item.map_places(
4635 |p| Point {
4636 x: p.x + Length::from_units(100),
4637 y: p.y,
4638 },
4639 |length| length,
4640 );
4641 let Item::Gradient(moved) = &item else {
4642 panic!("not a gradient");
4643 };
4644 assert_eq!(moved.commands[0], PathCommand::MoveTo(at(101, 2)));
4645 assert_eq!((moved.start, moved.end), (at(100, 0), at(110, 0)));
4646 assert_eq!(item.first_place(), Some(at(101, 2)));
4647 }
4648}