use gpui::{
AnyElement, App, Bounds, Context, Entity, MouseButton, ResizeEdge, Window, WindowBounds, WindowDecorations,
WindowHandle, WindowOptions, div, prelude::*, px, size,
};
use crate::app::{CONTROLS_IDLE, Rosier};
use crate::assets::Icon;
use crate::pane;
use crate::ui::icon;
pub const TITLE: &str = "Rosier PiP";
pub struct PipView {
rosier: Entity<Rosier>,
hovered: bool,
moved_at: std::time::Instant,
}
impl PipView {
fn new(rosier: Entity<Rosier>, cx: &mut Context<Self>) -> Self {
cx.observe(&rosier, |_, _, cx| cx.notify()).detach();
let r = rosier.clone();
cx.on_release(move |_, app| {
let r = r.clone();
app.defer(move |app| {
r.update(app, |this, cx| {
this.pip = None;
cx.notify();
});
});
})
.detach();
cx.spawn(async move |this, cx| {
loop {
cx.background_executor().timer(std::time::Duration::from_millis(300)).await;
let alive = this
.update(cx, |this, cx| {
if this.hovered && this.moved_at.elapsed() >= CONTROLS_IDLE {
cx.notify();
}
})
.is_ok();
if !alive {
break;
}
}
})
.detach();
PipView { rosier, hovered: false, moved_at: std::time::Instant::now() }
}
}
impl Render for PipView {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let vp = window.viewport_size();
let (w, h) = (f32::from(vp.width), f32::from(vp.height));
let r = self.rosier.read(cx);
let (cols, rows) = pane::layout(r.split, r.split_side);
let (pw, ph) = (w / cols as f32, h / rows as f32);
let n_panes = r.panes.len();
let focused = r.focused;
let playing = r.panes.get(focused).is_some_and(pane::Pane::playing);
let mut grid_rows = Vec::new();
for row in 0..rows {
let mut cells: Vec<AnyElement> = Vec::new();
for col in 0..cols {
let ix = row * cols + col;
let frame = r.panes.get(ix).and_then(|p| p.frame.clone());
let media = frame.map(|f| {
let sz = f.size(0);
let (x, y, dw, dh) =
pane::fit_rect(i32::from(sz.width) as f32, i32::from(sz.height) as f32, pw, ph);
crate::ui::media(&f).left(px(x)).top(px(y)).w(px(dw)).h(px(dh))
});
cells.push(
div()
.relative()
.flex_none()
.w(px(pw))
.h(px(ph))
.overflow_hidden()
.bg(gpui::black())
.when(cols * rows > 1, |d| d.border_1().border_color(gpui::rgba(0x0e0e10ff)))
.children(media)
.into_any_element(),
);
}
grid_rows.push(div().flex().flex_row().children(cells));
}
let show_bar = self.hovered && self.moved_at.elapsed() < CONTROLS_IDLE;
let rosier = self.rosier.clone();
let act = move |f: fn(&mut Rosier, usize, &mut Context<Rosier>)| {
let rosier = rosier.clone();
move |_: &gpui::ClickEvent, _: &mut Window, app: &mut App| {
rosier.update(app, |this, cx| {
let ix = this.focused;
f(this, ix, cx);
cx.notify();
});
}
};
let round = |id: &'static str, ic: Icon| {
div()
.id(id)
.size(px(28.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded_full()
.cursor_pointer()
.hover(|s| s.bg(gpui::rgba(0xffffff24)))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.child(icon(ic, 15.0, gpui::white()))
};
let pane_buttons = (n_panes > 1).then(|| {
div().flex().flex_row().gap_0p5().children((0..n_panes).map(|k| {
let rosier = self.rosier.clone();
div()
.id(("pip-pane", k))
.size(px(22.0))
.flex()
.items_center()
.justify_center()
.rounded_full()
.text_xs()
.cursor_pointer()
.when(k == focused, |d| d.bg(gpui::rgba(0xffffff30)).text_color(gpui::white()))
.when(k != focused, |d| {
d.text_color(gpui::rgba(0xffffffa0)).hover(|s| s.bg(gpui::rgba(0xffffff18)))
})
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(move |_, _, app| {
rosier.update(app, |this, cx| {
this.set_focus(k);
cx.notify();
});
})
.child((k + 1).to_string())
}))
});
let bar = crate::ui::glass(20.0)
.absolute()
.bottom(px(8.0))
.left(px(8.0))
.right(px(8.0))
.h(px(40.0))
.bg(gpui::rgba(0x16161ab8))
.flex()
.flex_row()
.items_center()
.justify_center()
.gap_1()
.px_2()
.when(!show_bar, |d| d.opacity(0.0))
.child(crate::ui::glass_sheen(20.0))
.child(round("pip-prev", Icon::Prev).on_click(act(|this, ix, cx| this.advance(ix, -1, cx))))
.child(
round("pip-play", if playing { Icon::Pause } else { Icon::Play })
.on_click(act(|this, ix, _| this.panes[ix].play_pause())),
)
.child(round("pip-next", Icon::Next).on_click(act(|this, ix, cx| this.advance(ix, 1, cx))))
.children(pane_buttons.map(|b| {
div()
.flex()
.flex_row()
.items_center()
.gap_1()
.child(div().w(px(1.0)).h(px(16.0)).bg(gpui::rgba(0xffffff20)))
.child(b)
}))
.child(div().w(px(1.0)).h(px(16.0)).bg(gpui::rgba(0xffffff20)))
.child(round("pip-library", Icon::Library).on_click({
let rosier = self.rosier.clone();
move |_, _, app| rosier.update(app, |this, cx| this.show_library_for_pip(cx))
}));
let close = div()
.absolute()
.top(px(8.0))
.right(px(8.0))
.rounded_full()
.bg(gpui::rgba(0x16161ab8))
.border_1()
.border_color(gpui::rgba(0xffffff1f))
.when(!show_bar, |d| d.opacity(0.0))
.child(round("pip-exit", Icon::Close).on_click(|_, window, _| window.remove_window()));
div()
.id("pip")
.group("pip")
.cursor(if show_bar || !self.hovered { gpui::CursorStyle::Arrow } else { gpui::CursorStyle::None })
.on_hover(cx.listener(|this, hovered: &bool, _, cx| {
this.hovered = *hovered;
this.moved_at = std::time::Instant::now();
cx.notify();
}))
.on_mouse_move(cx.listener(|this, _: &gpui::MouseMoveEvent, _, cx| {
let was = this.hovered && this.moved_at.elapsed() < CONTROLS_IDLE;
this.hovered = true;
this.moved_at = std::time::Instant::now();
if !was {
cx.notify();
}
}))
.relative()
.size_full()
.flex()
.flex_col()
.bg(gpui::black())
.children(grid_rows)
.on_mouse_down(MouseButton::Left, |_, window, _| window.start_window_move())
.on_click(|ev, window, _| {
if ev.click_count() == 2 {
window.remove_window();
}
})
.child(
div()
.id("pip-resize")
.absolute()
.right_0()
.bottom_0()
.size(px(18.0))
.cursor(gpui::CursorStyle::ResizeUpLeftDownRight)
.on_mouse_down(MouseButton::Left, |_, window, cx| {
cx.stop_propagation();
window.start_window_resize(ResizeEdge::BottomRight);
}),
)
.child(bar)
.child(close)
}
}
pub fn open(rosier: Entity<Rosier>, cx: &mut App) -> Option<WindowHandle<PipView>> {
let bounds = Bounds::centered(None, size(px(512.0), px(288.0)), cx);
let handle = cx
.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
titlebar: Some(gpui::TitlebarOptions { title: Some(TITLE.into()), ..Default::default() }),
window_decorations: Some(WindowDecorations::Client),
app_id: Some("rosier".into()),
window_min_size: Some(size(px(192.0), px(108.0))),
..Default::default()
},
|_, cx| cx.new(|cx| PipView::new(rosier, cx)),
)
.ok()?;
pin_on_kde();
Some(handle)
}
fn pin_on_kde() {
let kde = std::env::var("XDG_CURRENT_DESKTOP").is_ok_and(|d| d.to_ascii_uppercase().contains("KDE"));
if !kde {
return;
}
std::thread::spawn(|| {
std::thread::sleep(std::time::Duration::from_millis(400));
let script = format!(
"for (const w of workspace.windowList()) {{ if (w.caption === {TITLE:?}) {{ w.keepAbove = true; w.onAllDesktops = true; w.skipTaskbar = true; }} }}"
);
let path = std::env::temp_dir().join(format!("rosier-pip-{}.js", std::process::id()));
if std::fs::write(&path, script).is_err() {
return;
}
let call = |object: &str, method: &str, args: &[&str]| {
std::process::Command::new("gdbus")
.args(["call", "--session", "--dest", "org.kde.KWin", "--object-path", object, "--method", method])
.args(args)
.output()
.ok()
.filter(|o| o.status.success())
.map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
};
let name = "rosier-pip";
let _ = call("/Scripting", "org.kde.kwin.Scripting.unloadScript", &[name]);
let path_s = path.to_string_lossy().into_owned();
if let Some(out) = call("/Scripting", "org.kde.kwin.Scripting.loadScript", &[&path_s, name]) {
let id: String = out.chars().filter(|c| c.is_ascii_digit()).collect();
if !id.is_empty() {
let _ = call(&format!("/Scripting/Script{id}"), "org.kde.kwin.Script.run", &[]);
}
}
let _ = std::fs::remove_file(&path);
});
}