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};
8use gpui::{
9 AnyElement, App, Background, ClickEvent, Context, Decorations, Hsla, InteractiveElement,
10 IntoElement, MouseButton, ParentElement, Pixels, Render, RenderOnce, Rgba,
11 StatefulInteractiveElement as _, StyleRefinement, Styled, TitlebarOptions, Window,
12 WindowControlArea, WindowOptions, div, linear_color_stop, linear_gradient,
13 prelude::FluentBuilder as _, px, rems,
14};
15use gpui_base::TestSupportExt as _;
16use smallvec::SmallVec;
17
18pub const TITLE_BAR_HEIGHT: Pixels = px(34.);
19#[cfg(target_os = "macos")]
20const TITLE_BAR_LEFT_PADDING: Pixels = px(80.);
21#[cfg(not(target_os = "macos"))]
22const TITLE_BAR_LEFT_PADDING: Pixels = px(12.);
23
24fn default_title_bar_background(title_bar: Hsla, background: Hsla) -> Background {
25 let title_bar_rgb = title_bar.to_rgb();
26 let background_rgb = background.to_rgb();
27 let mixed = Hsla::from(Rgba {
28 r: title_bar_rgb.r * 0.55 + background_rgb.r * 0.45,
29 g: title_bar_rgb.g * 0.55 + background_rgb.g * 0.45,
30 b: title_bar_rgb.b * 0.55 + background_rgb.b * 0.45,
31 a: title_bar_rgb.a * 0.55 + background_rgb.a * 0.45,
32 });
33
34 linear_gradient(
35 180.,
36 linear_color_stop(mixed, 0.),
37 linear_color_stop(title_bar, 1.),
38 )
39}
40
41#[derive(IntoElement)]
45pub struct TitleBar {
46 style: StyleRefinement,
47 children: SmallVec<[AnyElement; 1]>,
48 on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
49}
50
51impl TitleBar {
52 pub fn new() -> Self {
54 Self {
55 style: StyleRefinement::default(),
56 children: SmallVec::new(),
57 on_close_window: None,
58 }
59 }
60
61 pub fn title_bar_options() -> TitlebarOptions {
63 TitlebarOptions {
64 title: None,
65 appears_transparent: true,
66 traffic_light_position: Some(gpui::point(px(9.0), px(9.0))),
67 }
68 }
69
70 pub fn window_options() -> WindowOptions {
85 WindowOptions {
86 titlebar: Some(Self::title_bar_options()),
87 app_owns_titlebar_drag: true,
92 ..Default::default()
93 }
94 }
95
96 pub fn on_close_window(
99 mut self,
100 f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
101 ) -> Self {
102 if cfg!(target_os = "linux") {
103 self.on_close_window = Some(Rc::new(Box::new(f)));
104 }
105 self
106 }
107}
108
109#[derive(IntoElement, Clone)]
114enum ControlIcon {
115 Minimize,
116 Restore,
117 Maximize,
118 Close {
119 on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
120 },
121}
122
123impl ControlIcon {
124 fn minimize() -> Self {
125 Self::Minimize
126 }
127
128 fn restore() -> Self {
129 Self::Restore
130 }
131
132 fn maximize() -> Self {
133 Self::Maximize
134 }
135
136 fn close(on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>) -> Self {
137 Self::Close { on_close_window }
138 }
139
140 fn id(&self) -> &'static str {
141 match self {
142 Self::Minimize => "minimize",
143 Self::Restore => "restore",
144 Self::Maximize => "maximize",
145 Self::Close { .. } => "close",
146 }
147 }
148
149 fn icon(&self) -> IconName {
150 match self {
151 Self::Minimize => IconName::WindowMinimize,
152 Self::Restore => IconName::WindowRestore,
153 Self::Maximize => IconName::WindowMaximize,
154 Self::Close { .. } => IconName::WindowClose,
155 }
156 }
157
158 fn window_control_area(&self) -> WindowControlArea {
159 match self {
160 Self::Minimize => WindowControlArea::Min,
161 Self::Restore | Self::Maximize => WindowControlArea::Max,
162 Self::Close { .. } => WindowControlArea::Close,
163 }
164 }
165
166 fn is_close(&self) -> bool {
167 matches!(self, Self::Close { .. })
168 }
169
170 #[inline]
171 fn hover_fg(&self, cx: &App) -> Hsla {
172 if self.is_close() {
173 cx.theme().danger_foreground
174 } else {
175 cx.theme().secondary_foreground
176 }
177 }
178
179 #[inline]
180 fn hover_bg(&self, cx: &App) -> Hsla {
181 if self.is_close() {
182 cx.theme().danger
183 } else {
184 cx.theme().secondary_hover
185 }
186 }
187
188 #[inline]
189 fn active_bg(&self, cx: &mut App) -> Hsla {
190 if self.is_close() {
191 cx.theme().danger_active
192 } else {
193 cx.theme().secondary_active
194 }
195 }
196}
197
198impl RenderOnce for ControlIcon {
199 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
200 let is_linux = cfg!(target_os = "linux");
201 let is_windows = cfg!(target_os = "windows");
202 let hover_fg = self.hover_fg(cx);
203 let hover_bg = self.hover_bg(cx);
204 let active_bg = self.active_bg(cx);
205 let icon = self.clone();
206 let on_close_window = match &self {
207 ControlIcon::Close { on_close_window } => on_close_window.clone(),
208 _ => None,
209 };
210
211 div()
212 .id(self.id())
213 .test_support()
214 .flex()
215 .w(TITLE_BAR_HEIGHT)
216 .h_full()
217 .flex_shrink_0()
218 .justify_center()
219 .content_center()
220 .items_center()
221 .text_color(cx.theme().foreground)
222 .hover(|style| style.bg(hover_bg).text_color(hover_fg))
223 .active(|style| style.bg(active_bg).text_color(hover_fg))
224 .when(is_windows, |this| {
225 this.window_control_area(self.window_control_area())
226 })
227 .when(is_linux, |this| {
228 this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
229 window.prevent_default();
230 cx.stop_propagation();
231 })
232 .on_click(move |_, window, cx| {
233 cx.stop_propagation();
234 match icon {
235 Self::Minimize => window.minimize_window(),
236 Self::Restore | Self::Maximize => window.zoom_window(),
237 Self::Close { .. } => {
238 if let Some(f) = on_close_window.clone() {
239 f(&ClickEvent::default(), window, cx);
240 } else {
241 window.remove_window();
242 }
243 }
244 }
245 })
246 })
247 .child(Icon::new(self.icon()).small())
248 }
249}
250
251#[derive(IntoElement)]
252struct WindowControls {
253 on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
254}
255
256impl RenderOnce for WindowControls {
257 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
258 if cfg!(target_os = "macos") || cfg!(target_family = "wasm") {
259 return div().id("window-controls").test_support();
260 }
261
262 #[cfg(target_os = "linux")]
272 if !matches!(window.window_decorations(), Decorations::Client { .. }) {
273 return div().id("window-controls").test_support();
274 }
275
276 let supported = window.window_controls();
280
281 h_flex()
283 .flex_row_dir(cx)
284 .id("window-controls")
285 .test_support()
286 .items_center()
287 .flex_shrink_0()
288 .h_full()
289 .when(supported.minimize, |this| {
290 this.child(ControlIcon::minimize())
291 })
292 .when(supported.maximize, |this| {
293 this.child(if window.is_maximized() {
294 ControlIcon::restore()
295 } else {
296 ControlIcon::maximize()
297 })
298 })
299 .child(ControlIcon::close(self.on_close_window))
300 }
301}
302
303impl Styled for TitleBar {
304 fn style(&mut self) -> &mut gpui::StyleRefinement {
305 &mut self.style
306 }
307}
308
309impl ParentElement for TitleBar {
310 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
311 self.children.extend(elements);
312 }
313}
314
315struct TitleBarState {
316 should_move: bool,
317}
318
319impl Render for TitleBarState {
321 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
322 div()
323 }
324}
325
326impl RenderOnce for TitleBar {
327 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
328 let is_client_decorated = matches!(window.window_decorations(), Decorations::Client { .. });
329 let is_web = cfg!(target_family = "wasm");
330 let is_linux = cfg!(target_os = "linux");
331 let is_macos = cfg!(target_os = "macos");
332
333 let state = window.use_state(cx, |_, _| TitleBarState { should_move: false });
334 let radii = crate::window_corner_radii(window, cx);
335
336 div().flex_shrink_0().child(
337 div()
338 .id("title-bar")
339 .flex_row_dir(cx)
340 .items_center()
341 .justify_between()
342 .h(TITLE_BAR_HEIGHT)
343 .map(|this| {
346 if is_macos {
347 this.pl(TITLE_BAR_LEFT_PADDING)
348 } else {
349 this.ps(TITLE_BAR_LEFT_PADDING, cx)
350 }
351 })
352 .rounded_tl(radii.top_left)
353 .rounded_tr(radii.top_right)
354 .border_b_1()
355 .border_color(cx.theme().title_bar_border)
356 .bg(default_title_bar_background(
357 cx.theme().title_bar,
358 cx.theme().background,
359 ))
360 .refine_style(&self.style)
361 .when(is_linux, |this| {
362 this.on_double_click(|_, window, _| window.zoom_window())
363 })
364 .when(is_macos, |this| {
365 this.on_double_click(|_, window, _| window.titlebar_double_click())
366 })
367 .test_support()
369 .on_mouse_down_out(window.listener_for(&state, |state, _, _, _| {
370 state.should_move = false;
371 }))
372 .on_mouse_down(
373 MouseButton::Left,
374 window.listener_for(&state, |state, _, window, cx| {
378 state.should_move = !window.default_prevented();
379 crate::GlobalState::suppress_text_selection(cx);
385 }),
386 )
387 .on_mouse_up(
388 MouseButton::Left,
389 window.listener_for(&state, |state, _, _, _| {
390 state.should_move = false;
391 }),
392 )
393 .on_mouse_move(window.listener_for(
394 &state,
395 |state, event: &gpui::MouseMoveEvent, window, cx| {
396 if event.pressed_button != Some(MouseButton::Left) {
397 state.should_move = false;
398 return;
399 }
400 if state.should_move {
401 state.should_move = false;
402 gpui_base::TextSelection::end(window, cx);
403 cx.stop_active_drag(window);
404 window.start_window_move();
405 }
406 },
407 ))
408 .child(
409 h_flex()
410 .id("bar")
411 .h_full()
412 .justify_between()
413 .flex_shrink_0()
414 .flex_1()
415 .when(!is_web, |this| {
416 this.window_control_area(WindowControlArea::Drag)
417 .when(window.is_fullscreen(), |this| this.ps(rems(0.75), cx))
418 .when(is_linux && is_client_decorated, |this| {
419 this.child(
420 div()
421 .top_0()
422 .left_0()
423 .absolute()
424 .size_full()
425 .h_full()
426 .on_mouse_down(
427 MouseButton::Right,
428 move |ev, window, _| {
429 window.show_window_menu(ev.position)
430 },
431 ),
432 )
433 })
434 })
435 .children(self.children),
436 )
437 .child(WindowControls {
438 on_close_window: self.on_close_window,
439 }),
440 )
441 }
442}
443
444#[cfg(test)]
445mod tests {
446 use super::*;
447 use gpui::{
448 AppContext as _, Modifiers, Rgba, TestAppContext, VisualTestContext, linear_color_stop,
449 linear_gradient, point, px,
450 };
451 use std::cell::Cell;
452
453 use crate::button::Button;
454
455 const BUTTON: &str = "title-bar-button";
456
457 struct BarWithButton {
458 clicks: Rc<Cell<usize>>,
459 }
460
461 impl Render for BarWithButton {
462 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
463 let clicks = self.clicks.clone();
464 TitleBar::new().child(div().w(px(200.)).child("App")).child(
465 Button::new("open")
466 .label("Open")
467 .debug_selector(|| BUTTON.to_string())
468 .on_click(move |_, _, _| clicks.set(clicks.get() + 1)),
469 )
470 }
471 }
472
473 fn open(cx: &mut TestAppContext) -> (VisualTestContext, Rc<Cell<usize>>) {
474 cx.update(crate::init);
475 let clicks = Rc::new(Cell::new(0));
476 let view = cx.new(|_| BarWithButton {
477 clicks: clicks.clone(),
478 });
479 let window = cx.update(|cx| {
480 cx.open_window(Default::default(), |window, cx| {
481 cx.new(|cx| crate::Root::new(view.clone(), window, cx))
482 })
483 .unwrap()
484 });
485 let mut cx = VisualTestContext::from_window(window.into(), cx);
486 cx.update(|window, cx| window.draw(cx).clear(cx));
487 (cx, clicks)
488 }
489
490 fn click_with_drift(cx: &mut VisualTestContext, at: gpui::Point<Pixels>) {
492 let drift = point(at.x + px(1.), at.y);
493 cx.simulate_mouse_down(at, MouseButton::Left, Modifiers::default());
494 cx.simulate_mouse_move(drift, Some(MouseButton::Left), Modifiers::default());
495 cx.simulate_mouse_up(drift, MouseButton::Left, Modifiers::default());
496 }
497
498 #[gpui::test]
499 fn a_press_on_a_control_keeps_its_click(cx: &mut TestAppContext) {
500 let (mut cx, clicks) = open(cx);
501 let at = cx
502 .debug_bounds(BUTTON)
503 .expect("the button is drawn")
504 .center();
505 click_with_drift(&mut cx, at);
506 assert_eq!(clicks.get(), 1);
507 }
508
509 #[gpui::test]
510 fn a_press_on_the_bar_does_not_start_a_text_selection(cx: &mut TestAppContext) {
511 let (mut cx, _) = open(cx);
512 let button = cx.debug_bounds(BUTTON).expect("the button is drawn");
513 let bar = point(button.left() - px(100.), button.center().y);
514 cx.simulate_mouse_down(bar, MouseButton::Left, Modifiers::default());
515 cx.update(|_, cx| assert!(crate::GlobalState::is_text_selection_suppressed(cx)));
516 }
517
518 #[gpui::test]
521 #[should_panic(expected = "not implemented")]
522 fn a_press_on_the_bar_itself_still_moves_the_window(cx: &mut TestAppContext) {
523 let (mut cx, _) = open(cx);
524 let button = cx.debug_bounds(BUTTON).expect("the button is drawn");
525 click_with_drift(&mut cx, point(button.left() - px(100.), button.center().y));
526 }
527
528 #[test]
529 fn test_default_title_bar_background() {
530 let title_bar = Hsla::black();
531 let background = Hsla::white();
532
533 assert_eq!(
534 default_title_bar_background(title_bar, background),
535 linear_gradient(
536 180.,
537 linear_color_stop(
538 Hsla::from(Rgba {
539 r: 0.45,
540 g: 0.45,
541 b: 0.45,
542 a: 1.,
543 }),
544 0.,
545 ),
546 linear_color_stop(title_bar, 1.),
547 )
548 );
549 }
550}