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
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
//! One cell of the split view: a folder (or the favorites) shown one item at
//! a time, as a slideshow or with video playback.

use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};

use gpui::RenderImage;

use crate::video::Video;

pub const DEFAULT_INTERVAL: Duration = Duration::from_secs(5);

/// Video speeds the speed keys step through.
const SPEEDS: [f64; 9] = [0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0];

/// How many decoded pictures a pane keeps ready besides the one on screen:
/// the next one, the previous one, and one spare.
const READY_MAX: usize = 3;

/// A decoded picture that can be shown at once.
pub struct Ready {
    /// Entry index.
    pub entry: usize,
    /// Long side it was decoded at.
    pub long: u32,
    pub image: Arc<RenderImage>,
    /// Its blurred strip for the glass controls.
    pub strip: crate::turbo::Bgra,
    /// The picture's full upright size.
    pub full: (u32, u32),
}

/// Where a pane takes its items from.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum PaneSource {
    Folder(PathBuf),
    Favorites,
}

pub struct Pane {
    pub source: Option<PaneSource>,
    /// Entry indices to play, in order.
    pub items: Vec<usize>,
    /// Position in `items` of what is shown now.
    pub pos: usize,
    pub slideshow: bool,
    pub shuffle: bool,
    /// Zoom and pan carry over to the next picture (Z), to compare the
    /// same spot across a series.
    pub lock_view: bool,
    /// How the picture fills the pane before zoom (the fit menu).
    pub fit: Fit,
    /// The user muted this pane's sound (every pane plays its own).
    pub muted: bool,
    pub interval: Duration,
    /// Paused by the user (slideshow timer and video both stop).
    pub paused: bool,
    /// What is on screen: a decoded image or the latest video frame.
    pub frame: Option<Arc<RenderImage>>,
    /// The part of the blurred strip under the glass controls, ready to draw.
    pub glass: Option<Arc<RenderImage>>,
    /// Latest blurred bottom strip of `frame` (small, CPU side).
    pub glass_src: Option<crate::turbo::Bgra>,
    pub video: Option<Video>,
    /// Playback position and duration in seconds, polled from mpv.
    pub time: (f64, f64),
    /// 0..=100.
    pub volume: f64,
    /// Video playback speed (1 = normal); kept for the next video too.
    pub speed: f64,
    /// Bumped whenever the shown item changes, so late results are ignored.
    pub generation: u64,
    pub shown_at: Instant,
    pub error: Option<String>,
    /// Size of the media area in physical pixels at the last layout.
    pub px_size: (u32, u32),
    /// Zoom over the fitted size (1 = fit) and pan in logical pixels.
    pub zoom: f32,
    pub pan: (f32, f32),
    /// Last pointer position while dragging to pan.
    pub drag: Option<(f32, f32)>,
    /// Pane rectangle in window coordinates at the last layout.
    pub rect: (f32, f32, f32, f32),
    /// Long side the current image was decoded at, to know when zooming in
    /// needs a sharper decode.
    pub decoded_long: u32,
    /// Entry of the picture in `frame` (None for video frames).
    pub shown: Option<usize>,
    /// Full upright size of the picture on screen, for actual size.
    pub full: (u32, u32),
    /// Pictures decoded ahead (and the last one shown), oldest first.
    pub ready: Vec<Ready>,
    /// With shuffle on, the position the next step forward goes to, picked
    /// early so that picture can be decoded ahead.
    upcoming: Option<usize>,
    /// Audio and subtitle tracks of the playing video.
    pub tracks: Vec<crate::mpv::Track>,
    /// Chapter start times of the playing video, in seconds.
    pub chapters: Vec<f64>,
    /// Where the pointer is over the seek bar (0 to 1), while it is.
    pub seek_hover: Option<f32>,
    /// The frame under the pointer on the seek bar: for which second.
    pub preview: Option<(u32, Arc<RenderImage>)>,
    /// A preview frame is being grabbed.
    pub preview_busy: bool,
    /// The picture shown before, fading out since then.
    pub fade_from: Option<(Arc<RenderImage>, Instant)>,
    /// The picture at full size, once zooming needs more than the whole
    /// view was decoded at: (entry, pixels).
    pub full_res: Option<(usize, Arc<crate::turbo::Bgra>)>,
    /// The entry whose full-size picture is being decoded.
    pub full_res_loading: Option<usize>,
    /// The visible part cut from `full_res` at screen resolution, and which
    /// part ([x0, y0, x1, y1] fractions of the picture).
    pub detail: Option<(Arc<RenderImage>, [f32; 4])>,
    /// A cut is being made; `detail_again` asks for another once it is done.
    pub detail_busy: bool,
    pub detail_again: bool,
    /// What the info panel shows for the item on screen, once read.
    pub info: Option<(usize, crate::exif::Info)>,
    /// Book view: pages one or two at a time (None: one item at a time, as
    /// usual). Always on for a book; for a folder, the user turns it on.
    pub layout: Option<crate::book::Layout>,
    /// The book on screen: its entry and its pages.
    pub book: Option<(usize, Arc<Vec<String>>)>,
    /// First page of the view on screen, in `book`; `usize::MAX` asks for
    /// the last view (stepping back into a book).
    pub page: usize,
    /// The item on screen came from the slideshow (it fades in); one the
    /// user stepped to shows at once. `auto_step_next` marks the coming step.
    pub auto_step: bool,
    pub auto_step_next: bool,
    /// Book views decoded ahead, at most two.
    pub book_ready: Vec<(BookKey, Ready)>,
}

/// A book view's pages, direction and decode size.
pub type BookKey = (Vec<PathBuf>, bool, u32);

impl Pane {
    pub fn empty() -> Self {
        Pane {
            source: None,
            items: Vec::new(),
            pos: 0,
            slideshow: false,
            shuffle: false,
            lock_view: false,
            fit: Fit::Contain,
            muted: false,
            interval: DEFAULT_INTERVAL,
            paused: false,
            frame: None,
            glass: None,
            glass_src: None,
            video: None,
            time: (0.0, 0.0),
            volume: 80.0,
            speed: 1.0,
            generation: 0,
            shown_at: Instant::now(),
            error: None,
            px_size: (1280, 720),
            zoom: 1.0,
            pan: (0.0, 0.0),
            drag: None,
            rect: (0.0, 0.0, 1.0, 1.0),
            decoded_long: 0,
            shown: None,
            full: (0, 0),
            ready: Vec::new(),
            upcoming: None,
            tracks: Vec::new(),
            chapters: Vec::new(),
            seek_hover: None,
            preview: None,
            preview_busy: false,
            fade_from: None,
            full_res: None,
            full_res_loading: None,
            detail: None,
            detail_busy: false,
            detail_again: false,
            info: None,
            layout: None,
            book: None,
            page: 0,
            auto_step: false,
            auto_step_next: false,
            book_ready: Vec::new(),
        }
    }

    pub fn current(&self) -> Option<usize> {
        self.items.get(self.pos).copied()
    }

    /// Whether the play button shows "pause": a video or slideshow running.
    pub fn playing(&self) -> bool {
        !self.paused && (self.video.is_some() || self.slideshow)
    }

    /// Moves `delta` items along, wrapping at either end. With shuffle on, a
    /// step forward jumps to any other item.
    pub fn step(&mut self, delta: isize, rng: &mut Rng) {
        let n = self.items.len();
        if n == 0 {
            return;
        }
        self.pos = if self.shuffle && delta > 0 && n > 1 {
            self.peek_next(rng).unwrap_or(0)
        } else {
            (self.pos as isize + delta).rem_euclid(n as isize) as usize
        };
        self.upcoming = None;
    }

    /// The position one step forward will go to.
    pub fn peek_next(&mut self, rng: &mut Rng) -> Option<usize> {
        let n = self.items.len();
        if n == 0 {
            return None;
        }
        if !self.shuffle || n == 1 {
            return Some((self.pos + 1) % n);
        }
        // Anything but the current item.
        let pos = self.pos;
        Some(*self.upcoming.get_or_insert_with(|| (pos + 1 + rng.below(n - 1)) % n))
    }

    /// Takes the ready picture of `entry` if it was decoded at `long` or
    /// sharper.
    pub fn take_ready(&mut self, entry: usize, long: u32) -> Option<Ready> {
        let k = self.ready.iter().position(|r| r.entry == entry && r.long >= long)?;
        Some(self.ready.remove(k))
    }

    /// Takes the book view decoded ahead for `key`, if there is one.
    pub fn take_book_ready(&mut self, key: &BookKey) -> Option<Ready> {
        let k = self.book_ready.iter().position(|(k2, _)| k2 == key)?;
        Some(self.book_ready.remove(k).1)
    }

    /// Keeps a book view decoded ahead; returns the images let go.
    pub fn keep_book_ready(&mut self, key: BookKey, r: Ready) -> Vec<Arc<RenderImage>> {
        let mut out = Vec::new();
        self.book_ready.retain(|(k, old)| {
            let same = *k == key;
            if same {
                out.push(old.image.clone());
            }
            !same
        });
        self.book_ready.push((key, r));
        while self.book_ready.len() > 2 {
            out.push(self.book_ready.remove(0).1.image);
        }
        out.retain(|i| !self.frame.as_ref().is_some_and(|f| Arc::ptr_eq(f, i)));
        out
    }

    pub fn is_ready(&self, entry: usize) -> bool {
        self.ready.iter().any(|r| r.entry == entry)
    }

    /// Keeps `r` ready, replacing an older copy of the same entry. Returns
    /// the images let go, for the renderer to free.
    pub fn keep(&mut self, r: Ready) -> Vec<Arc<RenderImage>> {
        let mut out: Vec<Arc<RenderImage>> = Vec::new();
        if let Some(k) = self.ready.iter().position(|o| o.entry == r.entry) {
            out.push(self.ready.remove(k).image);
        }
        self.ready.push(r);
        while self.ready.len() > READY_MAX {
            out.push(self.ready.remove(0).image);
        }
        // The picture on screen stays with the renderer.
        out.retain(|i| !self.frame.as_ref().is_some_and(|f| Arc::ptr_eq(f, i)));
        out
    }

    /// Lets go of every ready picture (the file list changed).
    pub fn clear_ready(&mut self) -> Vec<Arc<RenderImage>> {
        let frame = self.frame.clone();
        let ahead: Vec<Ready> = self.book_ready.drain(..).map(|(_, r)| r).collect();
        self.ready
            .drain(..)
            .chain(ahead)
            .map(|r| r.image)
            .filter(|i| !frame.as_ref().is_some_and(|f| Arc::ptr_eq(f, i)))
            .collect()
    }

    /// "0": back to fit, or from fit to actual size (one picture pixel per
    /// screen pixel). Returns the long side to decode at, as `zoom_by` does.
    pub fn toggle_actual_size(&mut self) -> Option<u32> {
        let (fw, fh) = self.full;
        let (_, _, w, h) = self.rect;
        if self.zoom != 1.0 || self.video.is_some() || fw == 0 || fh == 0 || w <= 0.0 {
            self.reset_view();
            return None;
        }
        let scale = self.px_size.0 as f32 / w;
        let base = self.base(fw as f32, fh as f32);
        // Already one to one: the other way is the whole picture.
        let target = if self.fit == Fit::Actual { fit_rect(fw as f32, fh as f32, w, h).2 } else { fw as f32 / scale };
        self.zoom_by(target / base.2, (0.0, 0.0))
    }

    /// The play button and Space: on a still image the first press starts
    /// the slideshow; after that, and for video, it pauses and resumes.
    pub fn play_pause(&mut self) {
        if self.video.is_none() && !self.slideshow {
            self.toggle_slideshow();
            self.paused = false;
        } else {
            self.toggle_pause();
        }
    }

    fn toggle_pause(&mut self) {
        self.paused = !self.paused;
        self.shown_at = Instant::now();
        if let Some(v) = &self.video {
            v.set_paused(self.paused);
        }
    }

    /// In a slideshow a video plays once and the next item follows; outside
    /// one it loops.
    pub fn toggle_slideshow(&mut self) {
        self.slideshow = !self.slideshow;
        self.shown_at = Instant::now();
        if let Some(v) = &self.video {
            v.set_looping(!self.slideshow);
        }
    }

    /// Steps the slideshow interval by one second, within 1 to 60.
    pub fn step_interval(&mut self, dir: i32) {
        let secs = self.interval.as_secs();
        let next = if dir > 0 { (secs + 1).min(60) } else { secs.saturating_sub(1).max(1) };
        self.interval = Duration::from_secs(next);
        self.shown_at = Instant::now();
    }

    /// Whether the slideshow should move on now.
    pub fn slide_due(&self) -> bool {
        self.slideshow
            && !self.paused
            && self.video.is_none()
            && self.current().is_some()
            && self.shown_at.elapsed() >= self.interval
    }

    pub fn set_volume(&mut self, vol: f64) {
        self.volume = vol.clamp(0.0, 100.0);
        if let Some(v) = &self.video {
            v.set_volume(self.volume);
        }
    }

    /// One step faster (`dir` > 0) or slower along `SPEEDS`; 0 goes back
    /// to normal speed.
    pub fn step_speed(&mut self, dir: i32) {
        let k = SPEEDS.iter().position(|&s| s >= self.speed).unwrap_or(SPEEDS.len() - 1);
        self.speed = match dir.signum() {
            0 => 1.0,
            1 => SPEEDS[(k + 1).min(SPEEDS.len() - 1)],
            _ => SPEEDS[k.saturating_sub(1)],
        };
        if let Some(v) = &self.video {
            v.set_speed(self.speed);
        }
    }

    /// "," and ".": one video frame back or forward, paused there.
    pub fn frame_step(&mut self, forward: bool) {
        if let Some(v) = &self.video {
            v.frame_step(forward);
            self.paused = true;
        }
    }

    pub fn reset_view(&mut self) {
        self.zoom = 1.0;
        self.pan = (0.0, 0.0);
    }

    /// Zooms by `factor` around `at` (relative to the pane's center), keeping
    /// that point of the image under the pointer. Returns the long side to
    /// decode the image at when the zoom outgrew the current decode.
    pub fn zoom_by(&mut self, factor: f32, at: (f32, f32)) -> Option<u32> {
        let old = self.zoom;
        // Below 1 the image shrinks inside the pane; above 1 it pans.
        let new = (old * factor).clamp(0.25, 16.0);
        if (new - old).abs() < f32::EPSILON {
            return None;
        }
        let (ux, uy) = ((at.0 - self.pan.0) / old, (at.1 - self.pan.1) / old);
        self.zoom = new;
        self.pan = if new <= 1.0 { (0.0, 0.0) } else { (at.0 - ux * new, at.1 - uy * new) };
        if (new - 1.0).abs() < 0.04 {
            // Snap back to exactly "fit" when passing through it.
            self.reset_view();
        }
        // The long side the picture is drawn at on screen, in pixels.
        let base = self.base(self.full.0 as f32, self.full.1 as f32);
        let base_px = if self.full.0 > 0 && self.rect.2 > 0.0 {
            base.2.max(base.3) * self.px_size.0 as f32 / self.rect.2
        } else {
            self.px_size.0.max(self.px_size.1) as f32
        };
        let need = (base_px * new).min(WHOLE_MAX as f32) as u32;
        if self.video.is_none() && need > self.decoded_long + self.decoded_long / 4 {
            self.decoded_long = need;
            return Some(need);
        }
        None
    }
}

/// Columns and rows of the split view: 1, 2 stacked or side by side, or 4.
pub fn layout(split: usize, side_by_side: bool) -> (usize, usize) {
    match (split, side_by_side) {
        (1, _) => (1, 1),
        (2, true) => (2, 1),
        (2, false) => (1, 2),
        _ => (2, 2),
    }
}

/// Where media of `iw`x`ih` lands when fitted into `w`x`h`: left, top,
/// width and height.
/// How a picture fills its pane before any zoom: the base that the zoom
/// multiplies (see `base_rect`). Chosen per pane from the player bar.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Fit {
    /// The whole picture, as large as fits.
    #[default]
    Contain,
    /// The pane filled, the overflow cut off.
    Cover,
    /// The pane filled, the picture's proportions ignored.
    Stretch,
    /// One picture pixel per screen pixel.
    Actual,
}

impl Fit {
    pub const ALL: [Fit; 4] = [Fit::Contain, Fit::Cover, Fit::Stretch, Fit::Actual];

    /// The word in the session file and the message key's suffix.
    pub fn key(self) -> &'static str {
        match self {
            Fit::Contain => "contain",
            Fit::Cover => "cover",
            Fit::Stretch => "stretch",
            Fit::Actual => "actual",
        }
    }

    pub fn from_key(k: &str) -> Option<Fit> {
        Fit::ALL.into_iter().find(|f| f.key() == k)
    }
}

/// Where an `iw`x`ih` picture sits in a `w`x`h` pane under `fit`, before
/// zoom. `full` is the picture's own size and `px_scale` the screen's
/// pixels per layout pixel, for actual size.
fn base_rect(fit: Fit, iw: f32, ih: f32, w: f32, h: f32, full: (u32, u32), px_scale: f32) -> (f32, f32, f32, f32) {
    let (dw, dh) = match fit {
        Fit::Contain => return fit_rect(iw, ih, w, h),
        Fit::Cover => {
            let s = (w / iw.max(1.0)).max(h / ih.max(1.0));
            (iw * s, ih * s)
        }
        Fit::Stretch => (w, h),
        Fit::Actual if full.0 > 0 && px_scale > 0.0 => (full.0 as f32 / px_scale, full.1 as f32 / px_scale),
        Fit::Actual => return fit_rect(iw, ih, w, h),
    };
    ((w - dw) / 2.0, (h - dh) / 2.0, dw, dh)
}

pub fn fit_rect(iw: f32, ih: f32, w: f32, h: f32) -> (f32, f32, f32, f32) {
    let s = (w / iw.max(1.0)).min(h / ih.max(1.0));
    let (dw, dh) = (iw * s, ih * s);
    ((w - dw) / 2.0, (h - dh) / 2.0, dw, dh)
}

/// The fitted rectangle `fit` after a zoom and pan in a `w`x`h` pane.
pub fn zoomed(fit: (f32, f32, f32, f32), w: f32, h: f32, zoom: f32, pan: (f32, f32)) -> (f32, f32, f32, f32) {
    let (zw, zh) = (fit.2 * zoom, fit.3 * zoom);
    (w / 2.0 - zw / 2.0 + pan.0, h / 2.0 - zh / 2.0 + pan.1, zw, zh)
}

/// The part of a `full`-sized picture placed at `place` (x, y, width,
/// height in logical pixels) that a `w`x`h` pane shows, as fractions of
/// the picture [x0, y0, x1, y1], and the size to cut it at: its source
/// pixels, but no more than the screen pixels it covers (`px_scale` device
/// pixels per logical pixel). None when nothing of it is on screen.
/// Screen pixels per picture pixel from which a picture is enlarged
/// without smoothing.
const NEAREST_FROM: f32 = 2.0;

pub fn visible_part(
    full: (u32, u32),
    place: (f32, f32, f32, f32),
    w: f32,
    h: f32,
    px_scale: f32,
    upscale: bool,
) -> Option<([f32; 4], (u32, u32))> {
    let (ox, oy, dw, dh) = place;
    if dw <= 0.0 || dh <= 0.0 || full.0 == 0 || full.1 == 0 {
        return None;
    }
    let frac = |v: f32, len: f32| (v / len).clamp(0.0, 1.0);
    let n = [frac(-ox, dw), frac(-oy, dh), frac(w - ox, dw), frac(h - oy, dh)];
    if n[2] <= n[0] || n[3] <= n[1] {
        return None;
    }
    let size = |a: f32, b: f32, src: u32, shown: f32| {
        let source = (b - a) * src as f32;
        let screen = (b - a) * shown * px_scale;
        // Enlarged pictures are cut at screen size (scaled up without
        // smoothing); others at no more than their own pixels.
        if upscale { screen } else { source.min(screen) }.round().max(1.0) as u32
    };
    Some((n, (size(n[0], n[2], full.0, dw), size(n[1], n[3], full.1, dh))))
}

impl Pane {
    /// Whether the view shows the picture larger than `frame` holds it, and
    /// the full-size picture has more to give: then cut-outs are drawn.
    pub fn wants_detail(&self) -> bool {
        let Some(frame) = &self.frame else { return false };
        if self.video.is_some() || self.shown.is_none() || self.rect.2 <= 0.0 {
            return false;
        }
        let sz = frame.size(0);
        let have = i32::from(sz.width).max(i32::from(sz.height)).max(1) as f32;
        let full = self.full.0.max(self.full.1) as f32;
        let (_, _, w, _) = self.rect;
        let fit = self.base(self.full.0 as f32, self.full.1 as f32);
        let shown = fit.2.max(fit.3) * self.zoom * (self.px_size.0 as f32 / w);
        (full > have * 1.05 && shown > have * 1.05) || self.enlarged()
    }

    /// Whether a still picture, zoomed in by the user, is shown at
    /// `NEAREST_FROM` screen pixels per picture pixel or more: from there it
    /// is scaled up without smoothing, so pixel art and fine detail stay
    /// crisp instead of going soft. Fitted pictures stay smooth.
    pub fn enlarged(&self) -> bool {
        let Some(frame) = &self.frame else { return false };
        if self.zoom <= 1.0 || self.video.is_some() || frame.frame_count() > 1 || self.rect.2 <= 0.0 || self.full.0 == 0
        {
            return false;
        }
        let (_, _, w, _) = self.rect;
        let fit = self.base(self.full.0 as f32, self.full.1 as f32);
        let shown = fit.2.max(fit.3) * self.zoom * (self.px_size.0 as f32 / w);
        shown / self.full.0.max(self.full.1) as f32 >= NEAREST_FROM
    }

    /// Where the picture sits in the pane now (x, y, width, height).
    pub fn placement(&self) -> (f32, f32, f32, f32) {
        let (_, _, w, h) = self.rect;
        zoomed(self.base(self.full.0 as f32, self.full.1 as f32), w, h, self.zoom, self.pan)
    }

    /// Where an `iw`x`ih` picture sits in this pane under its fit, before
    /// zoom.
    pub fn base(&self, iw: f32, ih: f32) -> (f32, f32, f32, f32) {
        let (_, _, w, h) = self.rect;
        base_rect(self.fit, iw, ih, w, h, self.full, self.px_size.0 as f32 / w.max(1.0))
    }
}

/// The long side to decode a picture of `full` size at for cut-outs: all
/// of it, unless it has more than 250 megapixels (a gigabyte in memory);
/// then as large as fits in that.
pub fn full_res_long(full: (u32, u32)) -> u32 {
    const MAX_PIXELS: f64 = 250e6;
    let (w, h) = (full.0.max(1) as f64, full.1.max(1) as f64);
    let long = w.max(h);
    if w * h <= MAX_PIXELS {
        return long as u32;
    }
    (long * (MAX_PIXELS / (w * h)).sqrt()) as u32
}

/// Above this long side a picture is decoded for the whole view only up to
/// it; zooming further shows cut-outs of the full-size picture instead
/// (GPUs refuse textures much larger, and memory would balloon).
pub const WHOLE_MAX: u32 = 8192;

/// Tiny xorshift so shuffle needs no extra dependency.
pub struct Rng(u64);

impl Rng {
    pub fn seeded() -> Self {
        let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(1, |d| d.as_nanos() as u64);
        Rng(t | 1)
    }

    pub fn below(&mut self, n: usize) -> usize {
        let mut x = self.0;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.0 = x;
        (x % n.max(1) as u64) as usize
    }
}

/// "1:05" or "1:02:05".
pub fn clock(secs: f64) -> String {
    let s = secs.max(0.0) as u64;
    let (h, m, s) = (s / 3600, (s / 60) % 60, s % 60);
    if h > 0 { format!("{h}:{m:02}:{s:02}") } else { format!("{m}:{s:02}") }
}

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

    fn pane(n: usize) -> Pane {
        let mut p = Pane::empty();
        p.items = (0..n).collect();
        p
    }

    #[test]
    fn steps_wrap_around_and_shuffle_never_repeats() {
        let mut rng = Rng(7);
        let mut p = pane(3);
        p.step(-1, &mut rng);
        assert_eq!(p.pos, 2);
        p.step(1, &mut rng);
        assert_eq!(p.pos, 0);
        p.step(4, &mut rng);
        assert_eq!(p.pos, 1);
        p.shuffle = true;
        for _ in 0..50 {
            let before = p.pos;
            p.step(1, &mut rng);
            assert_ne!(p.pos, before);
            assert!(p.pos < 3);
        }
        // Back still goes back, and an empty pane stays put.
        p.pos = 1;
        p.step(-1, &mut rng);
        assert_eq!(p.pos, 0);
        let mut empty = pane(0);
        empty.step(1, &mut rng);
        assert_eq!(empty.pos, 0);
    }

    #[test]
    fn play_starts_a_slideshow_then_pauses_it() {
        let mut p = pane(2);
        assert!(!p.playing());
        p.play_pause();
        assert!(p.slideshow && p.playing());
        p.play_pause();
        assert!(p.slideshow && p.paused && !p.playing());
        p.play_pause();
        assert!(p.playing());
    }

    #[test]
    fn slides_advance_only_when_running_and_due() {
        let mut p = pane(2);
        p.interval = Duration::ZERO;
        assert!(!p.slide_due());
        p.play_pause();
        assert!(p.slide_due());
        p.toggle_pause();
        assert!(!p.slide_due());
        p.toggle_pause();
        p.interval = Duration::from_secs(60);
        assert!(!p.slide_due());
    }

    #[test]
    fn slideshow_interval_moves_one_second_within_1_to_60() {
        let mut p = pane(1);
        let mut at = |secs: u64, dir: i32| {
            p.interval = Duration::from_secs(secs);
            p.step_interval(dir);
            p.interval.as_secs()
        };
        assert_eq!(at(5, 1), 6);
        assert_eq!(at(5, -1), 4);
        assert_eq!(at(1, -1), 1);
        assert_eq!(at(60, 1), 60);
        assert_eq!(at(0, -1), 1);
    }

    #[test]
    fn speed_steps_along_the_list_and_resets() {
        let mut p = pane(1);
        p.step_speed(1);
        assert_eq!(p.speed, 1.25);
        for _ in 0..20 {
            p.step_speed(1);
        }
        assert_eq!(p.speed, 4.0, "stops at the fastest");
        p.step_speed(0);
        assert_eq!(p.speed, 1.0);
        for _ in 0..20 {
            p.step_speed(-1);
        }
        assert_eq!(p.speed, 0.25, "stops at the slowest");
        // Without a video, frame steps change nothing.
        p.frame_step(true);
        assert!(!p.paused);
    }

    #[test]
    fn volume_stays_between_0_and_100() {
        let mut p = pane(1);
        p.set_volume(140.0);
        assert_eq!(p.volume, 100.0);
        p.set_volume(-5.0);
        assert_eq!(p.volume, 0.0);
    }

    #[test]
    fn zoom_keeps_the_point_under_the_pointer() {
        let mut p = pane(1);
        p.px_size = (1000, 500);
        p.decoded_long = 1000;
        // Zoom 2x around a point 100 px right of center.
        assert_eq!(p.zoom_by(2.0, (100.0, 0.0)), Some(2000), "needs a sharper decode");
        assert_eq!(p.zoom, 2.0);
        assert_eq!(p.pan, (-100.0, 0.0));
        // The image point under the pointer is the same before and after.
        let under = |p: &Pane| ((100.0 - p.pan.0) / p.zoom, (0.0 - p.pan.1) / p.zoom);
        let before = under(&p);
        assert_eq!(p.zoom_by(1.5, (100.0, 0.0)), Some(3000));
        assert_eq!(under(&p), before);
        // Small steps within the decoded size need no new decode.
        assert_eq!(p.zoom_by(1.1, (0.0, 0.0)), None);
    }

    #[test]
    fn zoom_snaps_to_fit_and_stays_in_range() {
        let mut p = pane(1);
        p.decoded_long = u32::MAX / 2;
        p.zoom_by(2.0, (50.0, 50.0));
        p.zoom_by(1.0 / 1.99, (50.0, 50.0));
        assert_eq!((p.zoom, p.pan), (1.0, (0.0, 0.0)));
        for _ in 0..40 {
            p.zoom_by(0.5, (0.0, 0.0));
        }
        assert_eq!(p.zoom, 0.25);
        assert_eq!(p.pan, (0.0, 0.0), "no panning below fit");
        assert_eq!(p.zoom_by(0.5, (0.0, 0.0)), None, "already at the minimum");
        for _ in 0..40 {
            p.zoom_by(2.0, (0.0, 0.0));
        }
        assert_eq!(p.zoom, 16.0);
        p.reset_view();
        assert_eq!((p.zoom, p.pan), (1.0, (0.0, 0.0)));
    }

    #[test]
    fn shuffle_decides_the_next_item_early() {
        let mut rng = Rng(11);
        let mut p = pane(10);
        assert_eq!(p.peek_next(&mut rng), Some(1), "in order without shuffle");
        p.shuffle = true;
        let next = p.peek_next(&mut rng).unwrap();
        assert_eq!(p.peek_next(&mut rng), Some(next), "asking again gives the same answer");
        p.step(1, &mut rng);
        assert_eq!(p.pos, next);
        assert_eq!(pane(0).peek_next(&mut rng), None);
        let mut one = pane(1);
        one.shuffle = true;
        assert_eq!(one.peek_next(&mut rng), Some(0));
    }

    #[test]
    fn actual_size_toggles_with_fit() {
        let mut p = pane(1);
        // A 4000x2000 picture in an 800x400 pane on a 2x screen.
        p.rect = (0.0, 0.0, 800.0, 400.0);
        p.px_size = (1600, 800);
        p.full = (4000, 2000);
        p.decoded_long = 1600;
        assert_eq!(p.toggle_actual_size(), Some(4000));
        assert_eq!(p.zoom, 2.5, "800 logical px wide at 2x is 1600 px; the picture has 4000");
        assert_eq!(p.toggle_actual_size(), None);
        assert_eq!(p.zoom, 1.0);
        // Without a known size, 0 only fits.
        p.full = (0, 0);
        p.toggle_actual_size();
        assert_eq!(p.zoom, 1.0);
    }

    #[test]
    fn split_layouts() {
        assert_eq!(layout(1, true), (1, 1));
        assert_eq!(layout(2, false), (1, 2));
        assert_eq!(layout(2, true), (2, 1));
        assert_eq!(layout(4, false), (2, 2));
    }

    #[test]
    fn media_is_fitted_and_centered() {
        // 2:1 media in a square: full width, centered vertically.
        assert_eq!(fit_rect(200.0, 100.0, 100.0, 100.0), (0.0, 25.0, 100.0, 50.0));
        // 200x100 in a 100x100 pane, 2 screen pixels per layout pixel.
        let b = |f| base_rect(f, 200.0, 100.0, 100.0, 100.0, (200, 100), 2.0);
        assert_eq!(b(Fit::Contain), (0.0, 25.0, 100.0, 50.0), "whole picture");
        assert_eq!(b(Fit::Cover), (-50.0, 0.0, 200.0, 100.0), "pane filled, sides cut");
        assert_eq!(b(Fit::Stretch), (0.0, 0.0, 100.0, 100.0), "pane filled, proportions ignored");
        assert_eq!(b(Fit::Actual), (0.0, 25.0, 100.0, 50.0), "200 picture pixels on 200 screen pixels");
        assert_eq!(Fit::from_key("cover"), Some(Fit::Cover));
        assert_eq!(Fit::from_key("nope"), None);
        // Zoom 2 around the center, then pan.
        let fit = fit_rect(200.0, 100.0, 100.0, 100.0);
        assert_eq!(zoomed(fit, 100.0, 100.0, 2.0, (10.0, 0.0)), (-40.0, 0.0, 200.0, 100.0));
    }

    #[test]
    fn full_size_is_capped_at_a_gigabyte() {
        assert_eq!(full_res_long((12000, 8000)), 12000);
        // 40000x20000 is 800 megapixels: decoded at 250.
        let long = full_res_long((40000, 20000));
        assert!((22360..=22361).contains(&long), "{long}");
    }

    #[test]
    fn the_visible_part_is_cut_at_screen_or_source_size() {
        // A 12000x8000 picture fitted into 1200x800 and zoomed 4x about the
        // center: the middle quarter shows, 3000x2000 source pixels on
        // 1200x800 logical (2400x1600 device) pixels.
        let place = zoomed(fit_rect(12000.0, 8000.0, 1200.0, 800.0), 1200.0, 800.0, 4.0, (0.0, 0.0));
        let (n, size) = visible_part((12000, 8000), place, 1200.0, 800.0, 2.0, false).unwrap();
        assert_eq!(n, [0.375, 0.375, 0.625, 0.625]);
        assert_eq!(size, (2400, 1600), "no more than the screen's pixels");
        // At 40x the source pixels are fewer than the screen's: cut at those.
        let place = zoomed(fit_rect(12000.0, 8000.0, 1200.0, 800.0), 1200.0, 800.0, 40.0, (0.0, 0.0));
        let (_, size) = visible_part((12000, 8000), place, 1200.0, 800.0, 2.0, false).unwrap();
        assert_eq!(size, (300, 200));
        // Panned to the left edge, and off screen entirely.
        let place = zoomed(fit_rect(12000.0, 8000.0, 1200.0, 800.0), 1200.0, 800.0, 4.0, (1800.0, 0.0));
        let (n, _) = visible_part((12000, 8000), place, 1200.0, 800.0, 1.0, false).unwrap();
        assert_eq!(n[0], 0.0);
        assert!(visible_part((12000, 8000), (5000.0, 0.0, 100.0, 100.0), 1200.0, 800.0, 1.0, false).is_none());
        // Enlarged: cut at screen size, past the picture's own pixels.
        let place = (0.0, 0.0, 1200.0, 800.0);
        assert_eq!(visible_part((120, 80), place, 1200.0, 800.0, 2.0, false).unwrap().1, (120, 80));
        assert_eq!(visible_part((120, 80), place, 1200.0, 800.0, 2.0, true).unwrap().1, (2400, 1600));
    }

    #[test]
    fn clock_formats() {
        assert_eq!(clock(0.0), "0:00");
        assert_eq!(clock(65.4), "1:05");
        assert_eq!(clock(3725.0), "1:02:05");
        assert_eq!(clock(-3.0), "0:00");
    }
}