dezoomify-rs 2.18.0

Allows downloading zoomable images. Supports several different formats such as zoomify, iiif, and deep zoom images.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//! Types for discovering logical images and their tiled resolution levels.
//!
//! A dezoomer returns [`Images`] rather than a flat level list. Most formats
//! contain one image and can finish their implementation with
//! `Ok(levels.into())`. Container formats such as krpano and IIIF manifests
//! return one [`ZoomableImage`] per scene or referenced image.

use std::borrow::Borrow;
use std::collections::HashMap;
use std::error::Error;
use std::fmt::{self, Debug};
use std::str::FromStr;

pub use crate::errors::DezoomerError;

pub use super::Vec2d;
use super::ZoomError;
use crate::dezoomer::PageContents::Success;

#[cfg(test)]
pub(crate) mod test_utils;

pub enum PageContents {
    Unknown,
    Success(Vec<u8>),
    Error(ZoomError),
}

impl From<Result<Vec<u8>, ZoomError>> for PageContents {
    fn from(res: Result<Vec<u8>, ZoomError>) -> Self {
        res.map(Self::Success).unwrap_or_else(Self::Error)
    }
}

impl std::fmt::Debug for PageContents {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Unknown => f.write_str("<not yet available>"),
            Success(contents) => f.write_str(&String::from_utf8_lossy(contents)),
            PageContents::Error(e) => write!(f, "{e}"),
        }
    }
}

pub struct DezoomerInput {
    pub uri: String,
    pub contents: PageContents,
}

pub struct DezoomerInputWithContents<'a> {
    pub uri: &'a str,
    pub contents: &'a [u8],
}

impl DezoomerInput {
    pub fn with_contents(&self) -> Result<DezoomerInputWithContents<'_>, DezoomerError> {
        match &self.contents {
            PageContents::Unknown => Err(DezoomerError::NeedsData {
                uri: self.uri.clone(),
            }),
            Success(contents) => Ok(DezoomerInputWithContents {
                uri: &self.uri,
                contents,
            }),
            PageContents::Error(e) => Err(DezoomerError::DownloadError { msg: e.to_string() }),
        }
    }
}

/// A single image with a given width and height
pub type ZoomLevel = Box<dyn TileProvider + Send + Sync>;

/// A collection of multiple resolutions at which an image is available
pub type ZoomLevels = Vec<ZoomLevel>;

/// A single logical image whose zoom levels are already available.
#[derive(Debug)]
pub struct ResolvedImage {
    zoom_levels: ZoomLevels,
    title: Option<String>,
}

impl ResolvedImage {
    pub fn new(zoom_levels: ZoomLevels, title: Option<String>) -> Self {
        Self { zoom_levels, title }
    }

    pub fn into_zoom_levels(self) -> ZoomLevels {
        self.zoom_levels
    }

    pub fn levels(&self) -> &[ZoomLevel] {
        &self.zoom_levels
    }

    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    fn with_fallback_title(mut self, title: Option<String>) -> Self {
        if self.title.as_deref().is_none_or(str::is_empty) {
            self.title = title;
        }
        self
    }
}

/// A deferred logical image that must be processed by a dezoomer.
#[derive(Debug, Clone)]
pub struct ImageUrl {
    pub url: String,
    pub title: Option<String>,
}

/// Logical images discovered by a dezoomer.
///
/// [`ZoomLevels`] converts into a collection containing one resolved image.
/// Vectors of [`ResolvedImage`] or [`ImageUrl`] preserve every logical image.
#[derive(Debug, Default)]
pub struct Images(Vec<ZoomableImage>);

impl Images {
    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn iter(&self) -> std::slice::Iter<'_, ZoomableImage> {
        self.0.iter()
    }

    fn with_fallback_title(self, title: Option<String>) -> Self {
        let Some(title) = title.filter(|title| !title.trim().is_empty()) else {
            return self;
        };

        Self(
            self.0
                .into_iter()
                .map(|image| match image {
                    ZoomableImage::Resolved(image) => {
                        ZoomableImage::Resolved(image.with_fallback_title(Some(title.clone())))
                    }
                    ZoomableImage::Url(mut image_url) => {
                        if image_url.title.as_deref().is_none_or(str::is_empty) {
                            image_url.title = Some(title.clone());
                        }
                        ZoomableImage::Url(image_url)
                    }
                })
                .collect(),
        )
    }
}

impl IntoIterator for Images {
    type Item = ZoomableImage;
    type IntoIter = std::vec::IntoIter<ZoomableImage>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl std::ops::Index<usize> for Images {
    type Output = ZoomableImage;

    fn index(&self, index: usize) -> &Self::Output {
        &self.0[index]
    }
}

impl From<ZoomLevels> for Images {
    fn from(levels: ZoomLevels) -> Self {
        ResolvedImage::new(levels, None).into()
    }
}

impl From<ResolvedImage> for Images {
    fn from(image: ResolvedImage) -> Self {
        Self(vec![ZoomableImage::Resolved(image)])
    }
}

impl From<Vec<ResolvedImage>> for Images {
    fn from(images: Vec<ResolvedImage>) -> Self {
        Self(images.into_iter().map(ZoomableImage::Resolved).collect())
    }
}

impl From<Vec<ImageUrl>> for Images {
    fn from(urls: Vec<ImageUrl>) -> Self {
        Self(urls.into_iter().map(ZoomableImage::Url).collect())
    }
}

impl From<Vec<ZoomableImage>> for Images {
    fn from(images: Vec<ZoomableImage>) -> Self {
        Self(images)
    }
}

impl FromIterator<ZoomableImage> for Images {
    fn from_iter<T: IntoIterator<Item = ZoomableImage>>(iter: T) -> Self {
        Self(iter.into_iter().collect())
    }
}

/// A logical image, either resolved or represented by a URL to resolve.
#[derive(Debug)]
pub enum ZoomableImage {
    /// An image whose levels are ready to use.
    Resolved(ResolvedImage),
    /// A URL that needs further processing.
    Url(ImageUrl),
}

impl ZoomableImage {
    pub fn title(&self) -> Option<&str> {
        match self {
            ZoomableImage::Resolved(image) => image.title(),
            ZoomableImage::Url(url) => url.title.as_deref(),
        }
    }

    pub async fn resolve(self, http: &reqwest::Client) -> Result<Images, DezoomerError> {
        let mut resolver = crate::auto::MetadataResolver::new(http);
        self.resolve_with(&mut resolver).await
    }

    pub(crate) async fn resolve_with(
        self,
        resolver: &mut crate::auto::MetadataResolver<'_>,
    ) -> Result<Images, DezoomerError> {
        match self {
            ZoomableImage::Resolved(image) => Ok(image.into()),
            ZoomableImage::Url(url) => {
                use crate::auto::AutoDezoomer;
                use log::debug;

                let ImageUrl { url, title } = url;

                debug!("Resolving image URL: {}", url);
                let mut dezoomer = AutoDezoomer::default();
                let images = resolver.resolve(&mut dezoomer, &url).await?;
                debug!("Successfully extracted {} images", images.len());
                Ok(images.with_fallback_title(title))
            }
        }
    }
}

pub trait IntoZoomLevels {
    fn into_zoom_levels(self) -> ZoomLevels;
}

impl<I, Z> IntoZoomLevels for I
where
    I: Iterator<Item = Z>,
    Z: TileProvider + Send + Sync + 'static,
{
    fn into_zoom_levels(self) -> ZoomLevels {
        self.map(|x| Box::new(x) as ZoomLevel).collect()
    }
}

/// Discovers logical zoomable images from downloaded metadata.
pub trait Dezoomer {
    /// The name of the image format. Used for dezoomer selection
    fn name(&self) -> &'static str;

    /// Discover logical images without flattening their zoom levels.
    ///
    /// Return [`DezoomerError::NeedsData`] when another resource must be
    /// downloaded, preserving any parser state needed for the next call.
    fn images(&mut self, data: &DezoomerInput) -> Result<Images, DezoomerError>;

    fn assert(&self, c: bool) -> Result<(), DezoomerError> {
        if c {
            Ok(())
        } else {
            Err(self.wrong_dezoomer())
        }
    }
    fn wrong_dezoomer(&self) -> DezoomerError {
        DezoomerError::WrongDezoomer { name: self.name() }
    }
}

#[derive(Clone, Copy)]
pub struct TileFetchResult {
    pub count: u64,
    pub successes: u64,
    pub tile_size: Option<Vec2d>,
}

impl TileFetchResult {
    pub fn is_success(&self) -> bool {
        self.tile_size
            .filter(|&Vec2d { x, y }| x > 0 && y > 0)
            .is_some()
            && self.successes > 0
    }
}

type PostProcessResult = Result<Vec<u8>, Box<dyn Error + Send>>;
// TODO : fix
// see: https://github.com/rust-lang/rust/issues/63033
#[derive(Clone, Copy)]
pub enum PostProcessFn {
    Fn(fn(&TileReference, Vec<u8>) -> PostProcessResult),
    None,
}

/// A single tiled image
pub trait TileProvider: Debug {
    /// Provide a list of image tiles. Should be called repetitively until it returns
    /// an empty list. Each new call takes the results of the previous tile fetch as a parameter.
    fn next_tiles(&mut self, previous: Option<TileFetchResult>) -> Vec<TileReference>;

    /// A function that takes the downloaded tile bytes and decodes them
    fn post_process_fn(&self) -> PostProcessFn {
        PostProcessFn::None
    }

    /// The name of the format
    fn name(&self) -> String {
        TileProviderName(self).to_string()
    }

    /// Format this provider for zoom-level pickers.
    fn fmt_name(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self:?}")
    }

    /// The title of the image
    fn title(&self) -> Option<String> {
        None
    }

    /// The width and height of the image. Can be unknown when dezooming starts
    fn size_hint(&self) -> Option<Vec2d> {
        None
    }

    /// The number of tiles in the image. Can be unknown when dezooming starts
    fn tile_count_hint(&self) -> Option<u32> {
        None
    }

    fn tile_size_hint(&self) -> Option<Vec2d> {
        None
    }

    fn scale_factor_hint(&self) -> Option<u32> {
        None
    }

    fn has_overlapping_tiles(&self) -> bool {
        false
    }

    /// A collection of http headers to use when requesting the tiles
    fn http_headers(&self) -> HashMap<String, String> {
        HashMap::new()
    }
}

struct TileProviderName<'a, T: TileProvider + ?Sized>(&'a T);

impl<T: TileProvider + ?Sized> fmt::Display for TileProviderName<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt_name(f)
    }
}

impl fmt::Display for dyn TileProvider + Send + Sync + '_ {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_name(f)
    }
}

fn fmt_level_name(
    f: &mut fmt::Formatter<'_>,
    label: fmt::Arguments<'_>,
    size: Option<Vec2d>,
    tile_count: Option<u32>,
) -> fmt::Result {
    f.write_fmt(label)?;
    match (size, tile_count) {
        (Some(Vec2d { x, y }), Some(tile_count)) => {
            write!(f, " ({x:>5} x {y:>5} pixels, {tile_count:>5} tiles)")
        }
        (Some(Vec2d { x, y }), None) => write!(f, " ({x:>5} x {y:>5} pixels)"),
        (None, Some(tile_count)) => write!(f, " ({tile_count:>5} tiles)"),
        (None, None) => Ok(()),
    }
}

/// Used to iterate over all the batches of tiles in a zoom level
pub struct ZoomLevelIter<'a> {
    zoom_level: &'a mut ZoomLevel,
    previous: Option<TileFetchResult>,
    waiting_results: bool,
}

impl<'a> ZoomLevelIter<'a> {
    pub fn new(zoom_level: &'a mut ZoomLevel) -> Self {
        ZoomLevelIter {
            zoom_level,
            previous: None,
            waiting_results: false,
        }
    }
    pub fn next_tile_references(&mut self) -> Option<Vec<TileReference>> {
        assert!(!self.waiting_results);
        self.waiting_results = true;
        let tiles = self.zoom_level.next_tiles(self.previous);
        if tiles.is_empty() { None } else { Some(tiles) }
    }
    pub fn set_fetch_result(&mut self, result: TileFetchResult) {
        assert!(self.waiting_results);
        self.waiting_results = false;
        self.previous = Some(result)
    }
    pub fn size_hint(&self) -> Option<Vec2d> {
        self.zoom_level.size_hint()
    }
    pub fn tile_size_hint(&self) -> Option<Vec2d> {
        self.zoom_level.tile_size_hint()
    }
    pub fn scale_factor_hint(&self) -> Option<u32> {
        self.zoom_level.scale_factor_hint()
    }
    pub fn has_overlapping_tiles(&self) -> bool {
        self.zoom_level.has_overlapping_tiles()
    }
}

/// Shortcut to return a single zoom level from a dezoomer
pub fn single_level<T: TileProvider + Send + Sync + 'static>(level: T) -> ZoomLevels {
    vec![Box::new(level)]
}

pub trait TilesRect: Debug {
    fn size(&self) -> Vec2d;
    fn tile_size(&self) -> Vec2d;
    fn tile_url(&self, pos: Vec2d) -> String;
    fn title(&self) -> Option<String> {
        None
    }
    fn tile_ref(&self, pos: Vec2d) -> TileReference {
        TileReference {
            url: self.tile_url(pos),
            position: self.tile_size() * pos,
        }
    }
    fn post_process_fn(&self) -> PostProcessFn {
        PostProcessFn::None
    }

    fn has_overlapping_tiles(&self) -> bool {
        false
    }

    fn scale_factor_hint(&self) -> Option<u32> {
        None
    }

    fn tile_count(&self) -> u32 {
        let Vec2d { x, y } = self.size().ceil_div(self.tile_size());
        x * y
    }
}

impl<T: TilesRect> TileProvider for T {
    fn next_tiles(&mut self, previous: Option<TileFetchResult>) -> Vec<TileReference> {
        // When the dimensions are known in advance, we can always generate
        // a single batch of tile references. So any subsequent call returns an empty vector.
        if previous.is_some() {
            return vec![];
        }

        let tile_size = self.tile_size();
        let Vec2d { x: w, y: h } = self.size().ceil_div(tile_size);
        let this: &T = self.borrow(); // Immutable borrow
        (0..h)
            .flat_map(move |y| (0..w).map(move |x| this.tile_ref(Vec2d { x, y })))
            .collect()
    }

    fn post_process_fn(&self) -> PostProcessFn {
        TilesRect::post_process_fn(self)
    }

    fn fmt_name(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt_level_name(
            f,
            format_args!("{self:?}"),
            Some(self.size()),
            Some(self.tile_count()),
        )
    }

    fn title(&self) -> Option<String> {
        TilesRect::title(self)
    }

    fn size_hint(&self) -> Option<Vec2d> {
        Some(self.size())
    }

    fn tile_count_hint(&self) -> Option<u32> {
        Some(self.tile_count())
    }

    fn tile_size_hint(&self) -> Option<Vec2d> {
        Some(self.tile_size())
    }

    fn scale_factor_hint(&self) -> Option<u32> {
        TilesRect::scale_factor_hint(self)
    }

    fn has_overlapping_tiles(&self) -> bool {
        TilesRect::has_overlapping_tiles(self)
    }

    fn http_headers(&self) -> HashMap<String, String> {
        let mut headers = HashMap::new();
        // By default, use the first tile as the referer, so that it is on the same domain
        headers.insert("Referer".into(), self.tile_url(Vec2d::default()));
        headers
    }
}

#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct TileReference {
    pub url: String,
    pub position: Vec2d,
}

impl FromStr for TileReference {
    type Err = ZoomError;

    fn from_str(tile_str: &str) -> Result<Self, Self::Err> {
        let mut parts = tile_str.split(' ');
        let make_error = || ZoomError::MalformedTileStr {
            tile_str: String::from(tile_str),
        };

        if let (Some(x), Some(y), Some(url)) = (parts.next(), parts.next(), parts.next()) {
            let x: u32 = x.parse().map_err(|_| make_error())?;
            let y: u32 = y.parse().map_err(|_| make_error())?;
            Ok(TileReference {
                url: String::from(url),
                position: Vec2d { x, y },
            })
        } else {
            Err(make_error())
        }
    }
}

impl fmt::Display for TileReference {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.url)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Default)]
    struct FakeLvl {
        title: Option<&'static str>,
    }

    impl std::fmt::Debug for FakeLvl {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("FakeLvl")
        }
    }

    impl TilesRect for FakeLvl {
        fn size(&self) -> Vec2d {
            Vec2d { x: 100, y: 100 }
        }

        fn tile_size(&self) -> Vec2d {
            Vec2d { x: 60, y: 60 }
        }

        fn tile_url(&self, pos: Vec2d) -> String {
            format!("{},{}", pos.x, pos.y)
        }

        fn title(&self) -> Option<String> {
            self.title.map(str::to_string)
        }
    }

    #[test]
    fn assert_tiles() {
        let mut lvl: ZoomLevel = Box::<FakeLvl>::default();
        let mut all_tiles = vec![];
        let mut zoom_level_iter = ZoomLevelIter::new(&mut lvl);
        while let Some(tiles) = zoom_level_iter.next_tile_references() {
            all_tiles.extend(tiles);
            zoom_level_iter.set_fetch_result(TileFetchResult {
                count: 0,
                successes: 0,
                tile_size: None,
            });
        }
        assert_eq!(
            all_tiles,
            vec![
                TileReference {
                    url: "0,0".into(),
                    position: Vec2d { x: 0, y: 0 },
                },
                TileReference {
                    url: "1,0".into(),
                    position: Vec2d { x: 60, y: 0 },
                },
                TileReference {
                    url: "0,1".into(),
                    position: Vec2d { x: 0, y: 60 },
                },
                TileReference {
                    url: "1,1".into(),
                    position: Vec2d { x: 60, y: 60 },
                }
            ]
        );
    }

    #[test]
    fn test_resolved_image() {
        let zoom_levels: ZoomLevels = vec![Box::<FakeLvl>::default()];
        let title = Some("Test Image".to_string());

        let image = ResolvedImage::new(zoom_levels, title.clone());

        assert_eq!(image.title(), title.as_deref());
        let extracted_levels = image.into_zoom_levels();
        assert_eq!(extracted_levels.len(), 1);
    }

    #[test]
    fn zoom_levels_convert_to_one_resolved_image() {
        let images: Images = vec![Box::<FakeLvl>::default() as ZoomLevel].into();

        let image = test_utils::expect_single_resolved(images);
        assert_eq!(image.into_zoom_levels().len(), 1);
    }

    #[test]
    fn fallback_title_does_not_replace_image_title() {
        let images = Images::from(vec![
            ResolvedImage::new(vec![], None),
            ResolvedImage::new(vec![], Some("Child".into())),
        ])
        .with_fallback_title(Some("Parent".into()));
        let titles = images
            .iter()
            .map(|image| image.title().map(str::to_string))
            .collect::<Vec<_>>();

        assert_eq!(titles, vec![Some("Parent".into()), Some("Child".into())]);
    }
}