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, CursorStyle, Decorations, Edges, InteractiveElement as _, IntoElement,
5    MouseButton, ParentElement, Pixels, Point, RenderOnce, ResizeEdge, Size, Styled as _, Tiling,
6    Window, div, hsla, 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/// GPUI currently clips overflowing children to a rectangular content mask. A non-zero
20/// radius here would round the frame itself but leave child backgrounds visible in the
21/// corners, so keep the generic window wrapper square until rounded content masks exist.
22pub(crate) const BORDER_RADIUS: Pixels = px(0.0);
23
24/// Create a new window border.
25pub fn window_border() -> WindowBorder {
26    WindowBorder::new()
27}
28
29/// Renders a custom window border and shadow on Linux.
30#[derive(IntoElement)]
31pub struct WindowBorder {
32    shadow_size: Pixels,
33    resize_hit_size: Pixels,
34    children: Vec<AnyElement>,
35}
36
37impl Default for WindowBorder {
38    fn default() -> Self {
39        Self {
40            shadow_size: SHADOW_SIZE,
41            resize_hit_size: RESIZE_HIT_SIZE,
42            children: Vec::new(),
43        }
44    }
45}
46
47impl WindowBorder {
48    pub fn new() -> Self {
49        Self::default()
50    }
51
52    /// Set the shadow size for typical Linux client-side decorations.
53    ///
54    /// Default: [`SHADOW_SIZE`]
55    pub fn shadow_size(mut self, size: impl Into<Pixels>) -> Self {
56        self.shadow_size = size.into();
57        self
58    }
59
60    /// Set the resize hit band half-width around the visible inner frame edge.
61    ///
62    /// Default: [`RESIZE_HIT_SIZE`]
63    pub fn resize_hit_size(mut self, size: impl Into<Pixels>) -> Self {
64        self.resize_hit_size = size.into();
65        self
66    }
67}
68
69/// Per-side inset of the visible frame from the outer window bounds.
70fn client_frame_insets(shadow_size: Pixels, tiling: &Tiling) -> Edges<Pixels> {
71    let mut insets = Edges::all(shadow_size);
72    if tiling.top {
73        insets.top = px(0.0);
74    }
75    if tiling.bottom {
76        insets.bottom = px(0.0);
77    }
78    if tiling.left {
79        insets.left = px(0.0);
80    }
81    if tiling.right {
82        insets.right = px(0.0);
83    }
84    insets
85}
86
87/// Get the window paddings.
88pub fn window_paddings(window: &Window) -> Edges<Pixels> {
89    let shadow_size = window.client_inset().unwrap_or(SHADOW_SIZE);
90    match window.window_decorations() {
91        Decorations::Server => Edges::all(px(0.0)),
92        Decorations::Client { tiling } => client_frame_insets(shadow_size, &tiling),
93    }
94}
95
96/// Per-side inset from the window bounds to the visible frame's content area.
97///
98/// This is [`window_paddings`] plus the frame's own border, which the window
99/// wrapper draws on every side it is not tiled against. Allows to lay an element
100/// flush against the inside of the window frame.
101pub(crate) fn window_content_insets(window: &Window) -> Edges<Pixels> {
102    let shadow_size = window.client_inset().unwrap_or(SHADOW_SIZE);
103    match window.window_decorations() {
104        Decorations::Server => Edges::all(px(0.0)),
105        Decorations::Client { tiling } => {
106            let mut insets = client_frame_insets(shadow_size, &tiling);
107            if !tiling.top {
108                insets.top += BORDER_SIZE;
109            }
110            if !tiling.bottom {
111                insets.bottom += BORDER_SIZE;
112            }
113            if !tiling.left {
114                insets.left += BORDER_SIZE;
115            }
116            if !tiling.right {
117                insets.right += BORDER_SIZE;
118            }
119            insets
120        }
121    }
122}
123
124impl ParentElement for WindowBorder {
125    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
126        self.children.extend(elements);
127    }
128}
129
130impl RenderOnce for WindowBorder {
131    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
132        let decorations = window.window_decorations();
133        let mut children = self.children;
134        if !uses_client_border(decorations) {
135            return match children.len() {
136                1 => children.pop().unwrap(),
137                _ => div().size_full().children(children).into_any_element(),
138            };
139        }
140        let Decorations::Client { tiling } = decorations else {
141            unreachable!("client border requires client decorations");
142        };
143
144        // Keep the platform client inset stable. When the window is tiled on all sides we stop drawing
145        // shadow padding, but `set_client_inset` must still use the full shadow size. Clearing it
146        // makes the first resize after restore double-count the shadow in `compute_outer_size`, and
147        // the window jumps larger.
148        let platform_inset = self.shadow_size;
149        let visual_shadow = if tiling.top && tiling.bottom && tiling.left && tiling.right {
150            px(0.0)
151        } else {
152            self.shadow_size
153        };
154        let resize_hit_size = self.resize_hit_size;
155        window.set_client_inset(platform_inset);
156        let window_size = window.window_bounds().get_bounds().size;
157        let is_window_active = window.is_window_active();
158        let border_color = if cx.theme().is_dark() {
159            hsla(0., 0., 0.2, 1.)
160        } else {
161            hsla(0., 0., 0.8, 1.)
162        };
163
164        div()
165            .id("window-backdrop")
166            .bg(gpui::transparent_black())
167            .flex()
168            .flex_col()
169            .overflow_hidden()
170            .when(!(tiling.top || tiling.right), |div| {
171                div.rounded_tr(BORDER_RADIUS)
172            })
173            .when(!(tiling.top || tiling.left), |div| {
174                div.rounded_tl(BORDER_RADIUS)
175            })
176            .when(!tiling.top, |div| div.pt(visual_shadow))
177            .when(!tiling.bottom, |div| div.pb(visual_shadow))
178            .when(!tiling.left, |div| div.pl(visual_shadow))
179            .when(!tiling.right, |div| div.pr(visual_shadow))
180            .on_mouse_down(MouseButton::Left, move |_, window, _| {
181                let Decorations::Client { tiling } = window.window_decorations() else {
182                    return;
183                };
184                if tiling.top && tiling.bottom && tiling.left && tiling.right {
185                    return;
186                }
187                let size = window.window_bounds().get_bounds().size;
188                let pos = window.mouse_position();
189                let insets = client_frame_insets(platform_inset, &tiling);
190
191                match resize_edge(pos, size, insets, &tiling, resize_hit_size) {
192                    Some(edge) => window.start_window_resize(edge),
193                    None => {}
194                };
195            })
196            .size_full()
197            .child(
198                div()
199                    .cursor(CursorStyle::default())
200                    .flex_1()
201                    .min_h_0()
202                    .min_w_0()
203                    .overflow_hidden()
204                    .when(!(tiling.top || tiling.right), |div| {
205                        div.rounded_tr(BORDER_RADIUS)
206                    })
207                    .when(!(tiling.top || tiling.left), |div| {
208                        div.rounded_tl(BORDER_RADIUS)
209                    })
210                    .border_color(border_color)
211                    .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
212                    .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
213                    .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
214                    .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
215                    .when(!tiling.is_tiled(), |div| {
216                        let opacity = if is_window_active { 1.0 } else { 0.7 };
217                        div.shadow(vec![
218                            // Keep the effective outer reach below SHADOW_SIZE. GPUI
219                            // does not grow the paint bounds for blur, so a larger blur
220                            // or offset would be visibly cut off by the window surface.
221                            gpui::BoxShadow {
222                                color: hsla(0., 0., 0., 0.18 * opacity).into(),
223                                // GNOME-style ambient shadow: horizontally centered
224                                // with only a slight downward bias.
225                                blur_radius: px(10.),
226                                spread_radius: px(-1.),
227                                offset: point(px(0.0), px(2.0)),
228                                inset: false,
229                            },
230                            // The contact layer adds definition without increasing the
231                            // space between the content and the outer window bounds.
232                            gpui::BoxShadow {
233                                color: hsla(0., 0., 0., 0.18 * opacity).into(),
234                                blur_radius: px(3.),
235                                spread_radius: px(0.),
236                                offset: point(px(0.0), px(1.0)),
237                                inset: false,
238                            },
239                        ])
240                    })
241                    .on_mouse_move(|_e, _, cx| {
242                        cx.stop_propagation();
243                    })
244                    .bg(gpui::transparent_black())
245                    .children(children),
246            )
247            .child(div().absolute().size_full().children(resize_hit_zones(
248                window_size,
249                platform_inset,
250                resize_hit_size,
251                &tiling,
252            )))
253            .into_any_element()
254    }
255}
256
257fn uses_client_border(decorations: Decorations) -> bool {
258    matches!(decorations, Decorations::Client { .. })
259}
260
261fn cursor_style_for_resize_edge(edge: ResizeEdge) -> CursorStyle {
262    match edge {
263        ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
264        ResizeEdge::Left | ResizeEdge::Right => CursorStyle::ResizeLeftRight,
265        ResizeEdge::TopLeft | ResizeEdge::BottomRight => CursorStyle::ResizeUpLeftDownRight,
266        ResizeEdge::TopRight | ResizeEdge::BottomLeft => CursorStyle::ResizeUpRightDownLeft,
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    #[test]
275    fn only_client_decorated_windows_use_the_client_border() {
276        assert!(!uses_client_border(Decorations::Server));
277        assert!(uses_client_border(Decorations::Client {
278            tiling: Tiling::default(),
279        }));
280    }
281}
282
283/// Cursor-only overlay for each resize edge/corner. Resize starts from the backdrop
284/// `on_mouse_down` via [`resize_edge`]. `.cursor()` updates immediately on hitbox changes
285/// without `window.refresh()` (PR #617).
286fn resize_hit_zones(
287    window_size: Size<Pixels>,
288    shadow_size: Pixels,
289    hit_size: Pixels,
290    tiling: &Tiling,
291) -> Vec<AnyElement> {
292    if tiling.top && tiling.bottom && tiling.left && tiling.right {
293        return Vec::new();
294    }
295
296    let insets = client_frame_insets(shadow_size, tiling);
297    let inner_left = insets.left;
298    let inner_right = window_size.width - insets.right;
299    let inner_top = insets.top;
300    let inner_bottom = window_size.height - insets.bottom;
301    // Overlay is laid out in the padded content box; convert from window coords.
302    let frame_origin = point(insets.left, insets.top);
303    let band = hit_size + hit_size;
304    let span_x = inner_right - inner_left + band;
305    let span_y = inner_bottom - inner_top + band;
306
307    let mut zones: Vec<AnyElement> = Vec::new();
308
309    let mut push_zone = |edge: ResizeEdge, origin: Point<Pixels>, zone_size: Size<Pixels>| {
310        let origin = origin - frame_origin;
311        zones.push(
312            div()
313                .absolute()
314                .left(origin.x)
315                .top(origin.y)
316                .w(zone_size.width)
317                .h(zone_size.height)
318                .cursor(cursor_style_for_resize_edge(edge))
319                .into_any_element(),
320        );
321    };
322
323    if !tiling.top {
324        push_zone(
325            ResizeEdge::Top,
326            point(inner_left - hit_size, inner_top - hit_size),
327            Size::new(span_x, band),
328        );
329    }
330    if !tiling.bottom {
331        push_zone(
332            ResizeEdge::Bottom,
333            point(inner_left - hit_size, inner_bottom - hit_size),
334            Size::new(span_x, band),
335        );
336    }
337    if !tiling.left {
338        push_zone(
339            ResizeEdge::Left,
340            point(inner_left - hit_size, inner_top - hit_size),
341            Size::new(band, span_y),
342        );
343    }
344    if !tiling.right {
345        push_zone(
346            ResizeEdge::Right,
347            point(inner_right - hit_size, inner_top - hit_size),
348            Size::new(band, span_y),
349        );
350    }
351
352    // Corners are pushed after edge strips so hit-testing prefers them over adjacent edges.
353    if !tiling.top && !tiling.left {
354        push_zone(
355            ResizeEdge::TopLeft,
356            point(inner_left - hit_size, inner_top - hit_size),
357            Size::new(band, band),
358        );
359    }
360    if !tiling.top && !tiling.right {
361        push_zone(
362            ResizeEdge::TopRight,
363            point(inner_right - hit_size, inner_top - hit_size),
364            Size::new(band, band),
365        );
366    }
367    if !tiling.bottom && !tiling.left {
368        push_zone(
369            ResizeEdge::BottomLeft,
370            point(inner_left - hit_size, inner_bottom - hit_size),
371            Size::new(band, band),
372        );
373    }
374    if !tiling.bottom && !tiling.right {
375        push_zone(
376            ResizeEdge::BottomRight,
377            point(inner_right - hit_size, inner_bottom - hit_size),
378            Size::new(band, band),
379        );
380    }
381
382    zones
383}
384
385/// Hit-test resize edges on a narrow band around the visible inner frame, not the full shadow padding.
386fn resize_edge(
387    pos: Point<Pixels>,
388    size: Size<Pixels>,
389    insets: Edges<Pixels>,
390    tiling: &Tiling,
391    hit_size: Pixels,
392) -> Option<ResizeEdge> {
393    let inner_left = insets.left;
394    let inner_right = size.width - insets.right;
395    let inner_top = insets.top;
396    let inner_bottom = size.height - insets.bottom;
397
398    // Each edge only applies along its corresponding inner-frame segment; it does not extend along the "extension lines" of the shadow padding.
399    let on_left = pos.x >= inner_left - hit_size
400        && pos.x <= inner_left + hit_size
401        && pos.y >= inner_top - hit_size
402        && pos.y <= inner_bottom + hit_size;
403    let on_right = pos.x >= inner_right - hit_size
404        && pos.x <= inner_right + hit_size
405        && pos.y >= inner_top - hit_size
406        && pos.y <= inner_bottom + hit_size;
407    let on_top = pos.y >= inner_top - hit_size
408        && pos.y <= inner_top + hit_size
409        && pos.x >= inner_left - hit_size
410        && pos.x <= inner_right + hit_size;
411    let on_bottom = pos.y >= inner_bottom - hit_size
412        && pos.y <= inner_bottom + hit_size
413        && pos.x >= inner_left - hit_size
414        && pos.x <= inner_right + hit_size;
415
416    if !tiling.top && !tiling.left && on_top && on_left {
417        return Some(ResizeEdge::TopLeft);
418    }
419    if !tiling.top && !tiling.right && on_top && on_right {
420        return Some(ResizeEdge::TopRight);
421    }
422    if !tiling.bottom && !tiling.left && on_bottom && on_left {
423        return Some(ResizeEdge::BottomLeft);
424    }
425    if !tiling.bottom && !tiling.right && on_bottom && on_right {
426        return Some(ResizeEdge::BottomRight);
427    }
428    if !tiling.top && on_top {
429        return Some(ResizeEdge::Top);
430    }
431    if !tiling.bottom && on_bottom {
432        return Some(ResizeEdge::Bottom);
433    }
434    if !tiling.left && on_left {
435        return Some(ResizeEdge::Left);
436    }
437    if !tiling.right && on_right {
438        return Some(ResizeEdge::Right);
439    }
440    None
441}