Skip to main content

gpui_component/
window_border.rs

1// From:
2// https://github.com/zed-industries/zed/blob/56daba28d40301ee4c05546fadb691d070b7b2b6/crates/gpui/examples/window_shadow.rs
3use gpui::{
4    AnyElement, App, Corners, CursorStyle, Decorations, Edges, Hsla, InteractiveElement as _,
5    IntoElement, MouseButton, ParentElement, Pixels, Point, RenderOnce, ResizeEdge, Size,
6    Styled as _, Tiling, Window, div, point, prelude::FluentBuilder as _, px,
7};
8
9use crate::ActiveTheme;
10
11#[cfg(not(target_os = "linux"))]
12pub(crate) const SHADOW_SIZE: Pixels = px(0.0);
13#[cfg(target_os = "linux")]
14pub(crate) const SHADOW_SIZE: Pixels = px(20.0);
15const BORDER_SIZE: Pixels = px(1.0);
16/// Half-width of the resize hit band on each side of the visible frame (inner border).
17const RESIZE_HIT_SIZE: Pixels = px(4.0);
18
19/// The window's current corner radii: the theme's `window.radius`
20/// ([`crate::Theme::window_radius`]) for every corner of a client-decorated
21/// window that isn't next to a tiled edge, zero otherwise.
22///
23/// GPUI clips overflowing children to a rectangular content mask, so a non-zero
24/// radius only rounds the frame itself. Elements with a background that touch a
25/// window corner (the root surface, [`crate::TitleBar`], an application's bottom
26/// bar) must round that corner too, for example
27/// `div().rounded_bl(radii.bottom_left)`. The default stays square.
28pub fn window_corner_radii(window: &Window, cx: &App) -> Corners<Pixels> {
29    corner_radii(cx.theme().window_radius, window.window_decorations())
30}
31
32fn corner_radii(radius: Pixels, decorations: Decorations) -> Corners<Pixels> {
33    let Decorations::Client { tiling } = decorations else {
34        return Corners::default();
35    };
36    let corner = |rounded: bool| if rounded { radius } else { px(0.0) };
37    Corners {
38        top_left: corner(!tiling.top && !tiling.left),
39        top_right: corner(!tiling.top && !tiling.right),
40        bottom_left: corner(!tiling.bottom && !tiling.left),
41        bottom_right: corner(!tiling.bottom && !tiling.right),
42    }
43}
44
45/// Create a new window border.
46pub fn window_border() -> WindowBorder {
47    WindowBorder::new()
48}
49
50/// Renders a custom window border and shadow on Linux.
51#[derive(IntoElement)]
52pub struct WindowBorder {
53    shadow_size: Pixels,
54    resize_hit_size: Pixels,
55    children: Vec<AnyElement>,
56}
57
58impl Default for WindowBorder {
59    fn default() -> Self {
60        Self {
61            shadow_size: SHADOW_SIZE,
62            resize_hit_size: RESIZE_HIT_SIZE,
63            children: Vec::new(),
64        }
65    }
66}
67
68impl WindowBorder {
69    pub fn new() -> Self {
70        Self::default()
71    }
72
73    /// Set the shadow size for typical Linux client-side decorations.
74    ///
75    /// Default: [`SHADOW_SIZE`]
76    pub fn shadow_size(mut self, size: impl Into<Pixels>) -> Self {
77        self.shadow_size = size.into();
78        self
79    }
80
81    /// Set the resize hit band half-width around the visible inner frame edge.
82    ///
83    /// Default: [`RESIZE_HIT_SIZE`]
84    pub fn resize_hit_size(mut self, size: impl Into<Pixels>) -> Self {
85        self.resize_hit_size = size.into();
86        self
87    }
88}
89
90/// Per-side inset of the visible frame from the outer window bounds.
91fn client_frame_insets(shadow_size: Pixels, tiling: &Tiling) -> Edges<Pixels> {
92    let mut insets = Edges::all(shadow_size);
93    if tiling.top {
94        insets.top = px(0.0);
95    }
96    if tiling.bottom {
97        insets.bottom = px(0.0);
98    }
99    if tiling.left {
100        insets.left = px(0.0);
101    }
102    if tiling.right {
103        insets.right = px(0.0);
104    }
105    insets
106}
107
108/// Get the window paddings.
109pub fn window_paddings(window: &Window) -> Edges<Pixels> {
110    let shadow_size = window.client_inset().unwrap_or(SHADOW_SIZE);
111    match window.window_decorations() {
112        Decorations::Server => Edges::all(px(0.0)),
113        Decorations::Client { tiling } => client_frame_insets(shadow_size, &tiling),
114    }
115}
116
117/// Per-side inset from the window bounds to the visible frame's content area.
118///
119/// This is [`window_paddings`] plus the frame's own border, which the window
120/// wrapper draws on every side it is not tiled against. Allows to lay an element
121/// flush against the inside of the window frame.
122pub(crate) fn window_content_insets(window: &Window) -> Edges<Pixels> {
123    let shadow_size = window.client_inset().unwrap_or(SHADOW_SIZE);
124    match window.window_decorations() {
125        Decorations::Server => Edges::all(px(0.0)),
126        Decorations::Client { tiling } => {
127            let mut insets = client_frame_insets(shadow_size, &tiling);
128            if !tiling.top {
129                insets.top += BORDER_SIZE;
130            }
131            if !tiling.bottom {
132                insets.bottom += BORDER_SIZE;
133            }
134            if !tiling.left {
135                insets.left += BORDER_SIZE;
136            }
137            if !tiling.right {
138                insets.right += BORDER_SIZE;
139            }
140            insets
141        }
142    }
143}
144
145/// Per-side inset from the window bounds to the part of the window that is
146/// fully visible: not under the system bars, a display cutout or the on-screen
147/// keyboard ([`Window::fully_visible_bounds`]). Zero on desktop.
148pub(crate) fn window_safe_insets(window: &Window) -> Edges<Pixels> {
149    let viewport = window.viewport_size();
150    let visible = window.fully_visible_bounds();
151    Edges {
152        top: visible.top(),
153        right: viewport.width - visible.right(),
154        bottom: viewport.height - visible.bottom(),
155        left: visible.left(),
156    }
157}
158
159impl ParentElement for WindowBorder {
160    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
161        self.children.extend(elements);
162    }
163}
164
165impl RenderOnce for WindowBorder {
166    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
167        let decorations = window.window_decorations();
168        let children = self.children;
169        if !uses_client_border(decorations) {
170            // Keep the same `window-backdrop` id as the client-decorated frame below. The
171            // decorations can change at runtime (an app switching to server-side decorations,
172            // or a compositor granting a different mode), and without the shared id every
173            // element id path in the window would change, dropping all keyed element state.
174            return div()
175                .id("window-backdrop")
176                .size_full()
177                .children(children)
178                .into_any_element();
179        }
180        let Decorations::Client { tiling } = decorations else {
181            unreachable!("client border requires client decorations");
182        };
183
184        // Keep the platform client inset stable. When the window is tiled on all sides we stop drawing
185        // shadow padding, but `set_client_inset` must still use the full shadow size. Clearing it
186        // makes the first resize after restore double-count the shadow in `compute_outer_size`, and
187        // the window jumps larger.
188        let platform_inset = self.shadow_size;
189        let visual_shadow = if tiling.top && tiling.bottom && tiling.left && tiling.right {
190            px(0.0)
191        } else {
192            self.shadow_size
193        };
194        let resize_hit_size = self.resize_hit_size;
195        window.set_client_inset(platform_inset);
196        let radii = window_corner_radii(window, cx);
197        // Lets the compositor treat the rounded corners as transparent.
198        window.set_client_corner_radii(radii);
199        let window_size = window.window_bounds().get_bounds().size;
200        let is_window_active = window.is_window_active();
201        let border_color = cx.theme().window_border;
202
203        div()
204            .id("window-backdrop")
205            .bg(gpui::transparent_black())
206            .flex()
207            .flex_col()
208            .overflow_hidden()
209            .rounded_tl(radii.top_left)
210            .rounded_tr(radii.top_right)
211            .rounded_bl(radii.bottom_left)
212            .rounded_br(radii.bottom_right)
213            .when(!tiling.top, |div| div.pt(visual_shadow))
214            .when(!tiling.bottom, |div| div.pb(visual_shadow))
215            .when(!tiling.left, |div| div.pl(visual_shadow))
216            .when(!tiling.right, |div| div.pr(visual_shadow))
217            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
218                let Decorations::Client { tiling } = window.window_decorations() else {
219                    return;
220                };
221                if !window.is_resizable() {
222                    return;
223                }
224                if tiling.top && tiling.bottom && tiling.left && tiling.right {
225                    return;
226                }
227                let size = window.window_bounds().get_bounds().size;
228                let pos = window.mouse_position();
229                let insets = client_frame_insets(platform_inset, &tiling);
230
231                match resize_edge(pos, size, insets, &tiling, resize_hit_size) {
232                    Some(edge) => {
233                        gpui_base::TextSelection::end(window, cx);
234                        cx.stop_active_drag(window);
235                        cx.stop_propagation();
236                        window.start_window_resize(edge);
237                    }
238                    None => {}
239                };
240            })
241            .size_full()
242            .child(
243                div()
244                    .cursor(CursorStyle::default())
245                    .flex_1()
246                    .min_h_0()
247                    .min_w_0()
248                    .overflow_hidden()
249                    .rounded_tl(radii.top_left)
250                    .rounded_tr(radii.top_right)
251                    .rounded_bl(radii.bottom_left)
252                    .rounded_br(radii.bottom_right)
253                    .border_color(border_color)
254                    .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
255                    .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
256                    .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
257                    .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
258                    .when(!tiling.is_tiled(), |div| {
259                        let opacity = if is_window_active { 1.0 } else { 0.7 };
260                        div.shadow(vec![
261                            // Keep the effective outer reach below SHADOW_SIZE. GPUI
262                            // does not grow the paint bounds for blur, so a larger blur
263                            // or offset would be visibly cut off by the window surface.
264                            gpui::BoxShadow {
265                                color: Hsla {
266                                    h: 0.,
267                                    s: 0.,
268                                    l: 0.,
269                                    a: 0.18 * opacity,
270                                },
271                                // GNOME-style ambient shadow: horizontally centered
272                                // with only a slight downward bias.
273                                blur_radius: px(10.),
274                                spread_radius: px(-1.),
275                                offset: point(px(0.0), px(2.0)),
276                                inset: false,
277                            },
278                            // The contact layer adds definition without increasing the
279                            // space between the content and the outer window bounds.
280                            gpui::BoxShadow {
281                                color: Hsla {
282                                    h: 0.,
283                                    s: 0.,
284                                    l: 0.,
285                                    a: 0.18 * opacity,
286                                },
287                                blur_radius: px(3.),
288                                spread_radius: px(0.),
289                                offset: point(px(0.0), px(1.0)),
290                                inset: false,
291                            },
292                        ])
293                    })
294                    .on_mouse_move(|_e, _, cx| {
295                        cx.stop_propagation();
296                    })
297                    .bg(gpui::transparent_black())
298                    .children(children),
299            )
300            .when(window.is_resizable(), |parent| {
301                parent.child(div().absolute().size_full().children(resize_hit_zones(
302                    window_size,
303                    platform_inset,
304                    resize_hit_size,
305                    &tiling,
306                )))
307            })
308            .into_any_element()
309    }
310}
311
312fn uses_client_border(decorations: Decorations) -> bool {
313    matches!(decorations, Decorations::Client { .. })
314}
315
316fn cursor_style_for_resize_edge(edge: ResizeEdge) -> CursorStyle {
317    match edge {
318        ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
319        ResizeEdge::Left | ResizeEdge::Right => CursorStyle::ResizeLeftRight,
320        ResizeEdge::TopLeft | ResizeEdge::BottomRight => CursorStyle::ResizeUpLeftDownRight,
321        ResizeEdge::TopRight | ResizeEdge::BottomLeft => CursorStyle::ResizeUpRightDownLeft,
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    #[test]
328    fn corners_round_only_next_to_untiled_edges() {
329        use super::corner_radii;
330        use gpui::{Corners, Decorations, Tiling, px};
331
332        let radius = px(10.0);
333        assert_eq!(
334            corner_radii(
335                radius,
336                Decorations::Client {
337                    tiling: Tiling::default()
338                }
339            ),
340            Corners::all(radius)
341        );
342        let top_tiled = Tiling {
343            top: true,
344            ..Tiling::default()
345        };
346        assert_eq!(
347            corner_radii(radius, Decorations::Client { tiling: top_tiled }),
348            Corners {
349                top_left: px(0.0),
350                top_right: px(0.0),
351                bottom_left: radius,
352                bottom_right: radius,
353            }
354        );
355        assert_eq!(
356            corner_radii(radius, Decorations::Server),
357            Corners::default()
358        );
359    }
360
361    use super::*;
362
363    #[test]
364    fn only_client_decorated_windows_use_the_client_border() {
365        assert!(!uses_client_border(Decorations::Server));
366        assert!(uses_client_border(Decorations::Client {
367            tiling: Tiling::default(),
368        }));
369    }
370}
371
372/// Cursor-only overlay for each resize edge/corner. Resize starts from the backdrop
373/// `on_mouse_down` via [`resize_edge`]. `.cursor()` updates immediately on hitbox changes
374/// without `window.refresh()` (PR #617).
375fn resize_hit_zones(
376    window_size: Size<Pixels>,
377    shadow_size: Pixels,
378    hit_size: Pixels,
379    tiling: &Tiling,
380) -> Vec<AnyElement> {
381    if tiling.top && tiling.bottom && tiling.left && tiling.right {
382        return Vec::new();
383    }
384
385    let insets = client_frame_insets(shadow_size, tiling);
386    let inner_left = insets.left;
387    let inner_right = window_size.width - insets.right;
388    let inner_top = insets.top;
389    let inner_bottom = window_size.height - insets.bottom;
390    // Overlay is laid out in the padded content box; convert from window coords.
391    let frame_origin = point(insets.left, insets.top);
392    let band = hit_size + hit_size;
393    let span_x = inner_right - inner_left + band;
394    let span_y = inner_bottom - inner_top + band;
395
396    let mut zones: Vec<AnyElement> = Vec::new();
397
398    let mut push_zone = |edge: ResizeEdge, origin: Point<Pixels>, zone_size: Size<Pixels>| {
399        let origin = origin - frame_origin;
400        zones.push(
401            div()
402                .absolute()
403                .left(origin.x)
404                .top(origin.y)
405                .w(zone_size.width)
406                .h(zone_size.height)
407                .cursor(cursor_style_for_resize_edge(edge))
408                .into_any_element(),
409        );
410    };
411
412    if !tiling.top {
413        push_zone(
414            ResizeEdge::Top,
415            point(inner_left - hit_size, inner_top - hit_size),
416            Size::new(span_x, band),
417        );
418    }
419    if !tiling.bottom {
420        push_zone(
421            ResizeEdge::Bottom,
422            point(inner_left - hit_size, inner_bottom - hit_size),
423            Size::new(span_x, band),
424        );
425    }
426    if !tiling.left {
427        push_zone(
428            ResizeEdge::Left,
429            point(inner_left - hit_size, inner_top - hit_size),
430            Size::new(band, span_y),
431        );
432    }
433    if !tiling.right {
434        push_zone(
435            ResizeEdge::Right,
436            point(inner_right - hit_size, inner_top - hit_size),
437            Size::new(band, span_y),
438        );
439    }
440
441    // Corners are pushed after edge strips so hit-testing prefers them over adjacent edges.
442    if !tiling.top && !tiling.left {
443        push_zone(
444            ResizeEdge::TopLeft,
445            point(inner_left - hit_size, inner_top - hit_size),
446            Size::new(band, band),
447        );
448    }
449    if !tiling.top && !tiling.right {
450        push_zone(
451            ResizeEdge::TopRight,
452            point(inner_right - hit_size, inner_top - hit_size),
453            Size::new(band, band),
454        );
455    }
456    if !tiling.bottom && !tiling.left {
457        push_zone(
458            ResizeEdge::BottomLeft,
459            point(inner_left - hit_size, inner_bottom - hit_size),
460            Size::new(band, band),
461        );
462    }
463    if !tiling.bottom && !tiling.right {
464        push_zone(
465            ResizeEdge::BottomRight,
466            point(inner_right - hit_size, inner_bottom - hit_size),
467            Size::new(band, band),
468        );
469    }
470
471    zones
472}
473
474/// Hit-test resize edges on a narrow band around the visible inner frame, not the full shadow padding.
475fn resize_edge(
476    pos: Point<Pixels>,
477    size: Size<Pixels>,
478    insets: Edges<Pixels>,
479    tiling: &Tiling,
480    hit_size: Pixels,
481) -> Option<ResizeEdge> {
482    let inner_left = insets.left;
483    let inner_right = size.width - insets.right;
484    let inner_top = insets.top;
485    let inner_bottom = size.height - insets.bottom;
486
487    // Each edge only applies along its corresponding inner-frame segment; it does not extend along the "extension lines" of the shadow padding.
488    let on_left = pos.x >= inner_left - hit_size
489        && pos.x <= inner_left + hit_size
490        && pos.y >= inner_top - hit_size
491        && pos.y <= inner_bottom + hit_size;
492    let on_right = pos.x >= inner_right - hit_size
493        && pos.x <= inner_right + hit_size
494        && pos.y >= inner_top - hit_size
495        && pos.y <= inner_bottom + hit_size;
496    let on_top = pos.y >= inner_top - hit_size
497        && pos.y <= inner_top + hit_size
498        && pos.x >= inner_left - hit_size
499        && pos.x <= inner_right + hit_size;
500    let on_bottom = pos.y >= inner_bottom - hit_size
501        && pos.y <= inner_bottom + hit_size
502        && pos.x >= inner_left - hit_size
503        && pos.x <= inner_right + hit_size;
504
505    if !tiling.top && !tiling.left && on_top && on_left {
506        return Some(ResizeEdge::TopLeft);
507    }
508    if !tiling.top && !tiling.right && on_top && on_right {
509        return Some(ResizeEdge::TopRight);
510    }
511    if !tiling.bottom && !tiling.left && on_bottom && on_left {
512        return Some(ResizeEdge::BottomLeft);
513    }
514    if !tiling.bottom && !tiling.right && on_bottom && on_right {
515        return Some(ResizeEdge::BottomRight);
516    }
517    if !tiling.top && on_top {
518        return Some(ResizeEdge::Top);
519    }
520    if !tiling.bottom && on_bottom {
521        return Some(ResizeEdge::Bottom);
522    }
523    if !tiling.left && on_left {
524        return Some(ResizeEdge::Left);
525    }
526    if !tiling.right && on_right {
527        return Some(ResizeEdge::Right);
528    }
529    None
530}