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 status bar shows this computer's load (off in tests).
181    pub meters: bool,
182    /// The app's own readings in the status bar, before the jobs (the frame's numbers, a device).
183    pub status_items: Option<StatusItems>,
184}
185
186/// Draws the app's readings in the status bar.
187pub type StatusItems = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
188
189impl ShellSpec {
190    /// An app named `app_name` with `registry` and `workspaces`, the rest empty.
191    pub fn new(app_name: impl Into<SharedString>, registry: Registry, workspaces: Vec<WorkspaceSpec>) -> Self {
192        Self {
193            app_name: app_name.into(),
194            registry,
195            app_menu: Vec::new(),
196            help_menu: Vec::new(),
197            workspaces,
198            settings: Vec::new(),
199            layout_toggles: Vec::new(),
200            remote: None,
201            meters: true,
202            status_items: None,
203        }
204    }
205}
206
207/// What the frame tells the app.
208#[derive(Clone, Debug, PartialEq)]
209pub enum ShellEvent {
210    /// The user changed the look in the title bar or Settings: store it in the preferences.
211    LookChanged(Look),
212    /// The user switched workspace.
213    WorkspaceChanged(SharedString),
214}
215
216/// The frame.
217pub struct Shell {
218    app_name: SharedString,
219    registry: Registry,
220    app_menu: MenuSpec,
221    help_menu: MenuSpec,
222    workspaces: Vec<WorkspaceSpec>,
223    sections: Vec<SettingsSection>,
224    layout_toggles: Vec<SharedString>,
225    remote: Option<RemoteSpec>,
226    status_items: Option<StatusItems>,
227    overlay: Option<AnyView>,
228    current: usize,
229    search: Option<(Entity<Search>, Subscription)>,
230    /// The Settings section shown, when Settings is open.
231    settings: Option<usize>,
232    accent: Entity<AccentPicker>,
233    status: SharedString,
234    project: Option<SharedString>,
235    /// This computer's load: CPU %, memory used and installed (bytes).
236    meters: Option<(f32, u64, u64)>,
237    focus: FocusHandle,
238    _subs: Vec<Subscription>,
239}
240
241impl EventEmitter<ShellEvent> for Shell {}
242
243impl Shell {
244    /// The frame for `spec`; adds the frame's commands to the registry and focuses the frame.
245    /// Bind the keys after ([`Registry::bind_keys`]), once every command is registered.
246    pub fn new(spec: ShellSpec, window: &mut Window, cx: &mut Context<Self>) -> Self {
247        let me = cx.entity().downgrade();
248        spec.registry.extend(frame_commands(&me, &spec.workspaces));
249        let mut app_items = spec.app_menu;
250        if !app_items.is_empty() {
251            app_items.push(MenuItem::Separator);
252        }
253        app_items.push(MenuItem::command("shell.settings"));
254        let mut help_items = spec.help_menu;
255        if !help_items.is_empty() {
256            help_items.push(MenuItem::Separator);
257        }
258        help_items.push(MenuItem::command("shell.search"));
259        let accent = cx.new(|cx| AccentPicker::new(theme::look().accent, window, cx));
260        let mut subs = vec![cx.subscribe(&accent, |_, _, e: &AccentChanged, cx| {
261            let look = theme::look().with_accent(e.0);
262            theme::use_look(look, cx);
263            cx.emit(ShellEvent::LookChanged(look));
264            cx.notify();
265        })];
266        subs.push(cx.observe_window_appearance(window, |_, _, cx| cx.notify()));
267        let focus = cx.focus_handle();
268        window.focus(&focus, cx);
269        let shell = Self {
270            app_name: spec.app_name.clone(),
271            registry: spec.registry,
272            app_menu: MenuSpec::new(spec.app_name, app_items),
273            help_menu: MenuSpec::new("Help", help_items),
274            workspaces: spec.workspaces,
275            sections: spec.settings,
276            layout_toggles: spec.layout_toggles,
277            remote: spec.remote,
278            status_items: spec.status_items,
279            overlay: None,
280            current: 0,
281            search: None,
282            settings: None,
283            accent,
284            status: "Ready".into(),
285            project: None,
286            meters: None,
287            focus,
288            _subs: subs,
289        };
290        if let Some(w) = shell.workspaces.first() {
291            crate::activity::focus(&w.title);
292        }
293        shell.watch_jobs(cx);
294        if spec.meters {
295            shell.watch_meters(cx);
296        }
297        shell
298    }
299
300    /// Redraws when a job starts, moves or ends.
301    fn watch_jobs(&self, cx: &mut Context<Self>) {
302        cx.spawn(async move |this, cx| {
303            let mut seen = jobs::generation();
304            loop {
305                cx.background_executor().timer(std::time::Duration::from_millis(250)).await;
306                let now = jobs::generation();
307                if now != seen {
308                    seen = now;
309                    if this.update(cx, |_, cx| cx.notify()).is_err() {
310                        break;
311                    }
312                }
313            }
314        })
315        .detach();
316    }
317
318    /// CPU and memory meters (as VS Code's resource monitor), read off the UI thread every 2 s.
319    fn watch_meters(&self, cx: &mut Context<Self>) {
320        cx.spawn(async move |this, cx| {
321            // No meters where the system cannot be read
322            let Ok(mut sys) = sysinfo::System::new() else { return };
323            loop {
324                let (s, m) = cx
325                    .background_executor()
326                    .spawn(async move {
327                        sys.refresh_cpu_usage();
328                        sys.refresh_memory();
329                        let m = (sys.global_cpu_usage(), sys.used_memory(), sys.total_memory());
330                        (sys, m)
331                    })
332                    .await;
333                sys = s;
334                let alive = this.update(cx, |s, cx| {
335                    s.meters = Some(m);
336                    cx.notify();
337                });
338                if alive.is_err() {
339                    break;
340                }
341                cx.background_executor().timer(std::time::Duration::from_secs(2)).await;
342            }
343        })
344        .detach();
345    }
346
347    /// The registry (the app's commands and the frame's).
348    pub fn registry(&self) -> &Registry {
349        &self.registry
350    }
351
352    /// The workspace shown.
353    pub fn workspace(&self) -> &WorkspaceSpec {
354        &self.workspaces[self.current]
355    }
356
357    /// Shows the workspace `id`; whether there is one.
358    pub fn set_workspace(&mut self, id: &str, cx: &mut Context<Self>) -> bool {
359        let Some(i) = self.workspaces.iter().position(|w| w.id == id) else { return false };
360        if i != self.current {
361            self.current = i;
362            crate::activity::focus(&self.workspaces[i].title);
363            cx.emit(ShellEvent::WorkspaceChanged(self.workspaces[i].id.clone()));
364        }
365        cx.notify();
366        true
367    }
368
369    /// The id of the workspace shown.
370    pub fn workspace_id(&self) -> SharedString {
371        self.workspaces[self.current].id.clone()
372    }
373
374    /// Replaces the menu row of the workspace `id`; whether there is one.
375    pub fn set_menus(&mut self, id: &str, menus: Vec<MenuSpec>, cx: &mut Context<Self>) -> bool {
376        let Some(w) = self.workspaces.iter_mut().find(|w| w.id == id) else { return false };
377        w.menus = menus;
378        cx.notify();
379        true
380    }
381
382    /// Shows `view` over everything (a help sheet, a dialog), or takes it away (`None`).
383    pub fn set_overlay(&mut self, view: Option<AnyView>, window: &mut Window, cx: &mut Context<Self>) {
384        self.overlay = view;
385        if self.overlay.is_none() {
386            window.focus(&self.focus, cx);
387        }
388        cx.notify();
389    }
390
391    /// Whether an overlay is shown.
392    pub fn has_overlay(&self) -> bool {
393        self.overlay.is_some()
394    }
395
396    /// Whether the Settings section `title` exists (0 is Appearance, then the app's).
397    pub fn settings_index(&self, title: &str) -> Option<usize> {
398        if title == "Appearance" {
399            return Some(0);
400        }
401        self.sections.iter().position(|s| s.title == title).map(|i| i + 1)
402    }
403
404    /// Sets the status line.
405    pub fn set_status(&mut self, status: impl Into<SharedString>, cx: &mut Context<Self>) {
406        self.status = status.into();
407        cx.notify();
408    }
409
410    /// The status line.
411    pub fn status(&self) -> &SharedString {
412        &self.status
413    }
414
415    /// Sets the project named in the title bar (`None`: none open).
416    pub fn set_project(&mut self, project: Option<SharedString>, cx: &mut Context<Self>) {
417        self.project = project;
418        cx.notify();
419    }
420
421    /// The search, when open.
422    pub fn search(&self) -> Option<Entity<Search>> {
423        self.search.as_ref().map(|(s, _)| s.clone())
424    }
425
426    /// Opens the search over every command.
427    pub fn open_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
428        self.open_search_with(None, window, cx);
429    }
430
431    /// Opens the search over the commands `filter` accepts, titled `title` (Process ▸ "Find an
432    /// operation…": one kind of command); every command when `None`. Open already: closes it.
433    pub fn open_search_with(&mut self, filter: Option<(SharedString, crate::search::Filter)>, window: &mut Window, cx: &mut Context<Self>) {
434        if self.search.take().is_some() {
435            window.focus(&self.focus, cx);
436            cx.notify();
437            return;
438        }
439        let registry = self.registry.clone();
440        let search = cx.new(|cx| {
441            let s = Search::new(registry, window, cx);
442            match filter {
443                Some((title, f)) => s.title(title).filter(move |c| f(c)),
444                None => s,
445            }
446        });
447        let sub = cx.subscribe_in(&search, window, |this, _, e: &SearchEvent, window, cx| {
448            this.search = None;
449            window.focus(&this.focus, cx);
450            if let SearchEvent::Run(id) = e {
451                // Run once this update is over: the command may change the frame itself
452                let (registry, id) = (this.registry.clone(), id.clone());
453                let me = cx.entity().downgrade();
454                window.defer(cx, move |window, cx| {
455                    if let Err(e) = registry.run_as(crate::activity::Actor::Person, "search", &id, Value::Null, window, cx) {
456                        let _ = me.update(cx, |s, cx| s.set_status(format!("{id}: {e}"), cx));
457                    }
458                });
459            }
460            cx.notify();
461        });
462        self.search = Some((search, sub));
463        cx.notify();
464    }
465
466    /// The Settings section shown, when Settings is open (0 is Appearance).
467    pub fn settings_section(&self) -> Option<usize> {
468        self.settings
469    }
470
471    /// Opens Settings at `section` (0: Appearance, then the app's in order), or closes it.
472    pub fn show_settings(&mut self, section: Option<usize>, window: &mut Window, cx: &mut Context<Self>) {
473        self.settings = section.map(|s| s.min(self.sections.len()));
474        if self.settings.is_none() {
475            window.focus(&self.focus, cx);
476        }
477        cx.notify();
478    }
479
480    /// Sets the look and tells the app.
481    pub fn set_look(&mut self, look: Look, cx: &mut Context<Self>) {
482        theme::use_look(look, cx);
483        cx.emit(ShellEvent::LookChanged(look));
484        cx.notify();
485    }
486
487    fn title_bar(&self, rounded: bool, fit: TitleFit, cx: &mut Context<Self>) -> impl IntoElement {
488        let app = self.registry.menu_button("menu-app", &MenuSpec { hint: "Files, projects, Settings".into(), ..self.app_menu.clone() });
489        let help = self.registry.menu_button("menu-help", &self.help_menu);
490        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)| {
491            let id = w.id.clone();
492            let count = w.badge.as_ref().map_or(0, |f| f(cx));
493            let pill = (count > 0).then(|| {
494                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() })
495            });
496            // Narrow: the icon only, its name in the tooltip
497            let button = Button::new(SharedString::from(format!("workspace-{}", w.id))).small().ghost().icon(w.icon);
498            let button = if fit == TitleFit::Narrow { button.tooltip(format!("{}: {}", w.title, w.hint)) } else { button.label(w.title.clone()).tooltip(w.hint.clone()) };
499            button
500                .children(pill)
501                .selected(i == self.current)
502                .on_click(cx.listener(move |this, _, _, cx| {
503                    this.set_workspace(&id, cx);
504                }))
505        }));
506        let toggles = self.layout_toggles.iter().filter(|_| fit != TitleFit::Narrow).filter_map(|id| self.registry.get(id)).map(|c| {
507            let (registry, id) = (self.registry.clone(), c.id.clone());
508            let tip = match c.key_label() {
509                Some(k) => format!("{} ({k})", c.title),
510                None => c.title.to_string(),
511            };
512            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| {
513                let _ = registry.run_as(crate::activity::Actor::Person, "title bar", &id, Value::Null, window, cx);
514            })
515        });
516        let remote = self.remote.clone().map(|r| {
517            let (registry, items) = (self.registry.clone(), Rc::new(r.menu.clone()));
518            let button = Button::new("remote").ghost().small().icon(r.icon);
519            // Compact: the icon only, where it runs in the tooltip
520            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)) };
521            button
522                .dropdown_menu(move |m, window, cx| registry.fill_menu(m.label("Run on"), &items, window, cx))
523        });
524        // Narrow: the layout toggles and the theme in one menu, as commands (checked when on)
525        let more = (fit == TitleFit::Narrow).then(|| {
526            let registry = self.registry.clone();
527            let items: Rc<Vec<MenuItem>> = Rc::new(self.layout_toggles.iter().map(|id| MenuItem::command(id.clone())).chain([MenuItem::command("shell.theme")]).collect());
528            icon_button("title-more", IconName::Ellipsis, "Panels and theme").dropdown_menu(move |m, window, cx| registry.fill_menu(m, &items, window, cx))
529        });
530        let dark = theme::is_dark();
531        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| {
532            let l = theme::look();
533            this.set_look(l.with_dark(!l.dark), cx);
534        })));
535        // Compact and narrow: the project's name is left to the app's status bar
536        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())));
537        // GPUI clips to rectangles: the bars round their own corners inside a rounded frame
538        TitleBar::new().when(rounded, |t| t.rounded_t(px(WINDOW_RADIUS - 1.0))).child(
539            h_flex()
540                .w_full()
541                .h(px(TITLE_BAR_H))
542                .gap(px(if fit == TitleFit::Narrow { theme::XS } else { theme::MD }))
543                .pr(px(theme::SM))
544                .items_center()
545                .child(h_flex().gap(px(2.)).child(div().font_weight(FontWeight::SEMIBOLD).child(app)).child(help))
546                .child(switcher)
547                .child(div().flex_1())
548                .children(project)
549                .children(remote)
550                .children(toggles)
551                .children(theme_button)
552                .children(more),
553        )
554    }
555
556    fn menu_row(&self) -> impl IntoElement {
557        let w = self.workspace();
558        h_flex()
559            .flex_none()
560            .w_full()
561            .h(px(MENU_ROW_H))
562            .px(px(theme::XS))
563            .gap(px(2.))
564            .items_center()
565            .bg(color::panel())
566            .border_b_1()
567            .border_color(color::border())
568            .children(w.menus.iter().enumerate().map(|(i, m)| self.registry.menu_button(format!("menu-{}-{i}", w.id), m)))
569    }
570
571    fn status_bar(&self, rounded: bool, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
572        let pct = |f: Option<f32>| f.map_or(String::new(), |f| format!(" {:.0} %", f * 100.0));
573        let items = self.status_items.clone().map(|f| f(window, cx));
574        let jobs = jobs::running().into_iter().map(|j| {
575            let id = j.id;
576            h_flex()
577                .gap(px(theme::XS))
578                .items_center()
579                .child(div().max_w(px(320.)).truncate().text_color(color::accent_mark()).child(format!("{}{}", j.name, pct(j.progress))))
580                .child(icon_button(SharedString::from(format!("job-cancel-{id}")), IconName::Close, format!("Stop: {}", j.name)).xsmall().on_click(cx.listener(move |_, _, _, cx| {
581                    jobs::cancel_id(id);
582                    cx.notify();
583                })))
584        });
585        let meter = |icon: IconName, text: String, tip: &'static str| {
586            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))
587        };
588        h_flex()
589            .flex_none()
590            .h(px(STATUS_BAR_H))
591            .px(px(theme::MD))
592            .gap(px(theme::LG))
593            .items_center()
594            .bg(color::chrome())
595            .when(rounded, |d| d.rounded_b(px(WINDOW_RADIUS - 1.0)))
596            .text_xs()
597            .child(div().min_w_0().flex_1().truncate().child(self.status.clone()))
598            .children(items)
599            .children(jobs)
600            .children(self.meters.map(|(cpu, used, total)| {
601                let gb = |b: u64| b as f64 / 1e9;
602                h_flex()
603                    .gap(px(theme::MD))
604                    .child(meter(IconName::Cpu, format!("{cpu:.0} %"), "CPU in use, all cores"))
605                    .child(meter(IconName::MemoryStick, format!("{:.1} / {:.1} GB", gb(used), gb(total)), "Memory in use / installed"))
606            }))
607    }
608
609    fn appearance(&self, cx: &mut Context<Self>) -> AnyElement {
610        let look = theme::look();
611        let me = cx.entity().downgrade();
612        let mode = MenuSelect::new("settings-theme", vec!["Dark".into(), "Light".into()], Some(if look.dark { 0 } else { 1 }), move |i, _, cx| {
613            let _ = me.update(cx, |s, cx| s.set_look(theme::look().with_dark(i == 0), cx));
614        });
615        let me = cx.entity().downgrade();
616        let size = stepper("settings-text", format!("{} px", look.font_size), move |step, _, cx| {
617            let _ = me.update(cx, |s, cx| {
618                let l = theme::look();
619                s.set_look(l.with_font_size(l.font_size + step), cx)
620            });
621        });
622        v_flex()
623            .gap(px(theme::MD))
624            .child(row("Theme", div().w_full().child(mode)))
625            .child(row("Accent", self.accent.clone()))
626            .child(row("Text size", size))
627            .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)))
628            .into_any_element()
629    }
630
631    fn settings_view(&self, section: usize, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
632        let mut nav: Vec<(SharedString, IconName)> = vec![("Appearance".into(), IconName::Palette)];
633        nav.extend(self.sections.iter().map(|s| (s.title.clone(), s.icon)));
634        let body = if section == 0 { self.appearance(cx) } else { (self.sections[section - 1].body)(window, cx) };
635        let close = cx.entity().downgrade();
636        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))| {
637            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)))
638        }));
639        div()
640            .id("settings-backdrop")
641            .absolute()
642            .inset_0()
643            .flex()
644            .items_center()
645            .justify_center()
646            .p(px(theme::XL))
647            .bg(gpui_kit::black().opacity(0.35))
648            .on_mouse_down(MouseButton::Left, cx.listener(|this, _, window, cx| this.show_settings(None, window, cx)))
649            .child(
650                v_flex()
651                    .id("settings")
652                    .occlude()
653                    .w_full()
654                    .max_w(px(820.))
655                    .h_full()
656                    .max_h(px(600.))
657                    .rounded(px(theme::RADIUS_LG))
658                    .border_1()
659                    .border_color(color::border())
660                    .bg(color::raised())
661                    .text_color(color::text())
662                    .shadow_lg()
663                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
664                    .child(
665                        h_flex()
666                            .flex_none()
667                            .px(px(theme::LG))
668                            .py(px(theme::SM))
669                            .border_b_1()
670                            .border_color(color::border())
671                            .child(div().flex_1().text_base().font_weight(FontWeight::SEMIBOLD).child("Settings"))
672                            .child(icon_button("settings-close", IconName::Close, "Close (Esc)").on_click(move |_, window, cx| {
673                                let _ = close.update(cx, |s, cx| s.show_settings(None, window, cx));
674                            })),
675                    )
676                    .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))),
677            )
678            .into_any_element()
679    }
680}
681
682/// The frame's own commands.
683fn frame_commands(me: &WeakEntity<Shell>, workspaces: &[WorkspaceSpec]) -> Vec<CommandSpec> {
684    let (m1, m2, m3) = (me.clone(), me.clone(), me.clone());
685    let mut out = vec![
686        CommandSpec::new("shell.search", "Search…", IconName::Search, move |window, cx| {
687            let _ = m1.update(cx, |s, cx| s.open_search(window, cx));
688        })
689        .group("App")
690        .hint("Find any command by name")
691        .key("secondary-k")
692        .read_only(),
693        CommandSpec::new("shell.settings", "Settings…", IconName::Settings, move |window, cx| {
694            let _ = m2.update(cx, |s, cx| {
695                let open = if s.settings.is_some() { None } else { Some(0) };
696                s.show_settings(open, window, cx)
697            });
698        })
699        .group("App")
700        .hint("Theme, accent, text size and the app's settings")
701        .key("secondary-,")
702        .read_only(),
703        CommandSpec::new("shell.theme", "Dark theme", IconName::Moon, move |_, cx| {
704            let _ = m3.update(cx, |s, cx| {
705                let l = theme::look();
706                s.set_look(l.with_dark(!l.dark), cx)
707            });
708        })
709        .group("View")
710        .hint("Switch between the dark and the light theme")
711        .checked(|_| theme::is_dark()),
712    ];
713    for (i, w) in workspaces.iter().enumerate() {
714        let (m, id) = (me.clone(), w.id.clone());
715        let mut c = CommandSpec::new(format!("shell.workspace.{}", w.id), format!("Go to {}", w.title), w.icon, move |_, cx| {
716            let _ = m.update(cx, |s, cx| s.set_workspace(&id, cx));
717        })
718        .group("Workspaces")
719        .hint(if w.hint.is_empty() { format!("Show the {} workspace", w.title).into() } else { w.hint.clone() })
720        .read_only();
721        if i < 9 {
722            c = c.key(format!("secondary-{}", i + 1));
723        }
724        out.push(c);
725    }
726    out
727}
728
729/// The edge a press at `p` (window px) resizes, within [`RESIZE_BAND`] of a `size` window's edge.
730pub fn resize_edge(p: gpui_kit::Point<gpui_kit::Pixels>, size: gpui_kit::Size<gpui_kit::Pixels>) -> Option<gpui_kit::ResizeEdge> {
731    use gpui_kit::ResizeEdge as E;
732    let band = RESIZE_BAND;
733    let (x, y, w, h) = (p.x.as_f32(), p.y.as_f32(), size.width.as_f32(), size.height.as_f32());
734    let (l, r, t, b) = (x < band, x > w - band, y < band, y > h - band);
735    Some(match (l, r, t, b) {
736        (true, _, true, _) => E::TopLeft,
737        (_, true, true, _) => E::TopRight,
738        (true, _, _, true) => E::BottomLeft,
739        (_, true, _, true) => E::BottomRight,
740        (true, ..) => E::Left,
741        (_, true, ..) => E::Right,
742        (_, _, true, _) => E::Top,
743        (_, _, _, true) => E::Bottom,
744        _ => return None,
745    })
746}
747
748/// Whether the window draws its own rounded frame: client-side decorations on a floating window
749/// (square when maximised, full screen or tiled).
750pub fn frame_rounded(window: &Window) -> bool {
751    match window.window_decorations() {
752        gpui_kit::Decorations::Client { tiling } => !(tiling.top || tiling.left || tiling.right || tiling.bottom) && !window.is_maximized() && !window.is_fullscreen(),
753        gpui_kit::Decorations::Server => false,
754    }
755}
756
757impl Render for Shell {
758    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
759        let registry = self.registry.clone();
760        let settings = self.settings.map(|s| self.settings_view(s, window, cx));
761        // Linux draws the frame itself (client-side decorations): no inset for a shadow margin
762        if matches!(window.window_decorations(), gpui_kit::Decorations::Client { .. }) {
763            window.set_client_inset(px(0.0));
764        }
765        let rounded = frame_rounded(window);
766        let shell = v_flex()
767            .id("shell")
768            .key_context("Shell")
769            .track_focus(&self.focus)
770            .size_full()
771            .relative()
772            // The chrome under everything: the panes are cards on it
773            .bg(color::chrome())
774            .text_color(color::text())
775            // Not a listener: a command may update the frame itself
776            .on_action(move |a: &RunCommand, window, cx| {
777                if let Err(e) = registry.run_as(crate::activity::Actor::Person, "key", &a.id, Value::Null, window, cx) {
778                    eprintln!("{}: {e}", a.id);
779                }
780            })
781            .on_key_down(cx.listener(|this, e: &KeyDownEvent, window, cx| {
782                if e.keystroke.key == "escape" && this.settings.is_some() {
783                    this.show_settings(None, window, cx);
784                    cx.stop_propagation();
785                }
786            }))
787            .child(self.title_bar(rounded, TitleFit::of(window.viewport_size().width.as_f32()), cx))
788            .child(self.menu_row())
789            .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())))
790            .child(self.status_bar(rounded, window, cx))
791            .children(self.overlay.clone())
792            .children(settings)
793            .children(self.search.as_ref().map(|(s, _)| s.clone()))
794            // No outline: the compositor's shadow sets a floating window apart
795            .when(rounded, |d| d.rounded(px(WINDOW_RADIUS)).overflow_hidden());
796        div()
797            .id("window-frame")
798            .size_full()
799            .when(rounded, |d| {
800                d.on_mouse_down(MouseButton::Left, |e, window, _| {
801                    if let Some(edge) = resize_edge(e.position, window.viewport_size()) {
802                        window.start_window_resize(edge);
803                    }
804                })
805            })
806            .child(shell)
807    }
808}