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;
#[derive(Clone, Copy)]
pub(crate) struct SliderStyle {
pub track: gpui::Rgba,
pub fill: gpui::Rgba,
knob: gpui::Rgba,
}
impl SliderStyle {
fn on_glass() -> Self {
SliderStyle { track: gpui::rgba(0xffffff40), fill: gpui::rgba(0xffffffff), knob: gpui::rgba(0xffffffff) }
}
pub fn on_chrome() -> Self {
SliderStyle { track: theme::raised_hover(), fill: theme::accent(), knob: gpui::rgba(0xf4f4f8ff) }
}
}
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 {
gpui::rgba(0x0c0c1038)
}
fn glass_edge() -> gpui::Rgba {
gpui::rgba(0xffffff3a)
}
fn glass_fallback() -> gpui::Rgba {
gpui::rgba(0x1c1c22c0)
}
impl Rosier {
fn info_panel(&self, ix: usize, w: f32) -> Option<AnyElement> {
let pane = &self.panes[ix];
let i = pane.current().filter(|_| self.show_info && pane.video.is_none())?;
let e = self.lib.entries.get(i)?;
let exif = pane.info.as_ref().filter(|(at, _)| *at == i).map(|(_, info)| info.clone()).unwrap_or_default();
let name = e.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let folder = e.path.parent().map(|p| p.display().to_string());
let (fw, fh) = pane.full;
let size = if fw > 0 {
format!("{fw} × {fh} · {}", crate::i18n::human_size(e.size))
} else {
crate::i18n::human_size(e.size)
};
let rows = [
(t("info.camera"), exif.camera),
(t("info.lens"), exif.lens),
(t("info.exposure"), exif.exposure),
(t("info.taken"), exif.taken),
];
let line = |label: SharedString, value: String| {
div()
.flex()
.flex_col()
.gap_0p5()
.child(div().text_xs().text_color(gpui::rgba(0xffffff90)).child(label))
.child(div().text_sm().text_color(gpui::white()).child(value))
};
Some(
crate::ui::glass(theme::R_PANEL)
.absolute()
.top(px(10.0))
.right(px(10.0))
.w(px(260.0f32.min(w - 20.0).max(120.0)))
.p_3()
.flex()
.flex_col()
.gap_2()
.child(crate::ui::glass_sheen(theme::R_PANEL))
.child(div().text_sm().text_color(gpui::white()).child(name))
.children(folder.map(|f| div().text_xs().text_color(gpui::rgba(0xffffff90)).child(f)))
.child(div().text_xs().text_color(gpui::rgba(0xffffffc0)).child(size))
.children(rows.into_iter().filter_map(|(label, v)| v.map(|v| line(label.into(), v))))
.into_any_element(),
)
}
fn star_row(&self, ix: usize, stars: u8, cx: &mut Context<Self>) -> AnyElement {
div()
.flex_none()
.flex()
.flex_row()
.items_center()
.px_1()
.children((1..=5u8).map(|n| {
let lit = n <= stars;
div()
.id(SharedString::from(format!("star-{ix}-{n}")))
.size(px(22.0))
.flex()
.items_center()
.justify_center()
.rounded_full()
.cursor_pointer()
.hover(|s| s.bg(gpui::rgba(0xffffff30)))
.child(icon(
if lit { Icon::StarFill } else { Icon::Star },
15.0,
if lit { theme::star() } else { gpui::rgba(0xffffffa0) },
))
.on_click(cx.listener(move |this, _, _, cx| {
if let Some(i) = this.panes[ix].current() {
let now = this.lib.rating(i);
this.set_rating(i, if now == n { 0 } else { n }, cx);
}
}))
}))
.into_any_element()
}
pub(crate) fn render_split(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
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);
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);
let rect = (col as f32 * pane_w, row as f32 * pane_h, pane_w, pane_h);
let resized = (p.rect.2, p.rect.3, p.px_size) != (rect.2, rect.3, phys);
p.rect = rect;
p.px_size = phys;
if resized && p.wants_detail() {
cx.defer_in(window, move |this, _, cx| this.update_detail(ix, cx));
}
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));
}
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)
.tooltip(crate::ui::tip(t([
"tip.split1",
"tip.split2stacked",
"tip.split2side",
"tip.split4",
][k])))
.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);
}))
}),
),
)
.when(self.split > 1, |d| {
d.child(
button("split-sync")
.tooltip(crate::ui::tip(t("help.syncview")))
.child(icon(Icon::Link, 16.0, if self.sync_view { theme::accent() } else { theme::text_dim() }))
.on_click(cx.listener(|this, _, _, cx| this.toggle_sync_view(cx))),
)
})
.child(div().w(px(1.0)).h(px(20.0)).bg(theme::line()))
.child(
button("split-pip")
.tooltip(crate::ui::tip(t("help.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")
.tooltip(crate::ui::tip(t("help.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())
.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())
.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| {
if ev.click_count() == 2 {
window.toggle_fullscreen();
cx.notify();
}
}))
.on_scroll_wheel(cx.listener(move |this, ev: &gpui::ScrollWheelEvent, _, cx| {
if ev.modifiers.control || ev.modifiers.platform {
let dy = f32::from(ev.delta.pixel_delta(px(20.0)).y);
if dy == 0.0 || this.panes[ix].video.is_some() {
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);
return;
}
let n = notches(&mut this.wheel_rest, &ev.delta);
if n != 0 {
this.advance(ix, -n as isize, 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));
this.update_detail(ix, cx);
this.mirror_view(ix, cx);
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();
}
if let Some(frame) = &pane.frame {
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.base(i32::from(sz.width) as f32, i32::from(sz.height) as f32);
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.base(i32::from(sz.width) as f32, i32::from(sz.height) as f32);
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))),
);
if let Some((detail, n)) = pane.detail.as_ref().filter(|_| pane.wants_detail()) {
root = root.child(
img(detail.clone())
.absolute()
.left(px(ox + n[0] * dw))
.top(px(oy + n[1] * dh))
.w(px((n[2] - n[0]) * dw))
.h(px((n[3] - n[1]) * dh)),
);
}
} 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),
);
}
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}", counter(pane)))),
);
if let Some(panel) = self.info_panel(ix, w) {
root = root.child(panel);
}
root = root.child(self.glass_controls(ix, w, h, cx));
root.children(focused.then(focus_ring)).into_any_element()
}
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();
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 shown = self.controls_visible(ix);
let round_btn = |id: SharedString, ic: Icon, size: f32, tip: &'static str| {
div()
.id(id)
.when(shown, |d| d.tooltip(crate::ui::tip(t(tip))))
.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, tip: &'static str| {
div()
.id(id)
.when(shown, |d| d.tooltip(crate::ui::tip(t(tip))))
.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, "tip.prev")
.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,
"help.play",
)
.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, "tip.next")
.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)))
.children((pane.speed != 1.0).then(|| div().flex_none().text_sm().child(format!("{}×", pane.speed))));
} else {
let secs = pane.interval.as_secs();
let step_btn = |id: SharedString, ic: Icon, tip: &'static str| {
div()
.id(id)
.when(shown, |d| d.tooltip(crate::ui::tip(t(tip))))
.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(counter(pane)),
)
.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, "help.interval").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, "help.interval").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,
"help.fav",
)
.on_click(cx.listener(move |this, _, _, cx| {
if let Some(i) = this.panes[ix].current() {
this.toggle_favorite(i, cx);
}
})),
)
.children(pane.current().map(|i| self.star_row(ix, self.lib.rating(i), cx)))
.children((!is_video).then(|| {
toggle_btn(format!("lock-{ix}").into(), Icon::Lock, pane.lock_view, "help.lockview")
.on_click(cx.listener(move |this, _, _, cx| this.toggle_lock_view(ix, cx)))
}))
.children((!is_video).then(|| {
toggle_btn(format!("info-{ix}").into(), Icon::Info, self.show_info, "help.info")
.on_click(cx.listener(|this, _, _, cx| this.toggle_info(cx)))
}))
.child(toggle_btn(format!("fit-{ix}").into(), Icon::Fit, self.fit_menu == Some(ix), "tip.fit").on_click(
cx.listener(move |this, ev: &gpui::ClickEvent, _, cx| {
this.toggle_menu(ev, ix, |r| &mut r.fit_menu, cx);
}),
))
.children((!is_video).then(|| {
let on = pane.layout.is_some() || self.book_menu == Some(ix);
toggle_btn(format!("book-{ix}").into(), Icon::Book, on, "tip.book").on_click(cx.listener(
move |this, ev: &gpui::ClickEvent, _, cx| {
this.toggle_menu(ev, ix, |r| &mut r.book_menu, cx);
},
))
}))
.child(toggle_btn(format!("shuffle-{ix}").into(), Icon::Shuffle, pane.shuffle, "help.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, "tip.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, "tip.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, "tip.tracks").on_click(
cx.listener(move |this, ev: &gpui::ClickEvent, _, cx| {
this.toggle_menu(ev, ix, |r| &mut r.track_menu, cx);
}),
));
}
if is_video {
let muted = pane.muted || pane.volume <= 0.0;
row = row
.child(
toggle_btn(
format!("mute-{ix}").into(),
if muted { Icon::Mute } else { Icon::Volume },
false,
"help.mute",
)
.on_click(cx.listener(move |this, _, _, cx| this.toggle_mute(ix, cx))),
)
.child(
div()
.id(("vol-wrap", ix))
.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),
))
.on_scroll_wheel(cx.listener(move |this, ev: &gpui::ScrollWheelEvent, _, cx| {
cx.stop_propagation();
let n = notches(&mut this.wheel_rest, &ev.delta);
if n != 0 {
let p = &mut this.panes[ix];
p.set_volume(p.volume + 5.0 * n as f64);
cx.notify();
}
})),
);
}
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)
.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)))
.children((self.fit_menu == Some(ix)).then(|| self.fit_menu_el(ix, cx)))
.children((self.book_menu == Some(ix) && !is_video).then(|| self.book_menu_el(ix, cx)))
.into_any_element()
}
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);
}
}))
.on_scroll_wheel(cx.listener(move |this, ev: &gpui::ScrollWheelEvent, _, cx| {
cx.stop_propagation();
let n = notches(&mut this.wheel_rest, &ev.delta);
if n != 0 {
this.seek_pane_by(ix, 5.0 * n as f64);
cx.notify();
}
}))
.into_any_element()
}
fn fit_menu_el(&self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
let current = self.panes[ix].fit;
self.menu_panel("fit-menu", ix, 220.0, cx, |this| this.fit_menu = None)
.children(pane::Fit::ALL.into_iter().map(|f| {
let label = t(match f {
pane::Fit::Contain => "fit.contain",
pane::Fit::Cover => "fit.cover",
pane::Fit::Stretch => "fit.stretch",
pane::Fit::Actual => "fit.actual",
});
menu_row(format!("fit-{ix}-{}", f.key()).into(), label.to_string(), f == current)
.on_click(cx.listener(move |this, _, _, cx| this.set_fit(ix, f, cx)))
}))
.into_any_element()
}
fn menu_panel(
&self,
id: &'static str,
ix: usize,
w: f32,
cx: &mut Context<Self>,
close: fn(&mut Self),
) -> gpui::Stateful<gpui::Div> {
div()
.id((id, ix))
.occlude()
.absolute()
.right(px(48.0))
.bottom(px(PILL_H + 8.0))
.w(px(w))
.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(move |this, ev, _, cx| {
this.menu_closed_by(ev);
close(this);
cx.notify();
}))
}
fn book_menu_el(&self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
use crate::book::Layout;
let pane = &self.panes[ix];
let cur = pane.layout;
let base = cur.unwrap_or_default();
let mut rows: Vec<(&str, bool, Option<Layout>)> = Vec::new();
if pane.book.is_none() {
rows.push(("book.off", cur.is_none(), None));
}
rows.extend([
("book.single", cur.is_some_and(|l| !l.spread), Some(Layout { spread: false, ..base })),
("book.spread", cur.is_some_and(|l| l.spread), Some(Layout { spread: true, ..base })),
("book.rtl", cur.is_some_and(|l| l.rtl), Some(Layout { rtl: true, ..base })),
("book.ltr", cur.is_some_and(|l| !l.rtl), Some(Layout { rtl: false, ..base })),
]);
self.menu_panel("book-menu", ix, 220.0, cx, |this| this.book_menu = None)
.children(rows.into_iter().map(|(key, on, layout)| {
menu_row(format!("{key}-{ix}").into(), t(key).to_string(), on).on_click(cx.listener(
move |this, _, _, cx| {
this.book_menu = None;
this.set_layout(ix, layout, cx);
},
))
}))
.into_any_element()
}
fn track_menu_el(&self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
let tracks = &self.panes[ix].tracks;
let row = menu_row;
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 = self
.menu_panel("track-menu", ix, 240.0, cx, |this| this.track_menu = None)
.max_h(px(320.0))
.overflow_y_scroll();
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()
}
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()
}
fn seek_pane_by(&mut self, ix: usize, secs: f64) {
let p = &mut self.panes[ix];
let (pos, dur) = p.time;
if let Some(v) = &p.video {
v.seek(secs);
p.time.0 = (pos + secs).clamp(0.0, dur.max(0.0));
}
}
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 menu_row(id: SharedString, label: String, on: bool) -> gpui::Stateful<gpui::Div> {
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),
)
}
fn counter(pane: &pane::Pane) -> String {
let (start, n) = match &pane.book {
Some((_, pages)) => (pane.page, pages.len()),
None => (pane.pos, pane.items.len()),
};
match pane.layout.map(|l| l.view(start, n)) {
Some(v) if v.len() == 2 => format!("{}-{} / {n}", v[0] + 1, v[1] + 1),
_ => format!("{} / {n}", start + 1),
}
}
pub(crate) fn notches(rest: &mut f32, delta: &gpui::ScrollDelta) -> i32 {
match delta {
gpui::ScrollDelta::Lines(p) => {
*rest = 0.0;
if p.y > 0.0 {
1
} else if p.y < 0.0 {
-1
} else {
0
}
}
gpui::ScrollDelta::Pixels(p) => {
*rest += f32::from(p.y);
let n = (*rest / WHEEL_NOTCH_PX).trunc();
*rest -= n * WHEEL_NOTCH_PX;
n as i32
}
}
}
const WHEEL_NOTCH_PX: f32 = 60.0;
fn focus_ring() -> gpui::Div {
div().absolute().top_0().left_0().size_full().border_2().border_color(theme::accent())
}
const PREVIEW_W: f32 = 168.0;
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()
}
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())]),
}
}
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::*;
#[test]
fn a_wheel_notch_is_one_step_and_touchpad_travel_adds_up() {
let mut rest = 0.0;
let lines = |y: f32| gpui::ScrollDelta::Lines(gpui::point(0.0, y));
let pixels = |y: f32| gpui::ScrollDelta::Pixels(gpui::point(px(0.0), px(y)));
assert_eq!(notches(&mut rest, &lines(3.0)), 1, "a notch is one step however many lines");
assert_eq!(notches(&mut rest, &lines(-1.0)), -1);
assert_eq!(notches(&mut rest, &lines(0.0)), 0);
assert_eq!(notches(&mut rest, &pixels(-25.0)), 0);
assert_eq!(notches(&mut rest, &pixels(-25.0)), 0);
assert_eq!(notches(&mut rest, &pixels(-25.0)), -1, "75 px make one notch");
assert_eq!(notches(&mut rest, &pixels(130.0)), 1, "-15 + 130 = 115: one notch, 55 left");
assert_eq!(notches(&mut rest, &pixels(70.0)), 2, "55 + 70 = 125: two");
}
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");
}
}