rosier 0.3.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
//! Drives the real view in gpui's test harness: a library of generated
//! pictures on disk, keys and clicks in, state and drawn frames checked.

use std::path::{Path, PathBuf};
use std::time::Duration;

use gpui::{Entity, Modifiers, TestAppContext, VisualTestContext, point, px};

use crate::app::{Rosier, Screen};
use crate::library::{KindFilter, Scope, SortBy};
use crate::mpv::TrackKind;

/// A temporary folder removed when dropped.
struct TempDir(PathBuf);

impl TempDir {
    fn new(tag: &str) -> Self {
        use std::sync::atomic::{AtomicU64, Ordering};
        static NEXT: AtomicU64 = AtomicU64::new(0);
        let p = std::env::temp_dir().join(format!(
            "rosier-ui-{tag}-{}-{}",
            std::process::id(),
            NEXT.fetch_add(1, Ordering::Relaxed)
        ));
        let _ = std::fs::remove_dir_all(&p);
        std::fs::create_dir_all(&p).unwrap();
        TempDir(p)
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

/// Writes a small gradient picture; the extension picks the format.
fn picture(path: &Path, w: u32, h: u32, seed: u8) {
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    let img = image::RgbImage::from_fn(w, h, |x, y| {
        image::Rgb([(x * 255 / w) as u8 ^ seed, (y * 255 / h) as u8, seed.wrapping_mul(37)])
    });
    img.save(path).unwrap();
}

/// A library folder: `trip/` with JPEGs, `trip/day2/` with one, `pngs/`
/// with PNGs, and an unreadable file at the top.
fn library(root: &Path) -> PathBuf {
    let src = root.join("Pictures");
    for i in 0..6u8 {
        picture(&src.join(format!("trip/img_{i}.jpg")), 64 + 8 * i as u32, 48, i * 40);
    }
    picture(&src.join("trip/day2/late.jpg"), 40, 80, 9);
    for i in 0..3u8 {
        picture(&src.join(format!("pngs/shot_{i}.png")), 32, 32, i * 70);
    }
    std::fs::write(src.join("broken.jpg"), b"not a picture").unwrap();
    src
}

struct Harness {
    view: Entity<Rosier>,
    cx: VisualTestContext,
    _dir: TempDir,
}

impl Harness {
    /// Opens rosier on a fresh database. With `folder`, the library starts
    /// with it; without, onboarding shows.
    fn open(cx: &mut TestAppContext, folder: bool) -> Self {
        let dir = TempDir::new("app");
        let initial = if folder { vec![library(&dir.0)] } else { Vec::new() };
        Self::open_in(cx, dir, initial)
    }

    /// Quits and starts rosier again on the same database.
    fn restart(self, cx: &mut TestAppContext) -> Self {
        let Harness { cx: mut old, _dir: dir, .. } = self;
        old.update(|window, _| window.remove_window());
        Self::open_in(cx, dir, Vec::new())
    }

    fn open_in(cx: &mut TestAppContext, dir: TempDir, initial: Vec<PathBuf>) -> Self {
        let db_path = dir.0.join("data/rosier.db");
        let window = cx.add_window(|_, cx| {
            let mut r = Rosier::new(db_path, initial, cx);
            r.register_app = false;
            r
        });
        let view = window.root(cx).unwrap();
        let mut vcx = VisualTestContext::from_window(window.into(), cx);
        vcx.update(|window, cx| window.focus(&view.read(cx).focus));
        let mut h = Harness { view, cx: vcx, _dir: dir };
        h.settle();
        h
    }

    /// Runs pending work, waits for thumbnail and decode threads, and draws.
    fn settle(&mut self) {
        for _ in 0..50 {
            self.cx.run_until_parked();
            self.cx.update(|window, _| window.refresh());
            self.cx.run_until_parked();
            let busy = self.read(|r| r.indexing || r.thumbs.pending > 0);
            if !busy {
                break;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
    }

    fn read<T>(&mut self, f: impl FnOnce(&Rosier) -> T) -> T {
        self.cx.update(|_, cx| f(self.view.read(cx)))
    }

    fn update<T>(&mut self, f: impl FnOnce(&mut Rosier, &mut gpui::Context<Rosier>) -> T) -> T {
        let out = self.cx.update(|_, cx| self.view.update(cx, f));
        self.settle();
        out
    }

    fn keys(&mut self, keys: &str) {
        self.cx.simulate_keystrokes(keys);
        self.settle();
    }

    fn name(&mut self, i: Option<usize>) -> String {
        self.read(|r| {
            i.and_then(|i| r.lib.path(i)).and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned())
        })
        .unwrap_or_default()
    }

    fn selected_name(&mut self) -> String {
        let i = self.read(|r| r.selected);
        self.name(i)
    }

    /// Waits until pane `ix` shows a decoded frame (or gives up).
    fn wait_frame(&mut self, ix: usize) -> bool {
        for _ in 0..100 {
            self.settle();
            if self.read(|r| r.panes[ix].frame.is_some()) {
                return true;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        false
    }
}

#[gpui::test]
fn onboarding_adds_the_picked_folders(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, false);
    assert_eq!(h.read(|r| r.screen), Screen::Onboarding);
    let src = library(&h._dir.0);
    h.update(|r, cx| r.folders_picked(vec![src.clone(), src.clone()], cx));
    assert_eq!(h.read(|r| r.pending_sources.len()), 1, "the same folder is listed once");
    // Keys do nothing on the first screen.
    h.keys("right 2");
    assert_eq!(h.read(|r| r.screen), Screen::Onboarding);
    h.update(|r, cx| r.finish_folder_step(cx));
    assert_eq!(h.read(|r| r.screen), Screen::Browse);
    assert_eq!(h.read(|r| r.lib.entries.len()), 11);
}

#[gpui::test]
fn onboarding_takes_dropped_folders_and_files(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, false);
    let src = library(&h._dir.0);
    let other = h._dir.0.join("Other/pic.png");
    picture(&other, 16, 16, 2);
    // A folder is listed as is; a file brings its folder; the rest is ignored.
    let dropped = [src.clone(), other.clone(), h._dir.0.join("missing")];
    h.update(|r, cx| r.dropped(&dropped, None, cx));
    assert_eq!(h.read(|r| r.screen), Screen::Onboarding, "nothing opens before Open is pressed");
    assert_eq!(h.read(|r| r.pending_sources.clone()), vec![src.clone(), h._dir.0.join("Other")]);
    h.update(|r, cx| r.dropped(std::slice::from_ref(&src), None, cx));
    assert_eq!(h.read(|r| r.pending_sources.len()), 2, "dropped again: listed once");
    h.update(|r, cx| r.finish_folder_step(cx));
    assert_eq!(h.read(|r| r.lib.entries.len()), 12);
}

#[gpui::test]
fn the_grid_moves_with_the_keyboard(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    assert_eq!(h.read(|r| (r.screen, r.shown.len())), (Screen::Browse, 11));
    assert_eq!(h.selected_name(), "broken.jpg");
    h.keys("right");
    assert_eq!(h.selected_name(), "shot_0.png");
    h.keys("end");
    assert_eq!(h.selected_name(), "img_5.jpg");
    h.keys("home");
    assert_eq!(h.selected_name(), "broken.jpg");
    h.keys("left");
    assert_eq!(h.selected_name(), "broken.jpg", "stops at the first tile");
    let cols = h.read(|r| r.cols);
    h.keys("down");
    let below = h.read(|r| r.rows.order.get(cols.min(10)).copied());
    assert_eq!(h.read(|r| r.selected), below);
    h.keys("up pagedown");
    assert_eq!(
        h.read(|r| r.rows.row_of(r.selected.unwrap())),
        h.read(|r| Some(r.rows.rows.len() - 1)),
        "PageDown stops on the last row"
    );
    h.keys("pageup j k l h");
    assert_eq!(h.selected_name(), "broken.jpg");
    // Thumbnails were made for every readable tile on screen.
    let (made, failed) = h.read(|r| {
        let made = (0..11).filter(|&i| r.thumbs.get(i).is_some()).count();
        let failed = (0..11).filter(|&i| r.thumbs.failed(i)).count();
        (made, failed)
    });
    assert_eq!((made, failed), (10, 1));
}

#[gpui::test]
fn filters_and_sort_change_what_the_grid_shows(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    let trip = h.read(|r| r.lib.sources[0].path.join("trip"));
    h.update(|r, cx| r.set_scope(Scope::Folder(trip.clone()), cx));
    assert_eq!(h.read(|r| r.shown.len()), 7);
    h.update(|r, _| {
        r.kind = KindFilter::Videos;
        r.recompute_shown();
    });
    assert_eq!(h.read(|r| r.shown.len()), 0, "no videos here");
    h.update(|r, cx| {
        r.kind = KindFilter::Photos;
        r.sort = SortBy::Size;
        r.recompute_shown();
        r.set_scope(Scope::All, cx);
    });
    assert_eq!(h.read(|r| r.shown.len()), 11);
    h.update(|r, _| {
        r.sort = SortBy::Date;
        r.recompute_shown();
    });
    // The sidebar lists the source's top folders with their counts.
    let folders = h.read(|r| r.lib.side_folders[0].iter().map(|f| (f.name.clone(), f.count)).collect::<Vec<_>>());
    assert_eq!(folders, vec![("pngs".to_string(), 3), ("trip".to_string(), 7)]);
}

#[gpui::test]
fn favorites_toggle_from_the_grid_and_the_player(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    h.keys("right f");
    assert!(h.read(|r| r.lib.is_favorite(r.selected.unwrap())));
    h.update(|r, cx| r.set_scope(Scope::Favorites, cx));
    assert_eq!(h.read(|r| r.shown.len()), 1);
    // Open it: the pane plays the favorites.
    h.keys("enter");
    assert_eq!(h.read(|r| r.screen), Screen::Split);
    assert_eq!(h.read(|r| r.panes[0].source.clone()), Some(crate::pane::PaneSource::Favorites));
    assert!(h.wait_frame(0));
    // Unfavorite from the player: the favorites list empties.
    h.keys("f");
    assert_eq!(h.read(|r| (r.shown.len(), r.panes[0].items.len())), (0, 0));
}

#[gpui::test]
fn opening_a_file_plays_its_folder(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    let first = h.read(|r| r.lib.find(&r.lib.sources[0].path.join("trip/img_2.jpg")).unwrap());
    h.update(|r, _| r.select(first));
    h.keys("enter");
    assert_eq!(h.read(|r| r.screen), Screen::Split);
    assert!(h.wait_frame(0));
    assert_eq!(h.read(|r| (r.panes[0].pos, r.panes[0].items.len())), (2, 6), "only trip/, not trip/day2/");
    h.keys("right");
    assert!(h.wait_frame(0));
    let cur = h.read(|r| r.panes[0].current());
    assert_eq!(h.name(cur), "img_3.jpg");
    h.keys("left left");
    let cur = h.read(|r| r.panes[0].current());
    assert_eq!(h.name(cur), "img_1.jpg");
    // Slideshow controls.
    h.keys("space");
    assert!(h.read(|r| r.panes[0].slideshow && r.panes[0].playing()));
    h.keys("= = -");
    assert_eq!(h.read(|r| r.panes[0].interval.as_secs()), 6);
    h.keys("space");
    assert!(h.read(|r| !r.panes[0].playing()));
    h.keys("s r");
    assert!(h.read(|r| !r.panes[0].slideshow && r.panes[0].shuffle));
    // Volume keys move in steps of 5.
    h.keys("up up down");
    assert_eq!(h.read(|r| r.panes[0].volume), 85.0);
    // A due slide moves on with the clock.
    h.update(|r, cx| {
        let p = &mut r.panes[0];
        p.shuffle = false;
        p.play_pause();
        p.interval = Duration::ZERO;
        r.tick(cx);
    });
    assert!(h.wait_frame(0));
    // Zoom in and back to fit.
    h.update(|r, cx| r.zoom_pane(0, 2.0, (10.0, 10.0), cx));
    assert_eq!(h.read(|r| r.panes[0].zoom), 2.0);
    h.keys("0");
    assert_eq!(h.read(|r| r.panes[0].zoom), 1.0);
    h.keys("escape");
    assert_eq!(h.read(|r| r.screen), Screen::Browse);
    h.keys("escape");
    assert_eq!(h.read(|r| r.screen), Screen::Split, "Esc goes back to what is playing");
}

#[gpui::test]
fn split_layouts_and_picking_panes(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    h.keys("enter");
    h.keys("4");
    assert_eq!(h.read(|r| (r.split, r.panes.len(), r.focused)), (4, 4, 1), "focus moves to the first empty pane");
    h.keys("escape");
    assert_eq!(h.read(|r| r.picking_for), Some(1));
    h.keys("right enter");
    assert_eq!(h.read(|r| (r.screen, r.panes[1].source.is_some())), (Screen::Split, true));
    h.keys("tab");
    assert_eq!(h.read(|r| r.focused), 2);
    h.update(|r, cx| r.go_browse(Some(3), cx));
    h.keys("escape");
    assert_eq!(h.read(|r| (r.screen, r.picking_for)), (Screen::Split, None));
    h.keys("2");
    assert_eq!(h.read(|r| (r.split, r.split_side)), (2, false));
    h.keys("2");
    assert!(h.read(|r| r.split_side), "2 again turns stacked into side by side");
    h.keys("1");
    assert_eq!(h.read(|r| (r.split, r.panes.len(), r.focused)), (1, 1, 0));
}

#[gpui::test]
fn help_sidebar_and_language(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    h.keys("?");
    assert!(h.read(|r| r.show_help));
    h.keys("escape");
    assert!(h.read(|r| !r.show_help));
    h.keys("ctrl-b");
    assert!(h.read(|r| !r.sidebar_visible));
    h.keys("ctrl-b");
    h.update(|r, _| r.lang_menu = true);
    let ja = crate::i18n::LANGS.iter().position(|l| l.0 == "ja").unwrap();
    h.update(|r, cx| r.set_language(ja, cx));
    let saved = h._dir.0.join("data/lang");
    assert_eq!(std::fs::read_to_string(saved).unwrap(), "ja");
    assert!(h.read(|r| !r.lang_menu));
    h.update(|r, cx| r.set_language(0, cx));
}

#[gpui::test]
fn hiding_and_removing_folders(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    let pngs = h.read(|r| r.lib.sources[0].path.join("pngs"));
    h.update(|r, cx| r.set_scope(Scope::Folder(pngs.clone()), cx));
    h.update(|r, cx| r.set_hidden(pngs.clone(), true, cx));
    assert_eq!(h.read(|r| (r.lib.entries.len(), r.scope.clone())), (8, Scope::All));
    assert_eq!(h.read(|r| r.lib.excluded.clone()), vec![pngs.clone()]);
    h.update(|r, cx| r.set_hidden(pngs, false, cx));
    assert_eq!(h.read(|r| r.lib.entries.len()), 11);
    let id = h.read(|r| r.lib.sources[0].id);
    h.update(|r, cx| r.remove_source(id, cx));
    assert_eq!(h.read(|r| (r.lib.entries.len(), r.lib.sources.len())), (0, 0));
}

#[gpui::test]
fn ctrl_wheel_resizes_tiles_around_the_pointer(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    let before = h.read(|r| r.tile_size);
    h.update(|r, _| r.resize_tiles(1.08, 10.0, 10.0));
    assert!(h.read(|r| r.tile_size) > before);
    h.update(|r, _| r.resize_tiles(0.01, 10.0, 10.0));
    assert_eq!(h.read(|r| r.tile_size), crate::theme::TILE_MIN);
}

#[gpui::test]
fn pointer_over_a_pane_shows_its_controls(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    h.keys("right enter");
    assert!(h.wait_frame(0));
    h.cx.simulate_mouse_move(point(px(200.0), px(200.0)), None, Modifiers::none());
    h.settle();
    assert!(h.read(|r| r.controls_visible(0)));
    // Clicking the media area focuses the pane and keeps it playing.
    h.cx.simulate_click(point(px(200.0), px(200.0)), Modifiers::none());
    h.settle();
    assert_eq!(h.read(|r| r.focused), 0);
}

#[gpui::test]
fn picture_in_picture_opens_and_closes(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    h.keys("p");
    assert!(h.read(|r| r.pip.is_none()), "nothing playing: no PiP");
    h.keys("right enter");
    assert!(h.wait_frame(0));
    h.keys("p");
    assert!(h.read(|r| r.pip.is_some()));
    // With PiP open, the library stays up and picks go to the PiP panes.
    h.update(|r, cx| r.show_library_for_pip(cx));
    assert_eq!(h.read(|r| r.screen), Screen::Browse);
    h.keys("right enter");
    assert_eq!(h.read(|r| r.screen), Screen::Browse);
    assert_eq!(h.read(|r| r.panes[0].current()), h.read(|r| r.selected));
    h.keys("p");
    assert!(h.read(|r| r.pip.is_none()));
}

#[gpui::test]
fn video_plays_seeks_and_moves_on(cx: &mut TestAppContext) {
    if !crate::mpv::available() {
        eprintln!("libmpv not found: skipped");
        return;
    }
    let mut h = Harness::open(cx, true);
    let clips = h._dir.0.join("Pictures/clips");
    std::fs::create_dir_all(&clips).unwrap();
    let clips = clips.canonicalize().unwrap();
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/clip.webm");
    for n in ["a.webm", "b.webm"] {
        std::fs::copy(&fixture, clips.join(n)).unwrap();
    }
    // Rescan picks up the clips; their tiles get a frame as thumbnail.
    h.update(|r, cx| r.folders_picked(Vec::new(), cx));
    h.update(|r, cx| r.set_scope(Scope::Folder(clips.clone()), cx));
    assert_eq!(h.read(|r| r.shown.len()), 2);
    for _ in 0..200 {
        h.settle();
        if h.read(|r| r.shown.iter().all(|&i| r.thumbs.get(i).is_some())) {
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    assert!(h.read(|r| r.shown.iter().all(|&i| r.thumbs.get(i).is_some())));
    h.keys("enter");
    assert!(h.read(|r| r.panes[0].video.is_some()));
    assert!(h.wait_frame(0));
    h.update(|r, cx| r.tick(cx));
    assert!(h.read(|r| r.panes[0].time.1 > 0.0), "duration is read from mpv");
    h.cx.simulate_mouse_move(point(px(300.0), px(300.0)), None, Modifiers::none());
    h.keys("] [ space space up");
    h.update(|r, _| r.seek_pane(0, 0.5));
    // Speed: faster, back to normal, slower; it stays for the next clip.
    h.keys("> > backspace <");
    assert_eq!(h.read(|r| r.panes[0].speed), 0.75);
    // Frame steps pause on the frame.
    h.keys(". . ,");
    assert!(h.read(|r| r.panes[0].paused));
    h.keys("backspace space");
    assert!(h.read(|r| !r.panes[0].paused && r.panes[0].speed == 1.0));
    // In a slideshow the clip plays once, then the next one starts.
    h.keys("s");
    let first = h.read(|r| r.panes[0].current());
    for _ in 0..300 {
        h.settle();
        // The app ticks on a timer the test clock does not run; a late
        // frame step that paused mpv is undone on the tick.
        h.update(|r, cx| r.tick(cx));
        if h.read(|r| r.panes[0].current()) != first {
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    assert_ne!(h.read(|r| r.panes[0].current()), first);
}

#[gpui::test]
fn new_files_appear_without_a_restart(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    let kept = h.read(|r| (0..11).filter(|&i| r.thumbs.get(i).is_some()).count());
    assert_eq!(kept, 10);
    picture(&h._dir.0.join("Pictures/trip/img_9.jpg"), 50, 50, 3);
    let mut seen = false;
    for _ in 0..250 {
        h.settle();
        if h.read(|r| r.lib.entries.len()) == 12 {
            seen = true;
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    assert!(seen, "the new picture was not picked up");
    assert_eq!(h.read(|r| r.shown.len()), 12);
    // Thumbnails already made followed their files to the new order.
    let broken = h.read(|r| r.lib.find(&r.lib.sources[0].path.join("broken.jpg")).unwrap());
    let shot = h.read(|r| r.lib.find(&r.lib.sources[0].path.join("pngs/shot_1.png")).unwrap());
    assert!(h.read(|r| r.thumbs.failed(broken) && r.thumbs.get(shot).is_some()));
}

#[gpui::test]
fn the_next_picture_is_decoded_ahead(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    let first = h.read(|r| r.lib.find(&r.lib.sources[0].path.join("trip/img_0.jpg")).unwrap());
    h.update(|r, _| r.select(first));
    h.keys("enter");
    assert!(h.wait_frame(0));
    let next = h.read(|r| r.panes[0].items[1]);
    for _ in 0..100 {
        h.settle();
        if h.read(|r| r.panes[0].is_ready(next)) {
            break;
        }
        std::thread::sleep(Duration::from_millis(10));
    }
    assert!(h.read(|r| r.panes[0].is_ready(next)));
    // Right shows it in the same frame, with no decode in between.
    h.cx.simulate_keystrokes("right");
    assert_eq!(h.read(|r| r.panes[0].shown), Some(next));
    // Left goes back to the kept picture just as fast.
    h.cx.simulate_keystrokes("left");
    assert_eq!(h.read(|r| r.panes[0].shown), Some(first));
}

#[gpui::test]
fn zero_toggles_fit_and_actual_size(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    h.keys("right enter");
    assert!(h.wait_frame(0));
    assert_eq!(h.read(|r| r.panes[0].full), (32, 32));
    h.keys("0");
    // A 32 px picture at actual size is far smaller than the pane.
    assert!(h.read(|r| r.panes[0].zoom) < 1.0);
    h.keys("0");
    assert_eq!(h.read(|r| r.panes[0].zoom), 1.0);
}

#[gpui::test]
fn the_last_session_comes_back(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    let src = h.read(|r| r.lib.sources[0].path.clone());
    let img = h.read(|r| r.lib.find(&src.join("trip/img_3.jpg")).unwrap());
    h.update(|r, cx| {
        r.set_scope(Scope::Folder(src.join("pngs")), cx);
        r.sort = SortBy::Size;
        r.tile_size = 240.0;
    });
    h.keys("2");
    h.update(|r, cx| r.play_in_pane(1, img, cx));
    h.keys("r > >");
    h.update(|r, _| r.save_session());
    let mut h = h.restart(cx);
    assert_eq!(h.read(|r| r.screen), Screen::Split, "back in the player");
    assert_eq!(h.read(|r| (r.split, r.focused, r.sort, r.tile_size)), (2, 1, SortBy::Size, 240.0));
    assert_eq!(h.read(|r| r.scope.clone()), Scope::Folder(src.join("pngs")));
    assert_eq!(h.read(|r| r.panes[0].source.clone()), None);
    assert!(h.wait_frame(1));
    let cur = h.read(|r| r.panes[1].current());
    assert_eq!(h.name(cur), "img_3.jpg");
    assert_eq!(h.read(|r| (r.panes[1].shuffle, r.panes[1].speed)), (true, 1.5));
    // Back in the library, then the player again: nothing is lost.
    h.keys("escape escape");
    assert_eq!(h.read(|r| r.screen), Screen::Split);
}

#[gpui::test]
fn dropped_files_and_folders_open(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    let src = h.read(|r| r.lib.sources[0].path.clone());
    // A folder already in the library is shown in the grid.
    h.update(|r, cx| r.dropped(&[src.join("trip")], None, cx));
    assert_eq!(h.read(|r| (r.screen, r.shown.len())), (Screen::Browse, 7));
    // A picture in the library plays at once, in the pane it was dropped on.
    h.keys("2");
    h.update(|r, cx| r.dropped(&[src.join("pngs/shot_2.png")], Some(1), cx));
    assert!(h.wait_frame(1));
    let cur = h.read(|r| r.panes[1].current());
    assert_eq!(h.name(cur), "shot_2.png");
    // A picture from elsewhere: its folder joins the library, then it plays.
    let elsewhere = h._dir.0.join("Downloads/new.png");
    picture(&elsewhere, 20, 20, 1);
    std::fs::write(h._dir.0.join("Downloads/notes.txt"), b"x").unwrap();
    h.update(|r, cx| r.dropped(std::slice::from_ref(&elsewhere), None, cx));
    let mut played = false;
    for _ in 0..200 {
        h.settle();
        let cur = h.read(|r| r.panes[r.focused].current());
        if h.name(cur) == "new.png" {
            played = true;
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    assert!(played, "the dropped picture did not play");
    assert_eq!(h.read(|r| r.lib.sources.len()), 2);
    // Anything else is ignored.
    let before = h.read(|r| r.lib.sources.len());
    let others = [PathBuf::from("/no/such/file.jpg"), h._dir.0.join("Downloads/notes.txt")];
    h.update(|r, cx| r.dropped(&others, None, cx));
    assert_eq!(h.read(|r| r.lib.sources.len()), before);
}

#[gpui::test]
fn animated_gifs_play_in_the_player(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    let path = h._dir.0.join("Pictures/anim/loop.gif");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, crate::anim::tests::gif(4, 40, 20, 8)).unwrap();
    h.update(|r, cx| r.rescan(cx));
    // The library keeps canonical paths (/private/var on macOS), and the
    // rescan runs in the background.
    let path = path.canonicalize().unwrap();
    let mut found = None;
    for _ in 0..250 {
        h.settle();
        found = h.read(|r| r.lib.find(&path));
        if found.is_some() {
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    let i = found.expect("the rescan finds the GIF");
    h.update(|r, cx| r.play_in_pane(0, i, cx));
    assert!(h.wait_frame(0));
    assert_eq!(h.read(|r| r.panes[0].frame.as_ref().unwrap().frame_count()), 4);
    assert_eq!(h.read(|r| r.panes[0].full), (40, 20));
}

#[gpui::test]
fn the_sponsor_dialog_explains_then_opens_github_sponsors(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    h.update(|r, cx| {
        r.show_sponsor = true;
        cx.notify();
    });
    h.settle();
    h.keys("escape");
    assert!(h.read(|r| !r.show_sponsor), "Esc closes it");
    assert_eq!(h.cx.opened_url(), None, "nothing opens until asked");
    h.update(|r, _| r.show_sponsor = true);
    h.update(|r, cx| r.open_sponsor_page(cx));
    assert_eq!(h.cx.opened_url().as_deref(), Some(crate::ui_sponsor::SPONSOR_URL));
    assert!(h.read(|r| !r.show_sponsor));
}

#[gpui::test]
fn videos_continue_where_they_stopped_and_switch_tracks(cx: &mut TestAppContext) {
    if !crate::mpv::available() {
        eprintln!("libmpv not found: skipped");
        return;
    }
    let mut h = Harness::open(cx, true);
    let films = h._dir.0.join("Pictures/films");
    std::fs::create_dir_all(&films).unwrap();
    let films = films.canonicalize().unwrap();
    let movie = films.join("movie.mkv");
    std::fs::copy(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/tracks.mkv"), &movie).unwrap();
    h.update(|r, cx| r.rescan(cx));
    let mut i = None;
    // The length is read in the background, for the tile.
    for _ in 0..250 {
        h.settle();
        i = h.read(|r| r.lib.find(&movie).filter(|&i| r.lib.duration(i).is_some()));
        if i.is_some() {
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    let i = i.expect("the length of the video is read");
    assert!((h.read(|r| r.lib.duration(i)).unwrap() - 30.0).abs() < 1.0);
    assert_eq!(h.read(|r| r.lib.continue_entries().len()), 0);

    h.update(|r, cx| r.play_in_pane(0, i, cx));
    assert!(h.wait_frame(0));
    h.update(|r, cx| r.tick(cx));
    // Two audio tracks and subtitles: both can be picked.
    let tracks = h.read(|r| r.panes[0].tracks.clone());
    assert_eq!(tracks.iter().filter(|t| t.kind == TrackKind::Audio).count(), 2);
    // Without a sound device (CI) mpv plays no audio track at all.
    let sound = tracks.iter().any(|t| t.kind == TrackKind::Audio && t.selected);
    let sub = tracks.iter().find(|t| t.kind == TrackKind::Sub).expect("the subtitles are listed").id;
    let commentary = tracks.iter().find(|t| t.title.as_deref() == Some("Commentary")).unwrap().id;
    h.update(|r, cx| r.set_track(0, TrackKind::Audio, Some(commentary), cx));
    h.update(|r, cx| r.set_track(0, TrackKind::Sub, Some(sub), cx));
    let picked = h.read(|r| r.panes[0].tracks.iter().filter(|t| t.selected).map(|t| t.id).collect::<Vec<_>>());
    assert!(picked.contains(&sub), "{picked:?}");
    assert!(!sound || picked.contains(&commentary), "{picked:?}");
    h.update(|r, cx| r.set_track(0, TrackKind::Sub, None, cx));
    assert!(h.read(|r| !r.panes[0].tracks.iter().any(|t| t.kind == TrackKind::Sub && t.selected)));
    h.keys("c");
    assert!(h.read(|r| r.panes[0].tracks.iter().any(|t| t.kind == TrackKind::Sub && t.selected)), "C turns them on");

    // Chapters: notches on the seek bar, and PgDn jumps to the next one.
    let chapters = h.read(|r| r.panes[0].chapters.clone());
    assert_eq!(chapters.iter().map(|t| t.round()).collect::<Vec<_>>(), vec![0.0, 10.0, 20.0]);
    h.keys("pagedown");
    let mut pos = 0.0;
    for _ in 0..100 {
        h.update(|r, cx| r.tick(cx));
        pos = h.read(|r| r.panes[0].time.0);
        if pos >= 9.0 {
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    assert!((9.0..15.0).contains(&pos), "PgDn went to {pos}");

    // Over the seek bar, the frame under the pointer shows.
    h.update(|r, cx| r.hover_seek(0, Some(0.75), cx));
    let mut key = None;
    for _ in 0..200 {
        h.settle();
        key = h.read(|r| r.panes[0].preview.as_ref().map(|(k, _)| *k));
        if key.is_some() {
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    assert!(matches!(key, Some(22 | 23)), "the frame at 0:22 of 0:30, got {key:?}");
    h.update(|r, cx| r.hover_seek(0, None, cx));
    assert_eq!(h.read(|r| r.panes[0].seek_hover), None);

    // Stop half way: the video is listed to continue, and starts there.
    h.update(|r, _| r.seek_pane(0, 0.5));
    let mut pos = 0.0;
    for _ in 0..100 {
        h.update(|r, cx| r.tick(cx));
        pos = h.read(|r| r.panes[0].time.0);
        if pos > 12.0 {
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    assert!(pos > 12.0, "seeked to {pos}");
    h.update(|r, cx| r.save_watch(cx));
    assert_eq!(h.read(|r| r.lib.continue_entries()), vec![i]);
    assert!(h.read(|r| r.lib.progress(i)).is_some_and(|f| f > 0.3 && f < 0.7));

    let mut h = h.restart(cx);
    let i = h.read(|r| r.lib.find(&movie)).unwrap();
    assert!(h.read(|r| r.lib.resume_at(i)).is_some_and(|p| p > 12.0), "kept across a restart");
    h.update(|r, cx| r.set_scope(Scope::Continue, cx));
    assert_eq!(h.read(|r| r.shown.clone()), vec![i]);
    h.update(|r, cx| r.play_in_pane(0, i, cx));
    assert!(h.wait_frame(0));
    h.update(|r, cx| r.tick(cx));
    assert!(h.read(|r| r.panes[0].time.0) > 12.0, "starts where it stopped");
}

#[gpui::test]
fn pictures_fade_into_the_next_unless_turned_off(cx: &mut TestAppContext) {
    let mut h = Harness::open(cx, true);
    h.keys("right enter");
    assert!(h.wait_frame(0));
    assert!(h.read(|r| r.fade), "on by default");
    let next = |h: &mut Harness| {
        h.keys("right");
        for _ in 0..100 {
            h.settle();
            if h.read(|r| r.panes[0].shown.is_some() && r.panes[0].shown == r.panes[0].current()) {
                return;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        panic!("the next picture did not show");
    };
    next(&mut h);
    assert!(h.read(|r| r.panes[0].fade_from.is_some()), "the picture before fades out");
    // Turned off: the next picture replaces it at once.
    h.update(|r, cx| {
        r.fade = false;
        cx.notify();
    });
    next(&mut h);
    assert!(h.read(|r| r.panes[0].fade_from.is_none()));
    // The choice is kept for next time.
    h.update(|r, _| r.save_session());
    let mut h = h.restart(cx);
    assert!(h.read(|r| !r.fade));
}

#[gpui::test]
fn video_tiles_play_while_the_pointer_rests_on_them(cx: &mut TestAppContext) {
    if !crate::mpv::available() {
        eprintln!("libmpv not found: skipped");
        return;
    }
    let mut h = Harness::open(cx, true);
    let clips = h._dir.0.join("Pictures/clips");
    std::fs::create_dir_all(&clips).unwrap();
    let clip = clips.canonicalize().unwrap().join("a.webm");
    std::fs::copy(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/clip.webm"), &clip).unwrap();
    h.update(|r, cx| r.rescan(cx));
    let mut i = None;
    for _ in 0..250 {
        h.settle();
        i = h.read(|r| r.lib.find(&clip));
        if i.is_some() {
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    let i = i.unwrap();
    // A picture tile does nothing.
    let pic = h.read(|r| r.lib.entries.iter().position(|e| e.kind == crate::media::Kind::Image)).unwrap();
    h.update(|r, cx| r.hover_tile(Some(pic), 96, cx));
    h.cx.executor().advance_clock(crate::app::TILE_PLAY_DELAY * 2);
    h.settle();
    assert!(h.read(|r| r.tile_play.is_none()));
    // A video starts only after the pointer rested on it.
    h.update(|r, cx| r.hover_tile(Some(i), 96, cx));
    assert!(h.read(|r| r.tile_play.is_none()), "not at once");
    h.cx.executor().advance_clock(crate::app::TILE_PLAY_DELAY * 2);
    let mut frame = false;
    for _ in 0..200 {
        h.settle();
        frame = h.read(|r| r.tile_play.as_ref().is_some_and(|tp| tp.entry == i && tp.frame.is_some()));
        if frame {
            break;
        }
        std::thread::sleep(Duration::from_millis(10));
    }
    assert!(frame, "the tile shows the playing video");
    h.update(|r, cx| r.hover_tile(None, 0, cx));
    assert!(h.read(|r| r.tile_play.is_none()), "stops when the pointer leaves");
}