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, InteractiveElement as _, IntoElement,
46 KeyDownEvent, MouseButton, ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, WeakEntity,
47 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(id: impl Into<SharedString>, title: impl Into<SharedString>, icon: IconName, view: impl Into<AnyView>) -> Self {
175 Self {
176 id: id.into(),
177 title: title.into(),
178 icon,
179 hint: SharedString::default(),
180 menus: Vec::new(),
181 view: view.into(),
182 badge: None,
183 placement: Placement::View,
184 key: None,
185 drawer: None,
186 }
187 }
188
189 pub fn pipeline(view: impl Into<AnyView>) -> Self {
192 WorkspaceSpec::new(PIPELINE_ID, "Pipeline", standard::PIPELINE, view).hint("The steps from raw data to results, as a graph").shared().key(PIPELINE_KEY)
193 }
194
195 pub fn code(view: impl Into<AnyView>) -> Self {
197 WorkspaceSpec::new(CODE_ID, "Code", standard::CODE, view).hint("Scripts: write them, run them, add them to the pipeline").shared().key(CODE_KEY)
198 }
199
200 pub fn shared(mut self) -> Self {
202 self.placement = Placement::Shared;
203 self
204 }
205
206 pub fn key(mut self, key: impl Into<SharedString>) -> Self {
208 self.key = Some(key.into());
209 self
210 }
211
212 pub fn drawer(mut self, view: impl Into<AnyView>) -> Self {
215 self.drawer = Some(view.into());
216 self
217 }
218
219 pub fn hint(mut self, hint: impl Into<SharedString>) -> Self {
221 self.hint = hint.into();
222 self
223 }
224
225 pub fn menus(mut self, menus: Vec<MenuSpec>) -> Self {
227 self.menus = menus;
228 self
229 }
230
231 pub fn badge(mut self, count: impl Fn(&App) -> usize + 'static) -> Self {
233 self.badge = Some(Rc::new(count));
234 self
235 }
236}
237
238pub type SectionBody = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
240
241#[derive(Clone)]
243pub struct SettingsSection {
244 pub title: SharedString,
246 pub icon: IconName,
248 pub body: SectionBody,
250}
251
252impl SettingsSection {
253 pub fn new(title: impl Into<SharedString>, icon: IconName, body: impl Fn(&mut Window, &mut App) -> AnyElement + 'static) -> Self {
255 Self { title: title.into(), icon, body: Rc::new(body) }
256 }
257}
258
259#[derive(Clone, Debug, PartialEq)]
262pub struct RemoteSpec {
263 pub label: SharedString,
265 pub icon: IconName,
267 pub menu: Vec<MenuItem>,
269}
270
271#[derive(Clone)]
274pub struct OpenSpec {
275 pub kinds: Vec<FileKind>,
277 pub start: Option<std::path::PathBuf>,
279 pub recent: Rc<dyn Fn(&App) -> Vec<std::path::PathBuf>>,
281 pub open: Rc<dyn Fn(std::path::PathBuf, &mut Window, &mut App)>,
283}
284
285impl OpenSpec {
286 pub fn new(kinds: Vec<FileKind>, open: impl Fn(std::path::PathBuf, &mut Window, &mut App) + 'static) -> Self {
288 Self { kinds, start: None, recent: Rc::new(|_| Vec::new()), open: Rc::new(open) }
289 }
290
291 pub fn recent(mut self, recent: impl Fn(&App) -> Vec<std::path::PathBuf> + 'static) -> Self {
293 self.recent = Rc::new(recent);
294 self
295 }
296
297 pub fn start(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
299 self.start = Some(dir.into());
300 self
301 }
302}
303
304pub struct ShellSpec {
306 pub app_name: SharedString,
308 pub registry: Registry,
310 pub open: Option<OpenSpec>,
312 pub file_menu: Vec<MenuItem>,
314 pub app_menu: Vec<MenuItem>,
316 pub edit_menu: Vec<MenuItem>,
318 pub view_menu: Vec<MenuItem>,
320 pub help_menu: Vec<MenuItem>,
322 pub workspaces: Vec<WorkspaceSpec>,
324 pub settings: Vec<SettingsSection>,
326 pub layout_toggles: Vec<SharedString>,
328 pub remote: Option<RemoteSpec>,
330 pub people: bool,
333 pub meters: bool,
335 pub status_items: Option<StatusItems>,
337}
338
339pub type StatusItems = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
341
342impl ShellSpec {
343 pub fn new(app_name: impl Into<SharedString>, registry: Registry, workspaces: Vec<WorkspaceSpec>) -> Self {
345 Self {
346 app_name: app_name.into(),
347 registry,
348 open: None,
349 file_menu: Vec::new(),
350 app_menu: Vec::new(),
351 edit_menu: Vec::new(),
352 view_menu: Vec::new(),
353 help_menu: Vec::new(),
354 workspaces,
355 settings: Vec::new(),
356 layout_toggles: Vec::new(),
357 remote: None,
358 people: false,
359 meters: true,
360 status_items: None,
361 }
362 }
363}
364
365#[derive(Clone, Debug, PartialEq)]
367pub enum ShellEvent {
368 LookChanged(Look),
370 WorkspaceChanged(SharedString),
372}
373
374pub struct Shell {
376 app_name: SharedString,
377 registry: Registry,
378 file_menu: MenuSpec,
379 edit_menu: Option<MenuSpec>,
380 view_menu: MenuSpec,
381 help_menu: MenuSpec,
382 open: Option<OpenSpec>,
383 picker: Option<(Entity<FilePickerView>, Subscription)>,
384 drawer_open: bool,
386 workspaces: Vec<WorkspaceSpec>,
387 sections: Vec<SettingsSection>,
388 layout_toggles: Vec<SharedString>,
389 remote: Option<RemoteSpec>,
390 people: Option<Entity<crate::people_view::PeopleSettings>>,
392 status_items: Option<StatusItems>,
393 overlay: Option<AnyView>,
394 current: usize,
395 search: Option<(Entity<Search>, Subscription)>,
396 settings: Option<usize>,
398 accent: Entity<AccentPicker>,
399 status: SharedString,
400 project: Option<SharedString>,
401 meters: Option<(f32, u64, u64)>,
403 focus: FocusHandle,
404 _subs: Vec<Subscription>,
405}
406
407impl EventEmitter<ShellEvent> for Shell {}
408
409impl Shell {
410 pub fn new(spec: ShellSpec, window: &mut Window, cx: &mut Context<Self>) -> Self {
413 let me = cx.entity().downgrade();
414 spec.registry.extend(frame_commands(&me, &spec.workspaces, spec.open.is_some()));
415 let people = spec.people.then(|| {
416 spec.registry.extend(people_commands(&me));
417 spec.registry.provide("people", |_| crate::people_view::menu_items());
418 cx.new(|cx| crate::people_view::PeopleSettings::new(window, cx))
419 });
420 let mut file_items = Vec::new();
422 if spec.open.is_some() {
423 file_items.push(MenuItem::command("shell.open"));
424 }
425 file_items.extend(spec.file_menu);
426 file_items.extend(spec.app_menu);
427 if !file_items.is_empty() {
428 file_items.push(MenuItem::Separator);
429 }
430 file_items.push(MenuItem::command("shell.settings"));
431 file_items.push(MenuItem::Separator);
432 file_items.push(MenuItem::command("shell.quit"));
433 let edit_menu = (!spec.edit_menu.is_empty()).then(|| MenuSpec::new("Edit", spec.edit_menu));
434 let mut view_items = spec.view_menu;
436 if !view_items.is_empty() {
437 view_items.push(MenuItem::Separator);
438 }
439 view_items.extend(spec.layout_toggles.iter().map(|id| MenuItem::command(id.clone())));
440 if spec.workspaces.iter().any(|w| w.drawer.is_some()) {
441 view_items.push(MenuItem::command("shell.panels"));
442 }
443 view_items.push(MenuItem::command("shell.theme"));
444 let mut help_items = spec.help_menu;
445 if !help_items.is_empty() {
446 help_items.push(MenuItem::Separator);
447 }
448 help_items.push(MenuItem::command("shell.search"));
449 let accent = cx.new(|cx| AccentPicker::new(theme::look().accent, window, cx));
450 let mut subs = vec![cx.subscribe(&accent, |_, _, e: &AccentChanged, cx| {
451 let look = theme::look().with_accent(e.0);
452 theme::use_look(look, cx);
453 cx.emit(ShellEvent::LookChanged(look));
454 cx.notify();
455 })];
456 subs.push(cx.observe_window_appearance(window, |_, _, cx| cx.notify()));
457 let focus = cx.focus_handle();
458 window.focus(&focus, cx);
459 let shell = Self {
460 app_name: spec.app_name.clone(),
461 registry: spec.registry,
462 file_menu: MenuSpec::new("File", file_items).hint("Open, save, export; Settings; Quit"),
463 edit_menu,
464 view_menu: MenuSpec::new("View", view_items),
465 help_menu: MenuSpec::new("Help", help_items),
466 open: spec.open,
467 picker: None,
468 drawer_open: false,
469 workspaces: spec.workspaces,
470 sections: spec.settings,
471 layout_toggles: spec.layout_toggles,
472 remote: spec.remote,
473 people,
474 status_items: spec.status_items,
475 overlay: None,
476 current: 0,
477 search: None,
478 settings: None,
479 accent,
480 status: "Ready".into(),
481 project: None,
482 meters: None,
483 focus,
484 _subs: subs,
485 };
486 if let Some(w) = shell.workspaces.first() {
487 crate::activity::focus(&w.title);
488 }
489 shell.watch_jobs(cx);
490 if spec.meters {
491 shell.watch_meters(cx);
492 }
493 shell
494 }
495
496 fn watch_jobs(&self, cx: &mut Context<Self>) {
498 cx.spawn(async move |this, cx| {
499 let mut seen = jobs::generation();
500 loop {
501 cx.background_executor().timer(std::time::Duration::from_millis(250)).await;
502 let now = jobs::generation();
503 if now != seen {
504 seen = now;
505 if this.update(cx, |_, cx| cx.notify()).is_err() {
506 break;
507 }
508 }
509 }
510 })
511 .detach();
512 }
513
514 fn watch_meters(&self, cx: &mut Context<Self>) {
516 cx.spawn(async move |this, cx| {
517 let Ok(mut sys) = sysinfo::System::new() else { return };
519 loop {
520 let (s, m) = cx
521 .background_executor()
522 .spawn(async move {
523 sys.refresh_cpu_usage();
524 sys.refresh_memory();
525 let m = (sys.global_cpu_usage(), sys.used_memory(), sys.total_memory());
526 (sys, m)
527 })
528 .await;
529 sys = s;
530 let alive = this.update(cx, |s, cx| {
531 s.meters = Some(m);
532 cx.notify();
533 });
534 if alive.is_err() {
535 break;
536 }
537 cx.background_executor().timer(std::time::Duration::from_secs(2)).await;
538 }
539 })
540 .detach();
541 }
542
543 pub fn registry(&self) -> &Registry {
545 &self.registry
546 }
547
548 pub fn workspace(&self) -> &WorkspaceSpec {
550 &self.workspaces[self.current]
551 }
552
553 pub fn set_workspace(&mut self, id: &str, cx: &mut Context<Self>) -> bool {
555 let Some(i) = self.workspaces.iter().position(|w| w.id == id) else { return false };
556 if i != self.current {
557 self.current = i;
558 self.drawer_open = false;
559 crate::activity::focus(&self.workspaces[i].title);
560 cx.emit(ShellEvent::WorkspaceChanged(self.workspaces[i].id.clone()));
561 }
562 cx.notify();
563 true
564 }
565
566 pub fn workspace_id(&self) -> SharedString {
568 self.workspaces[self.current].id.clone()
569 }
570
571 pub fn current_view(&self) -> Option<SharedString> {
574 let w = &self.workspaces[self.current];
575 (w.placement == Placement::View).then(|| w.id.clone())
576 }
577
578 pub fn open_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
580 let Some(open) = self.open.clone() else { return };
581 let start = open.start.clone().or_else(crate::picker::home_dir).unwrap_or_else(|| std::path::PathBuf::from("/"));
582 let picker = Picker::new(open.kinds.clone(), start).with_recent((open.recent)(cx));
583 let view = cx.new(|cx| FilePickerView::new(picker, window, cx));
584 let sub = cx.subscribe_in(&view, window, move |this, _, e: &PickerEvent, window, cx| {
585 this.picker = None;
586 window.focus(&this.focus, cx);
587 if let PickerEvent::Open(path) = e {
588 (open.open)(path.clone(), window, cx);
589 }
590 cx.notify();
591 });
592 self.picker = Some((view, sub));
593 cx.notify();
594 }
595
596 pub fn picker(&self) -> Option<Entity<FilePickerView>> {
598 self.picker.as_ref().map(|(p, _)| p.clone())
599 }
600
601 pub fn toggle_drawer(&mut self, cx: &mut Context<Self>) {
603 self.drawer_open = !self.drawer_open && self.workspace().drawer.is_some();
604 cx.notify();
605 }
606
607 pub fn drawer_open(&self) -> bool {
609 self.drawer_open
610 }
611
612 pub fn set_menus(&mut self, id: &str, menus: Vec<MenuSpec>, cx: &mut Context<Self>) -> bool {
614 let Some(w) = self.workspaces.iter_mut().find(|w| w.id == id) else { return false };
615 w.menus = menus;
616 cx.notify();
617 true
618 }
619
620 pub fn set_overlay(&mut self, view: Option<AnyView>, window: &mut Window, cx: &mut Context<Self>) {
622 self.overlay = view;
623 if self.overlay.is_none() {
624 window.focus(&self.focus, cx);
625 }
626 cx.notify();
627 }
628
629 pub fn has_overlay(&self) -> bool {
631 self.overlay.is_some()
632 }
633
634 pub fn settings_index(&self, title: &str) -> Option<usize> {
637 if title == "Appearance" {
638 return Some(0);
639 }
640 if title == PEOPLE && self.people.is_some() {
641 return Some(self.sections.len() + 1);
642 }
643 self.sections.iter().position(|s| s.title == title).map(|i| i + 1)
644 }
645
646 pub fn set_status(&mut self, status: impl Into<SharedString>, cx: &mut Context<Self>) {
648 self.status = status.into();
649 cx.notify();
650 }
651
652 pub fn status(&self) -> &SharedString {
654 &self.status
655 }
656
657 pub fn set_project(&mut self, project: Option<SharedString>, cx: &mut Context<Self>) {
659 self.project = project;
660 cx.notify();
661 }
662
663 pub fn search(&self) -> Option<Entity<Search>> {
665 self.search.as_ref().map(|(s, _)| s.clone())
666 }
667
668 pub fn open_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
670 self.open_search_with(None, window, cx);
671 }
672
673 pub fn open_search_with(&mut self, filter: Option<(SharedString, crate::search::Filter)>, window: &mut Window, cx: &mut Context<Self>) {
676 if self.search.take().is_some() {
677 window.focus(&self.focus, cx);
678 cx.notify();
679 return;
680 }
681 let registry = self.registry.clone();
682 let search = cx.new(|cx| {
683 let s = Search::new(registry, window, cx);
684 match filter {
685 Some((title, f)) => s.title(title).filter(move |c| f(c)),
686 None => s,
687 }
688 });
689 let sub = cx.subscribe_in(&search, window, |this, _, e: &SearchEvent, window, cx| {
690 this.search = None;
691 window.focus(&this.focus, cx);
692 if let SearchEvent::Run(id) = e {
693 let (registry, id) = (this.registry.clone(), id.clone());
695 let me = cx.entity().downgrade();
696 window.defer(cx, move |window, cx| {
697 if let Err(e) = registry.run_as(crate::activity::Actor::Person, "search", &id, Value::Null, window, cx) {
698 let _ = me.update(cx, |s, cx| s.set_status(format!("{id}: {e}"), cx));
699 }
700 });
701 }
702 cx.notify();
703 });
704 self.search = Some((search, sub));
705 cx.notify();
706 }
707
708 pub fn settings_section(&self) -> Option<usize> {
710 self.settings
711 }
712
713 pub fn show_settings(&mut self, section: Option<usize>, window: &mut Window, cx: &mut Context<Self>) {
715 self.settings = section.map(|s| s.min(self.sections.len() + usize::from(self.people.is_some())));
716 if self.settings.is_none() {
717 window.focus(&self.focus, cx);
718 }
719 cx.notify();
720 }
721
722 pub fn set_look(&mut self, look: Look, cx: &mut Context<Self>) {
724 theme::use_look(look, cx);
725 cx.emit(ShellEvent::LookChanged(look));
726 cx.notify();
727 }
728
729 fn title_bar(&self, rounded: bool, fit: TitleFit, cx: &mut Context<Self>) -> impl IntoElement {
730 let menus: Vec<&MenuSpec> = [Some(&self.file_menu), self.edit_menu.as_ref(), Some(&self.view_menu), Some(&self.help_menu)].into_iter().flatten().collect();
732 let general = if fit.folded() {
733 let registry = self.registry.clone();
734 let items: Rc<Vec<MenuItem>> = Rc::new(menus.iter().map(|m| MenuItem::submenu(m.title.clone(), m.items.clone())).collect());
735 icon_button("title-menu", standard::MENU, "File, Edit, View, Help").dropdown_menu(move |m, window, cx| registry.fill_menu(m, &items, window, cx)).into_any_element()
736 } else {
737 h_flex().gap(px(2.)).children(menus.iter().map(|m| self.registry.menu_button(format!("menu-{}", m.title.to_lowercase()), m))).into_any_element()
738 };
739 let mark = div().id("title-mark").flex_none().px(px(theme::SM)).text_sm().font_weight(FontWeight::SEMIBOLD).text_color(color::accent_mark()).child(if fit.folded() {
740 self.app_name.chars().next().map(String::from).unwrap_or_default()
741 } else {
742 self.app_name.to_string()
743 });
744 let divider = div().flex_none().w(px(1.)).h(px(16.)).bg(color::border());
745 let workspace_button = |i: usize, w: &WorkspaceSpec, labelled: bool, cx: &mut Context<Self>| {
746 let id = w.id.clone();
747 let count = w.badge.as_ref().map_or(0, |f| f(cx));
748 let pill = (count > 0).then(|| {
749 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() })
750 });
751 let key = self.registry.get(&format!("shell.workspace.{}", w.id)).and_then(|c| c.key_label());
752 let tip = match (&key, w.hint.is_empty()) {
753 (Some(k), false) => format!("{}: {} ({k})", w.title, w.hint),
754 (Some(k), true) => format!("{} ({k})", w.title),
755 (None, false) => format!("{}: {}", w.title, w.hint),
756 (None, true) => w.title.to_string(),
757 };
758 let button = Button::new(SharedString::from(format!("workspace-{}", w.id))).small().ghost().icon(w.icon).tooltip(tip);
759 let button = if labelled { button.label(w.title.clone()) } else { button };
760 button.children(pill).selected(i == self.current).on_click(cx.listener(move |this, _, _, cx| {
761 this.set_workspace(&id, cx);
762 }))
763 };
764 let views: Vec<_> = self.workspaces.iter().enumerate().filter(|(_, w)| w.placement == Placement::View).map(|(i, w)| workspace_button(i, w, fit.labels(), cx)).collect();
766 let switcher = (!views.is_empty()).then(|| h_flex().id("title-views").min_w_0().gap(px(2.)).p(px(2.)).rounded(px(theme::RADIUS)).bg(color::control().opacity(0.6)).children(views));
767 let shared: Vec<_> = self.workspaces.iter().enumerate().filter(|(_, w)| w.placement == Placement::Shared).map(|(i, w)| workspace_button(i, w, false, cx)).collect();
769 let shared = (!shared.is_empty()).then(|| h_flex().gap(px(2.)).children(shared));
770 let toggles = self.layout_toggles.iter().filter(|_| !fit.folded()).filter_map(|id| self.registry.get(id)).map(|c| {
771 let (registry, id) = (self.registry.clone(), c.id.clone());
772 let tip = match c.key_label() {
773 Some(k) => format!("{} ({k})", c.title),
774 None => c.title.to_string(),
775 };
776 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| {
777 let _ = registry.run_as(crate::activity::Actor::Person, "title bar", &id, Value::Null, window, cx);
778 })
779 });
780 let panels = (fit.drawer() && self.workspace().drawer.is_some()).then(|| {
782 icon_button("title-panels", standard::PANELS, "Panels (Ctrl+\\)").selected(self.drawer_open).on_click(cx.listener(|this, _, _, cx| this.toggle_drawer(cx)))
783 });
784 let search = icon_button("title-search", IconName::Search, "Search commands (Ctrl+K)").on_click(cx.listener(|this, _, window, cx| this.open_search(window, cx)));
785 let remote = self.remote.clone().map(|r| {
786 let (registry, items) = (self.registry.clone(), Rc::new(r.menu.clone()));
787 let button = Button::new("remote").ghost().small().icon(r.icon);
788 let button = if fit.labels() { 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)) };
790 button.dropdown_menu(move |m, window, cx| registry.fill_menu(m.label("Run on"), &items, window, cx))
791 });
792 let more = fit.folded().then(|| {
794 let registry = self.registry.clone();
795 let items: Rc<Vec<MenuItem>> = Rc::new(self.layout_toggles.iter().map(|id| MenuItem::command(id.clone())).chain([MenuItem::command("shell.theme")]).collect());
796 icon_button("title-more", IconName::Ellipsis, "Panels and theme").dropdown_menu(move |m, window, cx| registry.fill_menu(m, &items, window, cx))
797 });
798 let dark = theme::is_dark();
799 let theme_button = (!fit.folded()).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| {
800 let l = theme::look();
801 this.set_look(l.with_dark(!l.dark), cx);
802 })));
803 let person = self.people.as_ref().map(|_| {
805 let who = crate::people::current().map(|p| p.name);
806 let label: SharedString = who.clone().unwrap_or_else(|| "Guest".into()).into();
807 let tip = match &who {
808 Some(n) => format!("Working as {n}: what you do is recorded under this name"),
809 None => "Working as a guest: no name is recorded".to_string(),
810 };
811 let button = Button::new("title-person").ghost().small().icon(IconName::CircleUser);
812 let button = if fit.labels() { button.label(label) } else { button };
813 let (registry, items) = (self.registry.clone(), Rc::new(vec![MenuItem::Provided("people".into())]));
814 button.tooltip(tip).dropdown_menu(move |m, window, cx| registry.fill_menu(m.label("Who works"), &items, window, cx))
815 });
816 let project = fit.labels().then(|| div().min_w_0().text_sm().text_color(color::text_muted()).truncate().child(self.project.clone().unwrap_or_else(|| "No project".into())));
818 TitleBar::new().when(rounded, |t| t.rounded_t(px(WINDOW_RADIUS - 1.0))).child(
820 h_flex()
821 .w_full()
822 .h(px(TITLE_BAR_H))
823 .gap(px(if fit.folded() { theme::XS } else { theme::SM }))
824 .pr(px(theme::SM))
825 .items_center()
826 .children(panels)
827 .child(mark)
828 .child(general)
829 .when(switcher.is_some(), |d| d.child(divider))
830 .children(switcher)
831 .child(div().flex_1())
832 .child(search)
833 .children(project)
834 .children(person)
835 .children(remote)
836 .children(shared)
837 .children(toggles)
838 .children(theme_button)
839 .children(more),
840 )
841 }
842
843 fn menu_row(&self, fit: TitleFit) -> impl IntoElement {
844 let w = self.workspace();
845 h_flex()
846 .id("menu-row")
847 .flex_none()
848 .w_full()
849 .h(px(MENU_ROW_H))
850 .px(px(theme::XS))
851 .gap(px(theme::XS))
852 .items_center()
853 .bg(color::panel())
854 .border_b_1()
855 .border_color(color::border())
856 .when(fit.folded(), |d| d.overflow_x_scroll())
858 .children(w.menus.iter().enumerate().map(|(i, m)| self.registry.menu_button(format!("menu-{}-{i}", w.id), m)))
859 }
860
861 fn status_bar(&self, rounded: bool, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
862 let pct = |f: Option<f32>| f.map_or(String::new(), |f| format!(" {:.0} %", f * 100.0));
863 let items = self.status_items.clone().map(|f| f(window, cx));
864 let jobs = jobs::running().into_iter().map(|j| {
865 let id = j.id;
866 h_flex()
867 .gap(px(theme::XS))
868 .items_center()
869 .child(div().max_w(px(320.)).truncate().text_color(color::accent_mark()).child(format!("{}{}", j.name, pct(j.progress))))
870 .child(icon_button(SharedString::from(format!("job-cancel-{id}")), IconName::Close, format!("Stop: {}", j.name)).xsmall().on_click(cx.listener(move |_, _, _, cx| {
871 jobs::cancel_id(id);
872 cx.notify();
873 })))
874 });
875 let meter = |icon: IconName, text: String, tip: &'static str| {
876 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))
877 };
878 h_flex()
879 .flex_none()
880 .h(px(STATUS_BAR_H))
881 .px(px(theme::MD))
882 .gap(px(theme::LG))
883 .items_center()
884 .bg(color::chrome())
885 .when(rounded, |d| d.rounded_b(px(WINDOW_RADIUS - 1.0)))
886 .text_xs()
887 .child(div().min_w_0().flex_1().truncate().child(self.status.clone()))
888 .children(items)
889 .children(jobs)
890 .children(self.meters.map(|(cpu, used, total)| {
891 let gb = |b: u64| b as f64 / 1e9;
892 h_flex()
893 .gap(px(theme::MD))
894 .child(meter(IconName::Cpu, format!("{cpu:.0} %"), "CPU in use, all cores"))
895 .child(meter(IconName::MemoryStick, format!("{:.1} / {:.1} GB", gb(used), gb(total)), "Memory in use / installed"))
896 }))
897 }
898
899 fn appearance(&self, cx: &mut Context<Self>) -> AnyElement {
900 let look = theme::look();
901 let me = cx.entity().downgrade();
902 let mode = MenuSelect::new("settings-theme", vec!["Dark".into(), "Light".into()], Some(if look.dark { 0 } else { 1 }), move |i, _, cx| {
903 let _ = me.update(cx, |s, cx| s.set_look(theme::look().with_dark(i == 0), cx));
904 });
905 let me = cx.entity().downgrade();
906 let size = stepper("settings-text", format!("{} px", look.font_size), move |step, _, cx| {
907 let _ = me.update(cx, |s, cx| {
908 let l = theme::look();
909 s.set_look(l.with_font_size(l.font_size + step), cx)
910 });
911 });
912 v_flex()
913 .gap(px(theme::MD))
914 .child(row("Theme", div().w_full().child(mode)))
915 .child(row("Accent", self.accent.clone()))
916 .child(row("Text size", size))
917 .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)))
918 .into_any_element()
919 }
920
921 fn settings_view(&self, section: usize, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
922 let mut nav: Vec<(SharedString, IconName)> = vec![("Appearance".into(), IconName::Palette)];
923 nav.extend(self.sections.iter().map(|s| (s.title.clone(), s.icon)));
924 if self.people.is_some() {
925 nav.push((PEOPLE.into(), IconName::CircleUser));
926 }
927 let body = match (&self.people, section) {
928 (_, 0) => self.appearance(cx),
929 (Some(people), s) if s == self.sections.len() + 1 => people.update(cx, |p, cx| p.body(cx)),
930 (_, s) => (self.sections[s - 1].body)(window, cx),
931 };
932 let close = cx.entity().downgrade();
933 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))| {
934 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)))
935 }));
936 div()
937 .id("settings-backdrop")
938 .absolute()
939 .inset_0()
940 .flex()
941 .items_center()
942 .justify_center()
943 .p(px(theme::XL))
944 .bg(gpui_kit::black().opacity(0.35))
945 .on_mouse_down(MouseButton::Left, cx.listener(|this, _, window, cx| this.show_settings(None, window, cx)))
946 .child(
947 v_flex()
948 .id("settings")
949 .occlude()
950 .w_full()
951 .max_w(px(820.))
952 .h_full()
953 .max_h(px(600.))
954 .rounded(px(theme::RADIUS_LG))
955 .border_1()
956 .border_color(color::border())
957 .bg(color::raised())
958 .text_color(color::text())
959 .shadow_lg()
960 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
961 .child(
962 h_flex()
963 .flex_none()
964 .px(px(theme::LG))
965 .py(px(theme::SM))
966 .border_b_1()
967 .border_color(color::border())
968 .child(div().flex_1().text_base().font_weight(FontWeight::SEMIBOLD).child("Settings"))
969 .child(icon_button("settings-close", IconName::Close, "Close (Esc)").on_click(move |_, window, cx| {
970 let _ = close.update(cx, |s, cx| s.show_settings(None, window, cx));
971 })),
972 )
973 .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))),
974 )
975 .into_any_element()
976 }
977}
978
979const PEOPLE: &str = "People";
981
982fn people_commands(me: &WeakEntity<Shell>) -> Vec<CommandSpec> {
984 #[derive(serde::Deserialize, schemars::JsonSchema)]
985 struct UseArgs {
986 name: Option<String>,
988 }
989 let (m1, m2) = (me.clone(), me.clone());
990 vec![
991 CommandSpec::with_args("people.use", "Work as…", IconName::CircleUser, move |a: UseArgs, _, cx| {
992 crate::people::use_person(a.name.as_deref())?;
993 let _ = m1.update(cx, |_, cx| cx.notify());
994 Ok(Value::Null)
995 })
996 .group("App")
997 .hint("Who works now: what is done is recorded under their name (none: a guest)"),
998 CommandSpec::new("people.manage", "People…", IconName::CircleUser, move |window, cx| {
999 let _ = m2.update(cx, |s, cx| {
1000 let i = s.settings_index(PEOPLE);
1001 s.show_settings(i, window, cx)
1002 });
1003 })
1004 .group("App")
1005 .hint("Add, pick and remove the people who work in the app")
1006 .read_only(),
1007 ]
1008}
1009
1010fn frame_commands(me: &WeakEntity<Shell>, workspaces: &[WorkspaceSpec], opens_files: bool) -> Vec<CommandSpec> {
1012 let (m1, m2, m3) = (me.clone(), me.clone(), me.clone());
1013 let mut out = vec![
1014 CommandSpec::new("shell.search", "Search…", IconName::Search, move |window, cx| {
1015 let _ = m1.update(cx, |s, cx| s.open_search(window, cx));
1016 })
1017 .group("App")
1018 .hint("Find any command by name")
1019 .key("secondary-k")
1020 .read_only(),
1021 CommandSpec::new("shell.settings", "Settings…", IconName::Settings, move |window, cx| {
1022 let _ = m2.update(cx, |s, cx| {
1023 let open = if s.settings.is_some() { None } else { Some(0) };
1024 s.show_settings(open, window, cx)
1025 });
1026 })
1027 .group("App")
1028 .hint("Theme, accent, text size and the app's settings")
1029 .key("secondary-,")
1030 .read_only(),
1031 CommandSpec::new("shell.theme", "Dark theme", IconName::Moon, move |_, cx| {
1032 let _ = m3.update(cx, |s, cx| {
1033 let l = theme::look();
1034 s.set_look(l.with_dark(!l.dark), cx)
1035 });
1036 })
1037 .group("View")
1038 .hint("Switch between the dark and the light theme")
1039 .checked(|_| theme::is_dark()),
1040 ];
1041 let (m4, m5) = (me.clone(), me.clone());
1042 if opens_files {
1044 out.push(
1045 CommandSpec::new("shell.open", "Open…", standard::OPEN, move |window, cx| {
1046 let _ = m4.update(cx, |s, cx| s.open_picker(window, cx));
1047 })
1048 .group("File")
1049 .hint("Pick a file to open")
1050 .key("secondary-o")
1051 .read_only(),
1052 );
1053 }
1054 out.push(
1055 CommandSpec::new("shell.quit", "Quit", IconName::WindowClose, |_, cx| cx.quit())
1056 .group("File")
1057 .hint("Close the app")
1058 .key("secondary-q")
1059 .read_only(),
1060 );
1061 out.push(
1062 CommandSpec::new("shell.panels", "Panels", standard::PANELS, move |_, cx| {
1063 let _ = m5.update(cx, |s, cx| s.toggle_drawer(cx));
1064 })
1065 .group("View")
1066 .hint("Show the side panes of a narrow window")
1067 .key("secondary-\\")
1068 .read_only(),
1069 );
1070 let mut n = 0;
1072 for w in workspaces {
1073 let (m, id) = (me.clone(), w.id.clone());
1074 let mut c = CommandSpec::new(format!("shell.workspace.{}", w.id), format!("Go to {}", w.title), w.icon, move |_, cx| {
1075 let _ = m.update(cx, |s, cx| s.set_workspace(&id, cx));
1076 })
1077 .group("Workspaces")
1078 .hint(if w.hint.is_empty() { format!("Show the {} workspace", w.title).into() } else { w.hint.clone() })
1079 .read_only();
1080 if let Some(k) = &w.key {
1081 c = c.key(k.clone());
1082 } else if w.placement == Placement::View && n < 9 {
1083 n += 1;
1084 c = c.key(format!("secondary-{n}"));
1085 }
1086 out.push(c);
1087 }
1088 out
1089}
1090
1091pub fn resize_edge(p: gpui_kit::Point<gpui_kit::Pixels>, size: gpui_kit::Size<gpui_kit::Pixels>) -> Option<gpui_kit::ResizeEdge> {
1093 use gpui_kit::ResizeEdge as E;
1094 let band = RESIZE_BAND;
1095 let (x, y, w, h) = (p.x.as_f32(), p.y.as_f32(), size.width.as_f32(), size.height.as_f32());
1096 let (l, r, t, b) = (x < band, x > w - band, y < band, y > h - band);
1097 Some(match (l, r, t, b) {
1098 (true, _, true, _) => E::TopLeft,
1099 (_, true, true, _) => E::TopRight,
1100 (true, _, _, true) => E::BottomLeft,
1101 (_, true, _, true) => E::BottomRight,
1102 (true, ..) => E::Left,
1103 (_, true, ..) => E::Right,
1104 (_, _, true, _) => E::Top,
1105 (_, _, _, true) => E::Bottom,
1106 _ => return None,
1107 })
1108}
1109
1110pub fn frame_rounded(window: &Window) -> bool {
1113 match window.window_decorations() {
1114 gpui_kit::Decorations::Client { tiling } => !(tiling.top || tiling.left || tiling.right || tiling.bottom) && !window.is_maximized() && !window.is_fullscreen(),
1115 gpui_kit::Decorations::Server => false,
1116 }
1117}
1118
1119impl Render for Shell {
1120 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1121 let registry = self.registry.clone();
1122 let settings = self.settings.map(|s| self.settings_view(s, window, cx));
1123 if matches!(window.window_decorations(), gpui_kit::Decorations::Client { .. }) {
1125 window.set_client_inset(px(0.0));
1126 }
1127 let rounded = frame_rounded(window);
1128 let fit = fit(window);
1129 if !fit.drawer() {
1131 self.drawer_open = false;
1132 }
1133 let drawer = self.workspace().drawer.clone().filter(|_| self.drawer_open && fit.drawer()).map(|view| {
1135 let close = cx.listener(|this, _, _, cx| {
1136 this.drawer_open = false;
1137 cx.notify();
1138 });
1139 div()
1140 .id("panels-drawer")
1141 .absolute()
1142 .inset_0()
1143 .flex()
1144 .child(
1145 div()
1146 .id("panels-drawer-pane")
1147 .occlude()
1148 .h_full()
1149 .w(px(320.))
1150 .max_w(gpui_kit::relative(0.85))
1151 .bg(color::panel())
1152 .border_r_1()
1153 .border_color(color::border())
1154 .shadow_lg()
1155 .overflow_hidden()
1156 .child(view),
1157 )
1158 .child(gpui_kit::TestSupportExt::test_support(div().id("panels-drawer-scrim").role(gpui_kit::Role::Button).aria_label("Close the panels").flex_1().h_full().bg(gpui_kit::black().opacity(0.3)).on_click(close)))
1159 });
1160 let shell = v_flex()
1161 .id("shell")
1162 .key_context("Shell")
1163 .track_focus(&self.focus)
1164 .size_full()
1165 .relative()
1166 .bg(color::chrome())
1168 .text_color(color::text())
1169 .on_action(move |a: &RunCommand, window, cx| {
1171 if let Err(e) = registry.run_as(crate::activity::Actor::Person, "key", &a.id, Value::Null, window, cx) {
1172 eprintln!("{}: {e}", a.id);
1173 }
1174 })
1175 .on_key_down(cx.listener(|this, e: &KeyDownEvent, window, cx| {
1176 if e.keystroke.key == "escape" && this.settings.is_some() {
1177 this.show_settings(None, window, cx);
1178 cx.stop_propagation();
1179 } else if e.keystroke.key == "escape" && this.drawer_open {
1180 this.drawer_open = false;
1181 cx.notify();
1182 cx.stop_propagation();
1183 }
1184 }))
1185 .child(self.title_bar(rounded, fit, cx))
1186 .child(self.menu_row(fit))
1187 .child(
1188 div()
1189 .flex_1()
1190 .min_h_0()
1191 .relative()
1192 .p(px(theme::PANE_GAP))
1193 .child(div().size_full().rounded(px(theme::RADIUS_LG)).overflow_hidden().bg(color::panel()).child(self.workspace().view.clone()))
1194 .children(drawer),
1195 )
1196 .child(self.status_bar(rounded, window, cx))
1197 .children(self.overlay.clone().map(|o| div().absolute().inset_0().occlude().child(o)))
1199 .children(settings)
1200 .children(self.search.as_ref().map(|(s, _)| s.clone()))
1201 .children(self.picker.as_ref().map(|(p, _)| p.clone()))
1202 .when(rounded, |d| d.rounded(px(WINDOW_RADIUS)).overflow_hidden());
1204 div()
1205 .id("window-frame")
1206 .size_full()
1207 .when(rounded, |d| {
1208 d.on_mouse_down(MouseButton::Left, |e, window, _| {
1209 if let Some(edge) = resize_edge(e.position, window.viewport_size()) {
1210 window.start_window_resize(edge);
1211 }
1212 })
1213 })
1214 .child(shell)
1215 }
1216}