1use std::rc::Rc;
38
39use gpui_kit::assets::IconName;
40use gpui_kit::component::button::{Button, ButtonVariants as _};
41use gpui_kit::component::menu::DropdownMenu as _;
42use gpui_kit::component::{Icon, Selectable as _, Sizable as _, TitleBar, h_flex, v_flex};
43use gpui_kit::prelude::FluentBuilder as _;
44use gpui_kit::{
45 AnyElement, AnyView, App, AppContext as _, Context, Entity, EventEmitter, FocusHandle, FontWeight,
46 InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, ParentElement as _, Render, SharedString,
47 StatefulInteractiveElement as _, Styled as _, Subscription, WeakEntity, Window, div, px,
48};
49use kitchen_ui::icons::standard;
50use kitchen_ui::theme::{self, Look, color};
51use kitchen_ui::widgets::{AccentChanged, AccentPicker, MenuSelect, icon_button, row, stepper};
52use serde_json::Value;
53
54use crate::command::{CommandSpec, MenuItem, MenuSpec, Registry, RunCommand};
55use crate::jobs;
56use crate::picker::{FileKind, Picker};
57use crate::picker_view::{FilePickerView, PickerEvent};
58use crate::search::{Search, SearchEvent};
59
60pub const TITLE_BAR_H: f32 = 36.;
62pub const MENU_ROW_H: f32 = 32.;
64pub const STATUS_BAR_H: f32 = 24.;
66pub const RESIZE_BAND: f32 = 6.;
68pub const WINDOW_RADIUS: f32 = 10.;
70pub const TITLE_COMPACT_W: f32 = 1100.;
73pub const PANELS_W: f32 = 900.;
75pub const TITLE_NARROW_W: f32 = 560.;
78
79#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
82pub enum TitleFit {
83 Narrow,
85 Medium,
87 Compact,
89 Full,
91}
92
93impl TitleFit {
94 pub fn of(width: f32) -> Self {
96 if width < TITLE_NARROW_W {
97 TitleFit::Narrow
98 } else if width < PANELS_W {
99 TitleFit::Medium
100 } else if width < TITLE_COMPACT_W {
101 TitleFit::Compact
102 } else {
103 TitleFit::Full
104 }
105 }
106
107 pub fn labels(self) -> bool {
109 self == TitleFit::Full
110 }
111
112 pub fn drawer(self) -> bool {
114 self <= TitleFit::Medium
115 }
116
117 pub fn folded(self) -> bool {
119 self == TitleFit::Narrow
120 }
121}
122
123pub fn fit(window: &Window) -> TitleFit {
126 TitleFit::of(window.viewport_size().width.as_f32())
127}
128
129#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
131pub enum Placement {
132 #[default]
134 View,
135 Shared,
137}
138
139pub const PIPELINE_ID: &str = "pipeline";
141pub const CODE_ID: &str = "code";
143pub const PIPELINE_KEY: &str = "secondary-alt-p";
145pub const CODE_KEY: &str = "secondary-alt-c";
147
148pub struct WorkspaceSpec {
150 pub id: SharedString,
152 pub title: SharedString,
154 pub icon: IconName,
156 pub hint: SharedString,
158 pub menus: Vec<MenuSpec>,
160 pub view: AnyView,
162 pub badge: Option<Rc<dyn Fn(&App) -> usize>>,
164 pub placement: Placement,
166 pub key: Option<SharedString>,
168 pub drawer: Option<AnyView>,
170}
171
172impl WorkspaceSpec {
173 pub fn new(
175 id: impl Into<SharedString>,
176 title: impl Into<SharedString>,
177 icon: IconName,
178 view: impl Into<AnyView>,
179 ) -> Self {
180 Self {
181 id: id.into(),
182 title: title.into(),
183 icon,
184 hint: SharedString::default(),
185 menus: Vec::new(),
186 view: view.into(),
187 badge: None,
188 placement: Placement::View,
189 key: None,
190 drawer: None,
191 }
192 }
193
194 pub fn pipeline(view: impl Into<AnyView>) -> Self {
197 WorkspaceSpec::new(PIPELINE_ID, "Pipeline", standard::PIPELINE, view)
198 .hint("The steps from raw data to results, as a graph")
199 .shared()
200 .key(PIPELINE_KEY)
201 }
202
203 pub fn code(view: impl Into<AnyView>) -> Self {
205 WorkspaceSpec::new(CODE_ID, "Code", standard::CODE, view)
206 .hint("Scripts: write them, run them, add them to the pipeline")
207 .shared()
208 .key(CODE_KEY)
209 }
210
211 pub fn shared(mut self) -> Self {
213 self.placement = Placement::Shared;
214 self
215 }
216
217 pub fn key(mut self, key: impl Into<SharedString>) -> Self {
219 self.key = Some(key.into());
220 self
221 }
222
223 pub fn drawer(mut self, view: impl Into<AnyView>) -> Self {
226 self.drawer = Some(view.into());
227 self
228 }
229
230 pub fn hint(mut self, hint: impl Into<SharedString>) -> Self {
232 self.hint = hint.into();
233 self
234 }
235
236 pub fn menus(mut self, menus: Vec<MenuSpec>) -> Self {
238 self.menus = menus;
239 self
240 }
241
242 pub fn badge(mut self, count: impl Fn(&App) -> usize + 'static) -> Self {
244 self.badge = Some(Rc::new(count));
245 self
246 }
247}
248
249pub type SectionBody = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
251
252#[derive(Clone)]
254pub struct SettingsSection {
255 pub title: SharedString,
257 pub icon: IconName,
259 pub body: SectionBody,
261}
262
263impl SettingsSection {
264 pub fn new(
266 title: impl Into<SharedString>,
267 icon: IconName,
268 body: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
269 ) -> Self {
270 Self { title: title.into(), icon, body: Rc::new(body) }
271 }
272}
273
274#[derive(Clone, Debug, PartialEq)]
277pub struct RemoteSpec {
278 pub label: SharedString,
280 pub icon: IconName,
282 pub menu: Vec<MenuItem>,
284}
285
286#[derive(Clone)]
289pub struct OpenSpec {
290 pub kinds: Vec<FileKind>,
292 pub start: Option<std::path::PathBuf>,
294 pub recent: Rc<dyn Fn(&App) -> Vec<std::path::PathBuf>>,
296 pub open: Rc<dyn Fn(std::path::PathBuf, &mut Window, &mut App)>,
298}
299
300impl OpenSpec {
301 pub fn new(kinds: Vec<FileKind>, open: impl Fn(std::path::PathBuf, &mut Window, &mut App) + 'static) -> Self {
303 Self { kinds, start: None, recent: Rc::new(|_| Vec::new()), open: Rc::new(open) }
304 }
305
306 pub fn recent(mut self, recent: impl Fn(&App) -> Vec<std::path::PathBuf> + 'static) -> Self {
308 self.recent = Rc::new(recent);
309 self
310 }
311
312 pub fn start(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
314 self.start = Some(dir.into());
315 self
316 }
317}
318
319pub struct ShellSpec {
321 pub app_name: SharedString,
323 pub registry: Registry,
325 pub open: Option<OpenSpec>,
327 pub file_menu: Vec<MenuItem>,
329 pub app_menu: Vec<MenuItem>,
331 pub edit_menu: Vec<MenuItem>,
333 pub view_menu: Vec<MenuItem>,
335 pub help_menu: Vec<MenuItem>,
337 pub workspaces: Vec<WorkspaceSpec>,
339 pub settings: Vec<SettingsSection>,
341 pub layout_toggles: Vec<SharedString>,
343 pub remote: Option<RemoteSpec>,
345 pub people: bool,
348 pub meters: bool,
350 pub status_items: Option<StatusItems>,
352}
353
354pub type StatusItems = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
356
357impl ShellSpec {
358 pub fn new(app_name: impl Into<SharedString>, registry: Registry, workspaces: Vec<WorkspaceSpec>) -> Self {
360 Self {
361 app_name: app_name.into(),
362 registry,
363 open: None,
364 file_menu: Vec::new(),
365 app_menu: Vec::new(),
366 edit_menu: Vec::new(),
367 view_menu: Vec::new(),
368 help_menu: Vec::new(),
369 workspaces,
370 settings: Vec::new(),
371 layout_toggles: Vec::new(),
372 remote: None,
373 people: false,
374 meters: true,
375 status_items: None,
376 }
377 }
378}
379
380#[derive(Clone, Debug, PartialEq)]
382pub enum ShellEvent {
383 LookChanged(Look),
385 WorkspaceChanged(SharedString),
387}
388
389pub struct Shell {
391 app_name: SharedString,
392 registry: Registry,
393 file_menu: MenuSpec,
394 edit_menu: Option<MenuSpec>,
395 view_menu: MenuSpec,
396 help_menu: MenuSpec,
397 open: Option<OpenSpec>,
398 picker: Option<(Entity<FilePickerView>, Subscription)>,
399 drawer_open: bool,
401 workspaces: Vec<WorkspaceSpec>,
402 sections: Vec<SettingsSection>,
403 layout_toggles: Vec<SharedString>,
404 remote: Option<RemoteSpec>,
405 people: Option<Entity<crate::people_view::PeopleSettings>>,
407 status_items: Option<StatusItems>,
408 overlay: Option<AnyView>,
409 current: usize,
410 search: Option<(Entity<Search>, Subscription)>,
411 settings: Option<usize>,
413 accent: Entity<AccentPicker>,
414 status: SharedString,
415 project: Option<SharedString>,
416 meters: Option<(f32, u64, u64)>,
418 focus: FocusHandle,
419 _subs: Vec<Subscription>,
420}
421
422impl EventEmitter<ShellEvent> for Shell {}
423
424impl Shell {
425 pub fn new(spec: ShellSpec, window: &mut Window, cx: &mut Context<Self>) -> Self {
428 let me = cx.entity().downgrade();
429 spec.registry.extend(frame_commands(&me, &spec.workspaces, spec.open.is_some()));
430 let people = spec.people.then(|| {
431 spec.registry.extend(people_commands(&me));
432 spec.registry.provide("people", |_| crate::people_view::menu_items());
433 cx.new(|cx| crate::people_view::PeopleSettings::new(window, cx))
434 });
435 let mut file_items = Vec::new();
437 if spec.open.is_some() {
438 file_items.push(MenuItem::command("shell.open"));
439 }
440 file_items.extend(spec.file_menu);
441 file_items.extend(spec.app_menu);
442 if !file_items.is_empty() {
443 file_items.push(MenuItem::Separator);
444 }
445 file_items.push(MenuItem::command("shell.settings"));
446 file_items.push(MenuItem::Separator);
447 file_items.push(MenuItem::command("shell.quit"));
448 let edit_menu = (!spec.edit_menu.is_empty()).then(|| MenuSpec::new("Edit", spec.edit_menu));
449 let mut view_items = spec.view_menu;
451 if !view_items.is_empty() {
452 view_items.push(MenuItem::Separator);
453 }
454 view_items.extend(spec.layout_toggles.iter().map(|id| MenuItem::command(id.clone())));
455 if spec.workspaces.iter().any(|w| w.drawer.is_some()) {
456 view_items.push(MenuItem::command("shell.panels"));
457 }
458 view_items.push(MenuItem::command("shell.theme"));
459 let mut help_items = spec.help_menu;
460 if !help_items.is_empty() {
461 help_items.push(MenuItem::Separator);
462 }
463 help_items.push(MenuItem::command("shell.search"));
464 let accent = cx.new(|cx| AccentPicker::new(theme::look().accent, window, cx));
465 let mut subs = vec![cx.subscribe(&accent, |_, _, e: &AccentChanged, cx| {
466 let look = theme::look().with_accent(e.0);
467 theme::use_look(look, cx);
468 cx.emit(ShellEvent::LookChanged(look));
469 cx.notify();
470 })];
471 subs.push(cx.observe_window_appearance(window, |_, _, cx| cx.notify()));
472 let focus = cx.focus_handle();
473 window.focus(&focus, cx);
474 let shell = Self {
475 app_name: spec.app_name.clone(),
476 registry: spec.registry,
477 file_menu: MenuSpec::new("File", file_items).hint("Open, save, export; Settings; Quit"),
478 edit_menu,
479 view_menu: MenuSpec::new("View", view_items),
480 help_menu: MenuSpec::new("Help", help_items),
481 open: spec.open,
482 picker: None,
483 drawer_open: false,
484 workspaces: spec.workspaces,
485 sections: spec.settings,
486 layout_toggles: spec.layout_toggles,
487 remote: spec.remote,
488 people,
489 status_items: spec.status_items,
490 overlay: None,
491 current: 0,
492 search: None,
493 settings: None,
494 accent,
495 status: "Ready".into(),
496 project: None,
497 meters: None,
498 focus,
499 _subs: subs,
500 };
501 if let Some(w) = shell.workspaces.first() {
502 crate::activity::focus(&w.title);
503 }
504 shell.watch_jobs(cx);
505 if spec.meters {
506 shell.watch_meters(cx);
507 }
508 shell
509 }
510
511 fn watch_jobs(&self, cx: &mut Context<Self>) {
513 cx.spawn(async move |this, cx| {
514 let mut seen = jobs::generation();
515 loop {
516 cx.background_executor().timer(std::time::Duration::from_millis(250)).await;
517 let now = jobs::generation();
518 if now != seen {
519 seen = now;
520 if this.update(cx, |_, cx| cx.notify()).is_err() {
521 break;
522 }
523 }
524 }
525 })
526 .detach();
527 }
528
529 fn watch_meters(&self, cx: &mut Context<Self>) {
531 cx.spawn(async move |this, cx| {
532 let Ok(mut sys) = sysinfo::System::new() else { return };
534 loop {
535 let (s, m) = cx
536 .background_executor()
537 .spawn(async move {
538 sys.refresh_cpu_usage();
539 sys.refresh_memory();
540 let m = (sys.global_cpu_usage(), sys.used_memory(), sys.total_memory());
541 (sys, m)
542 })
543 .await;
544 sys = s;
545 let alive = this.update(cx, |s, cx| {
546 s.meters = Some(m);
547 cx.notify();
548 });
549 if alive.is_err() {
550 break;
551 }
552 cx.background_executor().timer(std::time::Duration::from_secs(2)).await;
553 }
554 })
555 .detach();
556 }
557
558 pub fn registry(&self) -> &Registry {
560 &self.registry
561 }
562
563 pub fn workspace(&self) -> &WorkspaceSpec {
565 &self.workspaces[self.current]
566 }
567
568 pub fn set_workspace(&mut self, id: &str, cx: &mut Context<Self>) -> bool {
570 let Some(i) = self.workspaces.iter().position(|w| w.id == id) else { return false };
571 if i != self.current {
572 self.current = i;
573 self.drawer_open = false;
574 crate::activity::focus(&self.workspaces[i].title);
575 cx.emit(ShellEvent::WorkspaceChanged(self.workspaces[i].id.clone()));
576 }
577 cx.notify();
578 true
579 }
580
581 pub fn workspace_id(&self) -> SharedString {
583 self.workspaces[self.current].id.clone()
584 }
585
586 pub fn current_view(&self) -> Option<SharedString> {
589 let w = &self.workspaces[self.current];
590 (w.placement == Placement::View).then(|| w.id.clone())
591 }
592
593 pub fn open_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
595 let Some(open) = self.open.clone() else { return };
596 let start =
597 open.start.clone().or_else(crate::picker::home_dir).unwrap_or_else(|| std::path::PathBuf::from("/"));
598 let picker = Picker::new(open.kinds.clone(), start).with_recent((open.recent)(cx));
599 let view = cx.new(|cx| FilePickerView::new(picker, window, cx));
600 let sub = cx.subscribe_in(&view, window, move |this, _, e: &PickerEvent, window, cx| {
601 this.picker = None;
602 window.focus(&this.focus, cx);
603 if let PickerEvent::Open(path) = e {
604 (open.open)(path.clone(), window, cx);
605 }
606 cx.notify();
607 });
608 self.picker = Some((view, sub));
609 cx.notify();
610 }
611
612 pub fn picker(&self) -> Option<Entity<FilePickerView>> {
614 self.picker.as_ref().map(|(p, _)| p.clone())
615 }
616
617 pub fn toggle_drawer(&mut self, cx: &mut Context<Self>) {
619 self.drawer_open = !self.drawer_open && self.workspace().drawer.is_some();
620 cx.notify();
621 }
622
623 pub fn drawer_open(&self) -> bool {
625 self.drawer_open
626 }
627
628 pub fn set_menus(&mut self, id: &str, menus: Vec<MenuSpec>, cx: &mut Context<Self>) -> bool {
630 let Some(w) = self.workspaces.iter_mut().find(|w| w.id == id) else { return false };
631 w.menus = menus;
632 cx.notify();
633 true
634 }
635
636 pub fn set_overlay(&mut self, view: Option<AnyView>, window: &mut Window, cx: &mut Context<Self>) {
638 self.overlay = view;
639 if self.overlay.is_none() {
640 window.focus(&self.focus, cx);
641 }
642 cx.notify();
643 }
644
645 pub fn has_overlay(&self) -> bool {
647 self.overlay.is_some()
648 }
649
650 pub fn settings_index(&self, title: &str) -> Option<usize> {
653 if title == "Appearance" {
654 return Some(0);
655 }
656 if title == PEOPLE && self.people.is_some() {
657 return Some(self.sections.len() + 1);
658 }
659 self.sections.iter().position(|s| s.title == title).map(|i| i + 1)
660 }
661
662 pub fn set_status(&mut self, status: impl Into<SharedString>, cx: &mut Context<Self>) {
664 self.status = status.into();
665 cx.notify();
666 }
667
668 pub fn status(&self) -> &SharedString {
670 &self.status
671 }
672
673 pub fn set_project(&mut self, project: Option<SharedString>, cx: &mut Context<Self>) {
675 self.project = project;
676 cx.notify();
677 }
678
679 pub fn search(&self) -> Option<Entity<Search>> {
681 self.search.as_ref().map(|(s, _)| s.clone())
682 }
683
684 pub fn open_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
686 self.open_search_with(None, window, cx);
687 }
688
689 pub fn open_search_with(
692 &mut self,
693 filter: Option<(SharedString, crate::search::Filter)>,
694 window: &mut Window,
695 cx: &mut Context<Self>,
696 ) {
697 if self.search.take().is_some() {
698 window.focus(&self.focus, cx);
699 cx.notify();
700 return;
701 }
702 let registry = self.registry.clone();
703 let search = cx.new(|cx| {
704 let s = Search::new(registry, window, cx);
705 match filter {
706 Some((title, f)) => s.title(title).filter(move |c| f(c)),
707 None => s,
708 }
709 });
710 let sub = cx.subscribe_in(&search, window, |this, _, e: &SearchEvent, window, cx| {
711 this.search = None;
712 window.focus(&this.focus, cx);
713 if let SearchEvent::Run(id) = e {
714 let (registry, id) = (this.registry.clone(), id.clone());
716 let me = cx.entity().downgrade();
717 window.defer(cx, move |window, cx| {
718 if let Err(e) =
719 registry.run_as(crate::activity::Actor::Person, "search", &id, Value::Null, window, cx)
720 {
721 let _ = me.update(cx, |s, cx| s.set_status(format!("{id}: {e}"), cx));
722 }
723 });
724 }
725 cx.notify();
726 });
727 self.search = Some((search, sub));
728 cx.notify();
729 }
730
731 pub fn settings_section(&self) -> Option<usize> {
733 self.settings
734 }
735
736 pub fn show_settings(&mut self, section: Option<usize>, window: &mut Window, cx: &mut Context<Self>) {
738 self.settings = section.map(|s| s.min(self.sections.len() + usize::from(self.people.is_some())));
739 if self.settings.is_none() {
740 window.focus(&self.focus, cx);
741 }
742 cx.notify();
743 }
744
745 pub fn set_look(&mut self, look: Look, cx: &mut Context<Self>) {
747 theme::use_look(look, cx);
748 cx.emit(ShellEvent::LookChanged(look));
749 cx.notify();
750 }
751
752 fn title_bar(&self, rounded: bool, fit: TitleFit, cx: &mut Context<Self>) -> impl IntoElement {
753 let menus: Vec<&MenuSpec> =
755 [Some(&self.file_menu), self.edit_menu.as_ref(), Some(&self.view_menu), Some(&self.help_menu)]
756 .into_iter()
757 .flatten()
758 .collect();
759 let general = if fit.folded() {
760 let registry = self.registry.clone();
761 let items: Rc<Vec<MenuItem>> =
762 Rc::new(menus.iter().map(|m| MenuItem::submenu(m.title.clone(), m.items.clone())).collect());
763 icon_button("title-menu", standard::MENU, "File, Edit, View, Help")
764 .dropdown_menu(move |m, window, cx| registry.fill_menu(m, &items, window, cx))
765 .into_any_element()
766 } else {
767 h_flex()
768 .gap(px(2.))
769 .children(
770 menus.iter().map(|m| self.registry.menu_button(format!("menu-{}", m.title.to_lowercase()), m)),
771 )
772 .into_any_element()
773 };
774 let mark = div()
775 .id("title-mark")
776 .flex_none()
777 .px(px(theme::SM))
778 .text_sm()
779 .font_weight(FontWeight::SEMIBOLD)
780 .text_color(color::accent_mark())
781 .child(if fit.folded() {
782 self.app_name.chars().next().map(String::from).unwrap_or_default()
783 } else {
784 self.app_name.to_string()
785 });
786 let divider = div().flex_none().w(px(1.)).h(px(16.)).bg(color::border());
787 let workspace_button = |i: usize, w: &WorkspaceSpec, labelled: bool, cx: &mut Context<Self>| {
788 let id = w.id.clone();
789 let count = w.badge.as_ref().map_or(0, |f| f(cx));
790 let pill = (count > 0).then(|| {
791 div()
792 .px(px(theme::XS))
793 .rounded(px(theme::RADIUS_SM))
794 .bg(color::accent())
795 .text_color(color::on_accent())
796 .text_xs()
797 .font_weight(FontWeight::SEMIBOLD)
798 .child(if count > 999 { "999+".to_string() } else { count.to_string() })
799 });
800 let key = self.registry.get(&format!("shell.workspace.{}", w.id)).and_then(|c| c.key_label());
801 let tip = match (&key, w.hint.is_empty()) {
802 (Some(k), false) => format!("{}: {} ({k})", w.title, w.hint),
803 (Some(k), true) => format!("{} ({k})", w.title),
804 (None, false) => format!("{}: {}", w.title, w.hint),
805 (None, true) => w.title.to_string(),
806 };
807 let button = Button::new(SharedString::from(format!("workspace-{}", w.id)))
808 .small()
809 .ghost()
810 .icon(w.icon)
811 .tooltip(tip);
812 let button = if labelled { button.label(w.title.clone()) } else { button };
813 button.children(pill).selected(i == self.current).on_click(cx.listener(move |this, _, _, cx| {
814 this.set_workspace(&id, cx);
815 }))
816 };
817 let views: Vec<_> = self
819 .workspaces
820 .iter()
821 .enumerate()
822 .filter(|(_, w)| w.placement == Placement::View)
823 .map(|(i, w)| workspace_button(i, w, fit.labels(), cx))
824 .collect();
825 let detent = |id: &'static str| {
827 h_flex().id(id).gap(px(2.)).p(px(2.)).rounded(px(theme::RADIUS)).bg(color::control().opacity(0.6))
828 };
829 let switcher = (!views.is_empty()).then(|| detent("title-views").min_w_0().children(views));
830 let shared: Vec<_> = self
832 .workspaces
833 .iter()
834 .enumerate()
835 .filter(|(_, w)| w.placement == Placement::Shared)
836 .map(|(i, w)| workspace_button(i, w, false, cx))
837 .collect();
838 let shared = (!shared.is_empty()).then(|| detent("title-shared").flex_none().children(shared));
839 let toggles =
840 self.layout_toggles.iter().filter(|_| !fit.folded()).filter_map(|id| self.registry.get(id)).map(|c| {
841 let (registry, id) = (self.registry.clone(), c.id.clone());
842 let tip = match c.key_label() {
843 Some(k) => format!("{} ({k})", c.title),
844 None => c.title.to_string(),
845 };
846 icon_button(SharedString::from(format!("toggle-{}", c.id)), c.icon, tip)
847 .selected(c.checked.as_ref().is_some_and(|f| f(cx)))
848 .on_click(move |_, window, cx| {
849 let _ =
850 registry.run_as(crate::activity::Actor::Person, "title bar", &id, Value::Null, window, cx);
851 })
852 });
853 let panels = (fit.drawer() && self.workspace().drawer.is_some()).then(|| {
855 icon_button("title-panels", standard::PANELS, "Panels (Ctrl+\\)")
856 .selected(self.drawer_open)
857 .on_click(cx.listener(|this, _, _, cx| this.toggle_drawer(cx)))
858 });
859 let search = icon_button("title-search", IconName::Search, "Search commands (Ctrl+K)")
860 .on_click(cx.listener(|this, _, window, cx| this.open_search(window, cx)));
861 let remote = self.remote.clone().map(|r| {
862 let (registry, items) = (self.registry.clone(), Rc::new(r.menu.clone()));
863 let button = Button::new("remote").ghost().small().icon(r.icon);
864 let button = if fit.labels() {
866 button.label(r.label.clone()).tooltip("Where the app runs: this computer or a server")
867 } else {
868 button.tooltip(format!("Runs on {}: this computer or a server", r.label))
869 };
870 button.dropdown_menu(move |m, window, cx| registry.fill_menu(m.label("Run on"), &items, window, cx))
871 });
872 let more = fit.folded().then(|| {
874 let registry = self.registry.clone();
875 let items: Rc<Vec<MenuItem>> = Rc::new(
876 self.layout_toggles
877 .iter()
878 .map(|id| MenuItem::command(id.clone()))
879 .chain([MenuItem::command("shell.theme")])
880 .collect(),
881 );
882 icon_button("title-more", IconName::Ellipsis, "Panels and theme")
883 .dropdown_menu(move |m, window, cx| registry.fill_menu(m, &items, window, cx))
884 });
885 let dark = theme::is_dark();
886 let theme_button = (!fit.folded()).then(|| {
887 icon_button(
888 "title-theme",
889 if dark { IconName::Sun } else { IconName::Moon },
890 if dark { "Light theme" } else { "Dark theme" },
891 )
892 .on_click(cx.listener(|this, _, _, cx| {
893 let l = theme::look();
894 this.set_look(l.with_dark(!l.dark), cx);
895 }))
896 });
897 let person = self.people.as_ref().map(|_| {
899 let who = crate::people::current().map(|p| p.name);
900 let label: SharedString = who.clone().unwrap_or_else(|| "Guest".into()).into();
901 let tip = match &who {
902 Some(n) => format!("Working as {n}: what you do is recorded under this name"),
903 None => "Working as a guest: no name is recorded".to_string(),
904 };
905 let button = Button::new("title-person").ghost().small().icon(IconName::CircleUser);
906 let button = if fit.labels() { button.label(label) } else { button };
907 let (registry, items) = (self.registry.clone(), Rc::new(vec![MenuItem::Provided("people".into())]));
908 button
909 .tooltip(tip)
910 .dropdown_menu(move |m, window, cx| registry.fill_menu(m.label("Who works"), &items, window, cx))
911 });
912 let project = fit.labels().then(|| {
914 div()
915 .min_w_0()
916 .text_sm()
917 .text_color(color::text_muted())
918 .truncate()
919 .child(self.project.clone().unwrap_or_else(|| "No project".into()))
920 });
921 TitleBar::new().when(rounded, |t| t.rounded_t(px(WINDOW_RADIUS - 1.0))).child(
923 h_flex()
924 .w_full()
925 .h(px(TITLE_BAR_H))
926 .gap(px(if fit.folded() { theme::XS } else { theme::SM }))
927 .pr(px(theme::SM))
928 .items_center()
929 .children(panels)
930 .child(mark)
931 .child(general)
932 .child(search)
933 .when(switcher.is_some(), |d| d.child(divider))
934 .children(switcher)
935 .child(div().flex_1())
936 .children(project)
937 .children(person)
938 .children(remote)
939 .children(shared)
940 .children(toggles)
941 .children(theme_button)
942 .children(more),
943 )
944 }
945
946 fn menu_row(&self, fit: TitleFit) -> impl IntoElement {
947 let w = self.workspace();
948 h_flex()
949 .id("menu-row")
950 .flex_none()
951 .w_full()
952 .h(px(MENU_ROW_H))
953 .px(px(theme::XS))
954 .gap(px(theme::XS))
955 .items_center()
956 .bg(color::panel())
957 .border_b_1()
958 .border_color(color::border())
959 .when(fit.folded(), |d| d.overflow_x_scroll())
961 .children(
962 w.menus.iter().enumerate().map(|(i, m)| self.registry.menu_button(format!("menu-{}-{i}", w.id), m)),
963 )
964 }
965
966 fn status_bar(&self, rounded: bool, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
967 let pct = |f: Option<f32>| f.map_or(String::new(), |f| format!(" {:.0} %", f * 100.0));
968 let items = self.status_items.clone().map(|f| f(window, cx));
969 let jobs = jobs::running().into_iter().map(|j| {
970 let id = j.id;
971 h_flex()
972 .gap(px(theme::XS))
973 .items_center()
974 .child(div().max_w(px(320.)).truncate().text_color(color::accent_mark()).child(format!(
975 "{}{}",
976 j.name,
977 pct(j.progress)
978 )))
979 .child(
980 icon_button(
981 SharedString::from(format!("job-cancel-{id}")),
982 IconName::Close,
983 format!("Stop: {}", j.name),
984 )
985 .xsmall()
986 .on_click(cx.listener(move |_, _, _, cx| {
987 jobs::cancel_id(id);
988 cx.notify();
989 })),
990 )
991 });
992 let meter = |icon: IconName, text: String, tip: &'static str| {
993 h_flex()
994 .id(tip)
995 .gap(px(theme::XS))
996 .items_center()
997 .text_color(color::text_muted())
998 .child(Icon::new(icon).small())
999 .child(text)
1000 .tooltip(move |w, cx| gpui_kit::component::tooltip::Tooltip::new(tip).build(w, cx))
1001 };
1002 h_flex()
1003 .flex_none()
1004 .h(px(STATUS_BAR_H))
1005 .px(px(theme::MD))
1006 .gap(px(theme::LG))
1007 .items_center()
1008 .bg(color::chrome())
1009 .when(rounded, |d| d.rounded_b(px(WINDOW_RADIUS - 1.0)))
1010 .text_xs()
1011 .child(div().min_w_0().flex_1().truncate().child(self.status.clone()))
1012 .children(items)
1013 .children(jobs)
1014 .children(self.meters.map(|(cpu, used, total)| {
1015 let gb = |b: u64| b as f64 / 1e9;
1016 h_flex()
1017 .gap(px(theme::MD))
1018 .child(meter(IconName::Cpu, format!("{cpu:.0} %"), "CPU in use, all cores"))
1019 .child(meter(
1020 IconName::MemoryStick,
1021 format!("{:.1} / {:.1} GB", gb(used), gb(total)),
1022 "Memory in use / installed",
1023 ))
1024 }))
1025 }
1026
1027 fn appearance(&self, cx: &mut Context<Self>) -> AnyElement {
1028 let look = theme::look();
1029 let me = cx.entity().downgrade();
1030 let mode = MenuSelect::new(
1031 "settings-theme",
1032 vec!["Dark".into(), "Light".into()],
1033 Some(if look.dark { 0 } else { 1 }),
1034 move |i, _, cx| {
1035 let _ = me.update(cx, |s, cx| s.set_look(theme::look().with_dark(i == 0), cx));
1036 },
1037 );
1038 let me = cx.entity().downgrade();
1039 let size = stepper("settings-text", format!("{} px", look.font_size), move |step, _, cx| {
1040 let _ = me.update(cx, |s, cx| {
1041 let l = theme::look();
1042 s.set_look(l.with_font_size(l.font_size + step), cx)
1043 });
1044 });
1045 v_flex()
1046 .gap(px(theme::MD))
1047 .child(row("Theme", div().w_full().child(mode)))
1048 .child(row("Accent", self.accent.clone()))
1049 .child(row("Text size", size))
1050 .child(div().text_xs().text_color(color::text_muted()).child(format!(
1051 "The accent defaults to {}'s; any colour is adjusted until text on it and its marks pass contrast.",
1052 self.app_name
1053 )))
1054 .into_any_element()
1055 }
1056
1057 fn settings_view(&self, section: usize, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
1058 let mut nav: Vec<(SharedString, IconName)> = vec![("Appearance".into(), IconName::Palette)];
1059 nav.extend(self.sections.iter().map(|s| (s.title.clone(), s.icon)));
1060 if self.people.is_some() {
1061 nav.push((PEOPLE.into(), IconName::CircleUser));
1062 }
1063 let body = match (&self.people, section) {
1064 (_, 0) => self.appearance(cx),
1065 (Some(people), s) if s == self.sections.len() + 1 => people.update(cx, |p, cx| p.body(cx)),
1066 (_, s) => (self.sections[s - 1].body)(window, cx),
1067 };
1068 let close = cx.entity().downgrade();
1069 let list = v_flex()
1070 .w(px(200.))
1071 .flex_none()
1072 .gap(px(2.))
1073 .p(px(theme::SM))
1074 .border_r_1()
1075 .border_color(color::border())
1076 .children(nav.iter().enumerate().map(|(i, (title, icon))| {
1077 Button::new(SharedString::from(format!("settings-section-{i}")))
1078 .ghost()
1079 .small()
1080 .w_full()
1081 .justify_start()
1082 .icon(*icon)
1083 .label(title.clone())
1084 .selected(i == section)
1085 .on_click(cx.listener(move |this, _, window, cx| this.show_settings(Some(i), window, cx)))
1086 }));
1087 div()
1088 .id("settings-backdrop")
1089 .absolute()
1090 .inset_0()
1091 .flex()
1092 .items_center()
1093 .justify_center()
1094 .p(px(theme::XL))
1095 .bg(gpui_kit::black().opacity(0.35))
1096 .on_mouse_down(MouseButton::Left, cx.listener(|this, _, window, cx| this.show_settings(None, window, cx)))
1097 .child(
1098 v_flex()
1099 .id("settings")
1100 .occlude()
1101 .w_full()
1102 .max_w(px(820.))
1103 .h_full()
1104 .max_h(px(600.))
1105 .rounded(px(theme::RADIUS_LG))
1106 .border_1()
1107 .border_color(color::border())
1108 .bg(color::raised())
1109 .text_color(color::text())
1110 .shadow_lg()
1111 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1112 .child(
1113 h_flex()
1114 .flex_none()
1115 .px(px(theme::LG))
1116 .py(px(theme::SM))
1117 .border_b_1()
1118 .border_color(color::border())
1119 .child(div().flex_1().text_base().font_weight(FontWeight::SEMIBOLD).child("Settings"))
1120 .child(icon_button("settings-close", IconName::Close, "Close (Esc)").on_click(
1121 move |_, window, cx| {
1122 let _ = close.update(cx, |s, cx| s.show_settings(None, window, cx));
1123 },
1124 )),
1125 )
1126 .child(
1127 h_flex().flex_1().min_h_0().items_start().child(list).child(
1128 v_flex()
1129 .id("settings-body")
1130 .flex_1()
1131 .min_w_0()
1132 .h_full()
1133 .overflow_y_scroll()
1134 .p(px(theme::LG))
1135 .gap(px(theme::MD))
1136 .child(
1137 div().text_base().font_weight(FontWeight::SEMIBOLD).child(nav[section].0.clone()),
1138 )
1139 .child(body),
1140 ),
1141 ),
1142 )
1143 .into_any_element()
1144 }
1145}
1146
1147const PEOPLE: &str = "People";
1149
1150fn people_commands(me: &WeakEntity<Shell>) -> Vec<CommandSpec> {
1152 #[derive(serde::Deserialize, schemars::JsonSchema)]
1153 struct UseArgs {
1154 name: Option<String>,
1156 }
1157 let (m1, m2) = (me.clone(), me.clone());
1158 vec![
1159 CommandSpec::with_args("people.use", "Work as…", IconName::CircleUser, move |a: UseArgs, _, cx| {
1160 crate::people::use_person(a.name.as_deref())?;
1161 let _ = m1.update(cx, |_, cx| cx.notify());
1162 Ok(Value::Null)
1163 })
1164 .group("App")
1165 .hint("Who works now: what is done is recorded under their name (none: a guest)"),
1166 CommandSpec::new("people.manage", "People…", IconName::CircleUser, move |window, cx| {
1167 let _ = m2.update(cx, |s, cx| {
1168 let i = s.settings_index(PEOPLE);
1169 s.show_settings(i, window, cx)
1170 });
1171 })
1172 .group("App")
1173 .hint("Add, pick and remove the people who work in the app")
1174 .read_only(),
1175 ]
1176}
1177
1178fn frame_commands(me: &WeakEntity<Shell>, workspaces: &[WorkspaceSpec], opens_files: bool) -> Vec<CommandSpec> {
1180 let (m1, m2, m3) = (me.clone(), me.clone(), me.clone());
1181 let mut out = vec![
1182 CommandSpec::new("shell.search", "Search…", IconName::Search, move |window, cx| {
1183 let _ = m1.update(cx, |s, cx| s.open_search(window, cx));
1184 })
1185 .group("App")
1186 .hint("Find any command by name")
1187 .key("secondary-k")
1188 .read_only(),
1189 CommandSpec::new("shell.settings", "Settings…", IconName::Settings, move |window, cx| {
1190 let _ = m2.update(cx, |s, cx| {
1191 let open = if s.settings.is_some() { None } else { Some(0) };
1192 s.show_settings(open, window, cx)
1193 });
1194 })
1195 .group("App")
1196 .hint("Theme, accent, text size and the app's settings")
1197 .key("secondary-,")
1198 .read_only(),
1199 CommandSpec::new("shell.theme", "Dark theme", IconName::Moon, move |_, cx| {
1200 let _ = m3.update(cx, |s, cx| {
1201 let l = theme::look();
1202 s.set_look(l.with_dark(!l.dark), cx)
1203 });
1204 })
1205 .group("View")
1206 .hint("Switch between the dark and the light theme")
1207 .checked(|_| theme::is_dark()),
1208 ];
1209 let (m4, m5) = (me.clone(), me.clone());
1210 if opens_files {
1212 out.push(
1213 CommandSpec::new("shell.open", "Open…", standard::OPEN, move |window, cx| {
1214 let _ = m4.update(cx, |s, cx| s.open_picker(window, cx));
1215 })
1216 .group("File")
1217 .hint("Pick a file to open")
1218 .key("secondary-o")
1219 .read_only(),
1220 );
1221 }
1222 out.push(
1223 CommandSpec::new("shell.quit", "Quit", IconName::WindowClose, |_, cx| cx.quit())
1224 .group("File")
1225 .hint("Close the app")
1226 .key("secondary-q")
1227 .read_only(),
1228 );
1229 out.push(
1230 CommandSpec::new("shell.panels", "Panels", standard::PANELS, move |_, cx| {
1231 let _ = m5.update(cx, |s, cx| s.toggle_drawer(cx));
1232 })
1233 .group("View")
1234 .hint("Show the side panes of a narrow window")
1235 .key("secondary-\\")
1236 .read_only(),
1237 );
1238 let mut n = 0;
1240 for w in workspaces {
1241 let (m, id) = (me.clone(), w.id.clone());
1242 let mut c = CommandSpec::new(
1243 format!("shell.workspace.{}", w.id),
1244 format!("Go to {}", w.title),
1245 w.icon,
1246 move |_, cx| {
1247 let _ = m.update(cx, |s, cx| s.set_workspace(&id, cx));
1248 },
1249 )
1250 .group("Workspaces")
1251 .hint(if w.hint.is_empty() { format!("Show the {} workspace", w.title).into() } else { w.hint.clone() })
1252 .read_only();
1253 if let Some(k) = &w.key {
1254 c = c.key(k.clone());
1255 } else if w.placement == Placement::View && n < 9 {
1256 n += 1;
1257 c = c.key(format!("secondary-{n}"));
1258 }
1259 out.push(c);
1260 }
1261 out
1262}
1263
1264pub fn resize_edge(
1266 p: gpui_kit::Point<gpui_kit::Pixels>,
1267 size: gpui_kit::Size<gpui_kit::Pixels>,
1268) -> Option<gpui_kit::ResizeEdge> {
1269 use gpui_kit::ResizeEdge as E;
1270 let band = RESIZE_BAND;
1271 let (x, y, w, h) = (p.x.as_f32(), p.y.as_f32(), size.width.as_f32(), size.height.as_f32());
1272 let (l, r, t, b) = (x < band, x > w - band, y < band, y > h - band);
1273 Some(match (l, r, t, b) {
1274 (true, _, true, _) => E::TopLeft,
1275 (_, true, true, _) => E::TopRight,
1276 (true, _, _, true) => E::BottomLeft,
1277 (_, true, _, true) => E::BottomRight,
1278 (true, ..) => E::Left,
1279 (_, true, ..) => E::Right,
1280 (_, _, true, _) => E::Top,
1281 (_, _, _, true) => E::Bottom,
1282 _ => return None,
1283 })
1284}
1285
1286pub fn frame_rounded(window: &Window) -> bool {
1289 match window.window_decorations() {
1290 gpui_kit::Decorations::Client { tiling } => {
1291 !(tiling.top || tiling.left || tiling.right || tiling.bottom)
1292 && !window.is_maximized()
1293 && !window.is_fullscreen()
1294 }
1295 gpui_kit::Decorations::Server => false,
1296 }
1297}
1298
1299impl Render for Shell {
1300 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1301 let registry = self.registry.clone();
1302 let settings = self.settings.map(|s| self.settings_view(s, window, cx));
1303 if matches!(window.window_decorations(), gpui_kit::Decorations::Client { .. }) {
1305 window.set_client_inset(px(0.0));
1306 }
1307 let rounded = frame_rounded(window);
1308 let fit = fit(window);
1309 if !fit.drawer() {
1311 self.drawer_open = false;
1312 }
1313 let drawer = self.workspace().drawer.clone().filter(|_| self.drawer_open && fit.drawer()).map(|view| {
1315 let close = cx.listener(|this, _, _, cx| {
1316 this.drawer_open = false;
1317 cx.notify();
1318 });
1319 div()
1320 .id("panels-drawer")
1321 .absolute()
1322 .inset_0()
1323 .flex()
1324 .child(
1325 div()
1326 .id("panels-drawer-pane")
1327 .occlude()
1328 .h_full()
1329 .w(px(320.))
1330 .max_w(gpui_kit::relative(0.85))
1331 .bg(color::panel())
1332 .border_r_1()
1333 .border_color(color::border())
1334 .shadow_lg()
1335 .overflow_hidden()
1336 .child(view),
1337 )
1338 .child(gpui_kit::TestSupportExt::test_support(
1339 div()
1340 .id("panels-drawer-scrim")
1341 .role(gpui_kit::Role::Button)
1342 .aria_label("Close the panels")
1343 .flex_1()
1344 .h_full()
1345 .bg(gpui_kit::black().opacity(0.3))
1346 .on_click(close),
1347 ))
1348 });
1349 let shell = v_flex()
1350 .id("shell")
1351 .key_context("Shell")
1352 .track_focus(&self.focus)
1353 .size_full()
1354 .relative()
1355 .bg(color::chrome())
1357 .text_color(color::text())
1358 .on_action(move |a: &RunCommand, window, cx| {
1360 if let Err(e) = registry.run_as(crate::activity::Actor::Person, "key", &a.id, Value::Null, window, cx) {
1361 eprintln!("{}: {e}", a.id);
1362 }
1363 })
1364 .on_key_down(cx.listener(|this, e: &KeyDownEvent, window, cx| {
1365 if e.keystroke.key == "escape" && this.settings.is_some() {
1366 this.show_settings(None, window, cx);
1367 cx.stop_propagation();
1368 } else if e.keystroke.key == "escape" && this.drawer_open {
1369 this.drawer_open = false;
1370 cx.notify();
1371 cx.stop_propagation();
1372 }
1373 }))
1374 .child(self.title_bar(rounded, fit, cx))
1375 .child(self.menu_row(fit))
1376 .child(
1377 div()
1378 .flex_1()
1379 .min_h_0()
1380 .relative()
1381 .p(px(theme::PANE_GAP))
1382 .child(
1383 div()
1384 .size_full()
1385 .rounded(px(theme::RADIUS_LG))
1386 .overflow_hidden()
1387 .bg(color::panel())
1388 .child(self.workspace().view.clone()),
1389 )
1390 .children(drawer),
1391 )
1392 .child(self.status_bar(rounded, window, cx))
1393 .children(self.overlay.clone().map(|o| div().absolute().inset_0().occlude().child(o)))
1395 .children(settings)
1396 .children(self.search.as_ref().map(|(s, _)| s.clone()))
1397 .children(self.picker.as_ref().map(|(p, _)| p.clone()))
1398 .when(rounded, |d| d.rounded(px(WINDOW_RADIUS)).overflow_hidden());
1400 div()
1401 .id("window-frame")
1402 .size_full()
1403 .when(rounded, |d| {
1404 d.on_mouse_down(MouseButton::Left, |e, window, _| {
1405 if let Some(edge) = resize_edge(e.position, window.viewport_size()) {
1406 window.start_window_resize(edge);
1407 }
1408 })
1409 })
1410 .child(shell)
1411 }
1412}