1use std::rc::Rc;
25
26use gpui_kit::assets::IconName;
27use gpui_kit::component::button::{Button, ButtonVariants as _};
28use gpui_kit::component::menu::DropdownMenu as _;
29use gpui_kit::component::{Icon, Selectable as _, Sizable as _, TitleBar, h_flex, v_flex};
30use gpui_kit::prelude::FluentBuilder as _;
31use gpui_kit::{
32 AnyElement, AnyView, App, AppContext as _, Context, Entity, EventEmitter, FocusHandle, FontWeight, InteractiveElement as _, IntoElement,
33 KeyDownEvent, MouseButton, ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, WeakEntity,
34 Window, div, px,
35};
36use kitchen_ui::theme::{self, Look, color};
37use kitchen_ui::widgets::{AccentChanged, AccentPicker, MenuSelect, icon_button, row, stepper};
38use serde_json::Value;
39
40use crate::command::{CommandSpec, MenuItem, MenuSpec, Registry, RunCommand};
41use crate::jobs;
42use crate::search::{Search, SearchEvent};
43
44pub const TITLE_BAR_H: f32 = 36.;
46pub const MENU_ROW_H: f32 = 32.;
48pub const STATUS_BAR_H: f32 = 24.;
50pub const RESIZE_BAND: f32 = 6.;
52pub const WINDOW_RADIUS: f32 = 10.;
54pub const TITLE_COMPACT_W: f32 = 1100.;
57pub const TITLE_NARROW_W: f32 = 640.;
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
64pub enum TitleFit {
65 Narrow,
67 Compact,
69 Full,
71}
72
73impl TitleFit {
74 pub fn of(width: f32) -> Self {
76 if width < TITLE_NARROW_W {
77 TitleFit::Narrow
78 } else if width < TITLE_COMPACT_W {
79 TitleFit::Compact
80 } else {
81 TitleFit::Full
82 }
83 }
84}
85
86pub struct WorkspaceSpec {
88 pub id: SharedString,
90 pub title: SharedString,
92 pub icon: IconName,
94 pub hint: SharedString,
96 pub menus: Vec<MenuSpec>,
98 pub view: AnyView,
100 pub badge: Option<Rc<dyn Fn(&App) -> usize>>,
102}
103
104impl WorkspaceSpec {
105 pub fn new(id: impl Into<SharedString>, title: impl Into<SharedString>, icon: IconName, view: impl Into<AnyView>) -> Self {
107 Self { id: id.into(), title: title.into(), icon, hint: SharedString::default(), menus: Vec::new(), view: view.into(), badge: None }
108 }
109
110 pub fn hint(mut self, hint: impl Into<SharedString>) -> Self {
112 self.hint = hint.into();
113 self
114 }
115
116 pub fn menus(mut self, menus: Vec<MenuSpec>) -> Self {
118 self.menus = menus;
119 self
120 }
121
122 pub fn badge(mut self, count: impl Fn(&App) -> usize + 'static) -> Self {
124 self.badge = Some(Rc::new(count));
125 self
126 }
127}
128
129pub type SectionBody = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
131
132#[derive(Clone)]
134pub struct SettingsSection {
135 pub title: SharedString,
137 pub icon: IconName,
139 pub body: SectionBody,
141}
142
143impl SettingsSection {
144 pub fn new(title: impl Into<SharedString>, icon: IconName, body: impl Fn(&mut Window, &mut App) -> AnyElement + 'static) -> Self {
146 Self { title: title.into(), icon, body: Rc::new(body) }
147 }
148}
149
150#[derive(Clone, Debug, PartialEq)]
153pub struct RemoteSpec {
154 pub label: SharedString,
156 pub icon: IconName,
158 pub menu: Vec<MenuItem>,
160}
161
162pub struct ShellSpec {
164 pub app_name: SharedString,
166 pub registry: Registry,
168 pub app_menu: Vec<MenuItem>,
170 pub help_menu: Vec<MenuItem>,
172 pub workspaces: Vec<WorkspaceSpec>,
174 pub settings: Vec<SettingsSection>,
176 pub layout_toggles: Vec<SharedString>,
178 pub remote: Option<RemoteSpec>,
180 pub people: bool,
183 pub meters: bool,
185 pub status_items: Option<StatusItems>,
187}
188
189pub type StatusItems = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
191
192impl ShellSpec {
193 pub fn new(app_name: impl Into<SharedString>, registry: Registry, workspaces: Vec<WorkspaceSpec>) -> Self {
195 Self {
196 app_name: app_name.into(),
197 registry,
198 app_menu: Vec::new(),
199 help_menu: Vec::new(),
200 workspaces,
201 settings: Vec::new(),
202 layout_toggles: Vec::new(),
203 remote: None,
204 people: false,
205 meters: true,
206 status_items: None,
207 }
208 }
209}
210
211#[derive(Clone, Debug, PartialEq)]
213pub enum ShellEvent {
214 LookChanged(Look),
216 WorkspaceChanged(SharedString),
218}
219
220pub struct Shell {
222 app_name: SharedString,
223 registry: Registry,
224 app_menu: MenuSpec,
225 help_menu: MenuSpec,
226 workspaces: Vec<WorkspaceSpec>,
227 sections: Vec<SettingsSection>,
228 layout_toggles: Vec<SharedString>,
229 remote: Option<RemoteSpec>,
230 people: Option<Entity<crate::people_view::PeopleSettings>>,
232 status_items: Option<StatusItems>,
233 overlay: Option<AnyView>,
234 current: usize,
235 search: Option<(Entity<Search>, Subscription)>,
236 settings: Option<usize>,
238 accent: Entity<AccentPicker>,
239 status: SharedString,
240 project: Option<SharedString>,
241 meters: Option<(f32, u64, u64)>,
243 focus: FocusHandle,
244 _subs: Vec<Subscription>,
245}
246
247impl EventEmitter<ShellEvent> for Shell {}
248
249impl Shell {
250 pub fn new(spec: ShellSpec, window: &mut Window, cx: &mut Context<Self>) -> Self {
253 let me = cx.entity().downgrade();
254 spec.registry.extend(frame_commands(&me, &spec.workspaces));
255 let people = spec.people.then(|| {
256 spec.registry.extend(people_commands(&me));
257 spec.registry.provide("people", |_| crate::people_view::menu_items());
258 cx.new(|cx| crate::people_view::PeopleSettings::new(window, cx))
259 });
260 let mut app_items = spec.app_menu;
261 if !app_items.is_empty() {
262 app_items.push(MenuItem::Separator);
263 }
264 app_items.push(MenuItem::command("shell.settings"));
265 let mut help_items = spec.help_menu;
266 if !help_items.is_empty() {
267 help_items.push(MenuItem::Separator);
268 }
269 help_items.push(MenuItem::command("shell.search"));
270 let accent = cx.new(|cx| AccentPicker::new(theme::look().accent, window, cx));
271 let mut subs = vec![cx.subscribe(&accent, |_, _, e: &AccentChanged, cx| {
272 let look = theme::look().with_accent(e.0);
273 theme::use_look(look, cx);
274 cx.emit(ShellEvent::LookChanged(look));
275 cx.notify();
276 })];
277 subs.push(cx.observe_window_appearance(window, |_, _, cx| cx.notify()));
278 let focus = cx.focus_handle();
279 window.focus(&focus, cx);
280 let shell = Self {
281 app_name: spec.app_name.clone(),
282 registry: spec.registry,
283 app_menu: MenuSpec::new(spec.app_name, app_items),
284 help_menu: MenuSpec::new("Help", help_items),
285 workspaces: spec.workspaces,
286 sections: spec.settings,
287 layout_toggles: spec.layout_toggles,
288 remote: spec.remote,
289 people,
290 status_items: spec.status_items,
291 overlay: None,
292 current: 0,
293 search: None,
294 settings: None,
295 accent,
296 status: "Ready".into(),
297 project: None,
298 meters: None,
299 focus,
300 _subs: subs,
301 };
302 if let Some(w) = shell.workspaces.first() {
303 crate::activity::focus(&w.title);
304 }
305 shell.watch_jobs(cx);
306 if spec.meters {
307 shell.watch_meters(cx);
308 }
309 shell
310 }
311
312 fn watch_jobs(&self, cx: &mut Context<Self>) {
314 cx.spawn(async move |this, cx| {
315 let mut seen = jobs::generation();
316 loop {
317 cx.background_executor().timer(std::time::Duration::from_millis(250)).await;
318 let now = jobs::generation();
319 if now != seen {
320 seen = now;
321 if this.update(cx, |_, cx| cx.notify()).is_err() {
322 break;
323 }
324 }
325 }
326 })
327 .detach();
328 }
329
330 fn watch_meters(&self, cx: &mut Context<Self>) {
332 cx.spawn(async move |this, cx| {
333 let Ok(mut sys) = sysinfo::System::new() else { return };
335 loop {
336 let (s, m) = cx
337 .background_executor()
338 .spawn(async move {
339 sys.refresh_cpu_usage();
340 sys.refresh_memory();
341 let m = (sys.global_cpu_usage(), sys.used_memory(), sys.total_memory());
342 (sys, m)
343 })
344 .await;
345 sys = s;
346 let alive = this.update(cx, |s, cx| {
347 s.meters = Some(m);
348 cx.notify();
349 });
350 if alive.is_err() {
351 break;
352 }
353 cx.background_executor().timer(std::time::Duration::from_secs(2)).await;
354 }
355 })
356 .detach();
357 }
358
359 pub fn registry(&self) -> &Registry {
361 &self.registry
362 }
363
364 pub fn workspace(&self) -> &WorkspaceSpec {
366 &self.workspaces[self.current]
367 }
368
369 pub fn set_workspace(&mut self, id: &str, cx: &mut Context<Self>) -> bool {
371 let Some(i) = self.workspaces.iter().position(|w| w.id == id) else { return false };
372 if i != self.current {
373 self.current = i;
374 crate::activity::focus(&self.workspaces[i].title);
375 cx.emit(ShellEvent::WorkspaceChanged(self.workspaces[i].id.clone()));
376 }
377 cx.notify();
378 true
379 }
380
381 pub fn workspace_id(&self) -> SharedString {
383 self.workspaces[self.current].id.clone()
384 }
385
386 pub fn set_menus(&mut self, id: &str, menus: Vec<MenuSpec>, cx: &mut Context<Self>) -> bool {
388 let Some(w) = self.workspaces.iter_mut().find(|w| w.id == id) else { return false };
389 w.menus = menus;
390 cx.notify();
391 true
392 }
393
394 pub fn set_overlay(&mut self, view: Option<AnyView>, window: &mut Window, cx: &mut Context<Self>) {
396 self.overlay = view;
397 if self.overlay.is_none() {
398 window.focus(&self.focus, cx);
399 }
400 cx.notify();
401 }
402
403 pub fn has_overlay(&self) -> bool {
405 self.overlay.is_some()
406 }
407
408 pub fn settings_index(&self, title: &str) -> Option<usize> {
411 if title == "Appearance" {
412 return Some(0);
413 }
414 if title == PEOPLE && self.people.is_some() {
415 return Some(self.sections.len() + 1);
416 }
417 self.sections.iter().position(|s| s.title == title).map(|i| i + 1)
418 }
419
420 pub fn set_status(&mut self, status: impl Into<SharedString>, cx: &mut Context<Self>) {
422 self.status = status.into();
423 cx.notify();
424 }
425
426 pub fn status(&self) -> &SharedString {
428 &self.status
429 }
430
431 pub fn set_project(&mut self, project: Option<SharedString>, cx: &mut Context<Self>) {
433 self.project = project;
434 cx.notify();
435 }
436
437 pub fn search(&self) -> Option<Entity<Search>> {
439 self.search.as_ref().map(|(s, _)| s.clone())
440 }
441
442 pub fn open_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
444 self.open_search_with(None, window, cx);
445 }
446
447 pub fn open_search_with(&mut self, filter: Option<(SharedString, crate::search::Filter)>, window: &mut Window, cx: &mut Context<Self>) {
450 if self.search.take().is_some() {
451 window.focus(&self.focus, cx);
452 cx.notify();
453 return;
454 }
455 let registry = self.registry.clone();
456 let search = cx.new(|cx| {
457 let s = Search::new(registry, window, cx);
458 match filter {
459 Some((title, f)) => s.title(title).filter(move |c| f(c)),
460 None => s,
461 }
462 });
463 let sub = cx.subscribe_in(&search, window, |this, _, e: &SearchEvent, window, cx| {
464 this.search = None;
465 window.focus(&this.focus, cx);
466 if let SearchEvent::Run(id) = e {
467 let (registry, id) = (this.registry.clone(), id.clone());
469 let me = cx.entity().downgrade();
470 window.defer(cx, move |window, cx| {
471 if let Err(e) = registry.run_as(crate::activity::Actor::Person, "search", &id, Value::Null, window, cx) {
472 let _ = me.update(cx, |s, cx| s.set_status(format!("{id}: {e}"), cx));
473 }
474 });
475 }
476 cx.notify();
477 });
478 self.search = Some((search, sub));
479 cx.notify();
480 }
481
482 pub fn settings_section(&self) -> Option<usize> {
484 self.settings
485 }
486
487 pub fn show_settings(&mut self, section: Option<usize>, window: &mut Window, cx: &mut Context<Self>) {
489 self.settings = section.map(|s| s.min(self.sections.len() + usize::from(self.people.is_some())));
490 if self.settings.is_none() {
491 window.focus(&self.focus, cx);
492 }
493 cx.notify();
494 }
495
496 pub fn set_look(&mut self, look: Look, cx: &mut Context<Self>) {
498 theme::use_look(look, cx);
499 cx.emit(ShellEvent::LookChanged(look));
500 cx.notify();
501 }
502
503 fn title_bar(&self, rounded: bool, fit: TitleFit, cx: &mut Context<Self>) -> impl IntoElement {
504 let app = self.registry.menu_button("menu-app", &MenuSpec { hint: "Files, projects, Settings".into(), ..self.app_menu.clone() });
505 let help = self.registry.menu_button("menu-help", &self.help_menu);
506 let switcher = h_flex().gap(px(2.)).p(px(2.)).rounded(px(theme::RADIUS)).bg(color::control().opacity(0.6)).children(self.workspaces.iter().enumerate().map(|(i, w)| {
507 let id = w.id.clone();
508 let count = w.badge.as_ref().map_or(0, |f| f(cx));
509 let pill = (count > 0).then(|| {
510 div().px(px(theme::XS)).rounded(px(theme::RADIUS_SM)).bg(color::accent()).text_color(color::on_accent()).text_xs().font_weight(FontWeight::SEMIBOLD).child(if count > 999 { "999+".to_string() } else { count.to_string() })
511 });
512 let button = Button::new(SharedString::from(format!("workspace-{}", w.id))).small().ghost().icon(w.icon);
514 let button = if fit == TitleFit::Narrow { button.tooltip(format!("{}: {}", w.title, w.hint)) } else { button.label(w.title.clone()).tooltip(w.hint.clone()) };
515 button
516 .children(pill)
517 .selected(i == self.current)
518 .on_click(cx.listener(move |this, _, _, cx| {
519 this.set_workspace(&id, cx);
520 }))
521 }));
522 let toggles = self.layout_toggles.iter().filter(|_| fit != TitleFit::Narrow).filter_map(|id| self.registry.get(id)).map(|c| {
523 let (registry, id) = (self.registry.clone(), c.id.clone());
524 let tip = match c.key_label() {
525 Some(k) => format!("{} ({k})", c.title),
526 None => c.title.to_string(),
527 };
528 icon_button(SharedString::from(format!("toggle-{}", c.id)), c.icon, tip).selected(c.checked.as_ref().is_some_and(|f| f(cx))).on_click(move |_, window, cx| {
529 let _ = registry.run_as(crate::activity::Actor::Person, "title bar", &id, Value::Null, window, cx);
530 })
531 });
532 let remote = self.remote.clone().map(|r| {
533 let (registry, items) = (self.registry.clone(), Rc::new(r.menu.clone()));
534 let button = Button::new("remote").ghost().small().icon(r.icon);
535 let button = if fit == TitleFit::Full { button.label(r.label.clone()).tooltip("Where the app runs: this computer or a server") } else { button.tooltip(format!("Runs on {}: this computer or a server", r.label)) };
537 button
538 .dropdown_menu(move |m, window, cx| registry.fill_menu(m.label("Run on"), &items, window, cx))
539 });
540 let more = (fit == TitleFit::Narrow).then(|| {
542 let registry = self.registry.clone();
543 let items: Rc<Vec<MenuItem>> = Rc::new(self.layout_toggles.iter().map(|id| MenuItem::command(id.clone())).chain([MenuItem::command("shell.theme")]).collect());
544 icon_button("title-more", IconName::Ellipsis, "Panels and theme").dropdown_menu(move |m, window, cx| registry.fill_menu(m, &items, window, cx))
545 });
546 let dark = theme::is_dark();
547 let theme_button = (fit != TitleFit::Narrow).then(|| icon_button("title-theme", if dark { IconName::Sun } else { IconName::Moon }, if dark { "Light theme" } else { "Dark theme" }).on_click(cx.listener(|this, _, _, cx| {
548 let l = theme::look();
549 this.set_look(l.with_dark(!l.dark), cx);
550 })));
551 let person = self.people.as_ref().map(|_| {
553 let who = crate::people::current().map(|p| p.name);
554 let label: SharedString = who.clone().unwrap_or_else(|| "Guest".into()).into();
555 let tip = match &who {
556 Some(n) => format!("Working as {n}: what you do is recorded under this name"),
557 None => "Working as a guest: no name is recorded".to_string(),
558 };
559 let button = Button::new("title-person").ghost().small().icon(IconName::CircleUser);
560 let button = if fit == TitleFit::Full { button.label(label) } else { button };
561 let (registry, items) = (self.registry.clone(), Rc::new(vec![MenuItem::Provided("people".into())]));
562 button.tooltip(tip).dropdown_menu(move |m, window, cx| registry.fill_menu(m.label("Who works"), &items, window, cx))
563 });
564 let project = (fit == TitleFit::Full).then(|| div().min_w_0().text_sm().text_color(color::text_muted()).truncate().child(self.project.clone().unwrap_or_else(|| "No project".into())));
566 TitleBar::new().when(rounded, |t| t.rounded_t(px(WINDOW_RADIUS - 1.0))).child(
568 h_flex()
569 .w_full()
570 .h(px(TITLE_BAR_H))
571 .gap(px(if fit == TitleFit::Narrow { theme::XS } else { theme::MD }))
572 .pr(px(theme::SM))
573 .items_center()
574 .child(h_flex().gap(px(2.)).child(div().font_weight(FontWeight::SEMIBOLD).child(app)).child(help))
575 .child(switcher)
576 .child(div().flex_1())
577 .children(project)
578 .children(person)
579 .children(remote)
580 .children(toggles)
581 .children(theme_button)
582 .children(more),
583 )
584 }
585
586 fn menu_row(&self) -> impl IntoElement {
587 let w = self.workspace();
588 h_flex()
589 .flex_none()
590 .w_full()
591 .h(px(MENU_ROW_H))
592 .px(px(theme::XS))
593 .gap(px(2.))
594 .items_center()
595 .bg(color::panel())
596 .border_b_1()
597 .border_color(color::border())
598 .children(w.menus.iter().enumerate().map(|(i, m)| self.registry.menu_button(format!("menu-{}-{i}", w.id), m)))
599 }
600
601 fn status_bar(&self, rounded: bool, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
602 let pct = |f: Option<f32>| f.map_or(String::new(), |f| format!(" {:.0} %", f * 100.0));
603 let items = self.status_items.clone().map(|f| f(window, cx));
604 let jobs = jobs::running().into_iter().map(|j| {
605 let id = j.id;
606 h_flex()
607 .gap(px(theme::XS))
608 .items_center()
609 .child(div().max_w(px(320.)).truncate().text_color(color::accent_mark()).child(format!("{}{}", j.name, pct(j.progress))))
610 .child(icon_button(SharedString::from(format!("job-cancel-{id}")), IconName::Close, format!("Stop: {}", j.name)).xsmall().on_click(cx.listener(move |_, _, _, cx| {
611 jobs::cancel_id(id);
612 cx.notify();
613 })))
614 });
615 let meter = |icon: IconName, text: String, tip: &'static str| {
616 h_flex().id(tip).gap(px(theme::XS)).items_center().text_color(color::text_muted()).child(Icon::new(icon).small()).child(text).tooltip(move |w, cx| gpui_kit::component::tooltip::Tooltip::new(tip).build(w, cx))
617 };
618 h_flex()
619 .flex_none()
620 .h(px(STATUS_BAR_H))
621 .px(px(theme::MD))
622 .gap(px(theme::LG))
623 .items_center()
624 .bg(color::chrome())
625 .when(rounded, |d| d.rounded_b(px(WINDOW_RADIUS - 1.0)))
626 .text_xs()
627 .child(div().min_w_0().flex_1().truncate().child(self.status.clone()))
628 .children(items)
629 .children(jobs)
630 .children(self.meters.map(|(cpu, used, total)| {
631 let gb = |b: u64| b as f64 / 1e9;
632 h_flex()
633 .gap(px(theme::MD))
634 .child(meter(IconName::Cpu, format!("{cpu:.0} %"), "CPU in use, all cores"))
635 .child(meter(IconName::MemoryStick, format!("{:.1} / {:.1} GB", gb(used), gb(total)), "Memory in use / installed"))
636 }))
637 }
638
639 fn appearance(&self, cx: &mut Context<Self>) -> AnyElement {
640 let look = theme::look();
641 let me = cx.entity().downgrade();
642 let mode = MenuSelect::new("settings-theme", vec!["Dark".into(), "Light".into()], Some(if look.dark { 0 } else { 1 }), move |i, _, cx| {
643 let _ = me.update(cx, |s, cx| s.set_look(theme::look().with_dark(i == 0), cx));
644 });
645 let me = cx.entity().downgrade();
646 let size = stepper("settings-text", format!("{} px", look.font_size), move |step, _, cx| {
647 let _ = me.update(cx, |s, cx| {
648 let l = theme::look();
649 s.set_look(l.with_font_size(l.font_size + step), cx)
650 });
651 });
652 v_flex()
653 .gap(px(theme::MD))
654 .child(row("Theme", div().w_full().child(mode)))
655 .child(row("Accent", self.accent.clone()))
656 .child(row("Text size", size))
657 .child(div().text_xs().text_color(color::text_muted()).child(format!("The accent defaults to {}'s; any colour is adjusted until text on it and its marks pass contrast.", self.app_name)))
658 .into_any_element()
659 }
660
661 fn settings_view(&self, section: usize, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
662 let mut nav: Vec<(SharedString, IconName)> = vec![("Appearance".into(), IconName::Palette)];
663 nav.extend(self.sections.iter().map(|s| (s.title.clone(), s.icon)));
664 if self.people.is_some() {
665 nav.push((PEOPLE.into(), IconName::CircleUser));
666 }
667 let body = match (&self.people, section) {
668 (_, 0) => self.appearance(cx),
669 (Some(people), s) if s == self.sections.len() + 1 => people.update(cx, |p, cx| p.body(cx)),
670 (_, s) => (self.sections[s - 1].body)(window, cx),
671 };
672 let close = cx.entity().downgrade();
673 let list = v_flex().w(px(200.)).flex_none().gap(px(2.)).p(px(theme::SM)).border_r_1().border_color(color::border()).children(nav.iter().enumerate().map(|(i, (title, icon))| {
674 Button::new(SharedString::from(format!("settings-section-{i}"))).ghost().small().w_full().justify_start().icon(*icon).label(title.clone()).selected(i == section).on_click(cx.listener(move |this, _, window, cx| this.show_settings(Some(i), window, cx)))
675 }));
676 div()
677 .id("settings-backdrop")
678 .absolute()
679 .inset_0()
680 .flex()
681 .items_center()
682 .justify_center()
683 .p(px(theme::XL))
684 .bg(gpui_kit::black().opacity(0.35))
685 .on_mouse_down(MouseButton::Left, cx.listener(|this, _, window, cx| this.show_settings(None, window, cx)))
686 .child(
687 v_flex()
688 .id("settings")
689 .occlude()
690 .w_full()
691 .max_w(px(820.))
692 .h_full()
693 .max_h(px(600.))
694 .rounded(px(theme::RADIUS_LG))
695 .border_1()
696 .border_color(color::border())
697 .bg(color::raised())
698 .text_color(color::text())
699 .shadow_lg()
700 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
701 .child(
702 h_flex()
703 .flex_none()
704 .px(px(theme::LG))
705 .py(px(theme::SM))
706 .border_b_1()
707 .border_color(color::border())
708 .child(div().flex_1().text_base().font_weight(FontWeight::SEMIBOLD).child("Settings"))
709 .child(icon_button("settings-close", IconName::Close, "Close (Esc)").on_click(move |_, window, cx| {
710 let _ = close.update(cx, |s, cx| s.show_settings(None, window, cx));
711 })),
712 )
713 .child(h_flex().flex_1().min_h_0().items_start().child(list).child(v_flex().id("settings-body").flex_1().min_w_0().h_full().overflow_y_scroll().p(px(theme::LG)).gap(px(theme::MD)).child(div().text_base().font_weight(FontWeight::SEMIBOLD).child(nav[section].0.clone())).child(body))),
714 )
715 .into_any_element()
716 }
717}
718
719const PEOPLE: &str = "People";
721
722fn people_commands(me: &WeakEntity<Shell>) -> Vec<CommandSpec> {
724 #[derive(serde::Deserialize, schemars::JsonSchema)]
725 struct UseArgs {
726 name: Option<String>,
728 }
729 let (m1, m2) = (me.clone(), me.clone());
730 vec![
731 CommandSpec::with_args("people.use", "Work as…", IconName::CircleUser, move |a: UseArgs, _, cx| {
732 crate::people::use_person(a.name.as_deref())?;
733 let _ = m1.update(cx, |_, cx| cx.notify());
734 Ok(Value::Null)
735 })
736 .group("App")
737 .hint("Who works now: what is done is recorded under their name (none: a guest)"),
738 CommandSpec::new("people.manage", "People…", IconName::CircleUser, move |window, cx| {
739 let _ = m2.update(cx, |s, cx| {
740 let i = s.settings_index(PEOPLE);
741 s.show_settings(i, window, cx)
742 });
743 })
744 .group("App")
745 .hint("Add, pick and remove the people who work in the app")
746 .read_only(),
747 ]
748}
749
750fn frame_commands(me: &WeakEntity<Shell>, workspaces: &[WorkspaceSpec]) -> Vec<CommandSpec> {
752 let (m1, m2, m3) = (me.clone(), me.clone(), me.clone());
753 let mut out = vec![
754 CommandSpec::new("shell.search", "Search…", IconName::Search, move |window, cx| {
755 let _ = m1.update(cx, |s, cx| s.open_search(window, cx));
756 })
757 .group("App")
758 .hint("Find any command by name")
759 .key("secondary-k")
760 .read_only(),
761 CommandSpec::new("shell.settings", "Settings…", IconName::Settings, move |window, cx| {
762 let _ = m2.update(cx, |s, cx| {
763 let open = if s.settings.is_some() { None } else { Some(0) };
764 s.show_settings(open, window, cx)
765 });
766 })
767 .group("App")
768 .hint("Theme, accent, text size and the app's settings")
769 .key("secondary-,")
770 .read_only(),
771 CommandSpec::new("shell.theme", "Dark theme", IconName::Moon, move |_, cx| {
772 let _ = m3.update(cx, |s, cx| {
773 let l = theme::look();
774 s.set_look(l.with_dark(!l.dark), cx)
775 });
776 })
777 .group("View")
778 .hint("Switch between the dark and the light theme")
779 .checked(|_| theme::is_dark()),
780 ];
781 for (i, w) in workspaces.iter().enumerate() {
782 let (m, id) = (me.clone(), w.id.clone());
783 let mut c = CommandSpec::new(format!("shell.workspace.{}", w.id), format!("Go to {}", w.title), w.icon, move |_, cx| {
784 let _ = m.update(cx, |s, cx| s.set_workspace(&id, cx));
785 })
786 .group("Workspaces")
787 .hint(if w.hint.is_empty() { format!("Show the {} workspace", w.title).into() } else { w.hint.clone() })
788 .read_only();
789 if i < 9 {
790 c = c.key(format!("secondary-{}", i + 1));
791 }
792 out.push(c);
793 }
794 out
795}
796
797pub fn resize_edge(p: gpui_kit::Point<gpui_kit::Pixels>, size: gpui_kit::Size<gpui_kit::Pixels>) -> Option<gpui_kit::ResizeEdge> {
799 use gpui_kit::ResizeEdge as E;
800 let band = RESIZE_BAND;
801 let (x, y, w, h) = (p.x.as_f32(), p.y.as_f32(), size.width.as_f32(), size.height.as_f32());
802 let (l, r, t, b) = (x < band, x > w - band, y < band, y > h - band);
803 Some(match (l, r, t, b) {
804 (true, _, true, _) => E::TopLeft,
805 (_, true, true, _) => E::TopRight,
806 (true, _, _, true) => E::BottomLeft,
807 (_, true, _, true) => E::BottomRight,
808 (true, ..) => E::Left,
809 (_, true, ..) => E::Right,
810 (_, _, true, _) => E::Top,
811 (_, _, _, true) => E::Bottom,
812 _ => return None,
813 })
814}
815
816pub fn frame_rounded(window: &Window) -> bool {
819 match window.window_decorations() {
820 gpui_kit::Decorations::Client { tiling } => !(tiling.top || tiling.left || tiling.right || tiling.bottom) && !window.is_maximized() && !window.is_fullscreen(),
821 gpui_kit::Decorations::Server => false,
822 }
823}
824
825impl Render for Shell {
826 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
827 let registry = self.registry.clone();
828 let settings = self.settings.map(|s| self.settings_view(s, window, cx));
829 if matches!(window.window_decorations(), gpui_kit::Decorations::Client { .. }) {
831 window.set_client_inset(px(0.0));
832 }
833 let rounded = frame_rounded(window);
834 let shell = v_flex()
835 .id("shell")
836 .key_context("Shell")
837 .track_focus(&self.focus)
838 .size_full()
839 .relative()
840 .bg(color::chrome())
842 .text_color(color::text())
843 .on_action(move |a: &RunCommand, window, cx| {
845 if let Err(e) = registry.run_as(crate::activity::Actor::Person, "key", &a.id, Value::Null, window, cx) {
846 eprintln!("{}: {e}", a.id);
847 }
848 })
849 .on_key_down(cx.listener(|this, e: &KeyDownEvent, window, cx| {
850 if e.keystroke.key == "escape" && this.settings.is_some() {
851 this.show_settings(None, window, cx);
852 cx.stop_propagation();
853 }
854 }))
855 .child(self.title_bar(rounded, TitleFit::of(window.viewport_size().width.as_f32()), cx))
856 .child(self.menu_row())
857 .child(div().flex_1().min_h_0().p(px(theme::PANE_GAP)).child(div().size_full().rounded(px(theme::RADIUS_LG)).overflow_hidden().bg(color::panel()).child(self.workspace().view.clone())))
858 .child(self.status_bar(rounded, window, cx))
859 .children(self.overlay.clone().map(|o| div().absolute().inset_0().occlude().child(o)))
861 .children(settings)
862 .children(self.search.as_ref().map(|(s, _)| s.clone()))
863 .when(rounded, |d| d.rounded(px(WINDOW_RADIUS)).overflow_hidden());
865 div()
866 .id("window-frame")
867 .size_full()
868 .when(rounded, |d| {
869 d.on_mouse_down(MouseButton::Left, |e, window, _| {
870 if let Some(edge) = resize_edge(e.position, window.viewport_size()) {
871 window.start_window_resize(edge);
872 }
873 })
874 })
875 .child(shell)
876 }
877}