BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / title_bar.rs

title_bar.rs

title_bar.rs 15.6 KiB Download Raw
1use std::rc::Rc;
2
3use crate::{
4 ActiveTheme, Icon, IconName, InteractiveElementExt as _, StyledExt, h_flex,
5};
6use gpui::{
7 AnyElement, App, Background, ClickEvent, Context, Decorations, Hsla, InteractiveElement,
8 IntoElement, MouseButton, ParentElement, Pixels, Render, RenderOnce, Rgba,
9 StatefulInteractiveElement as _, StyleRefinement, Styled, TitlebarOptions, Window,
10 WindowControlArea, WindowOptions, div, linear_color_stop, linear_gradient,
11 prelude::FluentBuilder as _, px,
12};
13use smallvec::SmallVec;
14
15pub const TITLE_BAR_HEIGHT: Pixels = px(34.);
16#[cfg(target_os = "macos")]
17const TITLE_BAR_LEFT_PADDING: Pixels = px(80.);
18#[cfg(not(target_os = "macos"))]
19const TITLE_BAR_LEFT_PADDING: Pixels = px(12.);
20/// Windows 11 caption button width at 100% scale.
21const CONTROL_BUTTON_WIDTH: Pixels = px(46.);
22/// Box that renders the 16/24 window glyphs 10 px wide, like Segoe Fluent Icons at 10 px.
23const CONTROL_ICON_SIZE: Pixels = px(15.);
24
25fn default_title_bar_background(title_bar: Hsla, background: Hsla) -> Background {
26 let title_bar_rgb = title_bar.to_rgb();
27 let background_rgb = background.to_rgb();
28 let mixed = Hsla::from(Rgba {
29 r: title_bar_rgb.r * 0.55 + background_rgb.r * 0.45,
30 g: title_bar_rgb.g * 0.55 + background_rgb.g * 0.45,
31 b: title_bar_rgb.b * 0.55 + background_rgb.b * 0.45,
32 a: title_bar_rgb.a * 0.55 + background_rgb.a * 0.45,
33 });
34
35 linear_gradient(
36 180.,
37 linear_color_stop(mixed, 0.),
38 linear_color_stop(title_bar, 1.),
39 )
40}
41
42/// TitleBar used to customize the appearance of the title bar.
43///
44/// We can put some elements inside the title bar.
45#[derive(IntoElement)]
46pub struct TitleBar {
47 style: StyleRefinement,
48 children: SmallVec<[AnyElement; 1]>,
49 on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
50 system_window_controls: bool,
51}
52
53impl TitleBar {
54 /// Create a new TitleBar.
55 pub fn new() -> Self {
56 Self {
57 style: StyleRefinement::default(),
58 children: SmallVec::new(),
59 on_close_window: None,
60 system_window_controls: true,
61 }
62 }
63
64 /// Returns the default title bar options for compatible with the [`crate::TitleBar`].
65 pub fn title_bar_options() -> TitlebarOptions {
66 TitlebarOptions {
67 title: None,
68 appears_transparent: true,
69 traffic_light_position: Some(gpui::point(px(9.0), px(9.0))),
70 }
71 }
72
73 /// Returns the default window options for compatible with the [`crate::TitleBar`].
74 ///
75 /// Use this as the base of the [`WindowOptions`] of any window that renders a
76 /// [`crate::TitleBar`], so the title bar owns dragging and double clicking itself:
77 ///
78 /// ```no_run
79 /// # mod gpui_kit { pub use gpui::*; pub extern crate gpui_component as component; }
80 /// # use gpui_kit::WindowOptions;
81 /// # use gpui_kit::component::TitleBar;
82 /// let options = WindowOptions {
83 /// window_min_size: None,
84 /// ..TitleBar::window_options()
85 /// };
86 /// ```
87 pub fn window_options() -> WindowOptions {
88 WindowOptions {
89 titlebar: Some(Self::title_bar_options()),
90 // The title bar draws itself and moves the window via `start_window_move`,
91 // so AppKit must not treat it as a system window-move region. Otherwise macOS
92 // handles title bar double clicks on its own (in addition to `on_double_click`
93 // below) and delays title bar clicks while disambiguating double clicks.
94 app_owns_titlebar_drag: true,
95 ..Default::default()
96 }
97 }
98
99 /// Add custom for close window event, default is None, then click X button will call `window.remove_window()`.
100 /// Linux only, this will do nothing on other platforms.
101 pub fn on_close_window(
102 mut self,
103 f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
104 ) -> Self {
105 if cfg!(target_os = "linux") {
106 self.on_close_window = Some(Rc::new(Box::new(f)));
107 }
108 self
109 }
110
111 /// Whether this title bar draws the built-in minimize/maximize/close buttons.
112 ///
113 /// Defaults to `true`. Set to `false` when the window draws its own buttons,
114 /// so the two sets are not stacked.
115 pub fn system_window_controls(mut self, show: bool) -> Self {
116 self.system_window_controls = show;
117 self
118 }
119}
120
121// We don't need implementation the click event for the control buttons.
122// If user clicked in the bounds, the window event will be triggered.
123#[derive(IntoElement, Clone)]
124enum ControlIcon {
125 Minimize,
126 Restore,
127 Maximize,
128 Close {
129 on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
130 },
131}
132
133impl ControlIcon {
134 fn minimize() -> Self {
135 Self::Minimize
136 }
137
138 fn restore() -> Self {
139 Self::Restore
140 }
141
142 fn maximize() -> Self {
143 Self::Maximize
144 }
145
146 fn close(on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>) -> Self {
147 Self::Close { on_close_window }
148 }
149
150 fn id(&self) -> &'static str {
151 match self {
152 Self::Minimize => "minimize",
153 Self::Restore => "restore",
154 Self::Maximize => "maximize",
155 Self::Close { .. } => "close",
156 }
157 }
158
159 fn icon(&self) -> IconName {
160 match self {
161 Self::Minimize => IconName::WindowMinimize,
162 Self::Restore => IconName::WindowRestore,
163 Self::Maximize => IconName::WindowMaximize,
164 Self::Close { .. } => IconName::WindowClose,
165 }
166 }
167
168 fn window_control_area(&self) -> WindowControlArea {
169 match self {
170 Self::Minimize => WindowControlArea::Min,
171 Self::Restore | Self::Maximize => WindowControlArea::Max,
172 Self::Close { .. } => WindowControlArea::Close,
173 }
174 }
175
176 fn is_close(&self) -> bool {
177 matches!(self, Self::Close { .. })
178 }
179
180 #[inline]
181 fn hover_fg(&self, cx: &App) -> Hsla {
182 if self.is_close() {
183 cx.theme().danger_foreground
184 } else {
185 cx.theme().secondary_foreground
186 }
187 }
188
189 #[inline]
190 fn hover_bg(&self, cx: &App) -> Hsla {
191 if self.is_close() {
192 cx.theme().danger
193 } else {
194 cx.theme().secondary_hover
195 }
196 }
197
198 #[inline]
199 fn active_bg(&self, cx: &mut App) -> Hsla {
200 if self.is_close() {
201 cx.theme().danger_active
202 } else {
203 cx.theme().secondary_active
204 }
205 }
206}
207
208impl RenderOnce for ControlIcon {
209 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
210 let is_linux = cfg!(target_os = "linux");
211 let is_windows = cfg!(target_os = "windows");
212 let hover_fg = self.hover_fg(cx);
213 let hover_bg = self.hover_bg(cx);
214 let active_bg = self.active_bg(cx);
215 let icon = self.clone();
216 let on_close_window = match &self {
217 ControlIcon::Close { on_close_window } => on_close_window.clone(),
218 _ => None,
219 };
220
221 div()
222 .id(self.id())
223 .flex()
224 .w(CONTROL_BUTTON_WIDTH)
225 .h_full()
226 .flex_shrink_0()
227 .justify_center()
228 .content_center()
229 .items_center()
230 .text_color(cx.theme().foreground)
231 .hover(|style| style.bg(hover_bg).text_color(hover_fg))
232 .active(|style| style.bg(active_bg).text_color(hover_fg))
233 .when(is_windows, |this| {
234 this.window_control_area(self.window_control_area())
235 })
236 .when(is_linux, |this| {
237 this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
238 window.prevent_default();
239 cx.stop_propagation();
240 })
241 .on_click(move |_, window, cx| {
242 cx.stop_propagation();
243 match icon {
244 Self::Minimize => window.minimize_window(),
245 Self::Restore | Self::Maximize => window.zoom_window(),
246 Self::Close { .. } => {
247 if let Some(f) = on_close_window.clone() {
248 f(&ClickEvent::default(), window, cx);
249 } else {
250 window.remove_window();
251 }
252 }
253 }
254 })
255 })
256 .child(Icon::new(self.icon()).size(CONTROL_ICON_SIZE))
257 }
258}
259
260#[derive(IntoElement)]
261struct WindowControls {
262 on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
263}
264
265impl RenderOnce for WindowControls {
266 fn render(self, window: &mut Window, _: &mut App) -> impl IntoElement {
267 if cfg!(target_os = "macos") || cfg!(target_family = "wasm") {
268 return div().id("window-controls");
269 }
270
271 // Under server-side decorations the window manager already renders
272 // its own title bar, complete with min/max/close; drawing ours as
273 // well stacks a duplicate set of controls on top of it (most
274 // visibly two close buttons). gpui falls back to server-side
275 // decorations on X11 sessions without a compositor, and a Wayland
276 // compositor may grant server mode even when client mode was
277 // requested. Skip ours unless this window is actually client-side
278 // decorated, mirroring the `is_client_decorated` gating of the
279 // title bar's window-menu overlay.
280 #[cfg(target_os = "linux")]
281 if !matches!(window.window_decorations(), Decorations::Client { .. }) {
282 return div().id("window-controls");
283 }
284
285 // The window manager declares which controls it can honor; a tiling
286 // compositor may support neither minimize nor maximize. Close is
287 // always ours to offer.
288 let supported = window.window_controls();
289
290 h_flex()
291 .id("window-controls")
292 .items_center()
293 .flex_shrink_0()
294 .h_full()
295 .when(supported.minimize, |this| {
296 this.child(ControlIcon::minimize())
297 })
298 .when(supported.maximize, |this| {
299 this.child(if window.is_maximized() {
300 ControlIcon::restore()
301 } else {
302 ControlIcon::maximize()
303 })
304 })
305 .child(ControlIcon::close(self.on_close_window))
306 }
307}
308
309impl Styled for TitleBar {
310 fn style(&mut self) -> &mut gpui::StyleRefinement {
311 &mut self.style
312 }
313}
314
315impl ParentElement for TitleBar {
316 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
317 self.children.extend(elements);
318 }
319}
320
321struct TitleBarState {
322 should_move: bool,
323}
324
325// TODO: Remove this when GPUI has released v0.2.3
326impl Render for TitleBarState {
327 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
328 div()
329 }
330}
331
332impl RenderOnce for TitleBar {
333 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
334 let is_client_decorated = matches!(window.window_decorations(), Decorations::Client { .. });
335 let is_web = cfg!(target_family = "wasm");
336 let is_linux = cfg!(target_os = "linux");
337 let is_macos = cfg!(target_os = "macos");
338
339 let state = window.use_state(cx, |_, _| TitleBarState { should_move: false });
340
341 div().flex_shrink_0().child(
342 div()
343 .id("title-bar")
344 .flex()
345 .flex_row()
346 .items_center()
347 .justify_between()
348 .h(TITLE_BAR_HEIGHT)
349 // The macOS traffic lights are hidden in fullscreen, so their inset goes too.
350 .when(!(cfg!(target_os = "macos") && window.is_fullscreen()), |this| {
351 this.pl(TITLE_BAR_LEFT_PADDING)
352 })
353 .border_b_1()
354 .border_color(cx.theme().title_bar_border)
355 .bg(default_title_bar_background(
356 cx.theme().title_bar,
357 cx.theme().background,
358 ))
359 .refine_style(&self.style)
360 .when(is_linux || cfg!(target_os = "windows"), |this| {
361 this.on_double_click(|_, window, _| window.zoom_window())
362 })
363 .when(is_macos, |this| {
364 this.on_double_click(|_, window, _| window.titlebar_double_click())
365 })
366 .on_mouse_down_out(window.listener_for(&state, |state, _, _, _| {
367 state.should_move = false;
368 }))
369 .on_mouse_down(
370 MouseButton::Left,
371 window.listener_for(&state, |state, _, _, _| {
372 state.should_move = true;
373 }),
374 )
375 .on_mouse_up(
376 MouseButton::Left,
377 window.listener_for(&state, |state, _, _, _| {
378 state.should_move = false;
379 }),
380 )
381 .on_mouse_move(window.listener_for(&state, |state, _, window, _| {
382 if state.should_move {
383 state.should_move = false;
384 window.start_window_move();
385 }
386 }))
387 .child(
388 h_flex()
389 .id("bar")
390 .h_full()
391 .justify_between()
392 .flex_shrink_0()
393 .flex_1()
394 .when(!is_web, |this| {
395 this.window_control_area(WindowControlArea::Drag)
396 .when(window.is_fullscreen(), |this| this.pl_3())
397 .when(is_linux && is_client_decorated, |this| {
398 this.child(
399 div()
400 .top_0()
401 .left_0()
402 .absolute()
403 .size_full()
404 .h_full()
405 .on_mouse_down(
406 MouseButton::Right,
407 move |ev, window, _| {
408 window.show_window_menu(ev.position)
409 },
410 ),
411 )
412 })
413 })
414 .children(self.children),
415 )
416 .when(self.system_window_controls, |this| {
417 this.child(WindowControls {
418 on_close_window: self.on_close_window,
419 })
420 }),
421 )
422 }
423}
424
425#[cfg(test)]
426mod tests {
427 use super::*;
428 use gpui::{Rgba, linear_color_stop, linear_gradient};
429
430 #[test]
431 fn test_default_title_bar_background() {
432 let title_bar = Hsla::black();
433 let background = Hsla::white();
434
435 assert_eq!(
436 default_title_bar_background(title_bar, background),
437 linear_gradient(
438 180.,
439 linear_color_stop(
440 Hsla::from(Rgba {
441 r: 0.45,
442 g: 0.45,
443 b: 0.45,
444 a: 1.,
445 }),
446 0.,
447 ),
448 linear_color_stop(title_bar, 1.),
449 )
450 );
451 }
452}