rosier 0.4.0

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
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
678
679
680
681
682
683
684
685
//! What a pane shows: decoding the picture (or the pages of a book view),
//! keeping the next one ready, zoom and pan, and the sharper decodes and
//! full-size cut-outs zooming in needs. Methods of `Rosier` that drive one
//! pane's picture live here; the library, sessions and input stay in app.rs.

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;

use gpui::{Context, RenderImage};

use crate::app::{FADE, Rosier, drop_images, render_decoded, swap_image, to_render_image};
use crate::media::{Entry, Kind};
use crate::pane::{Pane, Ready};
use crate::video::Video;
use crate::{db, glass, i18n, thumb};

/// Long side to decode a picture at for pane `p`: its size in pixels.
pub(crate) fn view_long(p: &Pane) -> u32 {
    p.px_size.0.max(p.px_size.1).max(256)
}

/// Long side to decode each of `n` pages of a book view at: a page of a
/// spread needs the pane's height, or its share of the width.
pub(crate) fn page_long(p: &Pane, n: usize) -> u32 {
    let (w, h) = p.px_size;
    h.max(w / n.max(1) as u32).max(256)
}

/// Decodes entry `i` for the viewer, with its glass strip.
pub(crate) fn decode_ready(e: &crate::media::Entry, i: usize, long: u32) -> anyhow::Result<Ready> {
    let d = thumb::decode_image(e, long)?;
    let strip = glass::strip(&d.image);
    let full = d.full;
    let image = render_decoded(d).ok_or_else(|| anyhow::anyhow!("cannot draw the picture"))?;
    Ok(Ready { entry: i, long, image, strip, full })
}

/// Decodes the pages of a book view and puts them side by side.
pub(crate) fn decode_pages(pages: &[crate::media::Entry], rtl: bool, long: u32) -> anyhow::Result<Ready> {
    use rayon::prelude::*;
    // The pages of a spread decode side by side.
    let each: Vec<thumb::Decoded> =
        pages.par_iter().map(|e| thumb::decode_image(e, long)).collect::<anyhow::Result<_>>()?;
    let mut decoded = Vec::with_capacity(each.len());
    let mut full = (0u32, 0u32);
    for d in each {
        // The spread's full size: pages at the tallest page's height.
        let (w, h) = d.full;
        let tall = full.1.max(h);
        full = (
            (u64::from(full.0) * u64::from(tall) / u64::from(full.1.max(1))) as u32
                + (u64::from(w) * u64::from(tall) / u64::from(h.max(1))) as u32,
            tall,
        );
        decoded.push(d.image);
    }
    if decoded.is_empty() {
        anyhow::bail!("no pages");
    }
    let image = crate::book::join_pages(decoded, rtl);
    let strip = glass::strip(&image);
    let image = to_render_image(image).ok_or_else(|| anyhow::anyhow!("cannot draw the pages"))?;
    Ok(Ready { entry: usize::MAX, long, image, strip, full })
}

/// What a decoded book view shows: its pages, direction and size.
pub(crate) fn book_key(pages: &[crate::media::Entry], rtl: bool, long: u32) -> crate::pane::BookKey {
    (pages.iter().map(|e| e.path.clone()).collect(), rtl, long)
}

impl Rosier {
    /// Shows `panes[ix].items[pos]`: decodes an image, or starts a video.
    pub(crate) fn load_current(&mut self, ix: usize, cx: &mut Context<Self>) {
        let muted = self.panes[ix].muted;
        let pane = &mut self.panes[ix];
        // Keep the picture leaving the screen, for stepping back to it.
        if let (Some(entry), Some(image), Some(strip)) = (pane.shown.take(), &pane.frame, &pane.glass_src)
            && !pane.is_ready(entry)
        {
            let r =
                Ready { entry, long: pane.decoded_long, image: image.clone(), strip: strip.clone(), full: pane.full };
            let evicted = pane.keep(r);
            drop_images(evicted, cx);
        }
        let pane = &mut self.panes[ix];
        // The full-size picture and its cut-outs belong to the one leaving.
        pane.full_res = None;
        pane.full_res_loading = None;
        if let Some((old, _)) = pane.detail.take() {
            cx.drop_image(old, None);
        }
        pane.video = None;
        pane.error = None;
        pane.time = (0.0, 0.0);
        // A locked view keeps zoom and pan for the next picture; videos
        // always start fitted.
        let video_next = pane.current().and_then(|i| self.lib.entries.get(i)).is_some_and(|e| e.kind == Kind::Video);
        if !pane.lock_view || video_next {
            pane.reset_view();
        }
        pane.drag = None;
        pane.generation += 1;
        pane.shown_at = Instant::now();
        let generation = pane.generation;
        let Some(entry_ix) = pane.current() else { return };
        let entry = self.lib.entries[entry_ix].clone();
        if self.show_info {
            self.read_info(ix, cx);
        }
        if !self.open_book(ix, entry_ix) {
            let path = entry.path.clone();
            cx.spawn(async move |this, cx| {
                let res = cx.background_executor().spawn(async move { crate::book::pages(&path) }).await;
                let _ = this.update(cx, |this, cx| {
                    let Some(p) = this.panes.get_mut(ix).filter(|p| p.generation == generation) else { return };
                    match res {
                        Ok(pages) => {
                            p.book = Some((entry_ix, Arc::new(pages)));
                            // Same item: keep the generation, show it now.
                            this.open_book(ix, entry_ix);
                            this.show_book(ix, generation, cx);
                        }
                        Err(_) => p.error = Some(i18n::t("pane.error").into()),
                    }
                    cx.notify();
                });
            })
            .detach();
            cx.notify();
            return;
        }
        if self.show_book(ix, generation, cx) {
            return;
        }
        let pane = &mut self.panes[ix];
        match entry.kind {
            Kind::Book => pane.error = Some(i18n::t("pane.error").into()),
            Kind::Image => {
                let long = view_long(pane);
                if let Some(r) = pane.take_ready(entry_ix, long) {
                    self.show_ready(ix, r, cx);
                    self.prefetch(ix, cx);
                } else {
                    cx.spawn(async move |this, cx| {
                        let res =
                            cx.background_executor().spawn(async move { decode_ready(&entry, entry_ix, long) }).await;
                        let _ = this.update(cx, |this, cx| {
                            if this.panes.get(ix).is_none_or(|p| p.generation != generation) {
                                return;
                            }
                            match res {
                                Ok(r) => this.show_ready(ix, r, cx),
                                Err(_) => this.panes[ix].error = Some(i18n::t("pane.error").into()),
                            }
                            this.prefetch(ix, cx);
                            cx.notify();
                        });
                    })
                    .detach();
                }
            }
            Kind::Video => {
                let looping = !pane.slideshow;
                let start = self.lib.resume_at(entry_ix).unwrap_or(0.0);
                match Video::start(&entry.path, muted, looping, pane.volume, pane.speed, start) {
                    Ok((video, rx)) => {
                        video.set_target(pane.px_size.0, pane.px_size.1);
                        video.set_paused(pane.paused);
                        pane.video = Some(video);
                        pane.tracks.clear();
                        pane.chapters.clear();
                        if let Some((_, old)) = pane.preview.take() {
                            cx.drop_image(old, None);
                        }
                        pane.time = (0.0, 0.0);
                        cx.spawn(async move |this, cx| {
                            while let Ok(msg) = rx.recv().await {
                                let keep =
                                    this.update(cx, |this, cx| this.on_video(ix, generation, msg, cx)).unwrap_or(false);
                                if !keep {
                                    break;
                                }
                            }
                        })
                        .detach();
                    }
                    Err(_) => pane.error = Some(i18n::t("pane.error").into()),
                }
            }
        }
        cx.notify();
    }

    /// Shows pane `ix`'s book view, if it is in one: from the views decoded
    /// ahead, or decoded now. Returns whether it was a book view.
    pub(crate) fn show_book(&mut self, ix: usize, generation: u64, cx: &mut Context<Self>) -> bool {
        let Some((pages, rtl)) = self.book_view(ix) else { return false };
        let long = page_long(&self.panes[ix], pages.len());
        self.panes[ix].shown = None;
        let key = book_key(&pages, rtl, long);
        if let Some(r) = self.panes[ix].take_book_ready(&key) {
            self.show_ready(ix, r, cx);
            self.panes[ix].shown = None;
            self.prefetch_spread(ix, cx);
            return true;
        }
        cx.spawn(async move |this, cx| {
            let res = cx.background_executor().spawn(async move { decode_pages(&pages, rtl, long) }).await;
            let _ = this.update(cx, |this, cx| {
                if this.panes.get(ix).is_none_or(|p| p.generation != generation) {
                    return;
                }
                match res {
                    Ok(r) => {
                        this.show_ready(ix, r, cx);
                        this.panes[ix].shown = None;
                    }
                    Err(_) => this.panes[ix].error = Some(i18n::t("pane.error").into()),
                }
                this.prefetch_spread(ix, cx);
                cx.notify();
            });
        })
        .detach();
        cx.notify();
        true
    }

    /// Puts a decoded picture on screen in pane `ix`.
    pub(crate) fn show_ready(&mut self, ix: usize, r: Ready, cx: &mut Context<Self>) {
        let pane = &mut self.panes[ix];
        pane.shown = Some(r.entry);
        pane.decoded_long = r.long;
        pane.full = r.full;
        pane.glass_src = Some(r.strip);
        pane.shown_at = Instant::now();
        let old = pane.frame.replace(r.image);
        // The picture before fades out over the new one; one that was
        // still fading is let go.
        // Only a slideshow fades; a picture the user steps to shows at once.
        let fading_out = old.filter(|_| self.fade && pane.zoom <= 1.0 && pane.auto_step).map(|o| (o, Instant::now()));
        let mut gone: Vec<Arc<RenderImage>> = Vec::new();
        if let Some((o, _)) = std::mem::replace(&mut pane.fade_from, fading_out) {
            gone.push(o);
        }
        let ready = &pane.ready;
        gone.retain(|o| {
            !ready.iter().any(|k| Arc::ptr_eq(&k.image, o))
                && !pane.fade_from.as_ref().is_some_and(|(f, _)| Arc::ptr_eq(f, o))
                && !pane.frame.as_ref().is_some_and(|f| Arc::ptr_eq(f, o))
        });
        drop_images(gone, cx);
        self.refresh_glass(ix, cx);
        // A locked, zoomed-in view: decode the new picture as sharp as the
        // zoom needs, and cut its full-size part past 8K.
        let pane = &self.panes[ix];
        if pane.zoom > 1.0 {
            let need = ((view_long(pane) as f32) * pane.zoom).min(crate::pane::WHOLE_MAX as f32) as u32;
            if need > pane.decoded_long + pane.decoded_long / 4 {
                self.panes[ix].decoded_long = need;
                self.sharpen(ix, need, cx);
            }
            self.update_detail(ix, cx);
        }
        cx.notify();
    }

    /// The fit menu: how pane `ix`'s picture fills it. The zoom starts over
    /// from the new fit.
    pub(crate) fn set_fit(&mut self, ix: usize, fit: crate::pane::Fit, cx: &mut Context<Self>) {
        let Some(p) = self.panes.get_mut(ix) else { return };
        p.fit = fit;
        p.reset_view();
        self.fit_menu = None;
        // Actual size and fill can show more of a big picture than was
        // decoded: decode again and cut the full-size part as zooming does.
        let p = &self.panes[ix];
        if p.video.is_none() && p.full.0 > 0 && p.rect.2 > 0.0 {
            let base = p.base(p.full.0 as f32, p.full.1 as f32);
            let need = (base.2.max(base.3) * p.px_size.0 as f32 / p.rect.2).min(crate::pane::WHOLE_MAX as f32) as u32;
            if need > p.decoded_long + p.decoded_long / 4 {
                self.panes[ix].decoded_long = need;
                self.sharpen(ix, need, cx);
            }
        }
        self.update_detail(ix, cx);
        self.mirror_view(ix, cx);
        cx.notify();
    }

    /// Z in the player: keep zoom and pan for the next picture, or not.
    pub(crate) fn toggle_lock_view(&mut self, ix: usize, cx: &mut Context<Self>) {
        if let Some(p) = self.panes.get_mut(ix) {
            p.lock_view = !p.lock_view;
        }
        cx.notify();
    }

    /// Lets go of pictures that finished fading out.
    pub(crate) fn end_fades(&mut self, cx: &mut Context<Self>) {
        for p in &mut self.panes {
            if p.fade_from.as_ref().is_some_and(|(_, at)| at.elapsed() >= FADE)
                && let Some((o, _)) = p.fade_from.take()
                && !p.ready.iter().any(|k| Arc::ptr_eq(&k.image, &o))
                && !p.frame.as_ref().is_some_and(|f| Arc::ptr_eq(f, &o))
            {
                cx.drop_image(o, None);
            }
        }
    }

    /// Decodes the picture pane `ix` shows next, so stepping forward (by
    /// key, button or slideshow) shows it at once.
    pub(crate) fn prefetch(&mut self, ix: usize, cx: &mut Context<Self>) {
        let pane = &mut self.panes[ix];
        let Some(next) = pane.peek_next(&mut self.rng).and_then(|p| pane.items.get(p).copied()) else { return };
        let long = view_long(pane);
        let entry = &self.lib.entries[next];
        if Some(next) == pane.current() || pane.is_ready(next) || entry.kind != Kind::Image {
            return;
        }
        let entry = entry.clone();
        cx.spawn(async move |this, cx| {
            let res = cx.background_executor().spawn(async move { decode_ready(&entry, next, long) }).await;
            let _ = this.update(cx, |this, cx| {
                if let (Ok(r), Some(pane)) = (res, this.panes.get_mut(ix))
                    && pane.items.contains(&next)
                {
                    let evicted = pane.keep(r);
                    drop_images(evicted, cx);
                }
            });
        })
        .detach();
    }

    /// Zooms pane `ix` by `factor` around `at` (relative to the pane's
    /// center), decoding the image sharper once zoomed past its decode.
    pub(crate) fn zoom_pane(&mut self, ix: usize, factor: f32, at: (f32, f32), cx: &mut Context<Self>) {
        if let Some(need) = self.panes[ix].zoom_by(factor, at) {
            self.sharpen(ix, need, cx);
        }
        self.update_detail(ix, cx);
        self.mirror_view(ix, cx);
        cx.notify();
    }

    /// Y: zooming or panning one pane does the same in the others.
    pub(crate) fn toggle_sync_view(&mut self, cx: &mut Context<Self>) {
        self.sync_view = !self.sync_view;
        if self.sync_view {
            // The focused pane's view, unless it is fitted and another pane
            // was zoomed: that one is what to compare.
            let zoomed = |p: &crate::pane::Pane| p.video.is_none() && p.frame.is_some() && p.zoom != 1.0;
            let from = if zoomed(&self.panes[self.focused]) {
                self.focused
            } else {
                (0..self.panes.len().min(self.split)).find(|&j| zoomed(&self.panes[j])).unwrap_or(self.focused)
            };
            self.mirror_view(from, cx);
        }
        cx.notify();
    }

    /// With the views in sync, gives every other pane showing a picture
    /// the zoom and pan of pane `ix`, decoding each as sharp as it needs.
    pub(crate) fn mirror_view(&mut self, ix: usize, cx: &mut Context<Self>) {
        if !self.sync_view || self.split < 2 {
            return;
        }
        let Some(src) = self.panes.get(ix).filter(|p| p.video.is_none() && p.frame.is_some()) else { return };
        let (zoom, pan) = (src.zoom, src.pan);
        for j in 0..self.panes.len().min(self.split) {
            let p = &mut self.panes[j];
            if j == ix || p.video.is_some() || p.frame.is_none() || (p.zoom, p.pan) == (zoom, pan) {
                continue;
            }
            p.zoom = zoom;
            p.pan = pan;
            let need = ((view_long(p) as f32) * zoom).min(crate::pane::WHOLE_MAX as f32) as u32;
            if zoom > 1.0 && need > p.decoded_long + p.decoded_long / 4 {
                p.decoded_long = need;
                self.sharpen(j, need, cx);
            }
            self.update_detail(j, cx);
        }
    }

    /// Past what the whole view was decoded at, draws the visible part cut
    /// from the full-size picture at screen resolution: a 100-megapixel
    /// photo zoomed in shows its own pixels, not a blown-up 8K copy. The
    /// full-size picture is decoded once; cuts follow the view, one at a
    /// time, the newest view next.
    pub(crate) fn update_detail(&mut self, ix: usize, cx: &mut Context<Self>) {
        let Some(pane) = self.panes.get_mut(ix) else { return };
        if !pane.wants_detail() {
            if let Some((old, _)) = pane.detail.take() {
                cx.drop_image(old, None);
            }
            return;
        }
        let Some(entry) = pane.shown else { return };
        let full = match &pane.full_res {
            Some((e, b)) if *e == entry => b.clone(),
            _ => {
                if pane.full_res_loading != Some(entry) {
                    pane.full_res_loading = Some(entry);
                    let e = self.lib.entries[entry].clone();
                    let long = crate::pane::full_res_long(pane.full);
                    cx.spawn(async move |this, cx| {
                        let res = cx
                            .background_executor()
                            .spawn(async move { thumb::decode_image(&e, long).map(|d| d.image) })
                            .await;
                        let _ = this.update(cx, |this, cx| {
                            let Some(p) = this.panes.get_mut(ix) else { return };
                            if p.full_res_loading == Some(entry) {
                                p.full_res_loading = None;
                                if let Ok(b) = res
                                    && p.shown == Some(entry)
                                {
                                    p.full_res = Some((entry, Arc::new(b)));
                                    this.update_detail(ix, cx);
                                }
                            }
                        });
                    })
                    .detach();
                }
                return;
            }
        };
        if pane.detail_busy {
            pane.detail_again = true;
            return;
        }
        let (_, _, w, h) = pane.rect;
        let px_scale = pane.px_size.0 as f32 / w.max(1.0);
        let nearest = pane.enlarged();
        let Some((n, size)) = crate::pane::visible_part(pane.full, pane.placement(), w, h, px_scale, nearest) else {
            return;
        };
        pane.detail_busy = true;
        pane.detail_again = false;
        cx.spawn(async move |this, cx| {
            let res = cx.background_executor().spawn(async move { thumb::cut(&full, n, size, nearest) }).await;
            let _ = this.update(cx, |this, cx| {
                let Some(p) = this.panes.get_mut(ix) else { return };
                p.detail_busy = false;
                if p.shown != Some(entry) {
                    return;
                }
                if let Some(image) = res.ok().and_then(to_render_image) {
                    let old = p.detail.replace((image, n));
                    if let Some((old, _)) = old {
                        cx.drop_image(old, None);
                    }
                }
                if p.detail_again {
                    this.update_detail(ix, cx);
                }
                cx.notify();
            });
        })
        .detach();
    }

    /// "0" in the player: fit, or actual size.
    pub(crate) fn toggle_actual_size(&mut self, ix: usize, cx: &mut Context<Self>) {
        if let Some(need) = self.panes[ix].toggle_actual_size() {
            self.sharpen(ix, need, cx);
        }
        self.update_detail(ix, cx);
        self.mirror_view(ix, cx);
        cx.notify();
    }

    /// Decodes pane `ix`'s picture again with a long side of `need`, after
    /// zooming in past what was decoded.
    pub(crate) fn sharpen(&mut self, ix: usize, need: u32, cx: &mut Context<Self>) {
        let p = &self.panes[ix];
        let Some(i) = p.current() else { return };
        let generation = p.generation;
        let entry = self.lib.entries[i].clone();
        // In book view the pages on screen are decoded again, side by side.
        let pages = self.book_view(ix);
        cx.spawn(async move |this, cx| {
            let res = cx
                .background_executor()
                .spawn(async move {
                    match pages {
                        Some((pages, rtl)) => decode_pages(&pages, rtl, need).map(|r| r.image),
                        None => thumb::decode_image(&entry, need)
                            .and_then(|d| render_decoded(d).ok_or_else(|| anyhow::anyhow!("cannot draw"))),
                    }
                })
                .await;
            let _ = this.update(cx, |this, cx| {
                let Some(pane) = this.panes.get_mut(ix).filter(|p| p.generation == generation) else { return };
                if let Ok(image) = res {
                    swap_image(&mut pane.frame, image, cx);
                }
                cx.notify();
            });
        })
        .detach();
    }

    /// Re-cuts the glass background for pane `ix` from its latest blurred
    /// strip.
    pub(crate) fn refresh_glass(&mut self, ix: usize, cx: &mut Context<Self>) {
        let Some(pane) = self.panes.get_mut(ix) else { return };
        let Some(src) = &pane.glass_src else { return };
        // The whole bottom strip, stretched under the whole bar: stable while
        // zooming or panning, and frosted edge to edge.
        if let Some(image) = to_render_image(glass::crop(src, [0.0, 0.0, 1.0, 1.0])) {
            swap_image(&mut pane.glass, image, cx);
        }
    }

    pub(crate) fn advance(&mut self, ix: usize, delta: isize, cx: &mut Context<Self>) {
        let p = &mut self.panes[ix];
        // Set by the slideshow just before; any other step is the user's.
        p.auto_step = std::mem::take(&mut p.auto_step_next);
        if p.items.is_empty() {
            return;
        }
        // Book view turns pages: one or two at a time, the cover alone.
        if let Some(layout) = p.layout
            && !(p.shuffle && p.book.is_none())
        {
            let in_book = p.book.is_some();
            let (start, n) = match &p.book {
                Some((_, pages)) => (p.page, pages.len()),
                None => (p.pos, p.items.len()),
            };
            match layout.step(start, delta, n) {
                Some(s) if in_book => p.page = s,
                Some(s) => p.pos = s,
                // Past either end of a book: the next or previous item,
                // entered from its first or last page.
                None if in_book => {
                    p.step(delta.signum(), &mut self.rng);
                    p.page = if delta < 0 { usize::MAX } else { 0 };
                }
                // Past either end of a folder: around to the other end.
                None => p.pos = if delta > 0 { 0 } else { layout.view_start(n - 1) },
            }
        } else {
            p.step(delta, &mut self.rng);
            p.page = 0;
        }
        self.load_current(ix, cx);
    }

    /// Before showing pane `ix`'s item `i`: lists the pages when it is a
    /// book, and sets the book view the folder or book was left in.
    /// Returns false while a book's pages still have to be listed.
    pub(crate) fn open_book(&mut self, ix: usize, i: usize) -> bool {
        let entry = &self.lib.entries[i];
        let p = &mut self.panes[ix];
        if entry.kind == Kind::Book {
            if p.book.as_ref().is_none_or(|(b, _)| *b != i) {
                // The pages are listed off the UI thread first.
                p.book = None;
                p.layout = None;
                return false;
            }
            let layout = self.layouts.get(&entry.path).copied().unwrap_or_default();
            p.layout = Some(layout);
            let n = p.book.as_ref().map_or(0, |(_, v)| v.len());
            p.page = layout.view_start(p.page.min(n.saturating_sub(1)));
        } else {
            p.book = None;
            p.page = 0;
            p.layout = entry.path.parent().and_then(|d| self.layouts.get(d)).copied();
            if let Some(l) = p.layout {
                p.pos = l.view_start(p.pos);
            }
        }
        true
    }

    /// The pictures pane `ix` shows side by side in book view, and whether
    /// right to left; None outside book view (and for a video).
    pub(crate) fn book_view(&self, ix: usize) -> Option<(Vec<Entry>, bool)> {
        let p = &self.panes[ix];
        self.book_view_at(ix, if p.book.is_some() { p.page } else { p.pos })
    }

    /// The pictures of the book view starting at `start` (a page of the
    /// book, or a position in the folder).
    pub(crate) fn book_view_at(&self, ix: usize, start: usize) -> Option<(Vec<Entry>, bool)> {
        let p = &self.panes[ix];
        let layout = p.layout?;
        if let Some((b, pages)) = &p.book {
            let book = &self.lib.entries[*b];
            let pics = layout.view(start, pages.len()).into_iter().map(|k| crate::book::page_entry(book, &pages[k]));
            return Some((pics.collect(), layout.rtl));
        }
        let first = &self.lib.entries[*p.items.get(start)?];
        if first.kind != Kind::Image {
            return None;
        }
        let pics = layout
            .view(start, p.items.len())
            .into_iter()
            .map(|k| &self.lib.entries[p.items[k]])
            .take_while(|e| e.kind == Kind::Image)
            .cloned();
        Some((pics.collect(), layout.rtl))
    }

    /// Decodes the next view of pane `ix`'s book ahead, so turning the page
    /// shows it at once.
    pub(crate) fn prefetch_spread(&mut self, ix: usize, cx: &mut Context<Self>) {
        let p = &self.panes[ix];
        let Some(layout) = p.layout else { return };
        let (start, n) = match &p.book {
            Some((_, pages)) => (p.page, pages.len()),
            None => (p.pos, p.items.len()),
        };
        let Some(next) = layout.step(start, 1, n) else { return };
        let Some((pages, rtl)) = self.book_view_at(ix, next) else { return };
        let long = page_long(p, pages.len());
        let key = book_key(&pages, rtl, long);
        if p.book_ready.iter().any(|(k, _)| *k == key) {
            return;
        }
        let generation = p.generation;
        cx.spawn(async move |this, cx| {
            let res = cx.background_executor().spawn(async move { decode_pages(&pages, rtl, long) }).await;
            let _ = this.update(cx, |this, cx| {
                if let (Ok(r), Some(p)) = (res, this.panes.get_mut(ix))
                    && p.generation == generation
                {
                    let evicted = p.keep_book_ready(key, r);
                    drop_images(evicted, cx);
                }
            });
        })
        .detach();
    }

    /// Book view on or off for the folder or book in pane `ix`, or another
    /// layout; remembered for that folder or book.
    pub(crate) fn set_layout(&mut self, ix: usize, layout: Option<crate::book::Layout>, cx: &mut Context<Self>) {
        let Some(i) = self.panes.get(ix).and_then(|p| p.current()) else { return };
        let entry = &self.lib.entries[i];
        let in_book = entry.kind == Kind::Book;
        let Some(key) = (if in_book { Some(entry.path.clone()) } else { entry.path.parent().map(PathBuf::from) })
        else {
            return;
        };
        // A book is always read as a book: "off" is one page at a time.
        let layout =
            if in_book { Some(layout.unwrap_or(crate::book::Layout { spread: false, rtl: true })) } else { layout };
        match layout {
            Some(l) => self.layouts.insert(key.clone(), l),
            None => self.layouts.remove(&key),
        };
        let bits = layout.map(crate::book::Layout::to_bits);
        let db_path = self.db_path.clone();
        cx.background_executor()
            .spawn(async move {
                if let Ok(conn) = db::open(&db_path) {
                    let _ = db::set_layout(&conn, &key, bits);
                }
            })
            .detach();
        self.load_current(ix, cx);
    }

    /// B: book view on or off for a folder; one page or two for a book.
    pub(crate) fn toggle_book(&mut self, ix: usize, cx: &mut Context<Self>) {
        let Some(p) = self.panes.get(ix) else { return };
        let next = match (p.book.is_some(), p.layout) {
            (true, Some(l)) => Some(crate::book::Layout { spread: !l.spread, ..l }),
            (_, Some(_)) => None,
            (_, None) => Some(crate::book::Layout::default()),
        };
        self.set_layout(ix, next, cx);
    }
}