1use std::collections::{BTreeMap, BTreeSet};
28use std::hash::{DefaultHasher, Hash, Hasher};
29
30use serde::{Deserialize, Serialize};
31
32use crate::Warning;
33use crate::content::{Block, Book};
34use crate::style::{ComputedStyle, ShapeOutside, StyleTree, Url};
35
36pub trait ImageLoader {
41 fn load(&self, url: &str) -> Option<Vec<u8>>;
44}
45
46pub struct NoImages;
48
49impl ImageLoader for NoImages {
50 fn load(&self, _url: &str) -> Option<Vec<u8>> {
51 None
52 }
53}
54
55impl ImageLoader for Assets {
58 fn load(&self, url: &str) -> Option<Vec<u8>> {
59 let (index, _) = self.lookup(url)?;
60 self.bytes(index).map(<[u8]>::to_vec)
61 }
62}
63
64pub const CSS_DPI: f32 = 96.0;
67
68#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
75pub struct Intrinsic {
76 pub width: u32,
78 pub height: u32,
80 pub dpi_x: f32,
82 pub dpi_y: f32,
84 pub sized: bool,
89}
90
91impl Intrinsic {
92 pub fn size(self) -> (f32, f32) {
96 (
97 self.width as f32 / self.dpi_x * 72.0,
98 self.height as f32 / self.dpi_y * 72.0,
99 )
100 }
101
102 pub fn size_within(self, measure: f32) -> (f32, f32) {
106 let (width, height) = self.size();
107 if self.sized || width <= 0.0 {
108 return (width, height);
109 }
110 (measure, measure * height / width)
111 }
112}
113
114#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
120pub struct Asset {
121 pub url: String,
123 pub intrinsic: Intrinsic,
125}
126
127#[derive(Debug, Default)]
132pub struct Assets {
133 assets: Vec<Asset>,
134 files: Vec<Vec<u8>>,
138 hashes: Vec<u64>,
142 refused: BTreeSet<String>,
146 warnings: Vec<Warning>,
147}
148
149#[derive(Debug, Clone, Copy, PartialEq)]
151pub enum Added {
152 Unchanged(u32),
154 Replaced {
160 index: u32,
162 previous: Option<Intrinsic>,
164 current: Intrinsic,
166 },
167 Refused,
169}
170
171fn content_hash(bytes: &[u8]) -> u64 {
174 let mut hasher = DefaultHasher::new();
175 bytes.hash(&mut hasher);
176 hasher.finish()
177}
178
179impl Assets {
180 pub fn none() -> Assets {
182 Assets::default()
183 }
184
185 pub fn probe(book: &Book, styles: &StyleTree, loader: &dyn ImageLoader) -> Assets {
193 let mut assets = Assets::default();
194 for section in &book.sections {
195 assets.walk(§ion.blocks, loader);
196 }
197 for background in backgrounds(styles) {
198 assets.take(background, loader);
199 }
200 assets
201 }
202
203 pub fn add(&mut self, url: &str, bytes: Vec<u8>) -> Added {
214 let hash = content_hash(&bytes);
215 if let Some(index) = self.assets.iter().position(|asset| asset.url == url) {
216 if self.hashes[index] == hash {
217 return Added::Unchanged(index as u32);
218 }
219 return match probe(&bytes) {
220 Some(intrinsic) => {
221 let previous = self.assets[index].intrinsic;
222 self.assets[index] = Asset {
223 url: url.to_string(),
224 intrinsic,
225 };
226 self.files[index] = bytes;
227 self.hashes[index] = hash;
228 self.refused.remove(url);
229 Added::Replaced {
230 index: index as u32,
231 previous: Some(previous),
232 current: intrinsic,
233 }
234 }
235 None => {
236 self.refuse(url, None);
237 Added::Refused
238 }
239 };
240 }
241 match probe(&bytes) {
242 Some(intrinsic) => {
243 self.refused.remove(url);
244 self.assets.push(Asset {
245 url: url.to_string(),
246 intrinsic,
247 });
248 self.files.push(bytes);
249 self.hashes.push(hash);
250 Added::Replaced {
251 index: self.assets.len() as u32 - 1,
252 previous: None,
253 current: intrinsic,
254 }
255 }
256 None => {
257 self.refuse(url, None);
258 Added::Refused
259 }
260 }
261 }
262
263 pub fn lookup(&self, url: &str) -> Option<(u32, Intrinsic)> {
265 self.assets
266 .iter()
267 .position(|asset| asset.url == url)
268 .map(|index| (index as u32, self.assets[index].intrinsic))
269 }
270
271 pub fn probed(&self, url: &str) -> bool {
275 self.refused.contains(url) || self.lookup(url).is_some()
276 }
277
278 pub fn assets(&self) -> &[Asset] {
280 &self.assets
281 }
282
283 pub fn bytes(&self, index: u32) -> Option<&[u8]> {
286 self.files.get(index as usize).map(Vec::as_slice)
287 }
288
289 pub fn digest(&self, index: u32) -> Option<u64> {
293 self.hashes.get(index as usize).copied()
294 }
295
296 pub fn warnings(&self) -> &[Warning] {
298 &self.warnings
299 }
300
301 fn refuse(&mut self, url: &str, origin: Option<String>) {
302 if self.refused.insert(url.to_string()) {
303 self.warnings.push(Warning {
304 message: format!("Image {url} has no size in it. The image is skipped."),
305 origin,
306 });
307 }
308 }
309
310 fn take(&mut self, url: &Url, loader: &dyn ImageLoader) {
313 if self.probed(&url.value) {
314 return;
315 }
316 match loader.load(&url.value) {
317 Some(bytes) => match probe(&bytes) {
318 Some(intrinsic) => {
319 self.assets.push(Asset {
320 url: url.value.clone(),
321 intrinsic,
322 });
323 self.hashes.push(content_hash(&bytes));
324 self.files.push(bytes);
325 }
326 None => self.refuse(&url.value, url.origin.clone()),
327 },
328 None => self.refuse(&url.value, url.origin.clone()),
329 }
330 }
331
332 fn walk(&mut self, blocks: &[Block], loader: &dyn ImageLoader) {
333 for block in blocks {
334 match block {
335 Block::Image { url, position, .. } => {
336 if self.probed(url) {
337 continue;
338 }
339 let origin = Some(crate::content::origin(None, *position));
340 match loader.load(url) {
341 Some(bytes) => match probe(&bytes) {
342 Some(intrinsic) => {
343 self.assets.push(Asset {
344 url: url.clone(),
345 intrinsic,
346 });
347 self.hashes.push(content_hash(&bytes));
348 self.files.push(bytes);
349 }
350 None => self.refuse(url, origin),
351 },
352 None => self.refuse(url, origin),
353 }
354 }
355 Block::Blockquote { blocks, .. } => self.walk(blocks, loader),
356 Block::Table { head, body, .. } => {
357 for blocks in crate::content::cell_blocks(head, body) {
358 self.walk(blocks, loader);
359 }
360 }
361 _ => {}
362 }
363 }
364 }
365}
366
367pub fn backgrounds(styles: &StyleTree) -> Vec<&Url> {
370 styles
371 .styles()
372 .iter()
373 .filter_map(|style| style.background.image.as_ref())
374 .chain(
375 styles
376 .masters()
377 .iter()
378 .filter_map(|master| master.style.background.image.as_ref()),
379 )
380 .collect()
381}
382
383#[derive(Debug, Default)]
397pub struct Contours {
398 traced: BTreeMap<u32, Traced>,
399 warned: BTreeSet<String>,
400 warnings: Vec<Warning>,
401}
402
403fn traceable(style: &ComputedStyle) -> bool {
409 style.shape_outside == ShapeOutside::Auto && style.excludes()
410}
411
412#[derive(Debug)]
414struct Traced {
415 digest: u64,
416 contour: Option<Contour>,
417}
418
419impl Contours {
420 pub fn none() -> Contours {
423 Contours::default()
424 }
425
426 pub fn update(&mut self, book: &Book, styles: &StyleTree, assets: &Assets) -> u32 {
432 fn walk(
433 contours: &mut Contours,
434 blocks: &[Block],
435 source: Option<&str>,
436 styles: &StyleTree,
437 assets: &Assets,
438 traced: &mut u32,
439 ) {
440 for block in blocks {
441 match block {
442 Block::Blockquote { blocks, .. } => {
443 walk(contours, blocks, source, styles, assets, traced)
444 }
445 Block::Table { head, body, .. } => {
446 for blocks in crate::content::cell_blocks(head, body) {
447 walk(contours, blocks, source, styles, assets, traced);
448 }
449 }
450 Block::Image {
451 id, url, position, ..
452 } if traceable(styles.style(*id)) => {
453 let Some(((index, _), digest)) = assets
454 .lookup(url)
455 .and_then(|found| Some((found, assets.digest(found.0)?)))
456 else {
457 continue;
458 };
459 let kept = contours
460 .traced
461 .get(&index)
462 .is_some_and(|kept| kept.digest == digest);
463 if !kept {
464 let contour = assets.bytes(index).and_then(trace);
465 *traced += 1;
466 contours.traced.insert(index, Traced { digest, contour });
467 }
468 if contours.get(index).is_none() && contours.warned.insert(url.clone()) {
469 let origin = crate::content::origin(source, *position);
470 contours.warnings.push(Warning {
471 message: format!(
472 "Missing alpha channel in {url}. Text wraps around the \
473 image rectangle."
474 ),
475 origin: (!origin.is_empty()).then_some(origin),
476 });
477 }
478 }
479 _ => {}
480 }
481 }
482 }
483 self.warnings.clear();
486 self.warned.clear();
487 let mut traced = 0;
488 for section in &book.sections {
489 walk(
490 self,
491 §ion.blocks,
492 section.source.as_deref(),
493 styles,
494 assets,
495 &mut traced,
496 );
497 }
498 traced
499 }
500
501 pub fn get(&self, asset: u32) -> Option<&Contour> {
504 self.traced.get(&asset)?.contour.as_ref()
505 }
506
507 pub fn traces(&self, asset: u32) -> bool {
510 self.traced.contains_key(&asset)
511 }
512
513 pub fn warnings(&self) -> &[Warning] {
515 &self.warnings
516 }
517}
518
519#[derive(Debug, Clone, PartialEq)]
526pub struct Contour {
527 pub rings: Vec<Vec<[f32; 2]>>,
529}
530
531const ROWS: u32 = 128;
534
535const CEILING: u64 = 32 * 1024 * 1024;
539
540struct Mask {
542 width: u32,
543 height: u32,
544 alpha: Vec<u8>,
545}
546
547impl Mask {
548 fn rows(&self) -> Vec<Option<(u32, u32)>> {
551 (0..self.height)
552 .map(|y| {
553 let row = &self.alpha[(y * self.width) as usize..][..self.width as usize];
554 let first = row.iter().position(|alpha| *alpha > 0)? as u32;
555 let last = row.iter().rposition(|alpha| *alpha > 0)? as u32;
556 Some((first, last + 1))
557 })
558 .collect()
559 }
560}
561
562pub fn trace(bytes: &[u8]) -> Option<Contour> {
570 let mask = mask(bytes)?;
571 let rows = mask.rows();
572 let bands: Vec<Option<(f32, f32)>> = (0..ROWS)
573 .map(|band| {
574 let from = (band as u64 * mask.height as u64 / ROWS as u64) as usize;
575 let to = ((band as u64 + 1) * mask.height as u64 / ROWS as u64).max(from as u64 + 1);
576 rows.get(from..(to as usize).min(rows.len()))?
577 .iter()
578 .flatten()
579 .copied()
580 .reduce(|(left, right), (start, end)| (left.min(start), right.max(end)))
581 .map(|(left, right)| {
582 (
583 left as f32 / mask.width as f32,
584 right as f32 / mask.width as f32,
585 )
586 })
587 })
588 .collect();
589 Some(Contour {
590 rings: rings(&bands),
591 })
592}
593
594fn rings(bands: &[Option<(f32, f32)>]) -> Vec<Vec<[f32; 2]>> {
598 let mut rings = Vec::new();
599 let mut run: Vec<(usize, (f32, f32))> = Vec::new();
600 let height = bands.len() as f32;
601 let close = |run: &mut Vec<(usize, (f32, f32))>, rings: &mut Vec<Vec<[f32; 2]>>| {
602 if run.is_empty() {
603 return;
604 }
605 let edge = |side: fn(&(f32, f32)) -> f32, run: &[(usize, (f32, f32))]| {
606 let mut points: Vec<[f32; 2]> = Vec::new();
607 for (band, span) in run {
608 let (top, bottom) = (*band as f32 / height, (*band + 1) as f32 / height);
609 let x = side(span);
610 match points.last_mut() {
613 Some(last) if last[0] == x => last[1] = bottom,
614 _ => {
615 points.push([x, top]);
616 points.push([x, bottom]);
617 }
618 }
619 }
620 points
621 };
622 let mut ring = edge(|span| span.0, run);
623 let mut right = edge(|span| span.1, run);
624 right.reverse();
625 ring.append(&mut right);
626 rings.push(ring);
627 run.clear();
628 };
629 for (band, span) in bands.iter().enumerate() {
630 match span {
631 Some(span) => run.push((band, *span)),
632 None => close(&mut run, &mut rings),
633 }
634 }
635 close(&mut run, &mut rings);
636 rings
637}
638
639fn mask(bytes: &[u8]) -> Option<Mask> {
641 let intrinsic = probe(bytes)?;
642 if intrinsic.width as u64 * intrinsic.height as u64 > CEILING {
643 return None;
644 }
645 png_mask(bytes)
646 .or_else(|| webp_mask(bytes))
647 .or_else(|| gif_mask(bytes))
648}
649
650fn png_mask(bytes: &[u8]) -> Option<Mask> {
653 let mut decoder = png::Decoder::new(bytes);
654 decoder.set_transformations(png::Transformations::normalize_to_color8());
655 let mut reader = decoder.read_info().ok()?;
656 let (channels, offset) = match reader.output_color_type() {
657 (png::ColorType::Rgba, _) => (4, 3),
658 (png::ColorType::GrayscaleAlpha, _) => (2, 1),
659 _ => return None,
660 };
661 let mut buffer = vec![0u8; reader.output_buffer_size()];
662 let info = reader.next_frame(&mut buffer).ok()?;
663 Some(Mask {
664 width: info.width,
665 height: info.height,
666 alpha: buffer[..(info.width * info.height * channels) as usize]
667 .iter()
668 .skip(offset)
669 .step_by(channels as usize)
670 .copied()
671 .collect(),
672 })
673}
674
675fn webp_mask(bytes: &[u8]) -> Option<Mask> {
677 let mut decoder = image_webp::WebPDecoder::new(std::io::Cursor::new(bytes)).ok()?;
678 if !decoder.has_alpha() {
679 return None;
680 }
681 let (width, height) = decoder.dimensions();
682 let mut buffer = vec![0u8; decoder.output_buffer_size()?];
683 decoder.read_image(&mut buffer).ok()?;
684 Some(Mask {
685 width,
686 height,
687 alpha: buffer.iter().skip(3).step_by(4).copied().collect(),
688 })
689}
690
691fn gif_mask(bytes: &[u8]) -> Option<Mask> {
695 let mut options = gif::DecodeOptions::new();
696 options.set_color_output(gif::ColorOutput::RGBA);
697 let mut decoder = options.read_info(bytes).ok()?;
698 let (width, height) = (decoder.width() as u32, decoder.height() as u32);
699 let frame = decoder.read_next_frame().ok()??;
700 let mut alpha = vec![0u8; (width * height) as usize];
701 for y in 0..frame.height as u32 {
702 for x in 0..frame.width as u32 {
703 let (at_x, at_y) = (x + frame.left as u32, y + frame.top as u32);
704 if at_x >= width || at_y >= height {
705 continue;
706 }
707 alpha[(at_y * width + at_x) as usize] =
708 frame.buffer[((y * frame.width as u32 + x) * 4 + 3) as usize];
709 }
710 }
711 Some(Mask {
712 width,
713 height,
714 alpha,
715 })
716}
717
718pub fn probe(bytes: &[u8]) -> Option<Intrinsic> {
721 png(bytes)
722 .or_else(|| jpeg(bytes))
723 .or_else(|| gif(bytes))
724 .or_else(|| webp(bytes))
725 .or_else(|| svg(bytes))
726}
727
728pub fn is_svg(bytes: &[u8]) -> bool {
730 svg_root(bytes).is_some()
731}
732
733fn be32(bytes: &[u8], at: usize) -> Option<u32> {
734 let slice: [u8; 4] = bytes.get(at..at + 4)?.try_into().ok()?;
735 Some(u32::from_be_bytes(slice))
736}
737
738fn be16(bytes: &[u8], at: usize) -> Option<u16> {
739 let slice: [u8; 2] = bytes.get(at..at + 2)?.try_into().ok()?;
740 Some(u16::from_be_bytes(slice))
741}
742
743fn le16(bytes: &[u8], at: usize) -> Option<u16> {
744 let slice: [u8; 2] = bytes.get(at..at + 2)?.try_into().ok()?;
745 Some(u16::from_le_bytes(slice))
746}
747
748fn png(bytes: &[u8]) -> Option<Intrinsic> {
751 if !bytes.starts_with(b"\x89PNG\r\n\x1a\n") || bytes.get(12..16)? != b"IHDR" {
752 return None;
753 }
754 let mut intrinsic = Intrinsic {
755 width: be32(bytes, 16)?,
756 height: be32(bytes, 20)?,
757 dpi_x: CSS_DPI,
758 dpi_y: CSS_DPI,
759 sized: true,
760 };
761 let mut at = 8usize;
762 while let (Some(length), Some(kind)) = (be32(bytes, at), bytes.get(at + 4..at + 8)) {
763 if kind == b"pHYs" {
764 let data = at + 8;
765 if bytes.get(data + 8) == Some(&1) {
768 let (x, y) = (be32(bytes, data)?, be32(bytes, data + 4)?);
769 if x > 0 && y > 0 {
770 intrinsic.dpi_x = x as f32 * 0.0254;
771 intrinsic.dpi_y = y as f32 * 0.0254;
772 }
773 }
774 break;
775 }
776 if kind == b"IDAT" {
777 break;
778 }
779 at = at.checked_add(12)?.checked_add(length as usize)?;
780 }
781 Some(intrinsic)
782}
783
784fn jpeg(bytes: &[u8]) -> Option<Intrinsic> {
787 if !bytes.starts_with(&[0xFF, 0xD8]) {
788 return None;
789 }
790 let (mut dpi_x, mut dpi_y) = (CSS_DPI, CSS_DPI);
791 let mut at = 2usize;
792 loop {
793 if bytes.get(at) != Some(&0xFF) {
794 return None;
795 }
796 let marker = *bytes.get(at + 1)?;
797 if marker == 0xFF {
800 at += 1;
801 continue;
802 }
803 if (0xD0..=0xD9).contains(&marker) || marker == 0x01 {
804 at += 2;
805 continue;
806 }
807 let length = be16(bytes, at + 2)? as usize;
808 let data = at + 4;
809 if marker == 0xE0 && bytes.get(data..data + 5) == Some(b"JFIF\0") {
810 let (x, y) = (be16(bytes, data + 8)?, be16(bytes, data + 10)?);
811 let per_inch = match bytes.get(data + 7) {
812 Some(1) => Some(1.0),
813 Some(2) => Some(2.54),
814 _ => None,
815 };
816 if let Some(scale) = per_inch
817 && x > 0
818 && y > 0
819 {
820 dpi_x = x as f32 * scale;
821 dpi_y = y as f32 * scale;
822 }
823 }
824 if (0xC0..=0xCF).contains(&marker) && !matches!(marker, 0xC4 | 0xC8 | 0xCC) {
827 return Some(Intrinsic {
828 width: be16(bytes, data + 3)? as u32,
829 height: be16(bytes, data + 1)? as u32,
830 dpi_x,
831 dpi_y,
832 sized: true,
833 });
834 }
835 if marker == 0xDA {
836 return None;
837 }
838 at = at.checked_add(2)?.checked_add(length)?;
839 }
840}
841
842fn gif(bytes: &[u8]) -> Option<Intrinsic> {
844 if !bytes.starts_with(b"GIF87a") && !bytes.starts_with(b"GIF89a") {
845 return None;
846 }
847 Some(Intrinsic {
848 width: le16(bytes, 6)? as u32,
849 height: le16(bytes, 8)? as u32,
850 dpi_x: CSS_DPI,
851 dpi_y: CSS_DPI,
852 sized: true,
853 })
854}
855
856fn webp(bytes: &[u8]) -> Option<Intrinsic> {
859 if !bytes.starts_with(b"RIFF") || bytes.get(8..12)? != b"WEBP" {
860 return None;
861 }
862 let size = |width: u32, height: u32| {
863 Some(Intrinsic {
864 width,
865 height,
866 dpi_x: CSS_DPI,
867 dpi_y: CSS_DPI,
868 sized: true,
869 })
870 };
871 match bytes.get(12..16)? {
872 b"VP8X" => {
873 let at = 24;
874 let three = |from: usize| -> Option<u32> {
875 let bytes = bytes.get(from..from + 3)?;
876 Some(u32::from(bytes[0]) | u32::from(bytes[1]) << 8 | u32::from(bytes[2]) << 16)
877 };
878 size(three(at)? + 1, three(at + 3)? + 1)
879 }
880 b"VP8 " => {
881 if bytes.get(23..26)? != [0x9D, 0x01, 0x2A] {
884 return None;
885 }
886 size(
887 (le16(bytes, 26)? & 0x3FFF) as u32,
888 (le16(bytes, 28)? & 0x3FFF) as u32,
889 )
890 }
891 b"VP8L" => {
892 if bytes.get(20) != Some(&0x2F) {
893 return None;
894 }
895 let bits = u32::from_le_bytes(bytes.get(21..25)?.try_into().ok()?);
896 size((bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1)
897 }
898 _ => None,
899 }
900}
901
902fn svg(bytes: &[u8]) -> Option<Intrinsic> {
906 let root = svg_root(bytes)?;
907 let width = attribute(root, "width").and_then(svg_length);
908 let height = attribute(root, "height").and_then(svg_length);
909 let view = attribute(root, "viewBox").and_then(view_box);
910 match (width, height, view) {
911 (Some(width), Some(height), _) => vector(width, height, true),
912 (Some(width), None, Some((across, down))) => vector(width, width * down / across, true),
913 (None, Some(height), Some((across, down))) => vector(height * across / down, height, true),
914 (None, None, Some((across, down))) => vector(across, down, false),
915 _ => None,
916 }
917}
918
919fn vector(width: f32, height: f32, sized: bool) -> Option<Intrinsic> {
922 let whole = |side: f32| side.round().max(1.0);
923 let finite = |side: f32| side.is_finite() && side > 0.0;
924 (finite(width) && finite(height)).then(|| Intrinsic {
925 width: whole(width) as u32,
926 height: whole(height) as u32,
927 dpi_x: CSS_DPI * whole(width) / width,
928 dpi_y: CSS_DPI * whole(height) / height,
929 sized,
930 })
931}
932
933fn svg_root(bytes: &[u8]) -> Option<&str> {
936 let after = |rest: &[u8], close: &[u8]| -> Option<usize> {
937 rest.windows(close.len())
938 .position(|window| window == close)
939 .map(|at| at + close.len())
940 };
941 let mut rest = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
942 loop {
943 rest = rest.trim_ascii_start();
944 let skip = if rest.starts_with(b"<?") {
945 after(rest, b"?>")?
946 } else if rest.starts_with(b"<!--") {
947 after(rest, b"-->")?
948 } else if rest.starts_with(b"<!") {
949 match rest.iter().position(|byte| matches!(byte, b'[' | b'>'))? {
951 at if rest[at] == b'[' => at + after(&rest[at..], b"]>")?,
952 at => at + 1,
953 }
954 } else {
955 break;
956 };
957 rest = &rest[skip..];
958 }
959 let rest = rest.strip_prefix(b"<")?;
960 let name = rest
961 .iter()
962 .position(|byte| byte.is_ascii_whitespace() || matches!(byte, b'>' | b'/'))?;
963 if rest[..name].rsplit(|byte| *byte == b':').next()? != b"svg" {
964 return None;
965 }
966 let mut quote = None;
967 for (at, byte) in rest.iter().enumerate().skip(name) {
968 match (quote, byte) {
969 (Some(open), _) if open == byte => quote = None,
970 (Some(_), _) => {}
971 (None, b'"' | b'\'') => quote = Some(byte),
972 (None, b'>') => return std::str::from_utf8(&rest[name..at]).ok(),
973 (None, _) => {}
974 }
975 }
976 None
977}
978
979fn attribute<'a>(mut tag: &'a str, name: &str) -> Option<&'a str> {
981 loop {
982 let (key, rest) = tag.split_once('=')?;
983 let rest = rest.trim_start();
984 let quote = rest.chars().next().filter(|c| matches!(c, '"' | '\''))?;
985 let (value, rest) = rest[1..].split_once(quote)?;
986 if key.trim() == name {
987 return Some(value);
988 }
989 tag = rest;
990 }
991}
992
993fn svg_length(value: &str) -> Option<f32> {
997 let value = value.trim();
998 let number = value.trim_end_matches(|c: char| c.is_ascii_alphabetic() || c == '%');
999 let unit = &value[number.len()..];
1000 let per = [
1001 ("", 1.0),
1002 ("px", 1.0),
1003 ("pt", CSS_DPI / 72.0),
1004 ("pc", CSS_DPI / 6.0),
1005 ("in", CSS_DPI),
1006 ("cm", CSS_DPI / 2.54),
1007 ("mm", CSS_DPI / 25.4),
1008 ("q", CSS_DPI / 101.6),
1009 ]
1010 .into_iter()
1011 .find_map(|(name, per)| unit.eq_ignore_ascii_case(name).then_some(per))?;
1012 let pixels = number.parse::<f32>().ok()? * per;
1013 (pixels.is_finite() && pixels > 0.0).then_some(pixels)
1014}
1015
1016fn view_box(value: &str) -> Option<(f32, f32)> {
1018 let mut numbers = value
1019 .split(|c: char| c.is_ascii_whitespace() || c == ',')
1020 .filter(|part| !part.is_empty())
1021 .map(|part| part.parse::<f32>().ok());
1022 let (_, _, width, height) = (
1023 numbers.next()??,
1024 numbers.next()??,
1025 numbers.next()??,
1026 numbers.next()??,
1027 );
1028 (numbers.next().is_none() && width > 0.0 && height > 0.0).then_some((width, height))
1029}
1030
1031#[cfg(test)]
1032mod tests {
1033 use super::*;
1034 use crate::content::Attributes;
1035
1036 #[test]
1039 fn a_table_loads_the_bytes_a_url_was_registered_with() {
1040 let mut assets = Assets::none();
1041 let png = png_bytes(4, 2, None);
1042 assets.add("a.png", png.clone());
1043 assets.add("b.bmp", b"BM....".to_vec());
1044 assert_eq!(ImageLoader::load(&assets, "a.png"), Some(png));
1045 assert_eq!(ImageLoader::load(&assets, "b.bmp"), None);
1046 assert_eq!(ImageLoader::load(&assets, "c.png"), None);
1047 }
1048
1049 fn png_bytes(width: u32, height: u32, ppm: Option<u32>) -> Vec<u8> {
1052 let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec();
1053 bytes.extend(13u32.to_be_bytes());
1054 bytes.extend(b"IHDR");
1055 bytes.extend(width.to_be_bytes());
1056 bytes.extend(height.to_be_bytes());
1057 bytes.extend([8, 6, 0, 0, 0]);
1058 bytes.extend([0, 0, 0, 0]); if let Some(ppm) = ppm {
1060 bytes.extend(9u32.to_be_bytes());
1061 bytes.extend(b"pHYs");
1062 bytes.extend(ppm.to_be_bytes());
1063 bytes.extend(ppm.to_be_bytes());
1064 bytes.push(1);
1065 bytes.extend([0, 0, 0, 0]);
1066 }
1067 bytes.extend(0u32.to_be_bytes());
1068 bytes.extend(b"IDAT");
1069 bytes
1070 }
1071
1072 fn jpeg_bytes(width: u16, height: u16, density: Option<u16>) -> Vec<u8> {
1074 let mut bytes = vec![0xFF, 0xD8];
1075 if let Some(density) = density {
1076 bytes.extend([0xFF, 0xE0, 0x00, 0x10]);
1077 bytes.extend(b"JFIF\0");
1078 bytes.extend([1, 2, 1]); bytes.extend(density.to_be_bytes());
1080 bytes.extend(density.to_be_bytes());
1081 bytes.extend([0, 0]);
1082 }
1083 bytes.extend([0xFF, 0xC0, 0x00, 0x11, 0x08]);
1084 bytes.extend(height.to_be_bytes());
1085 bytes.extend(width.to_be_bytes());
1086 bytes
1087 }
1088
1089 fn rgba_png(width: u32, height: u32, covered: impl Fn(u32, u32) -> bool) -> Vec<u8> {
1091 let mut pixels = Vec::with_capacity((width * height * 4) as usize);
1092 for y in 0..height {
1093 for x in 0..width {
1094 pixels.extend([0x33, 0x44, 0x55, if covered(x, y) { 0xFF } else { 0 }]);
1095 }
1096 }
1097 let mut bytes = Vec::new();
1098 let mut encoder = png::Encoder::new(&mut bytes, width, height);
1099 encoder.set_color(png::ColorType::Rgba);
1100 encoder.set_depth(png::BitDepth::Eight);
1101 let mut writer = encoder.write_header().expect("the header writes");
1102 writer.write_image_data(&pixels).expect("the pixels write");
1103 writer.finish().expect("the file closes");
1104 bytes
1105 }
1106
1107 fn span(contour: &Contour, top: f32, bottom: f32) -> Option<(f32, f32)> {
1110 let mut reach: Option<(f32, f32)> = None;
1111 for ring in &contour.rings {
1112 for point in ring {
1113 if point[1] < top || point[1] > bottom {
1114 continue;
1115 }
1116 reach = Some(match reach {
1117 None => (point[0], point[0]),
1118 Some((left, right)) => (left.min(point[0]), right.max(point[0])),
1119 });
1120 }
1121 }
1122 reach
1123 }
1124
1125 #[test]
1130 fn an_alpha_channel_traces_to_the_shape_it_covers() {
1131 let half = trace(&rgba_png(64, 64, |x, _| x < 32)).expect("a PNG with alpha traces");
1132 assert_eq!(half.rings.len(), 1);
1133 assert_eq!(span(&half, 0.0, 1.0), Some((0.0, 0.5)));
1134
1135 let wedge = trace(&rgba_png(64, 64, |x, y| x <= y)).expect("a PNG with alpha traces");
1138 let (_, top) = span(&wedge, 0.0, 0.1).expect("the top of the wedge");
1139 let (_, bottom) = span(&wedge, 0.9, 1.0).expect("the foot of the wedge");
1140 assert!(top < 0.2, "the wedge opens narrow: {top}");
1141 assert!(bottom > 0.9, "and closes wide: {bottom}");
1142 }
1143
1144 #[test]
1147 fn clear_space_across_an_image_splits_the_contour() {
1148 let split = trace(&rgba_png(64, 64, |_, y| !(24..40).contains(&y)))
1149 .expect("a PNG with alpha traces");
1150 assert_eq!(split.rings.len(), 2, "{:?}", split.rings.len());
1151 assert_eq!(span(&split, 0.4, 0.6), None, "nothing covers the gap");
1152 }
1153
1154 #[test]
1157 fn an_empty_alpha_channel_traces_to_nothing() {
1158 let empty = trace(&rgba_png(16, 16, |_, _| false)).expect("a PNG with alpha traces");
1159 assert!(empty.rings.is_empty());
1160 }
1161
1162 #[test]
1166 fn a_format_without_alpha_traces_to_nothing() {
1167 assert!(trace(&jpeg_bytes(64, 64, None)).is_none());
1168 assert!(trace(&png_bytes(64, 64, None)).is_none(), "a bare header");
1169 assert!(trace(b"not an image").is_none());
1170 assert!(trace(b"").is_none());
1171 }
1172
1173 #[test]
1176 fn one_shape_in_two_formats_traces_the_same() {
1177 let png = trace(include_bytes!("../../../fixtures/images/fleuron.png"))
1178 .expect("the ornament traces");
1179 let webp = trace(include_bytes!("../../../fixtures/images/fleuron.webp"))
1180 .expect("the ornament traces");
1181 assert_eq!(png.rings.len(), 1, "the ornament is one shape");
1182 for (top, bottom) in [(0.0, 0.25), (0.25, 0.5), (0.5, 0.75), (0.75, 1.0)] {
1183 let (one, two) = (span(&png, top, bottom), span(&webp, top, bottom));
1184 let (one, two) = (one.expect("the PNG covers it"), two.expect("the WebP does"));
1185 assert!(
1186 (one.0 - two.0).abs() < 0.02 && (one.1 - two.1).abs() < 0.02,
1187 "between {top} and {bottom}: {one:?} against {two:?}",
1188 );
1189 }
1190 let widest = (0..8)
1193 .filter_map(|band| span(&png, band as f32 / 8.0, (band as f32 + 1.0) / 8.0))
1194 .fold(0.0f32, |widest, (left, right)| widest.max(right - left));
1195 assert!(widest < 0.95, "the contour is the box: {widest}");
1196 }
1197
1198 #[test]
1201 fn a_transparent_palette_entry_traces_like_an_alpha_channel() {
1202 let (width, height) = (32u16, 32u16);
1203 let indices: Vec<u8> = (0..height)
1204 .flat_map(|y| (0..width).map(move |x| u8::from(x >= y)))
1205 .collect();
1206 let mut bytes = Vec::new();
1207 {
1208 let mut encoder =
1209 gif::Encoder::new(&mut bytes, width, height, &[0, 0, 0, 0x33, 0x44, 0x55])
1210 .expect("the header writes");
1211 let frame = gif::Frame {
1212 width,
1213 height,
1214 buffer: std::borrow::Cow::Borrowed(&indices),
1215 transparent: Some(0),
1216 ..gif::Frame::default()
1217 };
1218 encoder.write_frame(&frame).expect("the frame writes");
1219 }
1220 let traced = trace(&bytes).expect("a GIF with a transparent entry traces");
1221 assert_eq!(traced.rings.len(), 1);
1222 let (left, _) = span(&traced, 0.0, 0.1).expect("the top of the wedge");
1223 let (foot, _) = span(&traced, 0.9, 1.0).expect("the foot of it");
1224 assert!(left < 0.1, "the wedge opens at the left edge: {left}");
1225 assert!(foot > 0.8, "and closes at the right: {foot}");
1226 }
1227
1228 #[test]
1231 fn tracing_is_deterministic() {
1232 let bytes = rgba_png(48, 32, |x, y| (x + y) % 17 < 9);
1233 assert_eq!(trace(&bytes), trace(&bytes));
1234 }
1235
1236 #[test]
1238 fn headers_give_up_their_dimensions() {
1239 assert_eq!(
1240 probe(&png_bytes(640, 480, None)).map(|i| (i.width, i.height)),
1241 Some((640, 480)),
1242 );
1243 assert_eq!(
1244 probe(&jpeg_bytes(1200, 900, None)).map(|i| (i.width, i.height)),
1245 Some((1200, 900)),
1246 );
1247 let mut gif = b"GIF89a".to_vec();
1248 gif.extend(320u16.to_le_bytes());
1249 gif.extend(200u16.to_le_bytes());
1250 assert_eq!(probe(&gif).map(|i| (i.width, i.height)), Some((320, 200)));
1251
1252 let mut webp = b"RIFF\0\0\0\0WEBPVP8X".to_vec();
1253 webp.extend([0, 0, 0, 0, 0, 0, 0, 0]); webp.extend([0x3F, 0x00, 0x00, 0x1F, 0x00, 0x00]); assert_eq!(probe(&webp).map(|i| (i.width, i.height)), Some((64, 32)));
1256 }
1257
1258 #[test]
1263 fn an_svg_root_gives_up_its_size() {
1264 let plain = probe(br#"<svg xmlns="http://www.w3.org/2000/svg" width="192" height="96"/>"#)
1265 .expect("an SVG with a size probes");
1266 assert_eq!((plain.width, plain.height), (192, 96));
1267 assert_eq!(plain.size(), (144.0, 72.0));
1268 assert!(plain.sized);
1269
1270 let prefaced = probe(
1271 b"\xEF\xBB\xBF<?xml version=\"1.0\"?>\n<!-- a > rule -->\n\
1272 <!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"svg11.dtd\" [<!ENTITY a \"b\">]>\n\
1273 <svg:svg title='a > b' width='1in' height=\"36pt\" viewBox=\"0 0 10 10\">",
1274 )
1275 .expect("the root is found after its preamble");
1276 assert_eq!(prefaced.size(), (72.0, 36.0));
1277
1278 let metric = probe(br#"<svg width="10mm" height="2.5cm">"#).expect("metric units probe");
1280 let (width, height) = metric.size();
1281 assert!((width - 28.346).abs() < 0.001, "{width}");
1282 assert!((height - 70.866).abs() < 0.001, "{height}");
1283 }
1284
1285 #[test]
1288 fn an_svg_without_a_size_falls_back_to_its_view_box() {
1289 for root in [
1290 r#"<svg viewBox="0 0 300 100">"#,
1291 r#"<svg width="100%" height="100%" viewBox="0,0,300,100">"#,
1292 r#"<svg width="20em" viewBox="-5 -5 300 100">"#,
1293 ] {
1294 let ratio = probe(root.as_bytes()).unwrap_or_else(|| panic!("{root} probes"));
1295 assert!(!ratio.sized, "{root} has no size of its own");
1296 assert_eq!(ratio.size(), (225.0, 75.0), "{root}");
1297 assert_eq!(ratio.size_within(360.0), (360.0, 120.0), "{root}");
1298 }
1299 let wide = probe(br#"<svg width="150" viewBox="0 0 300 100">"#).unwrap();
1300 assert!(wide.sized);
1301 assert_eq!((wide.width, wide.height), (150, 50));
1302 let tall = probe(br#"<svg height="50" viewBox="0 0 300 100">"#).unwrap();
1303 assert_eq!((tall.width, tall.height), (150, 50));
1304 assert_eq!(
1305 tall.size_within(360.0),
1306 tall.size(),
1307 "a sized image keeps its size"
1308 );
1309 }
1310
1311 #[test]
1315 fn an_svg_with_no_size_and_no_view_box_is_refused_once() {
1316 for root in [
1317 "<svg xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M0 0\"/></svg>",
1318 "<svg width=\"100%\" height=\"50%\">",
1319 "<svg width=\"120\">",
1320 "<svg viewBox=\"0 0 0 10\">",
1321 "<svg viewBox=\"0 0 10\">",
1322 "<html><svg width=\"1\" height=\"1\"/></html>",
1323 "<svg width=\"10\" height=\"10\"",
1324 ] {
1325 assert!(probe(root.as_bytes()).is_none(), "{root} probed");
1326 }
1327 let mut assets = Assets::none();
1328 let bare = b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>".to_vec();
1329 assert_eq!(assets.add("rule.svg", bare.clone()), Added::Refused);
1330 assert_eq!(assets.add("rule.svg", bare), Added::Refused);
1331 assert_eq!(assets.warnings().len(), 1);
1332 assert_eq!(
1333 assets.warnings()[0].message,
1334 "Image rule.svg has no size in it. The image is skipped.",
1335 );
1336 assert!(assets.assets().is_empty());
1337 }
1338
1339 #[test]
1341 fn a_truncated_svg_probes_to_nothing() {
1342 let svg = "<?xml version=\"1.0\"?><!-- c --><!DOCTYPE svg [ ]>\
1343 <svg width=\"10\" height='10' viewBox=\"0 0 1 1\">";
1344 for cut in 0..svg.len() {
1345 assert!(probe(&svg.as_bytes()[..cut]).is_none(), "cut at {cut}");
1346 }
1347 assert!(probe(svg.as_bytes()).is_some());
1348 }
1349
1350 #[test]
1353 fn an_svg_traces_to_nothing() {
1354 let svg = br#"<svg width="64" height="64"><circle cx="32" cy="32" r="16"/></svg>"#;
1355 assert!(is_svg(svg));
1356 assert!(trace(svg).is_none());
1357 }
1358
1359 #[test]
1363 fn resolution_decides_the_intrinsic_size() {
1364 let bare = probe(&png_bytes(192, 96, None)).unwrap();
1365 assert_eq!(bare.size(), (144.0, 72.0));
1366 let dense = probe(&png_bytes(600, 300, Some(11811))).unwrap();
1368 assert!((dense.dpi_x - 300.0).abs() < 0.1, "{}", dense.dpi_x);
1369 assert!((dense.size().0 - 144.0).abs() < 0.1, "{:?}", dense.size());
1370 let inches = probe(&jpeg_bytes(600, 300, Some(300))).unwrap();
1371 assert_eq!(inches.dpi_x, 300.0);
1372 assert!((inches.size().0 - 144.0).abs() < 0.1);
1373 }
1374
1375 #[test]
1378 fn unknown_and_truncated_bytes_probe_to_nothing() {
1379 assert!(probe(b"").is_none());
1380 assert!(probe(b"not an image at all").is_none());
1381 let png = png_bytes(4, 4, None);
1382 for cut in 0..png.len() {
1383 let _ = probe(&png[..cut]);
1384 }
1385 let jpeg = jpeg_bytes(4, 4, Some(72));
1386 for cut in 0..jpeg.len() {
1387 let _ = probe(&jpeg[..cut]);
1388 }
1389 }
1390
1391 #[test]
1396 fn pushed_images_are_probed_and_kept() {
1397 let mut assets = Assets::none();
1398 let png = png_bytes(96, 48, None);
1399 let a = assets.add("a.png", png.clone());
1400 assert!(matches!(
1401 a,
1402 Added::Replaced {
1403 index: 0,
1404 previous: None,
1405 ..
1406 }
1407 ));
1408 let b = assets.add("b.jpg", jpeg_bytes(200, 100, None));
1409 assert!(matches!(
1410 b,
1411 Added::Replaced {
1412 index: 1,
1413 previous: None,
1414 ..
1415 }
1416 ));
1417 assert_eq!(assets.add("a.png", png.clone()), Added::Unchanged(0));
1420 assert_eq!(assets.bytes(0), Some(png.as_slice()));
1421 assert_eq!(assets.lookup("a.png").map(|(index, _)| index), Some(0));
1422
1423 assert_eq!(
1424 assets.add("c.txt", b"not an image".to_vec()),
1425 Added::Refused
1426 );
1427 assert!(assets.probed("c.txt"), "a refusal counts as probed");
1428 assert!(!assets.probed("d.png"), "a url nobody offered does not");
1429 assert_eq!(assets.warnings().len(), 1);
1430 assert!(assets.warnings()[0].message.contains("c.txt"));
1431 assert_eq!(assets.add("c.txt", b"still not".to_vec()), Added::Refused);
1433 assert_eq!(assets.warnings().len(), 1);
1434 }
1435
1436 #[test]
1441 fn different_bytes_at_the_same_url_replace_it_in_place() {
1442 let mut assets = Assets::none();
1443 assets.add("a.png", png_bytes(96, 48, None));
1444
1445 let same_size = assets.add("a.png", png_bytes(96, 48, Some(150)));
1446 let Added::Replaced {
1447 index,
1448 previous,
1449 current,
1450 } = same_size
1451 else {
1452 panic!("different bytes at a registered url did not replace it: {same_size:?}");
1453 };
1454 assert_eq!(index, 0, "the index moved");
1455 assert_eq!(previous.map(|i| (i.width, i.height)), Some((96, 48)));
1456 assert_eq!((current.width, current.height), (96, 48));
1457 assert_eq!(
1458 assets.bytes(0),
1459 Some(png_bytes(96, 48, Some(150)).as_slice())
1460 );
1461
1462 let resized = assets.add("a.png", png_bytes(200, 100, None));
1463 let Added::Replaced {
1464 index,
1465 previous,
1466 current,
1467 } = resized
1468 else {
1469 panic!("a resize did not replace the asset: {resized:?}");
1470 };
1471 assert_eq!(index, 0);
1472 assert_eq!(previous.map(|i| (i.width, i.height)), Some((96, 48)));
1473 assert_eq!((current.width, current.height), (200, 100));
1474 }
1475
1476 #[test]
1480 fn assets_index_the_book_in_document_order() {
1481 struct Two;
1482 impl ImageLoader for Two {
1483 fn load(&self, url: &str) -> Option<Vec<u8>> {
1484 match url {
1485 "a.png" => Some(png_bytes(96, 48, None)),
1486 "b.jpg" => Some(jpeg_bytes(200, 100, None)),
1487 _ => None,
1488 }
1489 }
1490 }
1491
1492 let image = |url: &str| Block::Image {
1493 id: crate::content::NodeId::UNASSIGNED,
1494 url: url.into(),
1495 alt: String::new(),
1496 attributes: Attributes::default(),
1497 position: None,
1498 span: None,
1499 };
1500 let mut book = Book {
1501 metadata: Default::default(),
1502 sections: vec![crate::content::Section {
1503 attributes: Default::default(),
1504 blocks: vec![
1505 image("a.png"),
1506 Block::Blockquote {
1507 id: crate::content::NodeId::UNASSIGNED,
1508 blocks: vec![image("b.jpg")],
1509 attributes: Attributes::default(),
1510 position: None,
1511 span: None,
1512 },
1513 image("a.png"),
1514 image("missing.png"),
1515 ],
1516 ..Default::default()
1517 }],
1518 };
1519 book.assign_node_ids();
1520 let styles = crate::style::defaults(
1521 &book,
1522 crate::fonts::bundled_registry()
1523 .as_ref()
1524 .expect("the bundled face parses"),
1525 );
1526 let assets = Assets::probe(&book, &styles, &Two);
1527 assert_eq!(assets.assets().len(), 2, "a.png was probed twice");
1528 assert_eq!(assets.lookup("a.png").map(|(index, _)| index), Some(0));
1529 assert_eq!(assets.lookup("b.jpg").map(|(index, _)| index), Some(1));
1530 assert_eq!(assets.lookup("missing.png"), None);
1531 assert_eq!(assets.warnings().len(), 1);
1532 assert!(assets.warnings()[0].message.contains("missing.png"));
1533 }
1534
1535 #[test]
1539 fn a_missing_contour_warns_only_while_the_sheet_asks_for_it() {
1540 let mut book = Book {
1541 metadata: Default::default(),
1542 sections: vec![crate::content::Section {
1543 attributes: Default::default(),
1544 blocks: vec![Block::Image {
1545 id: crate::content::NodeId::UNASSIGNED,
1546 url: "seal.svg".into(),
1547 alt: String::new(),
1548 attributes: Attributes::default(),
1549 position: None,
1550 span: None,
1551 }],
1552 ..Default::default()
1553 }],
1554 };
1555 book.assign_node_ids();
1556 let mut assets = Assets::none();
1557 assets.add("seal.svg", br#"<svg width="64" height="64"/>"#.to_vec());
1558 let anchored = "img { position: absolute; top: 0; left: 0; wrap-flow: end }";
1559 let asking = styled(&book, &format!("{anchored} img {{ shape-outside: auto }}"));
1560 let plain = styled(&book, anchored);
1561
1562 let mut contours = Contours::none();
1563 assert_eq!(contours.update(&book, &asking, &assets), 1);
1564 assert_eq!(contours.warnings().len(), 1);
1565 assert_eq!(contours.update(&book, &asking, &assets), 0, "traced twice");
1566 assert_eq!(contours.warnings().len(), 1);
1567 contours.update(&book, &plain, &assets);
1568 assert!(contours.warnings().is_empty(), "{:?}", contours.warnings());
1569 contours.update(&book, &asking, &assets);
1570 assert_eq!(contours.warnings().len(), 1);
1571 }
1572
1573 fn plain_book() -> Book {
1575 let mut book = Book {
1576 metadata: Default::default(),
1577 sections: vec![crate::content::Section {
1578 attributes: Default::default(),
1579 blocks: vec![Block::Paragraph {
1580 id: crate::content::NodeId::UNASSIGNED,
1581 inlines: vec![crate::content::Inline::Text {
1582 id: crate::content::NodeId::UNASSIGNED,
1583 value: "Nothing is placed here.".into(),
1584 attributes: Attributes::default(),
1585 position: None,
1586 span: None,
1587 }],
1588 attributes: Attributes::default(),
1589 position: None,
1590 span: None,
1591 }],
1592 ..Default::default()
1593 }],
1594 };
1595 book.assign_node_ids();
1596 book
1597 }
1598
1599 fn styled(book: &Book, css: &str) -> StyleTree {
1601 let registry = crate::fonts::bundled_registry().expect("the bundled face parses");
1602 let styles = crate::style::Stylesheets::parse(&[crate::style::Source::author(
1603 "background.css",
1604 css,
1605 )])
1606 .compile(book, ®istry);
1607 assert!(
1608 styles.warnings().is_empty(),
1609 "the sheet is in the subset: {:?}",
1610 styles.warnings(),
1611 );
1612 styles
1613 }
1614
1615 struct Counting(std::cell::RefCell<Vec<String>>);
1617
1618 impl ImageLoader for Counting {
1619 fn load(&self, url: &str) -> Option<Vec<u8>> {
1620 self.0.borrow_mut().push(url.to_string());
1621 (url != "missing.png").then(|| png_bytes(96, 48, None))
1622 }
1623 }
1624
1625 #[test]
1629 fn a_url_the_sheet_names_reaches_the_asset_table() {
1630 let book = plain_book();
1631 let styles = styled(
1632 &book,
1633 "@page { background-image: url(\"scan.png\") }\n\
1634 p { background-image: url(tint.png) }",
1635 );
1636 let loader = Counting(std::cell::RefCell::new(Vec::new()));
1637 let assets = Assets::probe(&book, &styles, &loader);
1638
1639 let mut named: Vec<&str> = assets.assets().iter().map(|a| a.url.as_str()).collect();
1640 named.sort_unstable();
1641 assert_eq!(named, ["scan.png", "tint.png"]);
1642 assert!(assets.warnings().is_empty(), "{:?}", assets.warnings());
1643 }
1644
1645 #[test]
1649 fn a_sheet_that_names_no_background_probes_nothing() {
1650 let book = plain_book();
1651 let styles = styled(&book, "p { background-color: #f4f1ea }");
1652 let loader = Counting(std::cell::RefCell::new(Vec::new()));
1653 let assets = Assets::probe(&book, &styles, &loader);
1654
1655 assert!(
1656 loader.0.borrow().is_empty(),
1657 "the loader was asked for {:?}",
1658 loader.0.borrow(),
1659 );
1660 assert!(assets.assets().is_empty());
1661 }
1662
1663 #[test]
1666 fn a_url_nothing_resolves_names_where_it_was_written() {
1667 let book = plain_book();
1668 let styles = styled(&book, "p {\n background-image: url(missing.png);\n}");
1669 let loader = Counting(std::cell::RefCell::new(Vec::new()));
1670 let assets = Assets::probe(&book, &styles, &loader);
1671
1672 assert!(assets.assets().is_empty());
1673 assert_eq!(assets.warnings().len(), 1);
1674 assert!(assets.warnings()[0].message.contains("missing.png"));
1675 assert_eq!(
1676 assets.warnings()[0].origin.as_deref(),
1677 Some("background.css:2:3"),
1678 );
1679 }
1680
1681 #[test]
1686 fn probed_and_pushed_assets_share_one_hash_table() {
1687 struct One;
1688 impl ImageLoader for One {
1689 fn load(&self, url: &str) -> Option<Vec<u8>> {
1690 (url == "a.png").then(|| png_bytes(96, 48, None))
1691 }
1692 }
1693
1694 let image = |url: &str| Block::Image {
1695 id: crate::content::NodeId::UNASSIGNED,
1696 url: url.into(),
1697 alt: String::new(),
1698 attributes: Attributes::default(),
1699 position: None,
1700 span: None,
1701 };
1702 let mut book = Book {
1703 metadata: Default::default(),
1704 sections: vec![crate::content::Section {
1705 attributes: Default::default(),
1706 blocks: vec![image("a.png")],
1707 ..Default::default()
1708 }],
1709 };
1710 book.assign_node_ids();
1711 let styles = crate::style::defaults(
1712 &book,
1713 crate::fonts::bundled_registry()
1714 .as_ref()
1715 .expect("the bundled face parses"),
1716 );
1717 let mut assets = Assets::probe(&book, &styles, &One);
1718
1719 assert_eq!(
1720 assets.add("a.png", png_bytes(96, 48, None)),
1721 Added::Unchanged(0),
1722 "the same bytes probed and pushed hash the same"
1723 );
1724 let resized = assets.add("a.png", png_bytes(200, 100, None));
1725 assert!(
1726 matches!(resized, Added::Replaced { index: 0, .. }),
1727 "different bytes replaced the probed asset in place: {resized:?}"
1728 );
1729 }
1730}