rosier 0.2.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
//! 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);

/// 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,
    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,
    /// 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>,
}

impl Pane {
    pub fn empty() -> Self {
        Pane {
            source: None,
            items: Vec::new(),
            pos: 0,
            slideshow: false,
            shuffle: false,
            interval: DEFAULT_INTERVAL,
            paused: false,
            frame: None,
            glass: None,
            glass_src: None,
            video: None,
            time: (0.0, 0.0),
            volume: 80.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,
        }
    }

    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))
    }

    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();
        self.ready.drain(..).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 fit = fit_rect(fw as f32, fh as f32, w, h);
        let scale = self.px_size.0 as f32 / w;
        self.zoom_by(fw as f32 / (fit.2 * scale), (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();
        }
    }

    pub 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);
        }
    }

    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();
        }
        let need = ((self.px_size.0.max(self.px_size.1) as f32) * new).min(8192.0) 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.
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)
}

/// 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 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));
        // 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 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");
    }
}