BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / title_bar.rs

title_bar.rs

title_bar.rs 15.0 KiB Download Raw
1use std::sync::{Arc, OnceLock};
2
3use gpui_kit::assets::IconName;
4use gpui_kit::component::{TitleBar, h_flex};
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7
8use super::widgets::icon;
9use crate::app_state::Mode;
10use crate::appearance::AppIcon;
11use crate::theme;
12use crate::updater::UpdateStatus;
13
14pub const TITLE_BAR_HEIGHT: f32 = 40.;
15const SEARCH_WIDTH: f32 = 380.;
16const SEARCH_MIN_WIDTH: f32 = 240.;
17const SEARCH_MIN_VISIBLE_WIDTH: f32 = 36.;
18const SEARCH_HEIGHT: f32 = 28.;
19const SEARCH_GAP: f32 = 8.;
20const SHORTCUT_MIN_WIDTH: f32 = 200.;
21const SEARCH_HINT: &str = "Search chats, people and channels";
22const SHORTCUT_HINT: &str = "Ctrl K";
23const APP_ICON_SIZE: f32 = 18.;
24const TITLE_BRAND_HEIGHT: f32 = app_base::kvt_brand::TITLE_LOGO_HEIGHT;
25const TITLE_BRAND_WIDTH: f32 = app_base::kvt_brand::TITLE_LOGO_WIDTH;
26/// Frame of one macOS traffic light button (14 x 14 since macOS 26).
27const TRAFFIC_LIGHT_SIZE: f32 = 14.;
28const TRAFFIC_LIGHT_LEFT: f32 = 9.;
29
30/// Base options for a window that renders a [`TitleBar`] of [`TITLE_BAR_HEIGHT`], with the macOS traffic lights centered in it.
31pub fn window_options() -> WindowOptions {
32 let mut options = TitleBar::window_options();
33 if let Some(titlebar) = options.titlebar.as_mut() {
34 titlebar.traffic_light_position = Some(point(
35 px(TRAFFIC_LIGHT_LEFT),
36 px((TITLE_BAR_HEIGHT - TRAFFIC_LIGHT_SIZE) / 2.),
37 ));
38 }
39 options
40}
41
42pub fn app_icon_image(app_icon: AppIcon) -> Arc<Image> {
43 static IMAGES: [OnceLock<Arc<Image>>; AppIcon::ALL.len()] =
44 [const { OnceLock::new() }; AppIcon::ALL.len()];
45 let index = AppIcon::ALL
46 .iter()
47 .position(|candidate| *candidate == app_icon)
48 .unwrap_or(0);
49 IMAGES[index]
50 .get_or_init(|| Arc::new(Image::from_bytes(ImageFormat::Png, app_icon.png().to_vec())))
51 .clone()
52}
53
54fn title_brand_image(dark: bool) -> Arc<Image> {
55 static LIGHT: OnceLock<Arc<Image>> = OnceLock::new();
56 static DARK: OnceLock<Arc<Image>> = OnceLock::new();
57 let bytes = app_base::kvt_brand::title_logo_png(if dark {
58 theme::Shade::Dark
59 } else {
60 theme::Shade::Light
61 })
62 .expect("kvt wordmark");
63 let slot = if dark { &DARK } else { &LIGHT };
64 slot.get_or_init(|| Arc::new(Image::from_bytes(ImageFormat::Png, bytes.to_vec())))
65 .clone()
66}
67
68fn title_leading_mark(app_icon: AppIcon) -> AnyElement {
69 if app_base::kvt_brand::title_logo_png(theme::shade()).is_some() {
70 img(title_brand_image(theme::shade().is_dark()))
71 .h(px(TITLE_BRAND_HEIGHT))
72 .w(px(TITLE_BRAND_WIDTH))
73 .flex_none()
74 .into_any_element()
75 } else {
76 img(app_icon_image(app_icon))
77 .size(px(APP_ICON_SIZE))
78 .flex_none()
79 .into_any_element()
80 }
81}
82
83fn mode_pill(label: &'static str) -> Div {
84 div()
85 .debug_selector(|| "shell/title-bar/mode-pill".into())
86 .flex_none()
87 .px(px(8.))
88 .h(px(18.))
89 .flex()
90 .items_center()
91 .rounded_full()
92 .bg(theme::amber().opacity(0.14))
93 .text_size(px(11.))
94 .font_weight(FontWeight::SEMIBOLD)
95 .text_color(theme::amber())
96 .child(label)
97}
98
99pub fn mode_label(mode: Mode) -> Option<&'static str> {
100 if mode.demo {
101 Some("Demo")
102 } else if mode.read_only {
103 Some("Read-only")
104 } else {
105 None
106 }
107}
108
109pub fn update_button(
110 update: &UpdateStatus,
111 on_restart: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
112) -> Option<AnyElement> {
113 let installing = match update {
114 UpdateStatus::Ready => false,
115 UpdateStatus::Installing => true,
116 UpdateStatus::UpToDate | UpdateStatus::Failed(_) => return None,
117 };
118 Some(
119 div()
120 .id("title-update-restart")
121 .debug_selector(|| "shell/title-bar/update".into())
122 .flex_none()
123 .h(px(24.))
124 .px(px(10.))
125 .flex()
126 .items_center()
127 .rounded(px(6.))
128 .bg(theme::accent())
129 .text_color(theme::on_accent())
130 .text_size(px(12.))
131 .font_weight(FontWeight::SEMIBOLD)
132 .when(!installing, |button| {
133 button
134 .cursor_pointer()
135 .hover(|button| button.bg(theme::accent_text()))
136 .on_click(on_restart)
137 })
138 .when(installing, |button| button.opacity(0.7))
139 .child(if installing {
140 "Restarting..."
141 } else {
142 "Restart to update"
143 })
144 .into_any_element(),
145 )
146}
147
148#[derive(Clone, Copy, Debug, PartialEq)]
149struct SearchSpan {
150 left: f32,
151 width: f32,
152}
153
154fn search_span(window_width: f32, leading_end: f32, trailing_start: f32) -> Option<SearchSpan> {
155 let start = leading_end + SEARCH_GAP;
156 let end = trailing_start - SEARCH_GAP;
157 let room = end - start;
158 if room < SEARCH_MIN_VISIBLE_WIDTH {
159 return None;
160 }
161 let center = window_width / 2.;
162 let centered_width = (2. * (center - start).min(end - center)).min(SEARCH_WIDTH);
163 let width = centered_width.max(SEARCH_MIN_WIDTH).min(room);
164 let left = (center - width / 2.).clamp(start, end - width);
165 Some(SearchSpan { left, width })
166}
167
168#[derive(Clone, Copy, PartialEq)]
169struct Reserved {
170 leading_end: f32,
171 trailing_from_right: f32,
172}
173
174#[derive(IntoElement)]
175struct TitleBarRow {
176 app_icon: AppIcon,
177 mode_label: Option<&'static str>,
178 controls: Vec<AnyElement>,
179 on_search: Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>,
180}
181
182pub fn render_title_bar(
183 app_icon: AppIcon,
184 mode_label: Option<&'static str>,
185 controls: impl IntoIterator<Item = AnyElement>,
186 on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
187) -> impl IntoElement {
188 TitleBarRow {
189 app_icon,
190 mode_label,
191 controls: controls.into_iter().collect(),
192 on_search: Box::new(on_search),
193 }
194}
195
196// The Windows caption hit-test takes every point the Drag area reaches, so a control without occlusion never gets its click.
197fn outside_caption(control: AnyElement) -> Div {
198 div().flex_none().occlude().child(control)
199}
200
201fn search_box(
202 span: SearchSpan,
203 on_search: Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>,
204) -> impl IntoElement {
205 h_flex()
206 .id("title-search")
207 .debug_selector(|| "shell/title-bar/search".into())
208 .occlude()
209 .absolute()
210 .top(px((TITLE_BAR_HEIGHT - SEARCH_HEIGHT) / 2.))
211 .left(px(span.left))
212 .w(px(span.width))
213 .h(px(SEARCH_HEIGHT))
214 .px(px(10.))
215 .gap(px(8.))
216 .items_center()
217 .overflow_hidden()
218 .rounded(px(6.))
219 .bg(theme::surface())
220 .cursor_pointer()
221 .text_size(px(12.))
222 .text_color(theme::text_muted())
223 .child(
224 div()
225 .flex_none()
226 .child(icon(IconName::Search, 14., theme::text_muted())),
227 )
228 .child(div().flex_1().min_w_0().truncate().child(SEARCH_HINT))
229 .when(span.width >= SHORTCUT_MIN_WIDTH, |search| {
230 search.child(
231 div()
232 .flex_none()
233 .px(px(6.))
234 .py(px(1.))
235 .rounded(px(4.))
236 .bg(theme::surface_raised())
237 .text_size(px(11.))
238 .child(SHORTCUT_HINT),
239 )
240 })
241 .on_click(move |event, window, cx| on_search(event, window, cx))
242}
243
244impl RenderOnce for TitleBarRow {
245 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
246 let reserved = window.use_keyed_state("title-bar-reserved", cx, |_, _| None::<Reserved>);
247 let window_width = f32::from(window.viewport_size().width);
248 let span = (*reserved.read(cx)).and_then(|reserved| {
249 search_span(
250 window_width,
251 reserved.leading_end,
252 window_width - reserved.trailing_from_right,
253 )
254 });
255 let leading = h_flex()
256 .debug_selector(|| "shell/title-bar/leading".into())
257 .flex_none()
258 .h_full()
259 .gap(px(12.))
260 .items_center()
261 .child(title_leading_mark(self.app_icon))
262 .child(
263 div()
264 .text_size(px(13.))
265 .font_weight(FontWeight::SEMIBOLD)
266 .text_color(theme::text())
267 .child(app_base::APP_NAME),
268 )
269 .children(self.mode_label.map(mode_pill));
270 let trailing = h_flex()
271 .debug_selector(|| "shell/title-bar/trailing".into())
272 .flex_none()
273 .h_full()
274 .gap(px(12.))
275 .items_center()
276 .children(self.controls.into_iter().map(outside_caption))
277 .child(div().w(px(4.)));
278 let row = h_flex()
279 .flex_1()
280 .h_full()
281 .gap(px(12.))
282 .items_center()
283 .child(leading)
284 .child(div().flex_1())
285 .child(trailing)
286 .on_children_prepainted(move |children, window, cx| {
287 let [leading, _, trailing] = children[..] else {
288 return;
289 };
290 let measured = Reserved {
291 leading_end: f32::from(leading.right()),
292 trailing_from_right: f32::from(window.viewport_size().width - trailing.left()),
293 };
294 reserved.update(cx, |current, cx| {
295 let unchanged = current.is_some_and(|current| {
296 (current.leading_end - measured.leading_end).abs() < 0.5
297 && (current.trailing_from_right - measured.trailing_from_right).abs()
298 < 0.5
299 });
300 if !unchanged {
301 *current = Some(measured);
302 cx.notify();
303 }
304 });
305 });
306 let bar = TitleBar::new()
307 .h(px(TITLE_BAR_HEIGHT))
308 .border_b_0()
309 .bg(theme::background())
310 .system_window_controls(crate::kvt::title_bar_system_window_controls(cx))
311 .child(row);
312 let on_search = self.on_search;
313 div()
314 .debug_selector(|| "shell/title-bar".into())
315 .relative()
316 .flex_none()
317 .w_full()
318 .child(bar)
319 .children(span.map(|span| search_box(span, on_search)))
320 }
321}
322
323#[cfg(test)]
324mod tests {
325 use std::cell::{Cell, RefCell};
326 use std::rc::Rc;
327
328 use gpui_kit::component::button::{Button, ButtonVariants as _};
329 use gpui_kit::{
330 Context, Hitbox, HitboxBehavior, InteractiveElement as _, IntoElement, Modifiers,
331 ParentElement, Render, Styled, TestAppContext, Window, canvas, div, px, size,
332 };
333
334 use super::{
335 AppIcon, SEARCH_MIN_WIDTH, SEARCH_WIDTH, UpdateStatus, render_title_bar, search_span,
336 update_button,
337 };
338
339 struct CaptionHarness {
340 caption: Rc<RefCell<Option<Hitbox>>>,
341 restarts: Rc<Cell<usize>>,
342 }
343
344 impl Render for CaptionHarness {
345 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
346 let caption = self.caption.clone();
347 let restarts = self.restarts.clone();
348 let own = div()
349 .debug_selector(|| "shell/title-bar/own-status".into())
350 .child(Button::new("own").ghost().size(px(32.)).child("O"))
351 .into_any_element();
352 div()
353 .relative()
354 .size_full()
355 .child(
356 canvas(
357 |bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal),
358 move |_, hitbox, _, _| *caption.borrow_mut() = Some(hitbox),
359 )
360 .absolute()
361 .size_full(),
362 )
363 .child(render_title_bar(
364 AppIcon::ALL[0],
365 Some("Demo"),
366 [
367 update_button(&UpdateStatus::Ready, move |_, _, _| {
368 restarts.set(restarts.get() + 1)
369 }),
370 Some(own),
371 ]
372 .into_iter()
373 .flatten(),
374 |_, _, _| {},
375 ))
376 }
377 }
378
379 #[gpui_kit::test]
380 fn title_bar_controls_stay_out_of_the_caption(cx: &mut TestAppContext) {
381 cx.update(gpui_kit::init);
382 cx.update(crate::theme::apply);
383 let caption = Rc::new(RefCell::new(None));
384 let restarts = Rc::new(Cell::new(0));
385 let (_, window_cx) = cx.add_window_view({
386 let caption = caption.clone();
387 let restarts = restarts.clone();
388 move |_, _| CaptionHarness { caption, restarts }
389 });
390 window_cx.simulate_resize(size(px(1280.), px(800.)));
391 for _ in 0..2 {
392 window_cx.update(|window, cx| window.draw(cx).clear(cx));
393 }
394 let mut found = Vec::new();
395 for (selector, caption_expected) in [
396 ("shell/title-bar/update", false),
397 ("shell/title-bar/own-status", false),
398 ("shell/title-bar/search", false),
399 ("shell/title-bar/leading", true),
400 ] {
401 let Some(bounds) = window_cx.debug_bounds(selector) else {
402 found.push(format!("{selector} was not rendered"));
403 continue;
404 };
405 let center = bounds.center();
406 let in_caption = window_cx.update(|window, _| {
407 caption
408 .borrow()
409 .as_ref()
410 .is_some_and(|hitbox| hitbox.is_hovered_at(center, window))
411 });
412 if in_caption != caption_expected {
413 found.push(format!("{selector} in caption: {in_caption}"));
414 }
415 }
416 assert!(found.is_empty(), "{}", found.join("\n"));
417 let update = window_cx
418 .debug_bounds("shell/title-bar/update")
419 .expect("update button rendered");
420 window_cx.simulate_click(update.center(), Modifiers::default());
421 assert_eq!(restarts.get(), 1);
422 }
423
424 #[test]
425 fn search_stays_centered_while_it_fits() {
426 let span = search_span(1280., 200., 1080.).expect("visible");
427 assert_eq!(span.width, SEARCH_WIDTH);
428 assert_eq!(span.left + span.width / 2., 640.);
429 }
430
431 #[test]
432 fn search_shrinks_centered_before_it_shifts() {
433 let span = search_span(800., 200., 580.).expect("visible");
434 assert_eq!(span.left + span.width / 2., 400.);
435 assert_eq!(span.width, 344.);
436 let shifted = search_span(800., 200., 500.).expect("visible");
437 assert_eq!(shifted.width, SEARCH_MIN_WIDTH);
438 assert_eq!(shifted.left + shifted.width, 492.);
439 }
440
441 #[test]
442 fn search_takes_the_room_left_and_hides_without_any() {
443 let span = search_span(640., 200., 400.).expect("visible");
444 assert_eq!((span.left, span.width), (208., 184.));
445 assert_eq!(search_span(640., 300., 340.), None);
446 }
447}