1use std::rc::Rc;
2
3use gpui_base::LogicalStyledExt as _;
4
5use crate::{
6 ActiveTheme, Icon, IconName, InteractiveElementExt as _, Sizable as _, StyledExt, h_flex,
7};
8#[cfg(target_os = "linux")]
9use gpui::Subscription;
10use gpui::{
11 AnyElement, App, Background, ClickEvent, Context, Decorations, Hsla, InteractiveElement,
12 IntoElement, MouseButton, ParentElement, Pixels, Render, RenderOnce, Rgba,
13 StatefulInteractiveElement as _, StyleRefinement, Styled, TitlebarOptions, Window,
14 WindowButton, WindowButtonLayout, WindowControlArea, WindowOptions, div, linear_color_stop,
15 linear_gradient, prelude::FluentBuilder as _, px, rems,
16};
17use gpui_base::TestSupportExt as _;
18use smallvec::SmallVec;
19
20pub const TITLE_BAR_HEIGHT: Pixels = px(34.);
21#[cfg(target_os = "macos")]
22const TITLE_BAR_LEFT_PADDING: Pixels = px(80.);
23#[cfg(not(target_os = "macos"))]
24const TITLE_BAR_LEFT_PADDING: Pixels = px(12.);
25
26fn default_title_bar_background(title_bar: Hsla, background: Hsla) -> Background {
27 let title_bar_rgb = title_bar.to_rgb();
28 let background_rgb = background.to_rgb();
29 let mixed = Hsla::from(Rgba {
30 r: title_bar_rgb.r * 0.55 + background_rgb.r * 0.45,
31 g: title_bar_rgb.g * 0.55 + background_rgb.g * 0.45,
32 b: title_bar_rgb.b * 0.55 + background_rgb.b * 0.45,
33 a: title_bar_rgb.a * 0.55 + background_rgb.a * 0.45,
34 });
35
36 linear_gradient(
37 180.,
38 linear_color_stop(mixed, 0.),
39 linear_color_stop(title_bar, 1.),
40 )
41}
42
43#[derive(IntoElement)]
47pub struct TitleBar {
48 style: StyleRefinement,
49 children: SmallVec<[AnyElement; 1]>,
50 on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
51}
52
53impl TitleBar {
54 pub fn new() -> Self {
56 Self {
57 style: StyleRefinement::default(),
58 children: SmallVec::new(),
59 on_close_window: None,
60 }
61 }
62
63 pub fn title_bar_options() -> TitlebarOptions {
65 TitlebarOptions {
66 title: None,
67 appears_transparent: true,
68 traffic_light_position: Some(gpui::point(px(9.0), px(9.0))),
69 }
70 }
71
72 pub fn window_options() -> WindowOptions {
87 WindowOptions {
88 titlebar: Some(Self::title_bar_options()),
89 app_owns_titlebar_drag: true,
94 ..Default::default()
95 }
96 }
97
98 pub fn on_close_window(
101 mut self,
102 f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
103 ) -> Self {
104 if cfg!(target_os = "linux") {
105 self.on_close_window = Some(Rc::new(Box::new(f)));
106 }
107 self
108 }
109}
110
111#[derive(IntoElement, Clone)]
116enum ControlIcon {
117 Minimize,
118 Restore,
119 Maximize,
120 Close {
121 on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
122 },
123}
124
125fn window_button_layout(_cx: &App) -> WindowButtonLayout {
126 #[cfg(target_os = "linux")]
127 {
128 _cx.button_layout()
129 .unwrap_or_else(WindowButtonLayout::linux_default)
130 }
131
132 #[cfg(not(target_os = "linux"))]
133 {
134 WindowButtonLayout {
135 left: [None; gpui::MAX_BUTTONS_PER_SIDE],
136 right: [
137 Some(WindowButton::Minimize),
138 Some(WindowButton::Maximize),
139 Some(WindowButton::Close),
140 ],
141 }
142 }
143}
144
145fn supported_buttons(
146 buttons: [Option<WindowButton>; gpui::MAX_BUTTONS_PER_SIDE],
147 supported: gpui::WindowControls,
148) -> SmallVec<[WindowButton; gpui::MAX_BUTTONS_PER_SIDE]> {
149 buttons
150 .into_iter()
151 .flatten()
152 .filter(|button| match button {
153 WindowButton::Minimize => supported.minimize,
154 WindowButton::Maximize => supported.maximize,
155 WindowButton::Close => true,
156 })
157 .collect()
158}
159
160impl ControlIcon {
161 fn minimize() -> Self {
162 Self::Minimize
163 }
164
165 fn restore() -> Self {
166 Self::Restore
167 }
168
169 fn maximize() -> Self {
170 Self::Maximize
171 }
172
173 fn close(on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>) -> Self {
174 Self::Close { on_close_window }
175 }
176
177 fn id(&self) -> &'static str {
178 match self {
179 Self::Minimize => "minimize",
180 Self::Restore => "restore",
181 Self::Maximize => "maximize",
182 Self::Close { .. } => "close",
183 }
184 }
185
186 fn icon(&self) -> IconName {
187 match self {
188 Self::Minimize => IconName::WindowMinimize,
189 Self::Restore => IconName::WindowRestore,
190 Self::Maximize => IconName::WindowMaximize,
191 Self::Close { .. } => IconName::WindowClose,
192 }
193 }
194
195 fn window_control_area(&self) -> WindowControlArea {
196 match self {
197 Self::Minimize => WindowControlArea::Min,
198 Self::Restore | Self::Maximize => WindowControlArea::Max,
199 Self::Close { .. } => WindowControlArea::Close,
200 }
201 }
202
203 fn is_close(&self) -> bool {
204 matches!(self, Self::Close { .. })
205 }
206
207 #[inline]
208 fn hover_fg(&self, cx: &App) -> Hsla {
209 if self.is_close() {
210 cx.theme().danger_foreground
211 } else {
212 cx.theme().secondary_foreground
213 }
214 }
215
216 #[inline]
217 fn hover_bg(&self, cx: &App) -> Hsla {
218 if self.is_close() {
219 cx.theme().danger
220 } else {
221 cx.theme().secondary_hover
222 }
223 }
224
225 #[inline]
226 fn active_bg(&self, cx: &mut App) -> Hsla {
227 if self.is_close() {
228 cx.theme().danger_active
229 } else {
230 cx.theme().secondary_active
231 }
232 }
233}
234
235impl RenderOnce for ControlIcon {
236 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
237 let is_linux = cfg!(target_os = "linux");
238 let is_windows = cfg!(target_os = "windows");
239 let hover_fg = self.hover_fg(cx);
240 let hover_bg = self.hover_bg(cx);
241 let active_bg = self.active_bg(cx);
242 let icon = self.clone();
243 let on_close_window = match &self {
244 ControlIcon::Close { on_close_window } => on_close_window.clone(),
245 _ => None,
246 };
247
248 div()
249 .id(self.id())
250 .test_support()
251 .flex()
252 .w(TITLE_BAR_HEIGHT)
253 .h_full()
254 .flex_shrink_0()
255 .justify_center()
256 .content_center()
257 .items_center()
258 .text_color(cx.theme().foreground)
259 .hover(|style| style.bg(hover_bg).text_color(hover_fg))
260 .active(|style| style.bg(active_bg).text_color(hover_fg))
261 .when(is_windows, |this| {
262 this.window_control_area(self.window_control_area())
263 })
264 .when(is_linux, |this| {
265 this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
266 window.prevent_default();
267 cx.stop_propagation();
268 })
269 .on_click(move |_, window, cx| {
270 cx.stop_propagation();
271 match icon {
272 Self::Minimize => window.minimize_window(),
273 Self::Restore | Self::Maximize => window.zoom_window(),
274 Self::Close { .. } => {
275 if let Some(f) = on_close_window.clone() {
276 f(&ClickEvent::default(), window, cx);
277 } else {
278 window.remove_window();
279 }
280 }
281 }
282 })
283 })
284 .child(Icon::new(self.icon()).small())
285 }
286}
287
288#[derive(IntoElement)]
289struct WindowControls {
290 id: &'static str,
291 buttons: [Option<WindowButton>; gpui::MAX_BUTTONS_PER_SIDE],
292 on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
293}
294
295impl RenderOnce for WindowControls {
296 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
297 if cfg!(target_os = "macos") || cfg!(target_family = "wasm") {
298 return div().id(self.id).test_support();
299 }
300
301 #[cfg(target_os = "linux")]
311 if !matches!(window.window_decorations(), Decorations::Client { .. }) {
312 return div().id(self.id).test_support();
313 }
314
315 let supported = window.window_controls();
318
319 h_flex()
321 .flex_row_dir(cx)
322 .id(self.id)
323 .test_support()
324 .items_center()
325 .flex_shrink_0()
326 .h_full()
327 .children(
328 supported_buttons(self.buttons, supported)
329 .into_iter()
330 .map(|button| match button {
331 WindowButton::Minimize => ControlIcon::minimize(),
332 WindowButton::Maximize if window.is_maximized() => ControlIcon::restore(),
333 WindowButton::Maximize => ControlIcon::maximize(),
334 WindowButton::Close => ControlIcon::close(self.on_close_window.clone()),
335 }),
336 )
337 }
338}
339
340impl Styled for TitleBar {
341 fn style(&mut self) -> &mut gpui::StyleRefinement {
342 &mut self.style
343 }
344}
345
346impl ParentElement for TitleBar {
347 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
348 self.children.extend(elements);
349 }
350}
351
352struct TitleBarState {
353 should_move: bool,
354 #[cfg(target_os = "linux")]
355 _button_layout_subscription: Subscription,
357}
358
359impl Render for TitleBarState {
361 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
362 div()
363 }
364}
365
366impl RenderOnce for TitleBar {
367 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
368 let is_client_decorated = matches!(window.window_decorations(), Decorations::Client { .. });
369 let is_web = cfg!(target_family = "wasm");
370 let is_linux = cfg!(target_os = "linux");
371 let is_macos = cfg!(target_os = "macos");
372
373 let state = window.use_state(cx, |_window, _state_cx| TitleBarState {
374 should_move: false,
375 #[cfg(target_os = "linux")]
376 _button_layout_subscription: _state_cx
377 .observe_button_layout_changed(_window, |_, _, cx| cx.notify()),
378 });
379 let radii = crate::window_corner_radii(window, cx);
380 let button_layout = window_button_layout(cx);
381
382 div().flex_shrink_0().child(
383 div()
384 .id("title-bar")
385 .flex_row_dir(cx)
386 .when(is_linux, |this| this.flex_row())
387 .items_center()
388 .justify_between()
389 .h(TITLE_BAR_HEIGHT)
390 .map(|this| {
393 if is_macos || is_linux {
394 this.pl(TITLE_BAR_LEFT_PADDING)
395 } else {
396 this.ps(TITLE_BAR_LEFT_PADDING, cx)
397 }
398 })
399 .rounded_tl(radii.top_left)
400 .rounded_tr(radii.top_right)
401 .border_b_1()
402 .border_color(cx.theme().title_bar_border)
403 .bg(default_title_bar_background(
404 cx.theme().title_bar,
405 cx.theme().background,
406 ))
407 .refine_style(&self.style)
408 .when(is_linux, |this| {
409 this.on_double_click(|_, window, _| window.zoom_window())
410 })
411 .when(is_macos, |this| {
412 this.on_double_click(|_, window, _| window.titlebar_double_click())
413 })
414 .test_support()
416 .on_mouse_down_out(window.listener_for(&state, |state, _, _, _| {
417 state.should_move = false;
418 }))
419 .on_mouse_down(
420 MouseButton::Left,
421 window.listener_for(&state, |state, _, window, cx| {
425 state.should_move = !window.default_prevented();
426 crate::GlobalState::suppress_text_selection(cx);
432 }),
433 )
434 .on_mouse_up(
435 MouseButton::Left,
436 window.listener_for(&state, |state, _, _, _| {
437 state.should_move = false;
438 }),
439 )
440 .on_mouse_move(window.listener_for(
441 &state,
442 |state, event: &gpui::MouseMoveEvent, window, cx| {
443 if event.pressed_button != Some(MouseButton::Left) {
444 state.should_move = false;
445 return;
446 }
447 if state.should_move {
448 state.should_move = false;
449 gpui_base::TextSelection::end(window, cx);
450 cx.stop_active_drag(window);
451 window.start_window_move();
452 }
453 },
454 ))
455 .when(is_linux, |this| {
456 this.child(WindowControls {
457 id: "window-controls-start",
458 buttons: button_layout.left,
459 on_close_window: self.on_close_window.clone(),
460 })
461 })
462 .child(
463 h_flex()
464 .id("bar")
465 .h_full()
466 .justify_between()
467 .flex_shrink_0()
468 .flex_1()
469 .when(!is_web, |this| {
470 this.window_control_area(WindowControlArea::Drag)
471 .when(window.is_fullscreen(), |this| this.ps(rems(0.75), cx))
472 .when(is_linux && is_client_decorated, |this| {
473 this.child(
474 div()
475 .top_0()
476 .left_0()
477 .absolute()
478 .size_full()
479 .h_full()
480 .on_mouse_down(
481 MouseButton::Right,
482 move |ev, window, _| {
483 window.show_window_menu(ev.position)
484 },
485 ),
486 )
487 })
488 })
489 .children(self.children),
490 )
491 .child(WindowControls {
492 id: "window-controls",
493 buttons: button_layout.right,
494 on_close_window: self.on_close_window,
495 }),
496 )
497 }
498}
499
500#[cfg(test)]
501mod tests {
502 use super::*;
503 use gpui::{
504 AppContext as _, Modifiers, Rgba, TestAppContext, VisualTestContext, linear_color_stop,
505 linear_gradient, point, px,
506 };
507 use std::cell::Cell;
508
509 use crate::button::Button;
510
511 #[test]
512 fn linux_window_controls_follow_layout_order_and_capabilities() {
513 let layout = WindowButtonLayout {
514 left: [
515 Some(WindowButton::Close),
516 Some(WindowButton::Minimize),
517 None,
518 ],
519 right: [
520 Some(WindowButton::Maximize),
521 Some(WindowButton::Close),
522 None,
523 ],
524 };
525 let supported = gpui::WindowControls {
526 fullscreen: true,
527 maximize: false,
528 minimize: true,
529 window_menu: true,
530 };
531
532 assert_eq!(
533 supported_buttons(layout.left, supported).as_slice(),
534 [WindowButton::Close, WindowButton::Minimize]
535 );
536 assert_eq!(
537 supported_buttons(layout.right, supported).as_slice(),
538 [WindowButton::Close]
539 );
540 }
541
542 const BUTTON: &str = "title-bar-button";
543
544 struct BarWithButton {
545 clicks: Rc<Cell<usize>>,
546 }
547
548 impl Render for BarWithButton {
549 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
550 let clicks = self.clicks.clone();
551 TitleBar::new().child(div().w(px(200.)).child("App")).child(
552 Button::new("open")
553 .label("Open")
554 .debug_selector(|| BUTTON.to_string())
555 .on_click(move |_, _, _| clicks.set(clicks.get() + 1)),
556 )
557 }
558 }
559
560 fn open(cx: &mut TestAppContext) -> (VisualTestContext, Rc<Cell<usize>>) {
561 cx.update(crate::init);
562 let clicks = Rc::new(Cell::new(0));
563 let view = cx.new(|_| BarWithButton {
564 clicks: clicks.clone(),
565 });
566 let window = cx.update(|cx| {
567 cx.open_window(Default::default(), |window, cx| {
568 cx.new(|cx| crate::Root::new(view.clone(), window, cx))
569 })
570 .unwrap()
571 });
572 let mut cx = VisualTestContext::from_window(window.into(), cx);
573 cx.update(|window, cx| window.draw(cx).clear(cx));
574 (cx, clicks)
575 }
576
577 fn click_with_drift(cx: &mut VisualTestContext, at: gpui::Point<Pixels>) {
579 let drift = point(at.x + px(1.), at.y);
580 cx.simulate_mouse_down(at, MouseButton::Left, Modifiers::default());
581 cx.simulate_mouse_move(drift, Some(MouseButton::Left), Modifiers::default());
582 cx.simulate_mouse_up(drift, MouseButton::Left, Modifiers::default());
583 }
584
585 #[gpui::test]
586 fn a_press_on_a_control_keeps_its_click(cx: &mut TestAppContext) {
587 let (mut cx, clicks) = open(cx);
588 let at = cx
589 .debug_bounds(BUTTON)
590 .expect("the button is drawn")
591 .center();
592 click_with_drift(&mut cx, at);
593 assert_eq!(clicks.get(), 1);
594 }
595
596 #[gpui::test]
597 fn a_press_on_the_bar_does_not_start_a_text_selection(cx: &mut TestAppContext) {
598 let (mut cx, _) = open(cx);
599 let button = cx.debug_bounds(BUTTON).expect("the button is drawn");
600 let bar = point(button.left() - px(100.), button.center().y);
601 cx.simulate_mouse_down(bar, MouseButton::Left, Modifiers::default());
602 cx.update(|_, cx| assert!(crate::GlobalState::is_text_selection_suppressed(cx)));
603 }
604
605 #[gpui::test]
608 #[should_panic(expected = "not implemented")]
609 fn a_press_on_the_bar_itself_still_moves_the_window(cx: &mut TestAppContext) {
610 let (mut cx, _) = open(cx);
611 let button = cx.debug_bounds(BUTTON).expect("the button is drawn");
612 click_with_drift(&mut cx, point(button.left() - px(100.), button.center().y));
613 }
614
615 #[test]
616 fn test_default_title_bar_background() {
617 let title_bar = Hsla::black();
618 let background = Hsla::white();
619
620 assert_eq!(
621 default_title_bar_background(title_bar, background),
622 linear_gradient(
623 180.,
624 linear_color_stop(
625 Hsla::from(Rgba {
626 r: 0.45,
627 g: 0.45,
628 b: 0.45,
629 a: 1.,
630 }),
631 0.,
632 ),
633 linear_color_stop(title_bar, 1.),
634 )
635 );
636 }
637}