subspace-shell 0.11.0

Subspace Framework shell: the window, switcher, palette, help, Settings and themes. Internal crate; apps depend on `subspace-framework`.
Documentation
//! On macOS the toolbar is the window's title bar: the traffic lights sit in
//! its leading edge and dragging its background moves the window. Other
//! platforms keep their native title bar.

use gpui_kit::{
    Div, InteractiveElement as _, MouseButton, MouseDownEvent, Pixels, Point, Stateful,
    TitlebarOptions, Window, point, px,
};

/// AppKit's standard window buttons on macOS 26 and 27: 14 pt squares with
/// 9 pt between them, measured from `NSWindow::standardWindowButton`.
const TRAFFIC_LIGHT_SIZE: f32 = 14.;
const TRAFFIC_LIGHT_GAP: f32 = 9.;
const TRAFFIC_LIGHTS: f32 = 3.;
/// The traffic lights' inset from the window's leading edge.
const TRAFFIC_LIGHTS_X: f32 = 14.;
/// Space after the zoom button before the first control: the wide end of the
/// unified-toolbar spacing in Finder and Xcode.
const CONTENT_GAP: f32 = 20.;
/// The title bar's height before the theme's own is laid out.
const INITIAL_ROW_HEIGHT: f32 = 38.;
const HALF: f32 = 2.;

pub(crate) const INTEGRATED: bool = cfg!(target_os = "macos");

/// The title bar of the product window.
pub(crate) fn options(title: String) -> TitlebarOptions {
    TitlebarOptions {
        title: Some(title.into()),
        appears_transparent: INTEGRATED,
        traffic_light_position: INTEGRATED.then(|| traffic_light_origin(px(INITIAL_ROW_HEIGHT))),
    }
}

/// Where the traffic lights go so they share the title-bar row's centre line.
pub(super) fn traffic_light_origin(row_height: Pixels) -> Point<Pixels> {
    let top = (row_height - px(TRAFFIC_LIGHT_SIZE)) / HALF;
    point(px(TRAFFIC_LIGHTS_X), top.max(Pixels::ZERO))
}

/// The zoom button's trailing edge, from the window's leading edge.
pub(super) const TRAFFIC_LIGHTS_END: f32 = TRAFFIC_LIGHTS_X
    + TRAFFIC_LIGHTS * TRAFFIC_LIGHT_SIZE
    + (TRAFFIC_LIGHTS - 1.) * TRAFFIC_LIGHT_GAP;
/// The distance from the window's leading edge to the first title-bar control.
pub(super) const CONTENT_START: f32 = TRAFFIC_LIGHTS_END + CONTENT_GAP;

/// The first row's own leading padding inside a bar already padded by
/// `bar_padding`, clear of the traffic lights except in full screen, where
/// they are hidden.
pub(super) fn leading_inset(window: &Window, bar_padding: Pixels) -> Pixels {
    if INTEGRATED && !window.is_fullscreen() {
        (px(CONTENT_START) - bar_padding).max(Pixels::ZERO)
    } else {
        Pixels::ZERO
    }
}

/// Centres the traffic lights on a title-bar row `row_height` tall. The
/// platform moves its buttons only when the height changes, such as after a
/// theme, density or zoom change.
pub(super) fn align_traffic_lights(
    placed: &mut Option<Pixels>,
    row_height: Pixels,
    window: &Window,
) {
    #[cfg(target_os = "macos")]
    let _ = row_changed(placed, row_height)
        .then(|| window.set_traffic_light_position(traffic_light_origin(row_height)));
    #[cfg(not(target_os = "macos"))]
    let _ = (placed, row_height, window);
}

#[cfg(any(target_os = "macos", test))]
fn row_changed(placed: &mut Option<Pixels>, row_height: Pixels) -> bool {
    INTEGRATED && placed.replace(row_height) != Some(row_height)
}

/// AppKit starts a native drag from the original mouse-down event. Getting
/// there on mouse-move can hand it a drag event, or miss the press entirely
/// if the pointer has already left the toolbar.
pub(super) fn draggable(bar: Stateful<Div>) -> Stateful<Div> {
    if !INTEGRATED {
        return bar;
    }
    on_background_press(bar, |event, window| match event.click_count {
        1 => window.start_window_move(),
        2 => window.titlebar_double_click(),
        _ => {}
    })
}

/// Native controls claim their presses before they bubble to the bar.
fn on_background_press(
    bar: Stateful<Div>,
    press: impl Fn(&MouseDownEvent, &mut Window) + 'static,
) -> Stateful<Div> {
    bar.on_mouse_down(MouseButton::Left, move |event, window, _| {
        if !window.default_prevented() && !window.is_fullscreen() {
            press(event, window);
        }
    })
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;
    use std::rc::Rc;

    use gpui_kit::component::button::Button;
    use gpui_kit::component::h_flex;
    use gpui_kit::test::TestWindowExt as _;
    use gpui_kit::{
        App, Context, InteractiveElement as _, IntoElement, ParentElement as _, Render,
        Styled as _, TestAppContext, TestSupportExt as _, Window, div, px,
    };

    use super::{
        TRAFFIC_LIGHT_SIZE, TRAFFIC_LIGHTS_X, on_background_press, row_changed,
        traffic_light_origin,
    };

    struct Presses {
        background: Rc<Cell<usize>>,
        controls: Rc<Cell<usize>>,
    }

    impl Render for Presses {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            let background = self.background.clone();
            let controls = self.controls.clone();
            on_background_press(h_flex().id("chrome").h(px(40.)), move |_, _| {
                background.set(background.get() + 1);
            })
            .child(
                Button::new("tab")
                    .label("Example Space")
                    .on_click(move |_, _, _: &mut App| controls.set(controls.get() + 1)),
            )
            .child(div().id("chrome-gap").test_support().h_full().w(px(130.)))
        }
    }

    #[gpui_kit::test]
    fn background_mouse_down_can_move_the_window_without_taking_control_presses(
        cx: &mut TestAppContext,
    ) {
        cx.update(gpui_kit::init);
        let background = Rc::new(Cell::new(0));
        let controls = Rc::new(Cell::new(0));
        let (_, cx) = cx.add_window_view(|_, _| Presses {
            background: background.clone(),
            controls: controls.clone(),
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            window.click("chrome-gap", cx);
            window.click("tab", cx);
        });
        assert_eq!(background.get(), 1);
        assert_eq!(controls.get(), 1);
    }

    #[test]
    fn the_traffic_lights_share_the_rows_centre_line() {
        for height in [30., 38., 44., 52.] {
            let origin = traffic_light_origin(px(height));
            assert_eq!(origin.y + px(TRAFFIC_LIGHT_SIZE / 2.), px(height / 2.));
            assert_eq!(origin.x, px(TRAFFIC_LIGHTS_X));
        }
    }

    #[test]
    fn the_lights_move_only_when_the_row_height_changes() {
        let mut placed = None;
        assert_eq!(row_changed(&mut placed, px(38.)), super::INTEGRATED);
        assert!(!row_changed(&mut placed, px(38.)));
        assert_eq!(row_changed(&mut placed, px(44.)), super::INTEGRATED);
    }
}