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
//! 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};

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