Skip to main content

kitchen_shell/
frame.rs

1//! The frame every app shares ([`Shell`]): an app hands it its registry, its workspaces, its
2//! menus and its Settings sections ([`ShellSpec`]), and the frame draws them the same way in
3//! every app (Affinity's layout):
4//!
5//! - **Title bar**: the app's menu (named after the app: files, Settings) and Help at the left,
6//!   then the workspace switcher; at the right the project, the remote button (where the app
7//!   runs), the layout toggles (commands, as icon buttons) and the theme.
8//! - **Menu row**: the current workspace's menus, built from the registry.
9//! - **Body**: the current workspace's view, a card on the chrome.
10//! - **Status bar**: a status line, the running jobs ([`crate::jobs`]) with a cancel button each,
11//!   and this computer's load (CPU, memory).
12//! - **Settings** (Ctrl+,): sections on the left (Appearance, built in, then the app's), the
13//!   section's settings on the right.
14//! - **Search** (Ctrl+K, F3) over the registry.
15//! - **Window frame**: where the app draws its own frame (client-side decorations on Linux), the
16//!   window has rounded corners while it floats and resizes from its own edge; no shadow margin
17//!   (compositors that do not draw it showed what was behind the window there).
18//! - **Overlay**: one view of the app's over everything ([`Shell::set_overlay`]: a help sheet, a
19//!   dialog).
20//!
21//! The frame adds its own commands to the registry (`shell.search`, `shell.settings`,
22//! `shell.theme`, `shell.workspace.<id>`), so they are in the search and an agent's tools too.
23
24use 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
44/// Height of the title bar (px).
45pub const TITLE_BAR_H: f32 = 36.;
46/// Height of the menu row (px).
47pub const MENU_ROW_H: f32 = 32.;
48/// Height of the status bar (px): one 24 px target.
49pub const STATUS_BAR_H: f32 = 24.;
50/// The band at the window's own edge that resizes it while it floats (px).
51pub const RESIZE_BAND: f32 = 6.;
52/// Rounded corners of the window while it floats (px).
53pub const WINDOW_RADIUS: f32 = 10.;
54/// Below this window width (px) the title bar drops the project name and shows the remote as
55/// an icon (a phone held sideways, a small laptop window).
56pub const TITLE_COMPACT_W: f32 = 1100.;
57/// Below this window width (px) the workspaces show only their icons, and the layout toggles and
58/// the theme button move into one "More" menu (a phone held upright).
59pub const TITLE_NARROW_W: f32 = 640.;
60
61/// How much of the title bar fits a window `width` px wide (see [`TITLE_COMPACT_W`],
62/// [`TITLE_NARROW_W`]).
63#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
64pub enum TitleFit {
65    /// Under [`TITLE_NARROW_W`]: icons, and a "More" menu.
66    Narrow,
67    /// Under [`TITLE_COMPACT_W`]: no project name, the remote as an icon.
68    Compact,
69    /// Everything with its label.
70    Full,
71}
72
73impl TitleFit {
74    /// The fit for a window `width` px wide.
75    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
86/// A workspace of the app (Explore, Pipeline, Analyze; Sorting…).
87pub struct WorkspaceSpec {
88    /// Its id (`explore`): the command `shell.workspace.<id>` switches to it.
89    pub id: SharedString,
90    /// Its name on the switcher.
91    pub title: SharedString,
92    /// Its icon on the switcher.
93    pub icon: IconName,
94    /// What it is for (the switcher's tooltip).
95    pub hint: SharedString,
96    /// Its menu row.
97    pub menus: Vec<MenuSpec>,
98    /// What it shows.
99    pub view: AnyView,
100    /// A count shown on its switcher button when above zero (changed lines, unread messages).
101    pub badge: Option<Rc<dyn Fn(&App) -> usize>>,
102}
103
104impl WorkspaceSpec {
105    /// A workspace `id` titled `title`, showing `view`.
106    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    /// Sets what it is for.
111    pub fn hint(mut self, hint: impl Into<SharedString>) -> Self {
112        self.hint = hint.into();
113        self
114    }
115
116    /// Sets its menu row.
117    pub fn menus(mut self, menus: Vec<MenuSpec>) -> Self {
118        self.menus = menus;
119        self
120    }
121
122    /// Shows `count` on its switcher button when above zero.
123    pub fn badge(mut self, count: impl Fn(&App) -> usize + 'static) -> Self {
124        self.badge = Some(Rc::new(count));
125        self
126    }
127}
128
129/// Draws a Settings section's body.
130pub type SectionBody = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
131
132/// A section of Settings an app registers (Compute, Models, Plugins…).
133#[derive(Clone)]
134pub struct SettingsSection {
135    /// Its name in the list.
136    pub title: SharedString,
137    /// Its icon in the list.
138    pub icon: IconName,
139    /// Its settings.
140    pub body: SectionBody,
141}
142
143impl SettingsSection {
144    /// A section `title` drawing `body`.
145    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/// Where the app runs, at the right of the title bar (as VS Code's remote indicator): this
151/// computer, or a server. Its menu lists the places.
152#[derive(Clone, Debug, PartialEq)]
153pub struct RemoteSpec {
154    /// Where it runs now ("This computer").
155    pub label: SharedString,
156    /// Its icon.
157    pub icon: IconName,
158    /// The places to choose from (commands).
159    pub menu: Vec<MenuItem>,
160}
161
162/// What an app hands the frame.
163pub struct ShellSpec {
164    /// The app's name: its menu's title.
165    pub app_name: SharedString,
166    /// Its commands.
167    pub registry: Registry,
168    /// The app menu's entries (files, projects…; Settings is added at its end).
169    pub app_menu: Vec<MenuItem>,
170    /// The Help menu's entries (the search and Settings are added).
171    pub help_menu: Vec<MenuItem>,
172    /// Its workspaces, in the switcher's order.
173    pub workspaces: Vec<WorkspaceSpec>,
174    /// Its Settings sections (after the built-in Appearance).
175    pub settings: Vec<SettingsSection>,
176    /// Commands shown as icon buttons at the right of the title bar (side panels…).
177    pub layout_toggles: Vec<SharedString>,
178    /// Where the app runs.
179    pub remote: Option<RemoteSpec>,
180    /// Whether the app records who works ([`crate::people`]): the title bar's person button and a
181    /// People section at the end of Settings. The app [`crate::people::load`]s the people first.
182    pub people: bool,
183    /// Whether the status bar shows this computer's load (off in tests).
184    pub meters: bool,
185    /// The app's own readings in the status bar, before the jobs (the frame's numbers, a device).
186    pub status_items: Option<StatusItems>,
187}
188
189/// Draws the app's readings in the status bar.
190pub type StatusItems = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
191
192impl ShellSpec {
193    /// An app named `app_name` with `registry` and `workspaces`, the rest empty.
194    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/// What the frame tells the app.
212#[derive(Clone, Debug, PartialEq)]
213pub enum ShellEvent {
214    /// The user changed the look in the title bar or Settings: store it in the preferences.
215    LookChanged(Look),
216    /// The user switched workspace.
217    WorkspaceChanged(SharedString),
218}
219
220/// The frame.
221pub 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    /// The People section, when the app records who works.
231    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    /// The Settings section shown, when Settings is open.
237    settings: Option<usize>,
238    accent: Entity<AccentPicker>,
239    status: SharedString,
240    project: Option<SharedString>,
241    /// This computer's load: CPU %, memory used and installed (bytes).
242    meters: Option<(f32, u64, u64)>,
243    focus: FocusHandle,
244    _subs: Vec<Subscription>,
245}
246
247impl EventEmitter<ShellEvent> for Shell {}
248
249impl Shell {
250    /// The frame for `spec`; adds the frame's commands to the registry and focuses the frame.
251    /// Bind the keys after ([`Registry::bind_keys`]), once every command is registered.
252    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    /// Redraws when a job starts, moves or ends.
313    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    /// CPU and memory meters (as VS Code's resource monitor), read off the UI thread every 2 s.
331    fn watch_meters(&self, cx: &mut Context<Self>) {
332        cx.spawn(async move |this, cx| {
333            // No meters where the system cannot be read
334            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    /// The registry (the app's commands and the frame's).
360    pub fn registry(&self) -> &Registry {
361        &self.registry
362    }
363
364    /// The workspace shown.
365    pub fn workspace(&self) -> &WorkspaceSpec {
366        &self.workspaces[self.current]
367    }
368
369    /// Shows the workspace `id`; whether there is one.
370    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    /// The id of the workspace shown.
382    pub fn workspace_id(&self) -> SharedString {
383        self.workspaces[self.current].id.clone()
384    }
385
386    /// Replaces the menu row of the workspace `id`; whether there is one.
387    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    /// Shows `view` over everything (a help sheet, a dialog), or takes it away (`None`).
395    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    /// Whether an overlay is shown.
404    pub fn has_overlay(&self) -> bool {
405        self.overlay.is_some()
406    }
407
408    /// Whether the Settings section `title` exists (0 is Appearance, then the app's, then People
409    /// when the app records who works).
410    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    /// Sets the status line.
421    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    /// The status line.
427    pub fn status(&self) -> &SharedString {
428        &self.status
429    }
430
431    /// Sets the project named in the title bar (`None`: none open).
432    pub fn set_project(&mut self, project: Option<SharedString>, cx: &mut Context<Self>) {
433        self.project = project;
434        cx.notify();
435    }
436
437    /// The search, when open.
438    pub fn search(&self) -> Option<Entity<Search>> {
439        self.search.as_ref().map(|(s, _)| s.clone())
440    }
441
442    /// Opens the search over every command.
443    pub fn open_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
444        self.open_search_with(None, window, cx);
445    }
446
447    /// Opens the search over the commands `filter` accepts, titled `title` (Process ▸ "Find an
448    /// operation…": one kind of command); every command when `None`. Open already: closes it.
449    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                // Run once this update is over: the command may change the frame itself
468                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    /// The Settings section shown, when Settings is open (0 is Appearance).
483    pub fn settings_section(&self) -> Option<usize> {
484        self.settings
485    }
486
487    /// Opens Settings at `section` (0: Appearance, then the app's in order), or closes it.
488    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    /// Sets the look and tells the app.
497    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            // Narrow: the icon only, its name in the tooltip
513            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            // Compact: the icon only, where it runs in the tooltip
536            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        // Narrow: the layout toggles and the theme in one menu, as commands (checked when on)
541        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        // Who works: their name (compact: the icon, the name in the tooltip); a guest says so
552        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        // Compact and narrow: the project's name is left to the app's status bar
565        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        // GPUI clips to rectangles: the bars round their own corners inside a rounded frame
567        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
719/// The People section's title.
720const PEOPLE: &str = "People";
721
722/// Who works: pick a person (or a guest), open People.
723fn people_commands(me: &WeakEntity<Shell>) -> Vec<CommandSpec> {
724    #[derive(serde::Deserialize, schemars::JsonSchema)]
725    struct UseArgs {
726        /// The person's name; none: a guest.
727        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
750/// The frame's own commands.
751fn 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
797/// The edge a press at `p` (window px) resizes, within [`RESIZE_BAND`] of a `size` window's edge.
798pub 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
816/// Whether the window draws its own rounded frame: client-side decorations on a floating window
817/// (square when maximised, full screen or tiled).
818pub 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        // Linux draws the frame itself (client-side decorations): no inset for a shadow margin
830        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            // The chrome under everything: the panes are cards on it
841            .bg(color::chrome())
842            .text_color(color::text())
843            // Not a listener: a command may update the frame itself
844            .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            // Over everything, and nothing under it takes a click meant for it
860            .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            // No outline: the compositor's shadow sets a floating window apart
864            .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}