rosier 0.5.2

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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
//! 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)
}

/// The picture given on the command line, decoding on its own thread from
/// the moment rosier starts: the window and the library take long enough
/// that it is usually ready when its pane asks for it.
/// Long side the early picture decodes at: a full HD screen's.
const EARLY_LONG: u32 = 1920;

pub(crate) struct Early {
    path: PathBuf,
    rx: async_channel::Receiver<anyhow::Result<Ready>>,
}

impl Early {
    /// Starts decoding the first picture in `args`. The window's size is not
    /// known yet; the decode fills a maximized full HD window (a JPEG costs
    /// about the same at that size as at a smaller one, other formats decode
    /// whole either way), and a larger screen sharpens it after it shows.
    pub(crate) fn start(args: &[PathBuf]) -> Option<Self> {
        let path = args.iter().find(|p| p.is_file())?;
        let path = path.canonicalize().unwrap_or_else(|_| path.clone());
        let entry = crate::media::entry(path.clone(), || std::fs::metadata(&path).ok())?;
        if entry.kind != Kind::Image {
            return None;
        }
        let long = view_long(&Pane::empty()).max(EARLY_LONG);
        let (tx, rx) = async_channel::bounded(1);
        std::thread::spawn(move || tx.send_blocking(decode_ready(&entry, 0, long)));
        Some(Self { path, rx })
    }
}

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

/// 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, partial: false })
}

/// 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 {
    /// Looks for the motion of pane `ix`'s picture in the background and,
    /// for a motion photo, plays it once over the still (muted).
    pub(crate) fn start_motion(&mut self, ix: usize, cx: &mut Context<Self>) {
        let Some(p) = self.panes.get(ix) else { return };
        let Some(i) = p.current() else { return };
        let entry = &self.lib.entries[i];
        if entry.kind != Kind::Image || p.layout.is_some() {
            return;
        }
        let path = entry.path.clone();
        let generation = p.generation;
        cx.spawn(async move |this, cx| {
            let clip = cx
                .background_executor()
                .spawn(async move { crate::motion::find(&path).and_then(|c| crate::motion::playable(&path, &c)) })
                .await;
            let _ = this.update(cx, |this, cx| {
                let Some(p) = this.panes.get_mut(ix).filter(|p| p.generation == generation) else { return };
                let Some(clip) = clip else { return };
                p.has_motion = true;
                let Ok((video, rx)) = Video::start(&clip, true, false, p.volume, 1.0, 0.0) else { return };
                video.set_target(p.px_size.0, p.px_size.1);
                p.motion = Some(video);
                cx.notify();
                cx.spawn(async move |this, cx| {
                    while let Ok(msg) = rx.recv().await {
                        let keep = this
                            .update(cx, |this, cx| {
                                let Some(p) = this.panes.get_mut(ix).filter(|p| p.generation == generation) else {
                                    return false;
                                };
                                match msg {
                                    crate::video::Msg::Frame(b, _) => {
                                        if let Some(image) = to_render_image(b) {
                                            swap_image(&mut p.motion_frame, image, cx);
                                        }
                                        cx.notify();
                                        true
                                    }
                                    // Played once: back to the still.
                                    _ => {
                                        p.motion = None;
                                        if let Some(old) = p.motion_frame.take() {
                                            cx.drop_image(old, None);
                                        }
                                        cx.notify();
                                        false
                                    }
                                }
                            })
                            .unwrap_or(false);
                        if !keep {
                            break;
                        }
                    }
                })
                .detach();
            });
        })
        .detach();
    }

    /// 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,
                partial: pane.partial,
            };
            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.motion = None;
        pane.has_motion = false;
        if let Some(old) = pane.motion_frame.take() {
            cx.drop_image(old, 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.scroll = 0.0;
        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);
                let early = self.early.take().filter(|e| e.path == entry.path);
                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 = match early {
                            Some(e) => {
                                e.rx.recv()
                                    .await
                                    .unwrap_or_else(|e| Err(e.into()))
                                    .map(|r| Ready { entry: entry_ix, ..r })
                            }
                            None => {
                                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) => {
                                    // The early picture can be smaller than a
                                    // large screen needs: shown now, sharpened.
                                    let short = r.long < long;
                                    this.show_ready(ix, r, cx);
                                    if short {
                                        this.panes[ix].decoded_long = long;
                                        this.sharpen(ix, long, 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 {
        if self.strip_at(ix).is_some() {
            self.panes[ix].shown = None;
            // Stepping back into a book lands on its last page: keep the
            // column within its end.
            self.scroll_strip(ix, 0.0, cx);
            return true;
        }
        self.clear_strip(ix, cx);
        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.partial = r.partial;
        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];
        let mut sharpening = false;
        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);
                sharpening = true;
            }
            self.update_detail(ix, cx);
        }
        // An animation shows its first frame at once; every frame follows.
        if r.partial && !sharpening {
            let long = self.panes[ix].decoded_long;
            self.sharpen(ix, long, cx);
        }
        if !self.panes[ix].has_motion {
            self.start_motion(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>) {
        // A column of pages does not zoom.
        if self.strip_at(ix).is_some() {
            return;
        }
        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);
                    pane.partial = false;
                }
                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;
        }
        // Vertical scroll moves most of a pane down or up; past either end,
        // the next or previous item.
        if let Some((_, n)) = self.strip_at(ix) {
            let h = self.panes[ix].rect.3;
            if !self.scroll_strip(ix, delta as f32 * h * 0.85, cx) {
                return;
            }
            let p = &mut self.panes[ix];
            match (p.book.is_some(), delta > 0) {
                (true, fwd) => {
                    p.step(delta.signum(), &mut self.rng);
                    p.page = if fwd { 0 } else { usize::MAX };
                }
                (false, true) => p.pos = 0,
                (false, false) => p.pos = n - 1,
            }
            self.load_current(ix, cx);
            return;
        }
        let p = &mut self.panes[ix];
        // 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, vertical: false }))
        } 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.vertical, vertical: false, ..l }),
            (_, Some(_)) => None,
            (_, None) => Some(crate::book::Layout::default()),
        };
        self.set_layout(ix, next, cx);
    }
}

/// A page of a column on screen: its top, its height, and its picture once
/// decoded.
pub(crate) type StripShown = (f32, f32, Option<Arc<RenderImage>>);

/// Vertical scroll: the pages of a book one under another (strip.rs).
impl Rosier {
    /// The top page of pane `ix`'s column and how many pages it has, when
    /// the pane scrolls its book vertically.
    pub(crate) fn strip_at(&self, ix: usize) -> Option<(usize, usize)> {
        let p = self.panes.get(ix)?;
        if !p.layout?.vertical || (p.shuffle && p.book.is_none()) {
            return None;
        }
        match &p.book {
            Some((_, pages)) => Some((p.page, pages.len())),
            None => {
                let first = self.lib.entries.get(*p.items.get(p.pos)?)?;
                (first.kind == Kind::Image).then_some((p.pos, p.items.len()))
            }
        }
    }

    /// Page `k` of pane `ix`'s column.
    pub(crate) fn strip_entry(&self, ix: usize, k: usize) -> Option<Entry> {
        let p = &self.panes[ix];
        match &p.book {
            Some((b, pages)) => Some(crate::book::page_entry(&self.lib.entries[*b], pages.get(k)?)),
            None => self.lib.entries.get(*p.items.get(k)?).cloned(),
        }
    }

    /// The height of page `k` in a column `cw` wide: as decoded, or a
    /// common page's until it is.
    fn strip_height(&self, ix: usize, k: usize, cw: f32) -> f32 {
        let aspect = self
            .strip_entry(ix, k)
            .and_then(|e| self.panes[ix].aspects.get(&e.path).copied())
            .unwrap_or(crate::strip::GUESS);
        cw * aspect
    }

    /// The pages pane `ix` shows in its column: page, top, height, and the
    /// picture once decoded. The column is `cw` wide.
    pub(crate) fn strip_visible(&self, ix: usize) -> Option<(f32, Vec<StripShown>)> {
        let (top, n) = self.strip_at(ix)?;
        let p = &self.panes[ix];
        let (_, _, w, h) = p.rect;
        let cw = crate::strip::column(w, h);
        let pos = crate::strip::Pos { top, offset: p.scroll };
        let shown = crate::strip::visible(pos, n, h, |k| self.strip_height(ix, k, cw));
        let pages = shown
            .into_iter()
            .map(|(k, y, ph)| {
                let image = self
                    .strip_entry(ix, k)
                    .and_then(|e| p.strip.iter().find(|s| s.path == e.path))
                    .map(|s| s.image.clone());
                (y, ph, image)
            })
            .collect();
        Some((cw, pages))
    }

    /// Scrolls pane `ix`'s column by `dy` pixels (down when positive).
    /// Returns whether it stopped at the top or the end.
    pub(crate) fn scroll_strip(&mut self, ix: usize, dy: f32, cx: &mut Context<Self>) -> bool {
        let Some((top, n)) = self.strip_at(ix) else { return true };
        let (_, _, w, h) = self.panes[ix].rect;
        let cw = crate::strip::column(w, h);
        let pos = crate::strip::Pos { top, offset: self.panes[ix].scroll };
        let (pos, stopped) = crate::strip::scroll(pos, dy, n, h, |k| self.strip_height(ix, k, cw));
        let p = &mut self.panes[ix];
        if p.book.is_some() {
            p.page = pos.top;
        } else {
            p.pos = pos.top;
        }
        p.scroll = pos.offset;
        self.fill_strip(ix, cx);
        cx.notify();
        stopped
    }

    /// Keeps the pages on screen and around them decoded for pane `ix`'s
    /// column, lets go of the others, and puts the top page under the glass
    /// controls.
    pub(crate) fn fill_strip(&mut self, ix: usize, cx: &mut Context<Self>) {
        let Some((top, n)) = self.strip_at(ix) else { return };
        let (_, _, w, h) = self.panes[ix].rect;
        let cw = crate::strip::column(w, h);
        let pos = crate::strip::Pos { top, offset: self.panes[ix].scroll };
        let last = crate::strip::visible(pos, n, h, |k| self.strip_height(ix, k, cw)).last().map_or(top, |v| v.0);
        let lo = top.saturating_sub(crate::strip::BEHIND);
        let hi = (last + crate::strip::AHEAD).min(n.saturating_sub(1));
        // Nearest first: the top page, the rest on screen, then ahead.
        let want: Vec<Entry> = (top..=hi).chain(lo..top).filter_map(|k| self.strip_entry(ix, k)).collect();
        let px_scale = self.panes[ix].px_size.0 as f32 / w.max(1.0);
        let p = &mut self.panes[ix];
        let mut gone = Vec::new();
        p.strip.retain(|s| {
            let keep = want.iter().any(|e| e.path == s.path);
            if !keep {
                gone.push(s.image.clone());
            }
            keep
        });
        // The top page under the glass controls.
        if let Some(s) = want.first().and_then(|e| p.strip.iter().find(|s| s.path == e.path))
            && !p.frame.as_ref().is_some_and(|f| Arc::ptr_eq(f, &s.image))
        {
            p.glass_src = Some(s.glass.clone());
            p.full = s.full;
            if let Some(old) = p.frame.replace(s.image.clone()) {
                gone.push(old);
            }
        }
        let p = &self.panes[ix];
        gone.retain(|g| {
            !p.strip.iter().any(|s| Arc::ptr_eq(&s.image, g)) && !p.frame.as_ref().is_some_and(|f| Arc::ptr_eq(f, g))
        });
        drop_images(gone, cx);
        self.refresh_glass(ix, cx);
        for e in want {
            let p = &mut self.panes[ix];
            if e.kind != Kind::Image || p.strip.iter().any(|s| s.path == e.path) || p.strip_loading.contains(&e.path) {
                continue;
            }
            p.strip_loading.push(e.path.clone());
            // Wide enough for the column; a tall page needs a longer side.
            let aspect = p.aspects.get(&e.path).copied().unwrap_or(crate::strip::GUESS).max(1.0);
            let long = (cw * px_scale * aspect).clamp(256.0, 16384.0) as u32;
            cx.spawn(async move |this, cx| {
                let path = e.path.clone();
                let res = cx
                    .background_executor()
                    .spawn(async move {
                        let d = thumb::decode_image(&e, long)?;
                        let glass = glass::strip(&d.image);
                        let full = d.full;
                        let image = to_render_image(d.image).ok_or_else(|| anyhow::anyhow!("cannot draw the page"))?;
                        anyhow::Ok(crate::pane::StripPage { path: e.path, image, glass, full })
                    })
                    .await;
                let _ = this.update(cx, |this, cx| {
                    let Some(p) = this.panes.get_mut(ix) else { return };
                    p.strip_loading.retain(|q| *q != path);
                    let Ok(page) = res else { return };
                    p.aspects.insert(path, page.full.1 as f32 / page.full.0.max(1) as f32);
                    if this.strip_at(ix).is_none() {
                        cx.drop_image(page.image, None);
                        return;
                    }
                    this.panes[ix].strip.push(page);
                    this.fill_strip(ix, cx);
                    cx.notify();
                });
            })
            .detach();
        }
    }

    /// Lets go of the pages decoded for vertical scroll.
    pub(crate) fn clear_strip(&mut self, ix: usize, cx: &mut Context<Self>) {
        let p = &mut self.panes[ix];
        let frame = p.frame.clone();
        let gone: Vec<_> =
            p.strip.drain(..).map(|s| s.image).filter(|i| !frame.as_ref().is_some_and(|f| Arc::ptr_eq(f, i))).collect();
        drop_images(gone, cx);
    }
}