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
96impl ParentElement for WindowBorder {
97    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
98        self.children.extend(elements);
99    }
100}
101
102impl RenderOnce for WindowBorder {
103    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
104        let decorations = window.window_decorations();
105        // Keep the platform client inset stable. When the window is tiled on all sides we stop drawing
106        // shadow padding, but `set_client_inset` must still use the full shadow size. Clearing it
107        // makes the first resize after restore double-count the shadow in `compute_outer_size`, and
108        // the window jumps larger.
109        let platform_inset = self.shadow_size;
110        let visual_shadow = match decorations {
111            Decorations::Client { tiling }
112                if tiling.top && tiling.bottom && tiling.left && tiling.right =>
113            {
114                px(0.0)
115            }
116            _ => self.shadow_size,
117        };
118        let resize_hit_size = self.resize_hit_size;
119        if matches!(decorations, Decorations::Client { .. }) {
120            window.set_client_inset(platform_inset);
121        }
122        let window_size = window.window_bounds().get_bounds().size;
123        let is_window_active = window.is_window_active();
124        let border_color = if cx.theme().is_dark() {
125            hsla(0., 0., 0.2, 1.)
126        } else {
127            hsla(0., 0., 0.8, 1.)
128        };
129
130        div()
131            .id("window-backdrop")
132            .bg(gpui::transparent_black())
133            .map(|div| match decorations {
134                Decorations::Server => div,
135                Decorations::Client { tiling, .. } => div
136                    .flex()
137                    .flex_col()
138                    .overflow_hidden()
139                    .bg(gpui::transparent_black())
140                    .when(!(tiling.top || tiling.right), |div| {
141                        div.rounded_tr(BORDER_RADIUS)
142                    })
143                    .when(!(tiling.top || tiling.left), |div| {
144                        div.rounded_tl(BORDER_RADIUS)
145                    })
146                    .when(!tiling.top, |div| div.pt(visual_shadow))
147                    .when(!tiling.bottom, |div| div.pb(visual_shadow))
148                    .when(!tiling.left, |div| div.pl(visual_shadow))
149                    .when(!tiling.right, |div| div.pr(visual_shadow))
150                    .on_mouse_down(MouseButton::Left, move |_, window, _| {
151                        let Decorations::Client { tiling } = window.window_decorations() else {
152                            return;
153                        };
154                        if tiling.top && tiling.bottom && tiling.left && tiling.right {
155                            return;
156                        }
157                        let size = window.window_bounds().get_bounds().size;
158                        let pos = window.mouse_position();
159                        let insets = client_frame_insets(platform_inset, &tiling);
160
161                        match resize_edge(pos, size, insets, &tiling, resize_hit_size) {
162                            Some(edge) => window.start_window_resize(edge),
163                            None => {}
164                        };
165                    }),
166            })
167            .size_full()
168            .child(
169                div()
170                    .cursor(CursorStyle::default())
171                    .map(|div| match decorations {
172                        Decorations::Server => div.size_full(),
173                        Decorations::Client { tiling } => div
174                            .flex_1()
175                            .min_h_0()
176                            .min_w_0()
177                            .overflow_hidden()
178                            .when(!(tiling.top || tiling.right), |div| {
179                                div.rounded_tr(BORDER_RADIUS)
180                            })
181                            .when(!(tiling.top || tiling.left), |div| {
182                                div.rounded_tl(BORDER_RADIUS)
183                            })
184                            .border_color(border_color)
185                            .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
186                            .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
187                            .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
188                            .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
189                            .when(!tiling.is_tiled(), |div| {
190                                let opacity = if is_window_active { 1.0 } else { 0.7 };
191                                div.shadow(vec![
192                                    // Keep the effective outer reach below SHADOW_SIZE. GPUI
193                                    // does not grow the paint bounds for blur, so a larger blur
194                                    // or offset would be visibly cut off by the window surface.
195                                    gpui::BoxShadow {
196                                        color: hsla(0., 0., 0., 0.18 * opacity),
197                                        // GNOME-style ambient shadow: horizontally centered
198                                        // with only a slight downward bias.
199                                        blur_radius: px(10.),
200                                        spread_radius: px(-1.),
201                                        offset: point(px(0.0), px(2.0)),
202                                        inset: false,
203                                    },
204                                    // The contact layer adds definition without increasing the
205                                    // space between the content and the outer window bounds.
206                                    gpui::BoxShadow {
207                                        color: hsla(0., 0., 0., 0.18 * opacity),
208                                        blur_radius: px(3.),
209                                        spread_radius: px(0.),
210                                        offset: point(px(0.0), px(1.0)),
211                                        inset: false,
212                                    },
213                                ])
214                            }),
215                    })
216                    .on_mouse_move(|_e, _, cx| {
217                        cx.stop_propagation();
218                    })
219                    .bg(gpui::transparent_black())
220                    .children(self.children),
221            )
222            .when(matches!(decorations, Decorations::Client { .. }), |this| {
223                let Decorations::Client { tiling, .. } = decorations else {
224                    return this;
225                };
226                this.child(div().absolute().size_full().children(resize_hit_zones(
227                    window_size,
228                    platform_inset,
229                    resize_hit_size,
230                    &tiling,
231                )))
232            })
233    }
234}
235
236fn cursor_style_for_resize_edge(edge: ResizeEdge) -> CursorStyle {
237    match edge {
238        ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
239        ResizeEdge::Left | ResizeEdge::Right => CursorStyle::ResizeLeftRight,
240        ResizeEdge::TopLeft | ResizeEdge::BottomRight => CursorStyle::ResizeUpLeftDownRight,
241        ResizeEdge::TopRight | ResizeEdge::BottomLeft => CursorStyle::ResizeUpRightDownLeft,
242    }
243}
244
245/// Cursor-only overlay for each resize edge/corner. Resize starts from the backdrop
246/// `on_mouse_down` via [`resize_edge`]. `.cursor()` updates immediately on hitbox changes
247/// without `window.refresh()` (PR #617).
248fn resize_hit_zones(
249    window_size: Size<Pixels>,
250    shadow_size: Pixels,
251    hit_size: Pixels,
252    tiling: &Tiling,
253) -> Vec<AnyElement> {
254    if tiling.top && tiling.bottom && tiling.left && tiling.right {
255        return Vec::new();
256    }
257
258    let insets = client_frame_insets(shadow_size, tiling);
259    let inner_left = insets.left;
260    let inner_right = window_size.width - insets.right;
261    let inner_top = insets.top;
262    let inner_bottom = window_size.height - insets.bottom;
263    // Overlay is laid out in the padded content box; convert from window coords.
264    let frame_origin = point(insets.left, insets.top);
265    let band = hit_size + hit_size;
266    let span_x = inner_right - inner_left + band;
267    let span_y = inner_bottom - inner_top + band;
268
269    let mut zones: Vec<AnyElement> = Vec::new();
270
271    let mut push_zone = |edge: ResizeEdge, origin: Point<Pixels>, zone_size: Size<Pixels>| {
272        let origin = origin - frame_origin;
273        zones.push(
274            div()
275                .absolute()
276                .left(origin.x)
277                .top(origin.y)
278                .w(zone_size.width)
279                .h(zone_size.height)
280                .cursor(cursor_style_for_resize_edge(edge))
281                .into_any_element(),
282        );
283    };
284
285    if !tiling.top {
286        push_zone(
287            ResizeEdge::Top,
288            point(inner_left - hit_size, inner_top - hit_size),
289            Size::new(span_x, band),
290        );
291    }
292    if !tiling.bottom {
293        push_zone(
294            ResizeEdge::Bottom,
295            point(inner_left - hit_size, inner_bottom - hit_size),
296            Size::new(span_x, band),
297        );
298    }
299    if !tiling.left {
300        push_zone(
301            ResizeEdge::Left,
302            point(inner_left - hit_size, inner_top - hit_size),
303            Size::new(band, span_y),
304        );
305    }
306    if !tiling.right {
307        push_zone(
308            ResizeEdge::Right,
309            point(inner_right - hit_size, inner_top - hit_size),
310            Size::new(band, span_y),
311        );
312    }
313
314    // Corners are pushed after edge strips so hit-testing prefers them over adjacent edges.
315    if !tiling.top && !tiling.left {
316        push_zone(
317            ResizeEdge::TopLeft,
318            point(inner_left - hit_size, inner_top - hit_size),
319            Size::new(band, band),
320        );
321    }
322    if !tiling.top && !tiling.right {
323        push_zone(
324            ResizeEdge::TopRight,
325            point(inner_right - hit_size, inner_top - hit_size),
326            Size::new(band, band),
327        );
328    }
329    if !tiling.bottom && !tiling.left {
330        push_zone(
331            ResizeEdge::BottomLeft,
332            point(inner_left - hit_size, inner_bottom - hit_size),
333            Size::new(band, band),
334        );
335    }
336    if !tiling.bottom && !tiling.right {
337        push_zone(
338            ResizeEdge::BottomRight,
339            point(inner_right - hit_size, inner_bottom - hit_size),
340            Size::new(band, band),
341        );
342    }
343
344    zones
345}
346
347/// Hit-test resize edges on a narrow band around the visible inner frame, not the full shadow padding.
348fn resize_edge(
349    pos: Point<Pixels>,
350    size: Size<Pixels>,
351    insets: Edges<Pixels>,
352    tiling: &Tiling,
353    hit_size: Pixels,
354) -> Option<ResizeEdge> {
355    let inner_left = insets.left;
356    let inner_right = size.width - insets.right;
357    let inner_top = insets.top;
358    let inner_bottom = size.height - insets.bottom;
359
360    // Each edge only applies along its corresponding inner-frame segment; it does not extend along the "extension lines" of the shadow padding.
361    let on_left = pos.x >= inner_left - hit_size
362        && pos.x <= inner_left + hit_size
363        && pos.y >= inner_top - hit_size
364        && pos.y <= inner_bottom + hit_size;
365    let on_right = pos.x >= inner_right - hit_size
366        && pos.x <= inner_right + hit_size
367        && pos.y >= inner_top - hit_size
368        && pos.y <= inner_bottom + hit_size;
369    let on_top = pos.y >= inner_top - hit_size
370        && pos.y <= inner_top + hit_size
371        && pos.x >= inner_left - hit_size
372        && pos.x <= inner_right + hit_size;
373    let on_bottom = pos.y >= inner_bottom - hit_size
374        && pos.y <= inner_bottom + hit_size
375        && pos.x >= inner_left - hit_size
376        && pos.x <= inner_right + hit_size;
377
378    if !tiling.top && !tiling.left && on_top && on_left {
379        return Some(ResizeEdge::TopLeft);
380    }
381    if !tiling.top && !tiling.right && on_top && on_right {
382        return Some(ResizeEdge::TopRight);
383    }
384    if !tiling.bottom && !tiling.left && on_bottom && on_left {
385        return Some(ResizeEdge::BottomLeft);
386    }
387    if !tiling.bottom && !tiling.right && on_bottom && on_right {
388        return Some(ResizeEdge::BottomRight);
389    }
390    if !tiling.top && on_top {
391        return Some(ResizeEdge::Top);
392    }
393    if !tiling.bottom && on_bottom {
394        return Some(ResizeEdge::Bottom);
395    }
396    if !tiling.left && on_left {
397        return Some(ResizeEdge::Left);
398    }
399    if !tiling.right && on_right {
400        return Some(ResizeEdge::Right);
401    }
402    None
403}