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
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
//! The split view: 1, 2 or 4 panes, each with floating glass controls that
//! appear while the pointer is over the pane.

use std::cell::Cell;
use std::rc::Rc;

use gpui::{
    AnyElement, Bounds, Context, MouseButton, MouseDownEvent, MouseMoveEvent, Pixels, SharedString, Window, canvas,
    div, img, prelude::*, px,
};

use crate::app::Rosier;
use crate::assets::Icon;
use crate::i18n::{t, tf};
use crate::mpv::{Track, TrackKind};
use crate::pane::{self, clock};
use crate::ui::{button, icon, primary_button, segment, segmented};
use crate::{grid, theme};

const PILL_H: f32 = 48.0;

/// Colors for `slider`.
#[derive(Clone, Copy)]
pub(crate) struct SliderStyle {
    pub track: gpui::Rgba,
    pub fill: gpui::Rgba,
    pub knob: gpui::Rgba,
}

impl SliderStyle {
    /// White on glass, for the player controls.
    pub fn on_glass() -> Self {
        SliderStyle { track: gpui::rgba(0xffffff40), fill: gpui::rgba(0xffffffff), knob: gpui::rgba(0xffffffff) }
    }
    /// Accent on chrome, for toolbars.
    pub fn on_chrome() -> Self {
        SliderStyle { track: theme::raised_hover(), fill: theme::accent(), knob: gpui::rgba(0xf4f4f8ff) }
    }
}

/// Left, top and width of the glass controls in a `w`x`h` pane.
/// Fixed to the bottom of the pane: it must not follow the media when the
/// user zooms or pans.
fn pill_geometry(w: f32, h: f32) -> (f32, f32, f32) {
    let pill_w = (w - 24.0).clamp(120.0, 840.0);
    let left = (w - pill_w) / 2.0;
    let top = (h - PILL_H - 16.0).max(8.0);
    (left, top, pill_w)
}

fn glass_tint() -> gpui::Rgba {
    // A little smoke keeps white text readable over bright video.
    gpui::rgba(0x0c0c1038)
}
fn glass_edge() -> gpui::Rgba {
    gpui::rgba(0xffffff3a)
}
fn glass_fallback() -> gpui::Rgba {
    gpui::rgba(0x1c1c22c0)
}

impl Rosier {
    pub(crate) fn render_split(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
        // Keep drawing while a picture fades in.
        if self.panes.iter().any(|p| p.fade_from.as_ref().is_some_and(|(_, at)| at.elapsed() < crate::app::FADE)) {
            window.request_animation_frame();
        }
        let vp = window.viewport_size();
        let scale = window.scale_factor();
        let (cols, rows) = pane::layout(self.split, self.split_side);
        // Panes fill the window below rosier's own title bar (if any); the
        // toolbar floats over them.
        let pane_w = f32::from(vp.width) / cols as f32;
        let pane_h = (f32::from(vp.height) - self.titlebar_h) / rows as f32;
        let phys = ((pane_w * scale) as u32, (pane_h * scale) as u32);
        for ix in 0..self.panes.len() {
            let p = &mut self.panes[ix];
            let (col, row) = (ix % cols, ix / cols);
            p.rect = (col as f32 * pane_w, row as f32 * pane_h, pane_w, pane_h);
            p.px_size = phys;
            if let Some(v) = &p.video {
                v.set_target(phys.0, phys.1);
            }
        }
        self.controls_shown = (0..self.panes.len()).any(|i| self.controls_visible(i));
        let mut grid_rows = Vec::new();
        for r in 0..rows {
            let mut row = Vec::new();
            for c in 0..cols {
                let ix = r * cols + c;
                if ix < self.panes.len() {
                    row.push(self.render_pane(ix, pane_w, pane_h, cx));
                }
            }
            grid_rows.push(div().flex().flex_row().children(row));
        }

        // Floating glass toolbar, shown with the pane controls or while the
        // pointer is near the top.
        let toolbar = crate::ui::glass(theme::R_PANEL)
            .flex()
            .flex_row()
            .items_center()
            .gap_2()
            .h(px(theme::TOOLBAR_H - 8.0))
            .px_2()
            .child(crate::ui::glass_sheen(theme::R_PANEL))
            .child(
                button("split-back")
                    .child(icon(Icon::Grid, 16.0, theme::text_dim()))
                    .child(t("tool.view.grid"))
                    .on_click(cx.listener(|this, _, _, cx| this.go_browse(None, cx))),
            )
            .child(div().w(px(1.0)).h(px(20.0)).bg(theme::line()))
            .child(
                segmented().children(
                    [
                        (1usize, false, Icon::Split1),
                        (2, false, Icon::Split2v),
                        (2, true, Icon::Split2),
                        (4, false, Icon::Split4),
                    ]
                    .into_iter()
                    .enumerate()
                    .map(|(k, (n, side, ic))| {
                        let active = self.split == n && (n != 2 || self.split_side == side);
                        segment(("split-n", k), active)
                            .child(icon(ic, 16.0, if active { theme::text() } else { theme::text_dim() }))
                            .on_click(cx.listener(move |this, _, _, cx| {
                                this.split_side = side;
                                this.set_split(n, cx);
                            }))
                    }),
                ),
            )
            .child(div().w(px(1.0)).h(px(20.0)).bg(theme::line()))
            .child(
                button("split-pip")
                    .child(icon(Icon::Pip, 16.0, if self.pip.is_some() { theme::accent() } else { theme::text_dim() }))
                    .on_click(cx.listener(|this, _, _, cx| this.toggle_pip(cx))),
            )
            .child(button("split-full").child(icon(Icon::Fullscreen, 16.0, theme::text_dim())).on_click(cx.listener(
                |_, _, window, cx| {
                    window.toggle_fullscreen();
                    cx.notify();
                },
            )));
        let top_zone = div()
            .absolute()
            .top_0()
            .left_0()
            .w_full()
            .h(px(72.0))
            .group("topbar")
            .flex()
            .justify_center()
            .pt(px(theme::GUTTER))
            .child(
                div()
                    .when(!self.controls_shown, |d| d.opacity(0.0).group_hover("topbar", |s| s.opacity(1.0)))
                    .child(toolbar),
            );

        div()
            .relative()
            .size_full()
            .flex()
            .flex_col()
            .bg(gpui::black())
            .children(grid_rows)
            .child(top_zone)
            .into_any_element()
    }

    fn render_pane(&self, ix: usize, w: f32, h: f32, cx: &mut Context<Self>) -> AnyElement {
        let pane = &self.panes[ix];
        let group: SharedString = format!("pane-{ix}").into();
        let focused = ix == self.focused && self.panes.len() > 1;

        let mut root = div()
            .id(("pane", ix))
            .group(group.clone())
            // A file dropped on a pane plays there.
            .on_drop(
                cx.listener(move |this, paths: &gpui::ExternalPaths, _, cx| this.dropped(paths.paths(), Some(ix), cx)),
            )
            .drag_over::<gpui::ExternalPaths>(|style, _, _, _| style.border_2().border_color(theme::accent()))
            .relative()
            .flex_none()
            .w(px(w))
            .h(px(h))
            .overflow_hidden()
            .bg(gpui::black())
            .when(pane.zoom > 1.0, |d| d.cursor_grab())
            // Idle over playing media: hide the pointer with the controls.
            .when(self.hover_pane == Some(ix) && !self.controls_visible(ix), |d| d.cursor(gpui::CursorStyle::None))
            .when(self.split > 1, |d| d.border_1().border_color(theme::stage()))
            .on_mouse_down(
                MouseButton::Left,
                cx.listener(move |this, _, _, cx| {
                    if this.focused != ix {
                        this.set_focus(ix);
                        cx.notify();
                    }
                }),
            )
            .on_click(cx.listener(|_, ev: &gpui::ClickEvent, window, cx| {
                // Double-click a pane for real full screen (and back).
                if ev.click_count() == 2 {
                    window.toggle_fullscreen();
                    cx.notify();
                }
            }))
            // Wheel zooms around the pointer; drag pans while zoomed in.
            .on_scroll_wheel(cx.listener(move |this, ev: &gpui::ScrollWheelEvent, _, cx| {
                let dy = f32::from(ev.delta.pixel_delta(px(20.0)).y);
                if dy == 0.0 {
                    return;
                }
                let (x, y, w, h) = this.panes[ix].rect;
                let at = (f32::from(ev.position.x) - (x + w / 2.0), f32::from(ev.position.y) - (y + h / 2.0));
                this.zoom_pane(ix, if dy > 0.0 { 1.15 } else { 1.0 / 1.15 }, at, cx);
            }))
            .on_mouse_down(
                MouseButton::Left,
                cx.listener(move |this, ev: &MouseDownEvent, _, _| {
                    let p = &mut this.panes[ix];
                    if p.zoom > 1.0 {
                        p.drag = Some((f32::from(ev.position.x), f32::from(ev.position.y)));
                    }
                }),
            )
            .on_hover(cx.listener(move |this, hovered: &bool, _, cx| {
                if !*hovered && this.hover_pane == Some(ix) {
                    this.hover_pane = None;
                    cx.notify();
                }
            }))
            .on_mouse_move(cx.listener(move |this, _: &MouseMoveEvent, _, cx| this.pointer_moved(Some(ix), cx)))
            .on_mouse_move(cx.listener(move |this, ev: &MouseMoveEvent, _, cx| {
                let p = &mut this.panes[ix];
                match (p.drag, ev.pressed_button) {
                    (Some((lx, ly)), Some(MouseButton::Left)) => {
                        let (x, y) = (f32::from(ev.position.x), f32::from(ev.position.y));
                        p.pan.0 += x - lx;
                        p.pan.1 += y - ly;
                        p.drag = Some((x, y));
                        cx.notify();
                    }
                    (Some(_), _) => p.drag = None,
                    _ => {}
                }
            }))
            .on_mouse_up(
                MouseButton::Left,
                cx.listener(move |this, _, _, _| {
                    this.panes[ix].drag = None;
                }),
            );

        if pane.source.is_none() {
            return root
                .flex()
                .items_center()
                .justify_center()
                .child(
                    div()
                        .flex()
                        .flex_col()
                        .items_center()
                        .gap_3()
                        .child(icon(Icon::Split4, 36.0, theme::text_faint()))
                        .child(
                            div()
                                .text_color(theme::text_dim())
                                .child(tf("pane.empty.title", &[("n", (ix + 1).to_string())])),
                        )
                        .child(
                            primary_button(("pane-pick", ix), t("pane.empty.pick"))
                                .on_click(cx.listener(move |this, _, _, cx| this.go_browse(Some(ix), cx))),
                        ),
                )
                .children(focused.then(focus_ring))
                .into_any_element();
        }

        // Media, fitted and centered.
        if let Some(frame) = &pane.frame {
            // While a picture fades in, the one before stays under it.
            let fade = pane
                .fade_from
                .as_ref()
                .map(|(old, at)| (old, at.elapsed().as_secs_f32() / crate::app::FADE.as_secs_f32()))
                .filter(|(_, t)| *t < 1.0);
            if let Some((old, _)) = fade {
                let sz = old.size(0);
                let (ox, oy, dw, dh) = pane::fit_rect(i32::from(sz.width) as f32, i32::from(sz.height) as f32, w, h);
                root = root.child(crate::ui::media(old).left(px(ox)).top(px(oy)).w(px(dw)).h(px(dh)));
            }
            let sz = frame.size(0);
            let fit = pane::fit_rect(i32::from(sz.width) as f32, i32::from(sz.height) as f32, w, h);
            let (ox, oy, dw, dh) = pane::zoomed(fit, w, h, pane.zoom, pane.pan);
            root = root.child(
                crate::ui::media(frame)
                    .left(px(ox))
                    .top(px(oy))
                    .w(px(dw))
                    .h(px(dh))
                    .when_some(fade, |d, (_, t)| d.opacity(t * t * (3.0 - 2.0 * t))),
            );
        } else {
            let msg = if pane.error.is_some() { t("pane.error") } else { t("pane.loading") };
            root = root.child(
                div()
                    .absolute()
                    .size_full()
                    .flex()
                    .items_center()
                    .justify_center()
                    .text_color(if pane.error.is_some() { theme::danger() } else { theme::text_faint() })
                    .child(msg),
            );
        }

        // Top-left chip: where this pane plays from and how far along.
        let title = match &pane.source {
            Some(crate::pane::PaneSource::Favorites) => t("side.favorites").to_string(),
            Some(crate::pane::PaneSource::Folder(p)) => grid::folder_title(p, &self.lib.sources),
            None => String::new(),
        };
        let name = pane
            .current()
            .and_then(|i| self.lib.path(i))
            .and_then(|p| p.file_name())
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        root = root.child(
            div()
                .absolute()
                .top(px(10.0))
                .left(px(10.0))
                .max_w(px((w - 20.0).max(40.0)))
                .px_2p5()
                .py_1()
                .rounded(px(theme::RADIUS))
                .bg(theme::scrim())
                .text_xs()
                .when(!self.controls_visible(ix), |d| d.opacity(0.0))
                .child(div().truncate().text_color(gpui::rgba(0xffffffc0)).child(title))
                .child(div().truncate().text_color(gpui::white()).child(format!(
                    "{} / {}  ·  {name}",
                    pane.pos + 1,
                    pane.items.len()
                ))),
        );

        root = root.child(self.glass_controls(ix, w, h, cx));
        root.children(focused.then(focus_ring)).into_any_element()
    }

    /// The floating glass pill: transport, seek bar (video), toggles, volume.
    fn glass_controls(&self, ix: usize, w: f32, h: f32, cx: &mut Context<Self>) -> AnyElement {
        let pane = &self.panes[ix];
        let (pill_left, pill_top, pill_w) = pill_geometry(w, h);
        let is_video = pane.video.is_some();

        // Frosted background: the slice of the blurred strip under the pill,
        // drawn with the pill's own rounded corners.
        // Fill: the strip is wide and short, so the default contain would
        // draw it as a band across the middle of the bar.
        let blur = pane.glass.as_ref().map(|g| {
            img(g.clone()).absolute().top_0().left_0().size_full().rounded_full().object_fit(gpui::ObjectFit::Fill)
        });

        let round_btn = |id: SharedString, ic: Icon, size: f32| {
            div()
                .id(id)
                .size(px(32.0))
                .flex_none()
                .flex()
                .items_center()
                .justify_center()
                .rounded_full()
                .cursor_pointer()
                .hover(|s| s.bg(gpui::rgba(0xffffff24)))
                .child(icon(ic, size, gpui::white()))
        };
        let toggle_btn = |id: SharedString, ic: Icon, on: bool| {
            div()
                .id(id)
                .size(px(32.0))
                .flex_none()
                .flex()
                .items_center()
                .justify_center()
                .rounded_full()
                .cursor_pointer()
                .when(on, |d| d.bg(gpui::rgba(0xffffff26)))
                .hover(|s| s.bg(gpui::rgba(0xffffff30)))
                .child(icon(ic, 17.0, if on { theme::accent_hover() } else { gpui::rgba(0xffffffd0) }))
        };

        let playing = pane.playing();
        let mut row = div()
            .relative()
            .size_full()
            .flex()
            .flex_row()
            .items_center()
            .gap_1()
            .px_2()
            .text_xs()
            .text_color(gpui::white())
            .child(
                round_btn(format!("prev-{ix}").into(), Icon::Prev, 16.0)
                    .on_click(cx.listener(move |this, _, _, cx| this.advance(ix, -1, cx))),
            )
            .child(
                round_btn(format!("play-{ix}").into(), if playing { Icon::Pause } else { Icon::Play }, 18.0).on_click(
                    cx.listener(move |this, _, _, cx| {
                        this.panes[ix].play_pause();
                        cx.notify();
                    }),
                ),
            )
            .child(
                round_btn(format!("next-{ix}").into(), Icon::Next, 16.0)
                    .on_click(cx.listener(move |this, _, _, cx| this.advance(ix, 1, cx))),
            );

        if is_video {
            let (pos, dur) = pane.time;
            row = row
                .child(div().flex_none().w(px(52.0)).text_right().child(clock(pos)))
                .child(self.seek_bar(ix, cx))
                .child(div().flex_none().w(px(52.0)).text_color(gpui::rgba(0xffffffb0)).child(clock(dur)))
                // The speed, only when it is not normal.
                .children((pane.speed != 1.0).then(|| div().flex_none().text_sm().child(format!("{}×", pane.speed))));
        } else {
            // Position, then the slideshow interval with -/+ right beside it.
            let secs = pane.interval.as_secs();
            let step_btn = |id: SharedString, ic: Icon| {
                div()
                    .id(id)
                    .size(px(24.0))
                    .flex_none()
                    .flex()
                    .items_center()
                    .justify_center()
                    .rounded_full()
                    .cursor_pointer()
                    .hover(|s| s.bg(gpui::rgba(0xffffff24)))
                    .child(icon(ic, 14.0, gpui::rgba(0xffffffd0)))
            };
            row = row
                .child(div().flex_grow().min_w_0().px_2().truncate().text_color(gpui::rgba(0xffffffd0)).child(format!(
                    "{} / {}",
                    pane.pos + 1,
                    pane.items.len()
                )))
                .child(
                    div()
                        .flex()
                        .flex_row()
                        .flex_none()
                        .items_center()
                        .gap_1()
                        .px_1()
                        .h(px(30.0))
                        .rounded_full()
                        .bg(gpui::rgba(0xffffff12))
                        .child(step_btn(format!("slower-{ix}").into(), Icon::Minus).on_click(cx.listener(
                            move |this, _, _, cx| {
                                this.panes[ix].step_interval(-1);
                                cx.notify();
                            },
                        )))
                        .child(icon(Icon::Timer, 14.0, gpui::rgba(0xffffffb0)))
                        .child(div().w(px(36.0)).text_center().child(tf("pane.secs", &[("n", secs.to_string())])))
                        .child(step_btn(format!("faster-{ix}").into(), Icon::Plus).on_click(cx.listener(
                            move |this, _, _, cx| {
                                this.panes[ix].step_interval(1);
                                cx.notify();
                            },
                        ))),
                );
        }

        let fav = pane.current().is_some_and(|i| self.lib.is_favorite(i));
        row = row
            .child(
                toggle_btn(format!("fav-{ix}").into(), if fav { Icon::HeartFill } else { Icon::Heart }, fav).on_click(
                    cx.listener(move |this, _, _, cx| {
                        if let Some(i) = this.panes[ix].current() {
                            this.toggle_favorite(i, cx);
                        }
                    }),
                ),
            )
            .child(toggle_btn(format!("shuffle-{ix}").into(), Icon::Shuffle, pane.shuffle).on_click(cx.listener(
                move |this, _, _, cx| {
                    this.panes[ix].shuffle ^= true;
                    cx.notify();
                },
            )))
            .child(toggle_btn(format!("slides-{ix}").into(), Icon::Slideshow, pane.slideshow).on_click(cx.listener(
                move |this, _, _, cx| {
                    this.panes[ix].toggle_slideshow();
                    cx.notify();
                },
            )));
        if !is_video {
            row = row.child(toggle_btn(format!("fade-{ix}").into(), Icon::Fade, self.fade).on_click(cx.listener(
                |this, _, _, cx| {
                    this.fade ^= true;
                    cx.notify();
                },
            )));
        }
        let has_tracks = pane.tracks.iter().filter(|t| t.kind == TrackKind::Audio).count() > 1
            || pane.tracks.iter().any(|t| t.kind == TrackKind::Sub);
        if is_video && has_tracks {
            let open = self.track_menu == Some(ix);
            row = row.child(toggle_btn(format!("tracks-{ix}").into(), Icon::Captions, open).on_click(cx.listener(
                move |this, _, _, cx| {
                    this.track_menu = if this.track_menu == Some(ix) { None } else { Some(ix) };
                    cx.notify();
                },
            )));
        }
        if is_video {
            let muted = ix != self.focused || pane.volume <= 0.0;
            row = row
                .child(div().flex_none().pl_1().child(icon(
                    if muted { Icon::Mute } else { Icon::Volume },
                    17.0,
                    gpui::rgba(0xffffffd0),
                )))
                .child(div().flex_none().w(px(72.0)).child(self.slider(
                    format!("vol-{ix}").into(),
                    pane.volume / 100.0,
                    SliderStyle::on_glass(),
                    None,
                    cx,
                    move |this, f| this.panes[ix].set_volume(f * 100.0),
                )));
        }

        div()
            .absolute()
            .left(px(pill_left))
            .top(px(pill_top))
            .w(px(pill_w))
            .h(px(PILL_H))
            .rounded_full()
            .bg(glass_fallback())
            .border_1()
            .border_color(glass_edge())
            .shadow(vec![gpui::BoxShadow {
                color: gpui::rgba(0x00000066).into(),
                offset: gpui::point(px(0.0), px(8.0)),
                blur_radius: px(24.0),
                spread_radius: px(0.0),
            }])
            .when(!self.controls_visible(ix), |d| d.opacity(0.0))
            .children(blur)
            // Tint plus a light rim along the top edge, like curved glass.
            .child(div().absolute().top_0().left_0().size_full().rounded_full().bg(glass_tint()))
            .child(div().absolute().top_0().left_0().size_full().rounded_full().bg(gpui::linear_gradient(
                180.0,
                gpui::linear_color_stop(gpui::rgba(0xffffff2a), 0.0),
                gpui::linear_color_stop(gpui::rgba(0xffffff00), 0.55),
            )))
            .child(row)
            .children((self.track_menu == Some(ix) && is_video).then(|| self.track_menu_el(ix, cx)))
            .into_any_element()
    }

    /// The seek bar of video pane `ix`, with what was watched most, the
    /// chapters, and the frame under the pointer while it hovers.
    fn seek_bar(&self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
        let pane = &self.panes[ix];
        let (pos, dur) = pane.time;
        let bounds: Rc<Cell<Bounds<Pixels>>> = Rc::new(Cell::new(Bounds::default()));
        let b1 = bounds.clone();
        let at = move |x: Pixels| {
            let b = bounds.get();
            (f32::from(x - b.origin.x) / f32::from(b.size.width).max(1.0)).clamp(0.0, 1.0)
        };
        let preview = pane.seek_hover.filter(|_| dur > 0.0).map(|f| {
            div()
                .absolute()
                .bottom(px(30.0))
                .left(gpui::relative(f))
                .ml(px(-PREVIEW_W / 2.0 - 4.0))
                .p_1()
                .flex()
                .flex_col()
                .items_center()
                .gap_1()
                .rounded(px(theme::RADIUS))
                .bg(gpui::rgba(0x1c1c21f2))
                .border_1()
                .border_color(theme::glass_edge())
                .shadow_lg()
                .children(pane.preview.as_ref().map(|(_, image)| {
                    let sz = image.size(0);
                    let (w, h) = (i32::from(sz.width).max(1) as f32, i32::from(sz.height).max(1) as f32);
                    img(image.clone()).w(px(PREVIEW_W)).h(px(PREVIEW_W * h / w)).rounded(px(theme::R_SMALL))
                }))
                .child(div().text_xs().text_color(gpui::white()).child(clock(f as f64 * dur)))
        });
        div()
            .id(("seek-wrap", ix))
            .relative()
            .flex_grow()
            .min_w(px(40.0))
            .mx_1()
            .child(canvas(move |b, _, _| b1.set(b), |_, _, _, _| {}).absolute().size_full())
            .child(self.slider(
                format!("seek-{ix}").into(),
                if dur > 0.0 { pos / dur } else { 0.0 },
                SliderStyle::on_glass(),
                Some(seek_marks(pane.current().and_then(|i| self.lib.heat_profile(i)), &pane.chapters, dur)),
                cx,
                move |this, f| this.seek_pane(ix, f),
            ))
            .children(preview)
            .on_mouse_move(cx.listener(move |this, ev: &MouseMoveEvent, _, cx| {
                this.hover_seek(ix, Some(at(ev.position.x)), cx);
            }))
            .on_hover(cx.listener(move |this, hovered: &bool, _, cx| {
                if !*hovered {
                    this.hover_seek(ix, None, cx);
                }
            }))
            .into_any_element()
    }

    /// The audio and subtitle list, above the controls.
    fn track_menu_el(&self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
        let tracks = &self.panes[ix].tracks;
        let row = |id: SharedString, label: String, on: bool| {
            div()
                .id(id)
                .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(on, |d| d.child(icon(Icon::Check, 14.0, theme::accent()))))
                .child(
                    div()
                        .flex_grow()
                        .min_w_0()
                        .truncate()
                        .text_color(if on { theme::text() } else { theme::text_dim() })
                        .child(label),
                )
        };
        let heading =
            |k: &'static str| div().px_2().pt_1().pb_0p5().text_xs().text_color(theme::text_faint()).child(t(k));
        let mut menu = div()
            .id(("track-menu", ix))
            .occlude()
            .absolute()
            .right(px(48.0))
            .bottom(px(PILL_H + 8.0))
            .w(px(240.0))
            .max_h(px(320.0))
            .overflow_y_scroll()
            .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, _, _, cx| {
                this.track_menu = None;
                cx.notify();
            }));
        let audio: Vec<&Track> = tracks.iter().filter(|t| t.kind == TrackKind::Audio).collect();
        if audio.len() > 1 {
            menu = menu.child(heading("tracks.audio"));
            for t in audio {
                let id = t.id;
                menu =
                    menu.child(row(format!("aid-{ix}-{id}").into(), track_label(t), t.selected).on_click(
                        cx.listener(move |this, _, _, cx| this.set_track(ix, TrackKind::Audio, Some(id), cx)),
                    ));
            }
        }
        let subs: Vec<&Track> = tracks.iter().filter(|t| t.kind == TrackKind::Sub).collect();
        if !subs.is_empty() {
            let none_on = !subs.iter().any(|t| t.selected);
            menu = menu.child(heading("tracks.subs")).child(
                row(format!("sid-{ix}-off").into(), t("tracks.off").to_string(), none_on)
                    .on_click(cx.listener(move |this, _, _, cx| this.set_track(ix, TrackKind::Sub, None, cx))),
            );
            for t in subs {
                let id = t.id;
                menu = menu.child(
                    row(format!("sid-{ix}-{id}").into(), track_label(t), t.selected)
                        .on_click(cx.listener(move |this, _, _, cx| this.set_track(ix, TrackKind::Sub, Some(id), cx))),
                );
            }
        }
        menu.into_any_element()
    }

    /// A horizontal slider (seek or volume). `on_set` gets 0..=1 on click
    /// and while dragging.
    pub(crate) fn slider(
        &self,
        id: SharedString,
        value: f64,
        style: SliderStyle,
        under: Option<AnyElement>,
        cx: &mut Context<Self>,
        on_set: impl Fn(&mut Self, f64) + Clone + 'static,
    ) -> AnyElement {
        let value = value.clamp(0.0, 1.0) as f32;
        let bounds: Rc<Cell<Bounds<Pixels>>> = Rc::new(Cell::new(Bounds::default()));
        let b1 = bounds.clone();
        let b2 = bounds.clone();
        let b3 = bounds.clone();
        let set_down = on_set.clone();
        let frac = move |b: &Rc<Cell<Bounds<Pixels>>>, x: Pixels| -> f64 {
            let b = b.get();
            let w = f32::from(b.size.width).max(1.0);
            (f32::from(x - b.origin.x) / w).clamp(0.0, 1.0) as f64
        };
        div()
            .id(id)
            .relative()
            .h(px(24.0))
            .w_full()
            .flex()
            .items_center()
            .cursor_pointer()
            .child(canvas(move |b, _, _| b1.set(b), |_, _, _, _| {}).absolute().size_full())
            .children(under)
            .child(div().relative().w_full().h(px(4.0)).rounded_full().bg(style.track).child(
                div().absolute().left_0().top_0().h_full().rounded_full().bg(style.fill).w(gpui::relative(value)),
            ))
            .child(
                div()
                    .absolute()
                    .left(gpui::relative(value))
                    .ml(px(-6.0))
                    .size(px(12.0))
                    .rounded_full()
                    .bg(style.knob)
                    .shadow_sm(),
            )
            .on_mouse_down(
                MouseButton::Left,
                cx.listener(move |this, ev: &MouseDownEvent, _, cx| {
                    set_down(this, frac(&b2, ev.position.x));
                    cx.stop_propagation();
                    cx.notify();
                }),
            )
            .on_mouse_move(cx.listener(move |this, ev: &MouseMoveEvent, _, cx| {
                if ev.pressed_button == Some(MouseButton::Left) {
                    on_set(this, frac(&b3, ev.position.x));
                    cx.notify();
                }
            }))
            .into_any_element()
    }

    pub(crate) fn seek_pane(&mut self, ix: usize, f: f64) {
        let p = &mut self.panes[ix];
        let dur = p.time.1;
        if let Some(v) = &p.video
            && dur > 0.0
        {
            v.seek_to(f * dur);
            p.time.0 = f * dur;
        }
    }
}

fn focus_ring() -> gpui::Div {
    div().absolute().top_0().left_0().size_full().border_2().border_color(theme::accent())
}

/// Width of the frame shown over the seek bar.
const PREVIEW_W: f32 = 168.0;

/// What sits on the seek bar besides the position: the parts watched most,
/// as a soft ridge just above it (one column per stretch, its height the
/// share of the most watched), and a notch where each chapter starts.
fn seek_marks(profile: Option<Vec<f32>>, chapters: &[f64], dur: f64) -> AnyElement {
    let ridge = profile.map(|p| {
        div()
            .absolute()
            .left_0()
            .bottom(px(14.0))
            .w_full()
            .h(px(9.0))
            .flex()
            .flex_row()
            .items_end()
            .children(p.into_iter().map(|v| div().flex_1().h(px(9.0 * v.max(0.08))).bg(gpui::rgba(0xffffff73))))
    });
    let notches = chapters.iter().filter(|&&t| dur > 0.0 && t > 0.0 && t < dur).map(|&t| {
        div()
            .absolute()
            .top(px(8.0))
            .left(gpui::relative((t / dur) as f32))
            .w(px(2.0))
            .h(px(8.0))
            .rounded_full()
            .bg(gpui::rgba(0x000000d0))
    });
    div().absolute().top_0().left_0().size_full().children(ridge).children(notches).into_any_element()
}

/// A track's name as the file gives it: its title, its language, or both.
fn track_label(tr: &Track) -> String {
    let lang = tr.lang.as_deref().map(language_name);
    match (&tr.title, lang) {
        (Some(title), Some(lang)) => format!("{title} ({lang})"),
        (Some(title), None) => title.clone(),
        (None, Some(lang)) => lang,
        (None, None) => tf("tracks.n", &[("n", tr.id.to_string())]),
    }
}

/// A language tag (ISO 639-1 or -2, as files carry them) as the language
/// calls itself; unknown tags as they are.
fn language_name(code: &str) -> String {
    let name = match code.to_ascii_lowercase().as_str() {
        "en" | "eng" => "English",
        "ja" | "jpn" => "日本語",
        "de" | "ger" | "deu" => "Deutsch",
        "es" | "spa" => "Español",
        "fr" | "fre" | "fra" => "Français",
        "it" | "ita" => "Italiano",
        "ko" | "kor" => "한국어",
        "pt" | "por" => "Português",
        "ru" | "rus" => "Русский",
        "zh" | "chi" | "zho" => "中文",
        "nl" | "dut" | "nld" => "Nederlands",
        "sv" | "swe" => "Svenska",
        "pl" | "pol" => "Polski",
        "tr" | "tur" => "Türkçe",
        "ar" | "ara" => "العربية",
        "hi" | "hin" => "हिन्दी",
        "th" | "tha" => "ไทย",
        "und" => return t("tracks.unknown").to_string(),
        _ => code,
    };
    name.to_string()
}

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

    fn track(id: i64, lang: Option<&str>, title: Option<&str>) -> Track {
        Track {
            kind: TrackKind::Audio,
            id,
            lang: lang.map(String::from),
            title: title.map(String::from),
            selected: false,
        }
    }

    #[test]
    fn tracks_are_named_by_title_and_language() {
        assert_eq!(track_label(&track(1, Some("jpn"), None)), "日本語");
        assert_eq!(track_label(&track(2, Some("en"), Some("Commentary"))), "Commentary (English)");
        assert_eq!(track_label(&track(3, Some("xyz"), None)), "xyz");
        assert_eq!(track_label(&track(4, None, Some("Director"))), "Director");
    }
}