rosier 0.5.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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
//! The library browser: sidebar, toolbar, grid of tiles, status bar.

use gpui::{AnyElement, ClickEvent, Context, MouseButton, SharedString, Window, div, img, list, prelude::*, px};

use crate::app::Rosier;
use crate::assets::Icon;
use crate::i18n::{human_size, t, tf, thousands};
use crate::library::{KindFilter, Scope, SortBy};
use crate::media::Kind;
use crate::pane::clock;
use crate::ui::{button, glass, glass_sheen, icon, segment, segmented};
use crate::{grid, theme};

impl Rosier {
    pub(crate) fn render_browse(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
        let vp = window.viewport_size();
        let side_w = if self.sidebar_visible { theme::SIDEBAR_W + theme::GUTTER } else { 0.0 };
        let main_w = f32::from(vp.width) - side_w - 2.0 * theme::GUTTER;
        let avail = (main_w - 2.0 * theme::GRID_PAD).max(120.0);
        (self.cols, self.cell_w) = grid::columns(avail, self.tile_size, theme::TILE_GAP);
        self.grid_h = f32::from(vp.height) - self.titlebar_h - 2.0 * theme::GUTTER - theme::STATUS_H - 16.0;
        // Thumbnails at least as sharp as the tiles they fill.
        let side = crate::thumb::side_for(self.cell_w * window.scale_factor());
        self.set_thumb_side(side, cx);
        self.ensure_rows();
        // Rows are laid out after this returns; send their wanted thumbnails
        // to the workers once the frame is done.
        cx.defer_in(window, |this, _, cx| {
            this.flush_wanted();
            this.update_ambient(cx);
        });

        // Rows drawn this frame say which tiles are on screen.
        self.thumbs.begin_frame();

        let view = cx.entity();
        let grid: AnyElement = if self.loaded && self.shown.is_empty() && !self.indexing {
            div()
                .flex_grow()
                .flex()
                .items_center()
                .justify_center()
                .text_color(theme::text_faint())
                .child(t("grid.empty"))
                .into_any_element()
        } else {
            let zoom_view = cx.entity().downgrade();
            div()
                .relative()
                .flex_grow()
                .flex()
                .flex_col()
                // Inset from the panel's rounded corners: gpui clips to the
                // rectangle, so tiles must not reach into the corners.
                .pt(px(8.0))
                .pb(px(4.0))
                .child(
                    list(self.list.clone(), move |ix, _window, app| {
                        view.update(app, |this, cx| this.render_row(ix, cx))
                    })
                    .flex_grow(),
                )
                .children(self.scrollbar(cx))
                // Ctrl + wheel resizes tiles. Caught in the capture phase so
                // the list does not scroll at the same time.
                .child(
                    gpui::canvas(
                        |_, _, _| {},
                        move |bounds, _, window, _| {
                            window.on_mouse_event(move |ev: &gpui::ScrollWheelEvent, phase, _window, app| {
                                if phase != gpui::DispatchPhase::Capture
                                    || !ev.modifiers.control
                                    || !bounds.contains(&ev.position)
                                {
                                    return;
                                }
                                let dy = f32::from(ev.delta.pixel_delta(px(20.0)).y);
                                if dy == 0.0 {
                                    return;
                                }
                                let _ = zoom_view.update(app, |this, cx| {
                                    // Zoom around the tile under the pointer: it stays put.
                                    this.resize_tiles(
                                        if dy > 0.0 { 1.08 } else { 1.0 / 1.08 },
                                        f32::from(ev.position.x - bounds.origin.x) - theme::GRID_PAD,
                                        f32::from(ev.position.y - bounds.origin.y),
                                    );
                                    cx.notify();
                                });
                                app.stop_propagation();
                            });
                        },
                    )
                    .absolute()
                    .size_full(),
                )
                .into_any_element()
        };

        // PiP open: files clicked here go to a PiP pane; pick which.
        let pip_banner = self.pip.is_some().then(|| {
            div()
                .flex()
                .flex_row()
                .items_center()
                .gap_3()
                .px(px(theme::GRID_PAD))
                .h(px(40.0))
                .flex_none()
                .bg(theme::accent_soft())
                .border_b_1()
                .border_color(theme::line())
                .text_sm()
                .child(icon(Icon::Pip, 16.0, theme::accent()))
                .child(div().flex_grow().child(t("grid.pip_banner")))
                .child(segmented().children((0..self.panes.len()).map(|k| {
                    segment(("pip-target", k), self.focused == k).h(px(22.0)).child((k + 1).to_string()).on_click(
                        cx.listener(move |this, _, _, cx| {
                            this.set_focus(k);
                            cx.notify();
                        }),
                    )
                })))
        });
        let banner = self.picking_for.map(|ix| {
            div()
                .flex()
                .flex_row()
                .items_center()
                .gap_3()
                .px(px(theme::GRID_PAD))
                .h(px(40.0))
                .flex_none()
                .bg(theme::accent_soft())
                .text_sm()
                .child(icon(Icon::Split4, 16.0, theme::accent()))
                .child(div().flex_grow().child(tf("grid.pick_banner", &[("n", (ix + 1).to_string())])))
                .child(
                    button("pick-cancel")
                        .child(t("grid.pick_cancel"))
                        .on_click(cx.listener(|this, _, _, cx| this.go_split(cx))),
                )
        });

        // Ambient backdrop: the selection, blurred to a wash of its colors,
        // under a scrim. The glass panels float over it.
        let backdrop = div()
            .absolute()
            .top_0()
            .left_0()
            .size_full()
            .children(
                self.ambient
                    .clone()
                    .map(|a| img(a).absolute().top_0().left_0().size_full().object_fit(gpui::ObjectFit::Fill)),
            )
            .child(div().absolute().top_0().left_0().size_full().bg(theme::backdrop_scrim()));

        let grid_panel = div()
            .flex_grow()
            .min_h_0()
            .flex()
            .flex_col()
            .rounded(px(theme::R_PANEL))
            .bg(theme::glass_deep())
            .border_1()
            .border_color(theme::glass_edge())
            .overflow_hidden()
            .children(pip_banner)
            .children(banner)
            .child(grid)
            .child(self.render_status(cx));

        div()
            .relative()
            .size_full()
            .bg(theme::stage())
            .child(backdrop)
            .child(
                div()
                    .relative()
                    .size_full()
                    .flex()
                    .flex_row()
                    .gap(px(theme::GUTTER))
                    .p(px(theme::GUTTER))
                    .when(self.sidebar_visible, |d| d.child(self.render_sidebar(cx)))
                    .child(div().flex_grow().min_w_0().h_full().flex().flex_col().child(grid_panel)),
            )
            .into_any_element()
    }

    fn render_sidebar(&mut self, cx: &mut Context<Self>) -> AnyElement {
        // Rows with a hover action (`group` set) swap their count for the
        // action in the same right-hand spot, so counts stay in one column.
        let item = |id: SharedString,
                    ic: Icon,
                    label: String,
                    count: usize,
                    active: bool,
                    indent: f32,
                    group: Option<&'static str>| {
            let count_el = div().flex_none().text_xs().text_color(theme::text_faint()).child(thousands(count));
            let count_el = match group {
                Some(g) => count_el.group_hover(g, |s| s.opacity(0.0)),
                None => count_el,
            };
            div()
                .id(id)
                .relative()
                .when_some(group, |d, g| d.group(g))
                .flex()
                .flex_row()
                .items_center()
                .gap_2()
                .h(px(theme::ROW_H))
                .mb(px(2.0))
                .pl(px(10.0 + indent))
                .pr_2()
                .mx_2()
                .rounded(px(theme::RADIUS))
                .text_sm()
                .cursor_pointer()
                .border_1()
                .when(active, |d| {
                    d.bg(theme::raised_active()).border_color(theme::glass_edge()).text_color(theme::text())
                })
                .when(!active, |d| {
                    d.border_color(gpui::rgba(0x00000000))
                        .text_color(theme::text_dim())
                        .hover(|s| s.bg(theme::raised()).text_color(theme::text()))
                })
                .child(icon(ic, 16.0, if active { theme::accent() } else { theme::text_faint() }))
                .child(div().flex_grow().truncate().child(label))
                .child(count_el)
        };
        let section = |label: &'static str| {
            div()
                .px_4()
                .pt(px(20.0))
                .pb(px(8.0))
                .text_xs()
                .font_weight(gpui::FontWeight::SEMIBOLD)
                .text_color(theme::text_faint())
                .child(label)
        };

        let mut rows: Vec<AnyElement> = Vec::new();
        // "Library" header with the kind filter beside it, as three icons.
        let kinds =
            [(KindFilter::All, Icon::Library), (KindFilter::Photos, Icon::Image), (KindFilter::Videos, Icon::Film)];
        rows.push(
            div()
                .flex()
                .flex_row()
                .items_center()
                .justify_between()
                .pl_4()
                .pr_3()
                .pt(px(16.0))
                .pb(px(6.0))
                .child(
                    div()
                        .text_xs()
                        .font_weight(gpui::FontWeight::SEMIBOLD)
                        .text_color(theme::text_faint())
                        .child(t("side.library")),
                )
                .child(segmented().children(kinds.into_iter().map(|(k, ic)| {
                    let on = self.kind == k;
                    segment(SharedString::from(format!("kind-{k:?}")), on)
                        .tooltip(crate::ui::tip(t(match k {
                            KindFilter::All => "side.all",
                            KindFilter::Photos => "tip.photos",
                            KindFilter::Videos => "tip.videos",
                        })))
                        .h(px(22.0))
                        .px_1p5()
                        .child(icon(ic, 14.0, if on { theme::text() } else { theme::text_faint() }))
                        .on_click(cx.listener(move |this, _, _, cx| {
                            this.kind = k;
                            this.recompute_shown();
                            cx.notify();
                        }))
                })))
                .into_any_element(),
        );
        rows.push(
            item(
                "side-all".into(),
                Icon::Library,
                t("side.all").into(),
                self.lib.source_counts.iter().map(|c| c.of(self.kind)).sum::<usize>(),
                self.scope == Scope::All,
                0.0,
                None,
            )
            .on_click(cx.listener(|this, _, _, cx| this.set_scope(Scope::All, cx)))
            .into_any_element(),
        );
        let fav_count = self.lib.count_kind(&self.lib.favorite_entries(), self.kind);
        rows.push(
            item(
                "side-fav".into(),
                Icon::Heart,
                t("side.favorites").into(),
                fav_count,
                self.scope == Scope::Favorites,
                0.0,
                None,
            )
            .on_click(cx.listener(|this, _, _, cx| this.set_scope(Scope::Favorites, cx)))
            .into_any_element(),
        );
        let rated_count = self.lib.count_kind(&self.lib.rated_entries(), self.kind);
        rows.push(
            item(
                "side-rated".into(),
                Icon::Star,
                t("side.rated").into(),
                rated_count,
                self.scope == Scope::Rated,
                0.0,
                None,
            )
            .on_click(cx.listener(|this, _, _, cx| this.set_scope(Scope::Rated, cx)))
            .into_any_element(),
        );
        // Shown once there is a video to continue.
        let cont_count = self.lib.count_kind(&self.lib.continue_entries(), self.kind);
        if cont_count > 0 || self.scope == Scope::Continue {
            rows.push(
                item(
                    "side-continue".into(),
                    Icon::Play,
                    t("side.continue").into(),
                    cont_count,
                    self.scope == Scope::Continue,
                    0.0,
                    None,
                )
                .on_click(cx.listener(|this, _, _, cx| this.set_scope(Scope::Continue, cx)))
                .into_any_element(),
            );
        }
        rows.push(section(t("side.sources")).into_any_element());
        for (si, src) in self.lib.sources.iter().enumerate() {
            let path = src.path.clone();
            let active = self.scope == Scope::Folder(path.clone());
            let id = src.id;
            rows.push(
                item(
                    format!("side-src-{si}").into(),
                    Icon::Folder,
                    grid::source_name(src),
                    self.lib.source_counts.get(si).map_or(0, |c| c.of(self.kind)),
                    active,
                    0.0,
                    Some("side-src"),
                )
                .child(
                    div()
                        .id(("side-remove", si))
                        .absolute()
                        .right(px(8.0))
                        .p_0p5()
                        .rounded(px(4.0))
                        .opacity(0.0)
                        .group_hover("side-src", |s| s.opacity(1.0))
                        .hover(|s| s.bg(theme::raised_hover()))
                        .child(icon(Icon::Close, 12.0, theme::text_dim()))
                        .on_click(cx.listener(move |this, _, _, cx| {
                            cx.stop_propagation();
                            this.remove_source(id, cx);
                        })),
                )
                .on_click(cx.listener(move |this, _, _, cx| this.set_scope(Scope::Folder(path.clone()), cx)))
                .into_any_element(),
            );
            if !self.collapsed.contains(&src.id) {
                for (fi, f) in self.lib.side_folders.get(si).map(|v| v.as_slice()).unwrap_or(&[]).iter().enumerate() {
                    let p = f.path.clone();
                    let active = self.scope == Scope::Folder(p.clone());
                    let hide_path = p.clone();
                    rows.push(
                        item(
                            format!("side-f-{si}-{fi}").into(),
                            Icon::Folder,
                            f.name.clone(),
                            f.count.of(self.kind),
                            active,
                            16.0,
                            Some("side-sub"),
                        )
                        .child(
                            div()
                                .id(SharedString::from(format!("side-hide-{si}-{fi}")))
                                .absolute()
                                .right(px(8.0))
                                .p_0p5()
                                .rounded(px(4.0))
                                .opacity(0.0)
                                .group_hover("side-sub", |s| s.opacity(1.0))
                                .hover(|s| s.bg(theme::raised_hover()))
                                .child(icon(Icon::Close, 12.0, theme::text_dim()))
                                .on_click(cx.listener(move |this, _, _, cx| {
                                    cx.stop_propagation();
                                    this.set_hidden(hide_path.clone(), true, cx);
                                })),
                        )
                        .on_click(cx.listener(move |this, _, _, cx| this.set_scope(Scope::Folder(p.clone()), cx)))
                        .into_any_element(),
                    );
                }
            }
        }

        if !self.lib.excluded.is_empty() {
            rows.push(section(t("side.hidden")).into_any_element());
            for (k, x) in self.lib.excluded.iter().enumerate() {
                let path = x.clone();
                let name = grid::folder_title(x, &self.lib.sources);
                rows.push(
                    div()
                        .id(("side-hidden", k))
                        .group("side-hidden")
                        .flex()
                        .flex_row()
                        .items_center()
                        .gap_2()
                        .h(px(28.0))
                        .pl(px(10.0))
                        .pr_2()
                        .mx_2()
                        .rounded(px(theme::RADIUS))
                        .text_xs()
                        .text_color(theme::text_faint())
                        .child(icon(Icon::Folder, 14.0, theme::text_faint()))
                        .child(div().flex_grow().truncate().line_through().child(name))
                        .child(
                            div()
                                .id(("side-show", k))
                                .flex_none()
                                .px_1p5()
                                .rounded(px(4.0))
                                .text_color(theme::text_dim())
                                .opacity(0.0)
                                .group_hover("side-hidden", |s| s.opacity(1.0))
                                .hover(|s| s.bg(theme::raised_hover()).text_color(theme::text()))
                                .child(t("side.show"))
                                .on_click(cx.listener(move |this, _, _, cx| this.set_hidden(path.clone(), false, cx))),
                        )
                        .into_any_element(),
                );
            }
        }

        glass(theme::R_PANEL)
            .w(px(theme::SIDEBAR_W))
            .flex_none()
            .h_full()
            .flex()
            .flex_col()
            .child(glass_sheen(theme::R_PANEL))
            .child(div().h(px(4.0)).flex_none())
            .child(div().id("sidebar-scroll").flex_grow().overflow_y_scroll().pb_2().children(rows))
            .child(
                div()
                    .p_2()
                    .border_t_1()
                    .border_color(theme::line())
                    .flex()
                    .flex_row()
                    .gap_1()
                    .child(
                        button("side-add")
                            .flex_grow()
                            .justify_start()
                            .child(icon(Icon::Plus, 16.0, theme::text_dim()))
                            .child(t("side.add"))
                            .on_click(cx.listener(|this, _, _, cx| this.add_folders(cx))),
                    )
                    .child(
                        button("side-sponsor")
                            .tooltip(crate::ui::tip(t("sponsor.title")))
                            .flex_none()
                            .w(px(theme::CONTROL_H))
                            .px_0()
                            .justify_center()
                            .child(icon(Icon::Heart, 16.0, theme::text_dim()))
                            .on_click(cx.listener(|this, _, _, cx| {
                                this.show_sponsor = true;
                                cx.notify();
                            })),
                    )
                    .child(
                        button("side-lang")
                            .tooltip(crate::ui::tip(t("tip.language")))
                            .flex_none()
                            .w(px(theme::CONTROL_H))
                            .px_0()
                            .justify_center()
                            .when(self.lang_menu, |b| b.bg(theme::raised_active()))
                            .child(icon(Icon::Languages, 16.0, theme::text_dim()))
                            .on_click(cx.listener(|this, ev: &gpui::ClickEvent, _, cx| {
                                let closed = this.click_closed_a_menu(ev);
                                this.lang_menu = !this.lang_menu && !closed;
                                cx.notify();
                            })),
                    ),
            )
            .children(self.lang_menu.then(|| {
                let cur = crate::i18n::current();
                div()
                    .id("lang-menu")
                    // Clicks on the list must not reach the folder rows below.
                    .occlude()
                    .absolute()
                    .right(px(8.0))
                    .bottom(px(52.0))
                    .w(px(208.0))
                    .p_1()
                    .flex()
                    .flex_col()
                    .rounded(px(theme::RADIUS + 4.0))
                    .bg(gpui::rgba(0x1c1c21f2))
                    .border_1()
                    .border_color(theme::glass_edge())
                    .shadow_lg()
                    .on_mouse_down_out(cx.listener(|this, ev, _, cx| {
                        this.menu_closed_by(ev);
                        this.lang_menu = false;
                        cx.notify();
                    }))
                    .children(crate::i18n::LANGS.iter().enumerate().map(|(i, (_, name, _))| {
                        div()
                            .id(("lang", i))
                            .h(px(theme::ROW_H))
                            .px_2()
                            .flex()
                            .flex_row()
                            .items_center()
                            .gap_2()
                            .rounded(px(theme::R_SMALL))
                            .text_sm()
                            .cursor_pointer()
                            .hover(|s| s.bg(theme::raised_hover()))
                            .child(
                                div()
                                    .w(px(16.0))
                                    .flex_none()
                                    .when(i == cur, |d| d.child(icon(Icon::Check, 14.0, theme::accent()))),
                            )
                            .child(
                                div()
                                    .flex_grow()
                                    .text_color(if i == cur { theme::text() } else { theme::text_dim() })
                                    .child(*name),
                            )
                            .on_click(cx.listener(move |this, _, _, cx| this.set_language(i, cx)))
                    }))
            }))
            .into_any_element()
    }

    /// Bottom bar: sidebar toggle and where we are on the left; sort order
    /// and tile size on the right.
    fn render_status(&mut self, cx: &mut Context<Self>) -> AnyElement {
        // Where we are, as a quiet breadcrumb: source / folder / subfolder.
        let crumbs: Vec<String> = match &self.scope {
            Scope::All => vec![t("side.all").into()],
            Scope::Favorites => vec![t("side.favorites").into()],
            Scope::Rated => vec![t("side.rated").into()],
            Scope::Continue => vec![t("side.continue").into()],
            Scope::Folder(p) => grid::folder_title(p, &self.lib.sources).split(" / ").map(String::from).collect(),
        };
        let last = crumbs.len().saturating_sub(1);
        let mut title = div().flex().flex_row().items_center().gap_1().min_w_0().flex_shrink().overflow_hidden();
        for (k, c) in crumbs.into_iter().enumerate() {
            if k > 0 {
                title = title.child(icon(Icon::Chevron, 12.0, theme::text_faint()));
            }
            title = title.child(
                div()
                    .truncate()
                    .when(k == last, |d| d.text_color(theme::text()))
                    .when(k != last, |d| d.text_color(theme::text_faint()))
                    .child(c),
            );
        }
        let mut meta = vec![crate::i18n::tn("grid.items", self.shown.len(), &[("n", thousands(self.shown.len()))])];
        if self.thumbs.pending > 0 {
            meta.push(tf("status.thumbs", &[("n", self.thumbs.pending.to_string())]));
        }
        if !self.loaded {
            meta.push(t("grid.loading").into());
        }
        // What the last rescan found (files added or gone while running),
        // or why reading the library failed.
        if let Some(note) = &self.sync_note {
            meta.push(note.clone());
        }
        let toggle = button("sidebar-toggle")
            .tooltip(crate::ui::tip(t("help.sidebar")))
            .h(px(24.0))
            .px_1p5()
            .child(icon(Icon::Sidebar, 16.0, if self.sidebar_visible { theme::text_faint() } else { theme::text() }))
            .on_click(cx.listener(|this, _, _, cx| {
                this.sidebar_visible = !this.sidebar_visible;
                cx.notify();
            }));
        let sorts = [
            (SortBy::Name, t("tool.sort.name")),
            (SortBy::Taken, t("tool.sort.taken")),
            (SortBy::Date, t("tool.sort.date")),
            (SortBy::Size, t("tool.sort.size")),
        ];
        let sort_ctl = segmented().children(sorts.into_iter().map(|(s, label)| {
            segment(SharedString::from(format!("sort-{s:?}")), self.sort == s).h(px(20.0)).child(label).on_click(
                cx.listener(move |this, _, _, cx| {
                    this.sort = s;
                    this.recompute_shown();
                    cx.notify();
                }),
            )
        }));
        let range = theme::TILE_MAX - theme::TILE_MIN;
        let size_ctl = div()
            .flex()
            .flex_row()
            .flex_none()
            .items_center()
            .gap_2()
            .child(icon(Icon::TilesSmall, 14.0, theme::text_faint()))
            .child(div().w(px(96.0)).child(self.slider(
                "tile-size".into(),
                ((self.tile_size - theme::TILE_MIN) / range) as f64,
                crate::ui_split::SliderStyle::on_chrome(),
                None,
                cx,
                move |this, f| {
                    this.tile_size = theme::TILE_MIN + f as f32 * range;
                    this.rows_dirty = true;
                },
            )))
            .child(icon(Icon::TilesLarge, 16.0, theme::text_faint()));
        div()
            .h(px(theme::STATUS_H + 4.0))
            .flex_none()
            .flex()
            .flex_row()
            .items_center()
            .gap_3()
            .pl(px(6.0))
            .pr(px(theme::GRID_PAD))
            .bg(theme::glass_fill())
            .border_t_1()
            .border_color(theme::line())
            .text_xs()
            .text_color(theme::text_dim())
            .child(toggle)
            .child(title)
            .child(div().flex_none().text_color(theme::text_faint()).child(meta.join(" · ")))
            .child(div().flex_grow())
            .child(sort_ctl)
            .child(size_ctl)
            .into_any_element()
    }

    /// A thin scrollbar on the grid's right edge: shows how far down the
    /// library you are, and can be dragged or clicked to jump.
    ///
    /// Rows all have the same height, so the position is computed from the
    /// row count instead of the list's measured (partial) heights.
    fn scrollbar(&mut self, cx: &mut Context<Self>) -> Option<AnyElement> {
        let row_h = self.cell_w.max(1.0);
        let rows = self.rows.rows.len();
        let view_h = f32::from(self.list.viewport_bounds().size.height);
        let content = rows as f32 * row_h;
        if view_h <= 0.0 || content <= view_h + 1.0 {
            return None;
        }
        let max_scroll = content - view_h;
        let top_px = self.scroll_top().min(max_scroll);
        let dragging = self.scroll_drag.is_some();
        let list = self.list.clone();
        let view = cx.entity().downgrade();
        Some(
            div()
                .absolute()
                .top(px(8.0))
                .bottom(px(4.0))
                .right(px(1.0))
                .w(px(10.0))
                .child(
                    gpui::canvas(
                        |_, _, _| {},
                        move |bounds, _, window, _| {
                            let track_h = f32::from(bounds.size.height);
                            let thumb_h = (track_h * view_h / content).clamp(32.0_f32.min(track_h), track_h);
                            let room = (track_h - thumb_h).max(1.0);
                            let thumb_y = room * top_px / max_scroll;
                            let thumb = gpui::Bounds::new(
                                gpui::point(bounds.origin.x + px(3.0), bounds.origin.y + px(thumb_y)),
                                gpui::size(px(4.0), px(thumb_h)),
                            );
                            let color = if dragging { gpui::rgba(0xffffffa0) } else { gpui::rgba(0xffffff50) };
                            window.paint_quad(gpui::fill(thumb, color).corner_radii(px(2.0)));

                            // Scroll so the thumb's top sits at `y` minus `grab`.
                            let scroll_to = {
                                let list = list.clone();
                                move |y: f32, grab: f32| {
                                    let f = ((y - f32::from(bounds.origin.y) - grab) / room).clamp(0.0, 1.0);
                                    let (item_ix, offset) = grid::row_offset(f * max_scroll, row_h);
                                    list.scroll_to(gpui::ListOffset { item_ix, offset_in_item: px(offset) });
                                }
                            };
                            {
                                let view = view.clone();
                                let scroll_to = scroll_to.clone();
                                window.on_mouse_event(move |ev: &gpui::MouseDownEvent, phase, _, app| {
                                    if phase != gpui::DispatchPhase::Bubble
                                        || ev.button != MouseButton::Left
                                        || !bounds.contains(&ev.position)
                                    {
                                        return;
                                    }
                                    let y = f32::from(ev.position.y);
                                    let on_thumb = thumb.contains(&ev.position);
                                    // Grabbing the thumb keeps the grab point; clicking
                                    // the track centres the thumb there.
                                    let grab = if on_thumb { y - f32::from(thumb.origin.y) } else { thumb_h / 2.0 };
                                    if !on_thumb {
                                        scroll_to(y, grab);
                                    }
                                    let _ = view.update(app, |this, cx| {
                                        this.scroll_drag = Some(grab);
                                        cx.notify();
                                    });
                                    app.stop_propagation();
                                });
                            }
                            {
                                let view = view.clone();
                                window.on_mouse_event(move |ev: &gpui::MouseMoveEvent, phase, _, app| {
                                    if phase != gpui::DispatchPhase::Bubble {
                                        return;
                                    }
                                    let Some(Some(grab)) = view.read_with(app, |this, _| this.scroll_drag).ok() else {
                                        return;
                                    };
                                    if ev.pressed_button != Some(MouseButton::Left) {
                                        let _ = view.update(app, |this, cx| {
                                            this.scroll_drag = None;
                                            cx.notify();
                                        });
                                        return;
                                    }
                                    scroll_to(f32::from(ev.position.y), grab);
                                    let _ = view.update(app, |_, cx| cx.notify());
                                });
                            }
                            window.on_mouse_event(move |ev: &gpui::MouseUpEvent, _, _, app| {
                                if ev.button == MouseButton::Left {
                                    let _ = view.update(app, |this, cx| {
                                        if this.scroll_drag.take().is_some() {
                                            cx.notify();
                                        }
                                    });
                                }
                            });
                        },
                    )
                    .size_full(),
                )
                .into_any_element(),
        )
    }

    /// Draws grid row `ix` and queues thumbnails for its tiles. The list
    /// calls this for rows on screen and in the overdraw band.
    fn render_row(&mut self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
        let Some(items) = self.rows.rows.get(ix).cloned() else { return div().into_any_element() };
        for &i in &items {
            self.thumbs.saw(i);
        }
        let tiles: Vec<AnyElement> = items.iter().map(|&i| self.tile(i, cx)).collect();
        div().flex().flex_row().px(px(theme::GRID_PAD)).pb(px(theme::TILE_GAP)).children(tiles).into_any_element()
    }

    /// One square tile: the thumbnail cropped to fill it, name and size on
    /// hover, a ring when selected, a heart when it is a favorite.
    fn tile(&self, i: usize, cx: &mut Context<Self>) -> AnyElement {
        let entry = &self.lib.entries[i];
        let side = self.cell_w - theme::TILE_GAP;
        // A video under the resting pointer plays in place of its still.
        let playing = self.tile_play.as_ref().filter(|tp| tp.entry == i).and_then(|tp| tp.frame.as_ref());
        let thumb = match playing.or(self.thumbs.get(i)) {
            Some(image) => {
                // Cover: the shorter side fills the tile and the tile clips
                // the rest. Sized by hand; object_fit did not constrain.
                let sz = image.size(0);
                let (w, h) = (i32::from(sz.width).max(1) as f32, i32::from(sz.height).max(1) as f32);
                // 2 px over on every side: the GPU samples the outermost
                // texels of a scaled sprite together with its neighbor in
                // the texture atlas, which showed as a line of another
                // picture's color along the tile's edge (and differed from
                // one Mesa build to the next). The tile clips the overscan.
                let fill = side + 4.0;
                let scale = (fill / w).max(fill / h);
                img(image.clone()).w(px(w * scale)).h(px(h * scale)).flex_none().into_any_element()
            }
            None if self.thumbs.failed(i) => {
                div().text_xs().text_color(theme::text_faint()).child(t("grid.unreadable")).into_any_element()
            }
            None => div().into_any_element(),
        };
        let name = entry.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
        let info = div()
            .absolute()
            .bottom_0()
            .left_0()
            .w_full()
            .px_2()
            .py_1p5()
            .bg(gpui::linear_gradient(
                0.0,
                gpui::linear_color_stop(gpui::rgba(0x000000d0), 0.0),
                gpui::linear_color_stop(gpui::rgba(0x00000000), 1.0),
            ))
            .text_xs()
            .text_color(gpui::white())
            .opacity(0.0)
            .group_hover("tile", |s| s.opacity(1.0))
            .child(div().truncate().child(name))
            .child(div().text_color(gpui::rgba(0xffffffb0)).child(human_size(entry.size)));
        // Videos show their length and books their page count once known;
        // how far a video was watched runs along the bottom edge.
        let badge = match entry.kind {
            Kind::Video => Some(tile_badge(Icon::Play, 10.0, self.lib.duration(i).map(clock))),
            // Books: a book mark with the page count once it is known.
            Kind::Book => Some(tile_badge(
                Icon::Book,
                12.0,
                self.book_pages.get(&entry.path).filter(|&&n| n > 0).map(|&n| crate::i18n::thousands(n)),
            )),
            Kind::Image => None,
        };
        let progress = self.lib.progress(i).map(|f| {
            div()
                .absolute()
                .bottom_0()
                .left_0()
                .w_full()
                .h(px(3.0))
                .bg(gpui::rgba(0xffffff40))
                .child(div().h_full().w(px(side * f)).bg(theme::accent()))
        });
        // Heart: always shown for favorites, on hover otherwise; click toggles.
        let is_fav = self.lib.is_favorite(i);
        let fav = div()
            .id(("tile-fav", i))
            .absolute()
            .top(px(6.0))
            .right(px(6.0))
            .p_1()
            .rounded_full()
            .bg(theme::scrim_light())
            .cursor_pointer()
            .hover(|s| s.bg(theme::scrim()))
            .when(!is_fav, |d| d.opacity(0.0).group_hover("tile", |s| s.opacity(1.0)))
            .child(icon(
                if is_fav { Icon::HeartFill } else { Icon::Heart },
                14.0,
                if is_fav { theme::accent_hover() } else { gpui::rgba(0xffffffe0) },
            ))
            .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation())
            .on_click(cx.listener(move |this, _, _, cx| {
                cx.stop_propagation();
                this.toggle_favorite(i, cx);
            }));
        // Stars, bottom right, for rated files.
        let stars = self.lib.rating(i);
        let rating = (stars > 0).then(|| {
            div()
                .absolute()
                .bottom(px(8.0))
                .right(px(6.0))
                .px_1()
                .py_0p5()
                .flex()
                .flex_row()
                .gap_0p5()
                .rounded(px(4.0))
                .bg(theme::scrim_light())
                .children((0..stars).map(|_| icon(Icon::StarFill, 10.0, theme::star())))
        });
        let selected = self.selected == Some(i);
        div()
            .id(("tile", i))
            .group("tile")
            .relative()
            .flex_none()
            .w(px(side))
            .h(px(side))
            .mr(px(theme::TILE_GAP))
            .flex()
            .items_center()
            .justify_center()
            .overflow_hidden()
            .rounded(px(2.0))
            .bg(theme::raised())
            .cursor_pointer()
            .child(thumb)
            .children(badge)
            .children(progress)
            .children(rating)
            .child(fav)
            .child(info)
            .children(selected.then(|| {
                div()
                    .absolute()
                    .top_0()
                    .left_0()
                    .size_full()
                    .rounded(px(2.0))
                    .border_3()
                    .border_color(theme::accent())
                    .child(div().size_full().border_1().border_color(gpui::rgba(0x00000080)))
            }))
            .when(entry.kind == Kind::Video, |d| {
                d.on_hover(cx.listener(move |this, hovered: &bool, _, cx| {
                    let side_px = (side * 2.0).min(640.0) as u32;
                    if *hovered {
                        this.hover_tile(Some(i), side_px, cx);
                    } else if this.tile_hovered == Some(i) {
                        this.hover_tile(None, 0, cx);
                    }
                }))
            })
            .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
                // Click plays the file in the pane being picked for, or else
                // in the focused pane.
                this.selected = Some(i);
                this.open(i, cx);
                cx.notify();
            }))
            .into_any_element()
    }
}

/// The mark in a tile's corner: an icon and, once known, a label.
fn tile_badge(ic: Icon, size: f32, label: Option<String>) -> gpui::Div {
    div()
        .absolute()
        .top(px(6.0))
        .left(px(6.0))
        .p_1()
        .flex()
        .flex_row()
        .items_center()
        .gap_1()
        .rounded(px(4.0))
        .bg(theme::scrim_light())
        .child(icon(ic, size, gpui::white()))
        .children(
            label.map(|l| div().pr_0p5().text_size(px(11.0)).line_height(px(12.0)).text_color(gpui::white()).child(l)),
        )
}