rosier 0.5.1

A fast picture and video viewer for large folders
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
//! Books: comic archives (ZIP, CBZ) and picture EPUBs, read as a run of
//! pages, and how a book is laid out on screen (one page or two side by
//! side, read right to left or left to right).
//!
//! Only the archive's directory and the pages shown are read; nothing is
//! extracted to disk.

use std::fs::File;
use std::io::{BufReader, Read};
use std::path::Path;

use anyhow::{Context as _, Result, bail};

/// Pictures a page can be. Formats libmpv decodes (AVIF, HEIC, JPEG XL)
/// are left out: it reads files, not bytes held in memory.
const PAGE_EXTS: [&str; 7] = ["jpg", "jpeg", "png", "gif", "webp", "bmp", "tif"];

/// Pages larger than this are skipped rather than read into memory.
const PAGE_MAX: u64 = 256 << 20;

fn is_page(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    // macOS adds "__MACOSX/._name" shadows to archives it makes.
    !lower.starts_with("__macosx/")
        && !lower.rsplit('/').next().is_some_and(|f| f.starts_with('.'))
        && lower.rsplit_once('.').is_some_and(|(_, e)| PAGE_EXTS.contains(&e))
}

type Archive = zip::ZipArchive<BufReader<File>>;

/// Archives opened lately, newest last, so turning a page does not read the
/// archive's directory again. Keyed by path, size and modification time:
/// a book changed on disk is opened afresh.
type Key = (std::path::PathBuf, u64, Option<std::time::SystemTime>);
static OPEN: std::sync::Mutex<Vec<(Key, std::sync::Arc<std::sync::Mutex<Archive>>)>> =
    std::sync::Mutex::new(Vec::new());

/// How many archives stay open.
const OPEN_MAX: usize = 4;

fn open(path: &Path) -> Result<std::sync::Arc<std::sync::Mutex<Archive>>> {
    let md = std::fs::metadata(path).with_context(|| format!("open {}", path.display()))?;
    let key: Key = (path.to_path_buf(), md.len(), md.modified().ok());
    let mut open = OPEN.lock().unwrap_or_else(|e| e.into_inner());
    if let Some(k) = open.iter().position(|(k, _)| *k == key) {
        let hit = open.remove(k);
        let a = hit.1.clone();
        open.push(hit);
        return Ok(a);
    }
    let f = File::open(path).with_context(|| format!("open {}", path.display()))?;
    let a = std::sync::Arc::new(std::sync::Mutex::new(zip::ZipArchive::new(BufReader::new(f))?));
    open.retain(|(k, _)| k.0 != key.0);
    open.push((key, a.clone()));
    if open.len() > OPEN_MAX {
        open.remove(0);
    }
    Ok(a)
}

/// The pages of the book at `path`, in reading order: an EPUB's spine, or
/// the archive's pictures in natural name order.
pub fn pages(path: &Path) -> Result<Vec<String>> {
    let z = open(path)?;
    let mut z = z.lock().unwrap_or_else(|e| e.into_inner());
    let z = &mut *z;
    let names: Vec<String> = z.file_names().filter_map(|n| n.ok().map(|n| n.into_owned())).collect();
    if let Some(order) = epub_order(z, &names) {
        if order.is_empty() {
            bail!("an EPUB without pictures (text books are not supported)");
        }
        return Ok(order);
    }
    let mut v: Vec<String> = names.into_iter().filter(|n| is_page(n)).collect();
    v.sort_by(|a, b| crate::media::natural_cmp(Path::new(a), Path::new(b)));
    if v.is_empty() {
        bail!("no pictures in the archive");
    }
    Ok(v)
}

/// Is `path` a book (by its name)?
fn is_book(path: &Path) -> bool {
    crate::media::kind_of(path) == Some(crate::media::Kind::Book)
}

/// A page as a picture entry: its path is the book's path with the page's
/// name inside it, which `read` understands.
pub fn page_entry(book: &crate::media::Entry, name: &str) -> crate::media::Entry {
    crate::media::Entry {
        id: 0,
        path: book.path.join(name),
        kind: crate::media::Kind::Image,
        size: book.size,
        mtime: book.mtime,
    }
}

/// Reads a file, or a page of a book given as `<book path>/<page name>`.
pub fn read(path: &Path) -> std::io::Result<Vec<u8>> {
    let err = match std::fs::read(path) {
        Ok(d) => return Ok(d),
        Err(e) => e,
    };
    // A page inside a book: the nearest parent that is a book file.
    for book in path.ancestors().skip(1) {
        if is_book(book) && book.is_file() {
            let name = path.strip_prefix(book).map_err(std::io::Error::other)?;
            let name = name.to_string_lossy().replace('\\', "/");
            return read_page(book, &name).map_err(std::io::Error::other);
        }
    }
    Err(err)
}

/// The bytes of page `name` of the book at `path`.
fn read_page(path: &Path, name: &str) -> Result<Vec<u8>> {
    let z = open(path)?;
    let mut z = z.lock().unwrap_or_else(|e| e.into_inner());
    let mut f = z.by_name(name)?;
    if f.size() > PAGE_MAX {
        bail!("page too large");
    }
    let mut data = Vec::with_capacity(f.size() as usize);
    f.read_to_end(&mut data)?;
    Ok(data)
}

/// The text of member `name`, if it is there and small.
fn read_text(z: &mut Archive, name: &str) -> Option<String> {
    let mut f = z.by_name(name).ok()?;
    if f.size() > 4 << 20 {
        return None;
    }
    let mut s = String::new();
    f.read_to_string(&mut s).ok()?;
    Some(s)
}

/// For an EPUB, its pictures in spine order: each spine document's first
/// picture, or the document itself when the spine lists pictures. None for
/// archives that are not EPUBs.
fn epub_order(z: &mut Archive, names: &[String]) -> Option<Vec<String>> {
    let container = read_text(z, "META-INF/container.xml")?;
    let opf_path = tags(&container, "rootfile").find_map(|t| attr(t, "full-path"))?;
    let opf = read_text(z, &opf_path)?;
    let base = opf_path.rsplit_once('/').map_or("", |(d, _)| d);
    // id -> href from the manifest.
    let mut manifest = Vec::new();
    for item in tags(&opf, "item") {
        if let (Some(id), Some(href)) = (attr(item, "id"), attr(item, "href")) {
            manifest.push((id, join(base, &href)));
        }
    }
    let mut out = Vec::new();
    for itemref in tags(&opf, "itemref") {
        let Some(idref) = attr(itemref, "idref") else { continue };
        let Some((_, href)) = manifest.iter().find(|(id, _)| *id == idref) else { continue };
        if is_page(href) {
            out.push(href.clone());
            continue;
        }
        let Some(doc) = read_text(z, href) else { continue };
        let dir = href.rsplit_once('/').map_or("", |(d, _)| d);
        // A picture page holds one <img src> or SVG <image xlink:href>.
        let src = tags(&doc, "img")
            .find_map(|t| attr(t, "src"))
            .or_else(|| tags(&doc, "image").find_map(|t| attr(t, "xlink:href").or_else(|| attr(t, "href"))));
        if let Some(src) = src {
            let p = join(dir, &src);
            if names.contains(&p) && !out.contains(&p) {
                out.push(p);
            }
        }
    }
    Some(out)
}

/// The start tags `<name ...>` in `xml`, each as its text up to '>'.
fn tags<'a>(xml: &'a str, name: &str) -> impl Iterator<Item = &'a str> + 'a {
    let open = format!("<{name}");
    let found: Vec<&'a str> = xml
        .match_indices(open.as_str())
        .filter_map(|(i, _)| {
            let rest = &xml[i + open.len()..];
            // "<item" must not match "<itemref".
            if !rest.starts_with(|c: char| c.is_whitespace() || c == '/' || c == '>') {
                return None;
            }
            rest.find('>').map(|end| &rest[..end])
        })
        .collect();
    found.into_iter()
}

/// The value of attribute `name` in a start tag's text.
fn attr(tag: &str, name: &str) -> Option<String> {
    let mut from = 0;
    while let Some(k) = tag[from..].find(name) {
        let at = from + k;
        from = at + name.len();
        // A whole attribute name, not the end of a longer one.
        if at > 0 && !tag[..at].ends_with(char::is_whitespace) {
            continue;
        }
        let rest = tag[from..].trim_start().strip_prefix('=')?.trim_start();
        let q = rest.chars().next().filter(|c| *c == '"' || *c == '\'')?;
        let value = &rest[1..];
        return value.find(q).map(|end| unescape(&value[..end]));
    }
    None
}

fn unescape(s: &str) -> String {
    s.replace("&amp;", "&").replace("%20", " ")
}

/// `href` relative to the folder `dir` inside the archive, with "./" and
/// "../" resolved.
fn join(dir: &str, href: &str) -> String {
    let href = href.split('#').next().unwrap_or(href);
    let mut parts: Vec<&str> = if dir.is_empty() { Vec::new() } else { dir.split('/').collect() };
    for p in href.split('/') {
        match p {
            "" | "." => {}
            ".." => {
                parts.pop();
            }
            p => parts.push(p),
        }
    }
    parts.join("/")
}

/// How a book is laid out in a pane.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Layout {
    /// Two pages side by side (a spread); the cover stays alone.
    pub spread: bool,
    /// Read right to left, as Japanese manga: in a spread the later page is
    /// on the left.
    pub rtl: bool,
    /// The pages one under another, scrolled (see strip.rs); `spread`
    /// does not apply then.
    pub vertical: bool,
}

impl Default for Layout {
    fn default() -> Self {
        Layout { spread: true, rtl: true, vertical: false }
    }
}

impl Layout {
    pub fn to_bits(self) -> i64 {
        i64::from(self.spread) | i64::from(self.rtl) << 1 | i64::from(self.vertical) << 2
    }

    pub fn from_bits(v: i64) -> Self {
        Layout { spread: v & 1 != 0, rtl: v & 2 != 0, vertical: v & 4 != 0 }
    }

    /// The first page of the view holding page `p` of `n`: the cover alone,
    /// then pages 1-2, 3-4 and so on.
    pub fn view_start(self, p: usize) -> usize {
        if !self.two() || p == 0 { p } else { p - (p + 1) % 2 }
    }

    /// The pages of the view starting at `start`: one, or two in a spread
    /// (the cover and a last odd page stay alone).
    pub fn view(self, start: usize, n: usize) -> Vec<usize> {
        if start >= n {
            return Vec::new();
        }
        if self.two() && start > 0 && start + 1 < n { vec![start, start + 1] } else { vec![start] }
    }

    /// Two pages side by side.
    fn two(self) -> bool {
        self.spread && !self.vertical
    }

    /// Where the view `delta` views away from the one starting at `start`
    /// starts, or None past either end.
    pub fn step(self, start: usize, delta: isize, n: usize) -> Option<usize> {
        let mut s = self.view_start(start);
        for _ in 0..delta.unsigned_abs() {
            s = if delta > 0 {
                let next = s + self.view(s, n).len();
                (next < n).then_some(next)?
            } else {
                (s > 0).then(|| self.view_start(s - 1))?
            };
        }
        Some(s)
    }
}

/// Puts `pages` side by side at a common height, in reading order: left to
/// right, or right to left when `rtl`.
pub fn join_pages(mut pages: Vec<crate::turbo::Bgra>, rtl: bool) -> crate::turbo::Bgra {
    if pages.len() == 1 {
        return pages.pop().unwrap_or_else(|| crate::turbo::Bgra { width: 1, height: 1, pixels: vec![0; 4] });
    }
    if rtl {
        pages.reverse();
    }
    let h = pages.iter().map(|p| p.height).max().unwrap_or(1).max(1);
    // Scale each page to the common height.
    let pages: Vec<crate::turbo::Bgra> = pages
        .into_iter()
        .map(|p| {
            if p.height == h {
                return p;
            }
            let w = ((p.width as u64 * h as u64) / p.height.max(1) as u64).max(1) as u32;
            crate::thumb::cut(&p, [0.0, 0.0, 1.0, 1.0], (w, h), false).unwrap_or(p)
        })
        .collect();
    let w: u32 = pages.iter().map(|p| p.width).sum();
    let mut pixels = vec![0u8; (w * h * 4) as usize];
    let mut x0 = 0usize;
    for p in &pages {
        let (pw, ph) = (p.width as usize, p.height as usize);
        for y in 0..ph.min(h as usize) {
            let dst = (y * w as usize + x0) * 4;
            pixels[dst..dst + pw * 4].copy_from_slice(&p.pixels[y * pw * 4..(y + 1) * pw * 4]);
        }
        x0 += pw;
    }
    crate::turbo::Bgra { width: w, height: h, pixels }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use std::io::Write;

    /// A ZIP holding `files` (name, bytes), stored without compression.
    pub fn zip_of(path: &Path, files: &[(&str, &[u8])]) {
        let mut w = zip::ZipWriter::new(File::create(path).unwrap());
        let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
        for (name, data) in files {
            w.start_file(*name, opts).unwrap();
            w.write_all(data).unwrap();
        }
        w.finish().unwrap();
    }

    /// A fresh folder for one test, removed when dropped.
    struct Dir(std::path::PathBuf);
    impl Dir {
        fn path(&self) -> &Path {
            &self.0
        }
    }
    impl Drop for Dir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }
    fn dir() -> Dir {
        use std::sync::atomic::{AtomicU32, Ordering};
        static N: AtomicU32 = AtomicU32::new(0);
        let p = std::env::temp_dir().join(format!(
            "rosier-book-{}-{}",
            std::process::id(),
            N.fetch_add(1, Ordering::Relaxed)
        ));
        std::fs::create_dir_all(&p).unwrap();
        Dir(p)
    }

    #[test]
    fn archive_pages_come_in_natural_order_without_other_files() {
        let d = dir();
        let p = d.path().join("vol1.cbz");
        zip_of(
            &p,
            &[
                ("p10.jpg", b"x"),
                ("p2.jpg", b"y"),
                ("notes.txt", b"z"),
                ("__MACOSX/._p2.jpg", b"w"),
                ("sub/p1.PNG", b"v"),
            ],
        );
        assert_eq!(pages(&p).unwrap(), ["p2.jpg", "p10.jpg", "sub/p1.PNG"]);
        assert_eq!(read_page(&p, "p2.jpg").unwrap(), b"y");
        assert_eq!(read(&p.join("sub/p1.PNG")).unwrap(), b"v", "a page read through its virtual path");
        assert!(read(&p.join("missing.jpg")).is_err());
        // The archive changed on disk: its new directory is read.
        zip_of(&p, &[("only.jpg", b"new one")]);
        assert_eq!(pages(&p).unwrap(), ["only.jpg"]);
        assert_eq!(read_page(&p, "only.jpg").unwrap(), b"new one");
        let empty = d.path().join("text.zip");
        zip_of(&empty, &[("a.txt", b"z")]);
        assert!(pages(&empty).is_err());
    }

    #[test]
    fn epub_pages_follow_the_spine() {
        let d = dir();
        let p = d.path().join("manga.epub");
        let opf = r#"<package><manifest>
            <item id="p1" href="xhtml/p1.xhtml" media-type="application/xhtml+xml"/>
            <item id="p2" href="xhtml/p2.xhtml" media-type="application/xhtml+xml"/>
            <item id="cover" href="img/cover.jpg" media-type="image/jpeg"/>
            </manifest><spine><itemref idref="cover"/><itemref idref="p2"/><itemref idref="p1"/></spine></package>"#;
        zip_of(
            &p,
            &[
                ("mimetype", b"application/epub+zip"),
                (
                    "META-INF/container.xml",
                    br#"<container><rootfiles><rootfile full-path="OEBPS/content.opf"/></rootfiles></container>"#,
                ),
                ("OEBPS/content.opf", opf.as_bytes()),
                ("OEBPS/xhtml/p1.xhtml", br#"<html><body><img src="../img/a.jpg"/></body></html>"#),
                (
                    "OEBPS/xhtml/p2.xhtml",
                    br#"<html><body><svg><image width="1" xlink:href="../img/b.jpg"/></svg></body></html>"#,
                ),
                ("OEBPS/img/cover.jpg", b"c"),
                ("OEBPS/img/a.jpg", b"a"),
                ("OEBPS/img/b.jpg", b"b"),
            ],
        );
        assert_eq!(pages(&p).unwrap(), ["OEBPS/img/cover.jpg", "OEBPS/img/b.jpg", "OEBPS/img/a.jpg"]);
        // A text EPUB has no picture pages.
        let text = d.path().join("novel.epub");
        zip_of(
            &text,
            &[
                (
                    "META-INF/container.xml",
                    br#"<container><rootfiles><rootfile full-path="c.opf"/></rootfiles></container>"#,
                ),
                ("c.opf", br#"<package><manifest><item id="t" href="t.xhtml"/></manifest><spine><itemref idref="t"/></spine></package>"#),
                ("t.xhtml", b"<html><body><p>Once upon a time</p></body></html>"),
            ],
        );
        assert!(pages(&text).is_err());
    }

    #[test]
    fn a_spread_keeps_the_cover_alone() {
        let s = Layout { spread: true, rtl: true, vertical: false };
        assert_eq!(s.view(0, 6), [0]);
        assert_eq!(s.view(1, 6), [1, 2]);
        assert_eq!(s.view(5, 6), [5], "a last odd page stays alone");
        assert_eq!(s.view_start(2), 1);
        assert_eq!(s.view_start(4), 3);
        assert_eq!(s.step(0, 1, 6), Some(1));
        assert_eq!(s.step(1, 1, 6), Some(3));
        assert_eq!(s.step(3, 1, 6), Some(5));
        assert_eq!(s.step(5, 1, 6), None, "past the end");
        assert_eq!(s.step(3, -1, 6), Some(1));
        assert_eq!(s.step(1, -1, 6), Some(0));
        assert_eq!(s.step(0, -1, 6), None);
        let one = Layout { spread: false, rtl: false, vertical: false };
        assert_eq!(one.view(3, 6), [3]);
        assert_eq!(one.step(3, 2, 6), Some(5));
        assert_eq!(Layout::from_bits(s.to_bits()), s);
        assert_eq!(Layout::from_bits(one.to_bits()), one);
        // Vertical scroll goes one page at a time, even from a spread.
        let v = Layout { vertical: true, ..s };
        assert_eq!(v.view(1, 6), [1]);
        assert_eq!(v.step(1, 1, 6), Some(2));
        assert_eq!(Layout::from_bits(v.to_bits()), v);
    }

    #[test]
    fn joined_pages_share_a_height_and_read_right_to_left() {
        let page = |w, h, v| crate::turbo::Bgra { width: w, height: h, pixels: vec![v; (w * h * 4) as usize] };
        let j = join_pages(vec![page(2, 4, 10), page(1, 2, 200)], true);
        assert_eq!((j.width, j.height), (4, 4), "the small page is scaled to height 4");
        // Right to left: the second page is on the left.
        assert_eq!(j.pixels[0], 200);
        assert_eq!(j.pixels[(2 * 4) as usize], 10);
        let l = join_pages(vec![page(2, 4, 10), page(2, 4, 200)], false);
        assert_eq!(l.pixels[0], 10);
    }

    #[test]
    fn epub_attributes_and_paths() {
        assert_eq!(attr(r#" id="a" href="b c.jpg""#, "href").as_deref(), Some("b c.jpg"));
        assert_eq!(attr(r#" xlink:href='x.jpg'"#, "href"), None, "href inside xlink:href is not href");
        assert_eq!(join("OEBPS/xhtml", "../img/a.jpg#frag"), "OEBPS/img/a.jpg");
        assert_eq!(tags("<item a/><itemref b/>", "item").count(), 1);
    }
}