rosier 0.5.1

A fast picture and video viewer for large folders
//! Small building blocks shared by every screen, so glass, buttons and
//! controls look the same everywhere.

use gpui::{
    AnyElement, Div, ElementId, MouseButton, SharedString, Stateful, Svg, Window, div, linear_color_stop,
    linear_gradient, prelude::*, px, svg,
};

use crate::assets::Icon;
use crate::theme;

pub fn icon(i: Icon, size: f32, color: impl Into<gpui::Hsla>) -> Svg {
    svg().path(i.path()).size(px(size)).flex_none().text_color(color)
}

/// A floating glass panel: translucent fill, a bright rim, a sheen that
/// fades down from the top edge, and a soft shadow underneath. Children go
/// after `glass_sheen`, which the caller adds first so it sits behind them.
/// A picture or video frame, absolutely placed by the caller. An animation
/// gets an element id named after the image, which is what makes gpui play
/// its frames; a new image starts again from its first frame.
pub fn media(frame: &std::sync::Arc<gpui::RenderImage>) -> Div {
    let image = gpui::img(frame.clone()).size_full();
    let image = if frame.frame_count() > 1 {
        image.id(("anim", frame.id.0)).into_any_element()
    } else {
        image.into_any_element()
    };
    div().absolute().child(image)
}

pub fn glass(radius: f32) -> Div {
    div().relative().rounded(px(radius)).bg(theme::glass_fill()).border_1().border_color(theme::glass_edge()).shadow(
        vec![gpui::BoxShadow {
            color: gpui::rgba(0x00000059).into(),
            offset: gpui::point(px(0.0), px(8.0)),
            blur_radius: px(24.0),
            spread_radius: px(0.0),
        }],
    )
}

/// The sheen layer for a `glass` panel of the same radius.
pub fn glass_sheen(radius: f32) -> Div {
    div().absolute().top_0().left_0().size_full().rounded(px(radius)).bg(linear_gradient(
        180.0,
        linear_color_stop(theme::glass_sheen(), 0.0),
        linear_color_stop(gpui::rgba(0xffffff00), 0.45),
    ))
}

/// The one filled button on a screen: off-white with dark text.
pub fn primary_button(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Stateful<Div> {
    div()
        .id(id)
        .flex()
        .items_center()
        .justify_center()
        .gap_2()
        .h(px(40.0))
        .px_5()
        .rounded(px(theme::RADIUS + 2.0))
        .bg(theme::primary())
        .text_color(theme::on_primary())
        .text_sm()
        .font_weight(gpui::FontWeight::MEDIUM)
        .cursor_pointer()
        .hover(|s| s.bg(theme::primary_hover()))
        .child(label.into())
}

/// Quiet glass button for secondary actions.
pub fn button(id: impl Into<ElementId>) -> Stateful<Div> {
    div()
        .id(id)
        .flex()
        .flex_none()
        .items_center()
        .justify_center()
        .gap_2()
        .h(px(theme::CONTROL_H))
        .px_3()
        .rounded(px(theme::RADIUS))
        .text_sm()
        .text_color(theme::text_dim())
        .cursor_pointer()
        .hover(|s| s.bg(theme::raised_hover()).text_color(theme::text()))
}

/// One option in a segmented control. `active` draws it as brighter glass.
pub fn segment(id: impl Into<ElementId>, active: bool) -> Stateful<Div> {
    let base = div()
        .id(id)
        .flex()
        .items_center()
        .justify_center()
        .gap_1p5()
        .h(px(theme::CONTROL_H - 6.0))
        .px_3()
        .rounded(px(theme::R_SMALL))
        .text_xs()
        .cursor_pointer();
    if active {
        base.bg(theme::raised_active())
            .border_1()
            .border_color(theme::glass_edge())
            .text_color(theme::text())
            .font_weight(gpui::FontWeight::MEDIUM)
    } else {
        base.border_1()
            .border_color(gpui::rgba(0x00000000))
            .text_color(theme::text_dim())
            .hover(|s| s.text_color(theme::text()))
    }
}

/// Container that groups `segment`s into one glass pill.
/// A round button holding one icon, for the controls over a picture: a
/// `size` px circle that lightens under the pointer.
pub fn round_button(id: impl Into<ElementId>, size: f32) -> Stateful<Div> {
    div().id(id).size(px(size)).flex_none().flex().items_center().justify_center().rounded_full().cursor_pointer()
}

pub fn segmented() -> Div {
    div()
        .flex()
        .flex_row()
        .flex_none()
        .items_center()
        .gap_0p5()
        .p(px(2.0))
        .rounded(px(theme::RADIUS))
        .bg(theme::raised())
        .border_1()
        .border_color(theme::line())
}

/// rosier draws its own title bar on every system, so the window looks the
/// same everywhere instead of wearing each desktop's (KDE's was a light gray
/// strip over the dark window). On Linux the desktop is asked to leave it to
/// rosier; an X11 session without a compositor, or a Wayland compositor that
/// insists, keeps its own, and rosier then draws none (see `own_titlebar`).
/// macOS and Windows hide theirs through `TitlebarOptions::appears_transparent`.
pub fn decorations() -> gpui::WindowDecorations {
    gpui::WindowDecorations::Client
}

/// The title bar options for the main window: the system's is hidden and
/// rosier's drawn in its place. macOS keeps its traffic lights, set in the
/// middle of rosier's bar.
pub fn titlebar_options() -> gpui::TitlebarOptions {
    gpui::TitlebarOptions {
        title: Some(crate::i18n::t("app.title").into()),
        appears_transparent: true,
        traffic_light_position: Some(gpui::point(px(12.0), px((TITLEBAR_H - 14.0) / 2.0))),
    }
}

/// Whether rosier draws the title bar of `window` now: always on macOS and
/// Windows, on Linux when the desktop left it to rosier; never in full screen.
pub fn own_titlebar(window: &Window) -> bool {
    let left_to_us = cfg!(any(target_os = "macos", target_os = "windows"))
        || matches!(window.window_decorations(), gpui::Decorations::Client { .. });
    left_to_us && !window.is_fullscreen()
}

/// Whether rosier has to provide resize handles: only where it took the
/// decorations from a Linux desktop (macOS and Windows keep their borders).
pub fn own_resize_edges(window: &Window) -> bool {
    cfg!(target_os = "linux") && own_titlebar(window)
}

/// Height of the title bar rosier draws when the desktop does not.
pub const TITLEBAR_H: f32 = 36.0;

/// rosier's title bar: the name, and minimize, maximize and close. Drag to
/// move, double-click to maximize, right-click for the window menu. On
/// Windows each part also tells the system what it is, so snapping and the
/// system menu work; on macOS the system's traffic lights take the left end
/// and rosier draws no buttons of its own.
pub fn titlebar(window: &Window) -> AnyElement {
    use gpui::WindowControlArea as Area;
    let maximized = window.is_maximized();
    let mac = cfg!(target_os = "macos");
    let control = |id: &'static str, ic: Icon, area: Area| {
        div()
            .id(id)
            .window_control_area(area)
            .size(px(26.0))
            .flex()
            .items_center()
            .justify_center()
            .rounded_full()
            .cursor_pointer()
            .hover(|s| s.bg(theme::raised_hover()))
            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
            .child(icon(ic, 14.0, theme::text_dim()))
    };
    div()
        .id("titlebar")
        .flex_none()
        .h(px(TITLEBAR_H))
        .w_full()
        .flex()
        .flex_row()
        .items_center()
        .px_2()
        .bg(theme::stage())
        .border_b_1()
        .border_color(theme::line())
        .on_mouse_down(MouseButton::Left, |ev, window, _| {
            if ev.click_count == 2 {
                window.zoom_window();
            } else {
                window.start_window_move();
            }
        })
        .on_mouse_down(MouseButton::Right, |ev, window, _| window.show_window_menu(ev.position))
        .window_control_area(Area::Drag)
        .child(div().w(px(84.0)))
        .child(
            div()
                .flex_grow()
                .flex()
                .justify_center()
                .text_sm()
                .text_color(theme::text_dim())
                .child(crate::i18n::t("app.title")),
        )
        .child(div().w(px(84.0)).flex().flex_row().justify_end().gap_1().when(!mac, |d| {
            d.child(control("tb-min", Icon::Minus, Area::Min).on_click(|_, window, _| window.minimize_window()))
                .child(
                    control("tb-max", if maximized { Icon::Split1 } else { Icon::Fullscreen }, Area::Max)
                        .on_click(|_, window, _| window.zoom_window()),
                )
                .child(control("tb-close", Icon::Close, Area::Close).on_click(|_, _, cx| cx.quit()))
        }))
        .into_any_element()
}

/// Invisible handles along the window's edges and corners for resizing,
/// needed when the app draws its own decorations.
pub fn resize_edges(window: &Window) -> Vec<AnyElement> {
    use gpui::{CursorStyle as C, ResizeEdge as E};
    if window.is_maximized() {
        return Vec::new();
    }
    const T: f32 = 6.0;
    let edge = |id: &'static str, e: E, cursor: C| {
        div().id(id).absolute().cursor(cursor).on_mouse_down(MouseButton::Left, move |_, window, cx| {
            cx.stop_propagation();
            window.start_window_resize(e);
        })
    };
    vec![
        edge("rz-t", E::Top, C::ResizeUpDown).top_0().left(px(T)).right(px(T)).h(px(T)).into_any_element(),
        edge("rz-b", E::Bottom, C::ResizeUpDown).bottom_0().left(px(T)).right(px(T)).h(px(T)).into_any_element(),
        edge("rz-l", E::Left, C::ResizeLeftRight).left_0().top(px(T)).bottom(px(T)).w(px(T)).into_any_element(),
        edge("rz-r", E::Right, C::ResizeLeftRight).right_0().top(px(T)).bottom(px(T)).w(px(T)).into_any_element(),
        edge("rz-tl", E::TopLeft, C::ResizeUpLeftDownRight).top_0().left_0().size(px(T)).into_any_element(),
        edge("rz-tr", E::TopRight, C::ResizeUpRightDownLeft).top_0().right_0().size(px(T)).into_any_element(),
        edge("rz-bl", E::BottomLeft, C::ResizeUpRightDownLeft).bottom_0().left_0().size(px(T)).into_any_element(),
        edge("rz-br", E::BottomRight, C::ResizeUpLeftDownRight).bottom_0().right_0().size(px(T)).into_any_element(),
    ]
}

/// A short label shown when the pointer rests on a button.
struct Tip(SharedString);

impl gpui::Render for Tip {
    fn render(&mut self, _: &mut gpui::Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
        gpui::div()
            .px_2()
            .py_1()
            .rounded(gpui::px(theme::R_SMALL))
            .bg(gpui::rgba(0x18181cf0))
            .border_1()
            .border_color(theme::glass_edge())
            .text_xs()
            .text_color(theme::text())
            .child(self.0.clone())
    }
}

/// For `.tooltip(..)`: shows `text` by the button under the pointer.
pub fn tip(text: impl Into<SharedString>) -> impl Fn(&mut gpui::Window, &mut gpui::App) -> gpui::AnyView + 'static {
    let text: SharedString = text.into();
    move |_, cx| cx.new(|_| Tip(text.clone())).into()
}