1use gpui::{
2 AccessibleAction, App, Bounds, ClickEvent, ElementId, Hsla, InteractiveElement, IntoElement,
3 ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement,
4 Styled, Window, WindowControlArea, canvas, div, point, prelude::FluentBuilder, px,
5 transparent_black,
6};
7use gpui_base::TestSupportExt as _;
8use gpui_material_foundation::{color, current_material_strings, current_material_theme};
9use gpui_material_theme::{ColorRole, Direction};
10
11use super::platform::{
12 ChromePlatform, CloseHandler, activate_close, activate_maximize_or_restore, activate_minimize,
13 sanitize_positive, should_show_caption_buttons,
14};
15
16#[derive(Clone, Copy, Debug, Default, PartialEq)]
19pub struct CaptionButtonColors {
20 pub active_foreground: Option<Hsla>,
22 pub inactive_foreground: Option<Hsla>,
24 pub hover_background: Option<Hsla>,
26 pub hover_foreground: Option<Hsla>,
28 pub pressed_background: Option<Hsla>,
30 pub pressed_foreground: Option<Hsla>,
32 pub close_hover_background: Option<Hsla>,
34 pub close_hover_foreground: Option<Hsla>,
36 pub close_pressed_background: Option<Hsla>,
38 pub close_pressed_foreground: Option<Hsla>,
40}
41
42#[derive(Clone, Debug, PartialEq, Eq)]
44pub struct CaptionButtonLabels {
45 pub minimize: SharedString,
47 pub maximize: SharedString,
49 pub restore: SharedString,
51 pub close: SharedString,
53}
54
55impl Default for CaptionButtonLabels {
56 fn default() -> Self {
57 Self {
58 minimize: SharedString::new_static("Minimize"),
59 maximize: SharedString::new_static("Maximize"),
60 restore: SharedString::new_static("Restore"),
61 close: SharedString::new_static("Close"),
62 }
63 }
64}
65
66impl CaptionButtonLabels {
67 fn for_control(&self, control: CaptionButton) -> SharedString {
68 match control {
69 CaptionButton::Minimize => self.minimize.clone(),
70 CaptionButton::Maximize => self.maximize.clone(),
71 CaptionButton::Restore => self.restore.clone(),
72 CaptionButton::Close => self.close.clone(),
73 }
74 }
75}
76
77#[derive(IntoElement)]
83pub struct CaptionButtons {
84 id: ElementId,
85 colors: CaptionButtonColors,
86 labels: Option<CaptionButtonLabels>,
87 button_width: Option<Pixels>,
88 platform: ChromePlatform,
89 show: Option<bool>,
90 on_close: Option<CloseHandler>,
91}
92
93impl CaptionButtons {
94 pub fn new(id: impl Into<ElementId>) -> Self {
96 Self {
97 id: id.into(),
98 colors: CaptionButtonColors::default(),
99 labels: None,
100 button_width: None,
101 platform: ChromePlatform::current(),
102 show: None,
103 on_close: None,
104 }
105 }
106
107 pub fn colors(mut self, colors: CaptionButtonColors) -> Self {
109 self.colors = colors;
110 self
111 }
112
113 pub fn labels(mut self, labels: CaptionButtonLabels) -> Self {
116 self.labels = Some(labels);
117 self
118 }
119
120 pub fn button_width(mut self, width: Pixels) -> Self {
123 self.button_width = Some(width);
124 self
125 }
126
127 pub fn platform(mut self, platform: ChromePlatform) -> Self {
129 self.platform = platform;
130 self
131 }
132
133 pub fn show(mut self, show: bool) -> Self {
137 self.show = Some(show);
138 self
139 }
140
141 pub fn on_close(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
143 self.on_close = Some(std::rc::Rc::new(handler));
144 self
145 }
146
147 pub(super) fn with_close_handler(mut self, handler: Option<CloseHandler>) -> Self {
148 self.on_close = handler;
149 self
150 }
151
152 pub(super) fn with_show_override(mut self, show: Option<bool>) -> Self {
153 self.show = show;
154 self
155 }
156
157 pub(super) fn with_button_width_override(mut self, width: Option<Pixels>) -> Self {
158 self.button_width = width;
159 self
160 }
161}
162
163impl RenderOnce for CaptionButtons {
164 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
165 let parent_id = self.id.clone();
166 let buttons = div().id(self.id);
167 if !should_show_caption_buttons(window, self.platform, self.show) {
168 return buttons;
169 }
170
171 let controls = window.window_controls();
172 let show_minimize = window.is_minimizable() && controls.minimize;
173 let show_maximize = window.is_resizable() && controls.maximize;
174 let button_width = self.button_width.map_or_else(
175 || self.platform.default_caption_button_width(),
176 |width| sanitize_positive(width, self.platform.default_caption_button_width()),
177 );
178 let rtl = current_material_theme(window, cx).layout.direction == Direction::Rtl;
179 let labels = self.labels.unwrap_or_else(|| {
180 let strings = current_material_strings(window, cx);
181 CaptionButtonLabels {
182 minimize: SharedString::from(strings.minimize.clone()),
183 maximize: SharedString::from(strings.maximize.clone()),
184 restore: SharedString::from(strings.restore.clone()),
185 close: SharedString::from(strings.close.clone()),
186 }
187 });
188
189 let minimize = show_minimize.then(|| {
190 title_bar_control(
191 &parent_id,
192 CaptionButton::Minimize,
193 self.platform,
194 button_width,
195 self.colors,
196 labels.for_control(CaptionButton::Minimize),
197 None,
198 window,
199 cx,
200 )
201 });
202 let maximize = show_maximize.then(|| {
203 let control = if window.is_maximized() {
204 CaptionButton::Restore
205 } else {
206 CaptionButton::Maximize
207 };
208 title_bar_control(
209 &parent_id,
210 control,
211 self.platform,
212 button_width,
213 self.colors,
214 labels.for_control(control),
215 None,
216 window,
217 cx,
218 )
219 });
220 let close = title_bar_control(
221 &parent_id,
222 CaptionButton::Close,
223 self.platform,
224 button_width,
225 self.colors,
226 labels.for_control(CaptionButton::Close),
227 self.on_close,
228 window,
229 cx,
230 );
231
232 buttons
233 .flex()
234 .items_stretch()
235 .flex_shrink_0()
236 .when(rtl, |buttons| buttons.flex_row_reverse())
237 .when_some(minimize, |buttons, button| buttons.child(button))
238 .when_some(maximize, |buttons, button| buttons.child(button))
239 .child(close)
240 }
241}
242
243#[derive(Clone, Copy)]
244enum CaptionButton {
245 Minimize,
246 Maximize,
247 Restore,
248 Close,
249}
250
251impl CaptionButton {
252 fn id(self) -> &'static str {
253 match self {
254 Self::Minimize => "minimize",
255 Self::Maximize | Self::Restore => "maximize-restore",
256 Self::Close => "close",
257 }
258 }
259
260 fn area(self) -> WindowControlArea {
261 match self {
262 Self::Minimize => WindowControlArea::Min,
263 Self::Maximize | Self::Restore => WindowControlArea::Max,
264 Self::Close => WindowControlArea::Close,
265 }
266 }
267
268 fn activate(self, window: &mut Window, cx: &mut App, on_close: Option<&CloseHandler>) {
269 match self {
270 Self::Minimize => activate_minimize(window),
271 Self::Maximize | Self::Restore => activate_maximize_or_restore(window),
272 Self::Close => activate_close(window, cx, on_close),
273 }
274 }
275}
276
277#[allow(clippy::too_many_arguments)]
278fn title_bar_control(
279 parent_id: &ElementId,
280 control: CaptionButton,
281 platform: ChromePlatform,
282 button_width: Pixels,
283 colors: CaptionButtonColors,
284 label: SharedString,
285 on_close: Option<CloseHandler>,
286 window: &mut Window,
287 cx: &mut App,
288) -> impl IntoElement + use<> {
289 let key = ElementId::from((ElementId::from((parent_id.clone(), control.id())), "focus"));
290 let focus_handle = window
291 .use_keyed_state(key, cx, |_, cx| cx.focus_handle().tab_stop(true))
292 .read(cx)
293 .clone();
294 let theme = current_material_theme(window, cx);
295 let tone = |role| color(theme.colors.color(role));
296 let foreground = if window.is_window_active() {
297 colors
298 .active_foreground
299 .unwrap_or_else(|| tone(ColorRole::OnSurface))
300 } else {
301 colors
302 .inactive_foreground
303 .unwrap_or_else(|| tone(ColorRole::OnSurfaceVariant))
304 };
305 let (hover_fill, hover_text, pressed_fill, pressed_text) = match control {
306 CaptionButton::Close => (
307 colors
308 .close_hover_background
309 .unwrap_or_else(|| tone(ColorRole::Error)),
310 colors
311 .close_hover_foreground
312 .unwrap_or_else(|| tone(ColorRole::OnError)),
313 colors
314 .close_pressed_background
315 .unwrap_or_else(|| tone(ColorRole::ErrorContainer)),
316 colors
317 .close_pressed_foreground
318 .unwrap_or_else(|| tone(ColorRole::OnErrorContainer)),
319 ),
320 _ => (
321 colors
322 .hover_background
323 .unwrap_or_else(|| tone(ColorRole::SurfaceContainerHigh)),
324 colors
325 .hover_foreground
326 .unwrap_or_else(|| tone(ColorRole::OnSurface)),
327 colors
328 .pressed_background
329 .unwrap_or_else(|| tone(ColorRole::SurfaceContainerHighest)),
330 colors
331 .pressed_foreground
332 .unwrap_or_else(|| tone(ColorRole::OnSurface)),
333 ),
334 };
335 let ring = tone(ColorRole::Secondary);
336
337 let use_native_win32_area = platform == ChromePlatform::Windows
340 && !(matches!(control, CaptionButton::Close) && on_close.is_some());
341
342 let click_close = on_close.clone();
343 let a11y_close = on_close;
344
345 div()
346 .id(control.id())
347 .flex()
348 .items_center()
349 .justify_center()
350 .w(button_width)
351 .min_h(px(32.))
352 .flex_shrink_0()
353 .border_1()
354 .border_color(transparent_black())
355 .text_color(foreground)
356 .when(use_native_win32_area, |button| {
357 button.window_control_area(control.area())
358 })
359 .role(Role::Button)
360 .aria_label(label)
361 .track_focus(&focus_handle)
362 .tab_index(0)
363 .focus_visible(move |style| style.border_color(ring))
364 .hover(move |style| style.bg(hover_fill).text_color(hover_text))
365 .active(move |style| style.bg(pressed_fill).text_color(pressed_text))
366 .on_click(move |event, window, cx| {
367 if !use_native_win32_area || matches!(event, ClickEvent::Keyboard(_)) {
368 control.activate(window, cx, click_close.as_ref());
369 }
370 })
371 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
372 control.activate(window, cx, a11y_close.as_ref());
373 })
374 .child(caption_glyph(control))
375 .test_support()
376}
377
378fn caption_glyph(control: CaptionButton) -> impl IntoElement {
379 canvas(
380 |_, _, _| {},
381 move |bounds: Bounds<Pixels>, _, window: &mut Window, _| {
382 let stroke = window.text_style().color;
383 let x = bounds.origin.x;
384 let y = bounds.origin.y;
385 let w = bounds.size.width;
386 let h = bounds.size.height;
387 let mut builder = PathBuilder::stroke(px(1.));
388 match control {
389 CaptionButton::Minimize => {
390 let mid_y = y + h * 0.5;
391 builder.move_to(point(x, mid_y));
392 builder.line_to(point(x + w, mid_y));
393 }
394 CaptionButton::Maximize => {
395 let inset = px(0.5);
396 let x0 = x + inset;
397 let y0 = y + inset;
398 let x1 = x + w - inset;
399 let y1 = y + h - inset;
400 builder.add_polygon(
401 &[point(x0, y0), point(x1, y0), point(x1, y1), point(x0, y1)],
402 true,
403 );
404 }
405 CaptionButton::Restore => {
406 let inset = px(0.5);
407 let offset = px(2.);
408 let fx0 = x + inset;
410 let fy0 = y + offset + inset;
411 let fx1 = x + w - offset - inset;
412 let fy1 = y + h - inset;
413 builder.add_polygon(
414 &[
415 point(fx0, fy0),
416 point(fx1, fy0),
417 point(fx1, fy1),
418 point(fx0, fy1),
419 ],
420 true,
421 );
422 let bx0 = x + offset + inset;
424 let by0 = y + inset;
425 let bx1 = x + w - inset;
426 let by1 = y + h - offset - inset;
427 builder.move_to(point(bx0, fy0));
428 builder.line_to(point(bx0, by0));
429 builder.line_to(point(bx1, by0));
430 builder.line_to(point(bx1, by1));
431 builder.line_to(point(fx1, by1));
432 }
433 CaptionButton::Close => {
434 let inset = px(0.5);
435 let x0 = x + inset;
436 let y0 = y + inset;
437 let x1 = x + w - inset;
438 let y1 = y + h - inset;
439 builder.move_to(point(x0, y0));
440 builder.line_to(point(x1, y1));
441 builder.move_to(point(x1, y0));
442 builder.line_to(point(x0, y1));
443 }
444 }
445 if let Ok(path) = builder.build() {
446 window.paint_path(path, stroke);
447 }
448 },
449 )
450 .size(px(10.))
451 .flex_shrink_0()
452}