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