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 (Design System, "The frame"):
4//!
5//! - **Title bar**, left to right: the app's mark, the general menus (File · Edit · View · Help),
6//!   a divider, then the app's views in one switcher (Explore, Sorting, Curation, Analysis…).
7//!   At the right: search, the project, who works, where the app runs, the shared workspaces as
8//!   icons (Pipeline, Code: the same in every app, [`Placement::Shared`]), the layout toggles and
9//!   the theme. While a shared workspace is open the switcher shows no view as current.
10//! - **File** keeps its usual items: Open… (the file picker, [`crate::picker_view`], only when the
11//!   app says what it opens: [`OpenSpec`]), the app's own (Open recent, Save, Export…), Settings
12//!   and Quit.
13//! - **Menu row**: the current workspace's menus, built from the registry.
14//! - **Body**: the current workspace's view, a card on the chrome.
15//! - **Status bar**: a status line, the running jobs ([`crate::jobs`]) with a cancel button each,
16//!   and this computer's load (CPU, memory).
17//! - **Settings** (Ctrl+,): sections on the left (Appearance, built in, then the app's), the
18//!   section's settings on the right.
19//! - **Search** (Ctrl+K, F3) over the registry.
20//! - **Window frame**: where the app draws its own frame (client-side decorations on Linux), the
21//!   window has rounded corners while it floats and resizes from its own edge; no shadow margin
22//!   (compositors that do not draw it showed what was behind the window there).
23//! - **Overlay**: one view of the app's over everything ([`Shell::set_overlay`]: a help sheet, a
24//!   dialog).
25//!
26//! The frame adapts to the window's own width ([`TitleFit`]): under [`TITLE_COMPACT_W`] the
27//! views show as icons; under [`PANELS_W`] a workspace's side panes move into the Panels drawer
28//! ([`WorkspaceSpec::drawer`]; the app asks [`fit`] and leaves them out of its own layout); under
29//! [`TITLE_NARROW_W`] the four general menus fold into one menu button, and the layout toggles and
30//! the theme into a "More" menu.
31//!
32//! The frame adds its own commands to the registry (`shell.search`, `shell.settings`,
33//! `shell.theme`, `shell.open`, `shell.quit`, `shell.panels`, `shell.workspace.<id>`), so they are
34//! in the search and an agent's tools too. Keys: Ctrl/⌘+1…9 the views in order, Ctrl/⌘+Alt+P
35//! Pipeline, Ctrl/⌘+Alt+C Code, Ctrl/⌘+O Open…, Ctrl/⌘+\ the Panels drawer.
36
37use 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
60/// Height of the title bar (px).
61pub const TITLE_BAR_H: f32 = 36.;
62/// Height of the menu row (px).
63pub const MENU_ROW_H: f32 = 32.;
64/// Height of the status bar (px): one 24 px target.
65pub const STATUS_BAR_H: f32 = 24.;
66/// The band at the window's own edge that resizes it while it floats (px).
67pub const RESIZE_BAND: f32 = 6.;
68/// Rounded corners of the window while it floats (px).
69pub const WINDOW_RADIUS: f32 = 10.;
70/// Below this window width (px) the views show only their icons, the title bar drops the
71/// project name and shows the remote as an icon (a small laptop window, a tablet held upright).
72pub const TITLE_COMPACT_W: f32 = 1100.;
73/// Below this window width (px) a workspace's side panes move into the Panels drawer.
74pub const PANELS_W: f32 = 900.;
75/// Below this window width (px) the general menus fold into one menu button, and the layout
76/// toggles and the theme button into one "More" menu (a phone held upright).
77pub const TITLE_NARROW_W: f32 = 560.;
78
79/// How much of the frame fits a window `width` px wide (see [`TITLE_COMPACT_W`], [`PANELS_W`],
80/// [`TITLE_NARROW_W`]). Ordered: `Narrow < Medium < Compact < Full`.
81#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
82pub enum TitleFit {
83    /// Under [`TITLE_NARROW_W`]: one menu button, icons, a "More" menu; panes stack.
84    Narrow,
85    /// Under [`PANELS_W`]: side panes in the Panels drawer.
86    Medium,
87    /// Under [`TITLE_COMPACT_W`]: views as icons, no project name, the remote as an icon.
88    Compact,
89    /// Everything with its label.
90    Full,
91}
92
93impl TitleFit {
94    /// The fit for a window `width` px wide.
95    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    /// Whether labels show next to the icons (views, the remote).
108    pub fn labels(self) -> bool {
109        self == TitleFit::Full
110    }
111
112    /// Whether side panes go into the Panels drawer.
113    pub fn drawer(self) -> bool {
114        self <= TitleFit::Medium
115    }
116
117    /// Whether the general menus fold into one button.
118    pub fn folded(self) -> bool {
119        self == TitleFit::Narrow
120    }
121}
122
123/// The fit of `window` ([`TitleFit::of`] its width): a workspace's view asks it to leave its side
124/// panes out (they are in the drawer) and to stack its panes when narrow.
125pub fn fit(window: &Window) -> TitleFit {
126    TitleFit::of(window.viewport_size().width.as_f32())
127}
128
129/// Where a workspace sits in the title bar.
130#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
131pub enum Placement {
132    /// One of the app's views, in the switcher (Explore, Sorting, Curation, Analysis).
133    #[default]
134    View,
135    /// A workspace every app has, as an icon at the right (Pipeline, Code).
136    Shared,
137}
138
139/// The shared Pipeline workspace's id.
140pub const PIPELINE_ID: &str = "pipeline";
141/// The shared Code workspace's id.
142pub const CODE_ID: &str = "code";
143/// Pipeline's key: Ctrl/⌘+Alt+P.
144pub const PIPELINE_KEY: &str = "secondary-alt-p";
145/// Code's key: Ctrl/⌘+Alt+C.
146pub const CODE_KEY: &str = "secondary-alt-c";
147
148/// A workspace of the app (Explore, Pipeline, Analyze; Sorting…).
149pub struct WorkspaceSpec {
150    /// Its id (`explore`): the command `shell.workspace.<id>` switches to it.
151    pub id: SharedString,
152    /// Its name on the switcher.
153    pub title: SharedString,
154    /// Its icon on the switcher.
155    pub icon: IconName,
156    /// What it is for (the switcher's tooltip).
157    pub hint: SharedString,
158    /// Its menu row.
159    pub menus: Vec<MenuSpec>,
160    /// What it shows.
161    pub view: AnyView,
162    /// A count shown on its switcher button when above zero (changed lines, unread messages).
163    pub badge: Option<Rc<dyn Fn(&App) -> usize>>,
164    /// Where it sits: a view of the app's, or shared.
165    pub placement: Placement,
166    /// Its key (views get Ctrl/⌘+1…9 in order without one).
167    pub key: Option<SharedString>,
168    /// Its side panes, shown in the Panels drawer when the window is narrow ([`TitleFit::drawer`]).
169    pub drawer: Option<AnyView>,
170}
171
172impl WorkspaceSpec {
173    /// A workspace `id` titled `title`, showing `view`.
174    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    /// The shared Pipeline workspace: the app's pipeline screen in `view`. The app fills its
190    /// Operations and Plugins menus ([`WorkspaceSpec::menus`]).
191    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    /// The shared Code workspace (kitchen-code's `CodeWorkspace` in `view`).
196    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    /// Makes it shared: an icon at the right of the title bar, not a view in the switcher.
201    pub fn shared(mut self) -> Self {
202        self.placement = Placement::Shared;
203        self
204    }
205
206    /// Gives it a key (`secondary-alt-p`).
207    pub fn key(mut self, key: impl Into<SharedString>) -> Self {
208        self.key = Some(key.into());
209        self
210    }
211
212    /// Its side panes, for the Panels drawer of a narrow window. The workspace's view leaves them
213    /// out of its own layout when [`fit`] says [`TitleFit::drawer`].
214    pub fn drawer(mut self, view: impl Into<AnyView>) -> Self {
215        self.drawer = Some(view.into());
216        self
217    }
218
219    /// Sets what it is for.
220    pub fn hint(mut self, hint: impl Into<SharedString>) -> Self {
221        self.hint = hint.into();
222        self
223    }
224
225    /// Sets its menu row.
226    pub fn menus(mut self, menus: Vec<MenuSpec>) -> Self {
227        self.menus = menus;
228        self
229    }
230
231    /// Shows `count` on its switcher button when above zero.
232    pub fn badge(mut self, count: impl Fn(&App) -> usize + 'static) -> Self {
233        self.badge = Some(Rc::new(count));
234        self
235    }
236}
237
238/// Draws a Settings section's body.
239pub type SectionBody = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
240
241/// A section of Settings an app registers (Compute, Models, Plugins…).
242#[derive(Clone)]
243pub struct SettingsSection {
244    /// Its name in the list.
245    pub title: SharedString,
246    /// Its icon in the list.
247    pub icon: IconName,
248    /// Its settings.
249    pub body: SectionBody,
250}
251
252impl SettingsSection {
253    /// A section `title` drawing `body`.
254    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/// Where the app runs, at the right of the title bar (as VS Code's remote indicator): this
260/// computer, or a server. Its menu lists the places.
261#[derive(Clone, Debug, PartialEq)]
262pub struct RemoteSpec {
263    /// Where it runs now ("This computer").
264    pub label: SharedString,
265    /// Its icon.
266    pub icon: IconName,
267    /// The places to choose from (commands).
268    pub menu: Vec<MenuItem>,
269}
270
271/// What File → Open… opens: the kinds the app reads, where to start, and what to do with the
272/// file picked.
273#[derive(Clone)]
274pub struct OpenSpec {
275    /// What the app opens (an empty list: any file).
276    pub kinds: Vec<FileKind>,
277    /// The folder the picker starts in (home when `None` or unreadable).
278    pub start: Option<std::path::PathBuf>,
279    /// The app's recent files, newest first, listed under Places.
280    pub recent: Rc<dyn Fn(&App) -> Vec<std::path::PathBuf>>,
281    /// Opens what was picked.
282    pub open: Rc<dyn Fn(std::path::PathBuf, &mut Window, &mut App)>,
283}
284
285impl OpenSpec {
286    /// Opens `kinds` with `open`; no recent files, starting at home.
287    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    /// Lists the app's recent files under Places.
292    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    /// Starts the picker in `dir`.
298    pub fn start(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
299        self.start = Some(dir.into());
300        self
301    }
302}
303
304/// What an app hands the frame.
305pub struct ShellSpec {
306    /// The app's name: its mark at the left of the title bar, and the window's.
307    pub app_name: SharedString,
308    /// Its commands.
309    pub registry: Registry,
310    /// What File → Open… opens; no Open… item without it.
311    pub open: Option<OpenSpec>,
312    /// File's entries after Open… (Open recent, Save, Export…; Settings and Quit are added).
313    pub file_menu: Vec<MenuItem>,
314    /// Older name of [`ShellSpec::file_menu`]: its entries follow `file_menu`'s.
315    pub app_menu: Vec<MenuItem>,
316    /// Edit's entries (Undo, Redo, Copy…); no Edit menu when empty.
317    pub edit_menu: Vec<MenuItem>,
318    /// View's entries (the layout toggles and the theme are added).
319    pub view_menu: Vec<MenuItem>,
320    /// The Help menu's entries (the search is added).
321    pub help_menu: Vec<MenuItem>,
322    /// Its workspaces, in the switcher's order.
323    pub workspaces: Vec<WorkspaceSpec>,
324    /// Its Settings sections (after the built-in Appearance).
325    pub settings: Vec<SettingsSection>,
326    /// Commands shown as icon buttons at the right of the title bar (side panels…).
327    pub layout_toggles: Vec<SharedString>,
328    /// Where the app runs.
329    pub remote: Option<RemoteSpec>,
330    /// Whether the app records who works ([`crate::people`]): the title bar's person button and a
331    /// People section at the end of Settings. The app [`crate::people::load`]s the people first.
332    pub people: bool,
333    /// Whether the status bar shows this computer's load (off in tests).
334    pub meters: bool,
335    /// The app's own readings in the status bar, before the jobs (the frame's numbers, a device).
336    pub status_items: Option<StatusItems>,
337}
338
339/// Draws the app's readings in the status bar.
340pub type StatusItems = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
341
342impl ShellSpec {
343    /// An app named `app_name` with `registry` and `workspaces`, the rest empty.
344    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/// What the frame tells the app.
366#[derive(Clone, Debug, PartialEq)]
367pub enum ShellEvent {
368    /// The user changed the look in the title bar or Settings: store it in the preferences.
369    LookChanged(Look),
370    /// The user switched workspace.
371    WorkspaceChanged(SharedString),
372}
373
374/// The frame.
375pub 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    /// Whether the Panels drawer is open (narrow windows).
385    drawer_open: bool,
386    workspaces: Vec<WorkspaceSpec>,
387    sections: Vec<SettingsSection>,
388    layout_toggles: Vec<SharedString>,
389    remote: Option<RemoteSpec>,
390    /// The People section, when the app records who works.
391    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    /// The Settings section shown, when Settings is open.
397    settings: Option<usize>,
398    accent: Entity<AccentPicker>,
399    status: SharedString,
400    project: Option<SharedString>,
401    /// This computer's load: CPU %, memory used and installed (bytes).
402    meters: Option<(f32, u64, u64)>,
403    focus: FocusHandle,
404    _subs: Vec<Subscription>,
405}
406
407impl EventEmitter<ShellEvent> for Shell {}
408
409impl Shell {
410    /// The frame for `spec`; adds the frame's commands to the registry and focuses the frame.
411    /// Bind the keys after ([`Registry::bind_keys`]), once every command is registered.
412    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        // File: Open…, the app's items, Settings, Quit
421        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        // View: the app's items, then the layout toggles, the Panels drawer and the theme
435        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    /// Redraws when a job starts, moves or ends.
497    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    /// CPU and memory meters (as VS Code's resource monitor), read off the UI thread every 2 s.
515    fn watch_meters(&self, cx: &mut Context<Self>) {
516        cx.spawn(async move |this, cx| {
517            // No meters where the system cannot be read
518            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    /// The registry (the app's commands and the frame's).
544    pub fn registry(&self) -> &Registry {
545        &self.registry
546    }
547
548    /// The workspace shown.
549    pub fn workspace(&self) -> &WorkspaceSpec {
550        &self.workspaces[self.current]
551    }
552
553    /// Shows the workspace `id`; whether there is one.
554    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    /// The id of the workspace shown.
567    pub fn workspace_id(&self) -> SharedString {
568        self.workspaces[self.current].id.clone()
569    }
570
571    /// The view of the app's shown, if the workspace shown is one (`None` while a shared one, Pipeline
572    /// or Code, is open).
573    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    /// Opens the file picker (File → Open…); nothing when the app opens no files.
579    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    /// The file picker, while it is open.
597    pub fn picker(&self) -> Option<Entity<FilePickerView>> {
598        self.picker.as_ref().map(|(p, _)| p.clone())
599    }
600
601    /// Opens or closes the Panels drawer.
602    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    /// Whether the Panels drawer is open.
608    pub fn drawer_open(&self) -> bool {
609        self.drawer_open
610    }
611
612    /// Replaces the menu row of the workspace `id`; whether there is one.
613    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    /// Shows `view` over everything (a help sheet, a dialog), or takes it away (`None`).
621    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    /// Whether an overlay is shown.
630    pub fn has_overlay(&self) -> bool {
631        self.overlay.is_some()
632    }
633
634    /// Whether the Settings section `title` exists (0 is Appearance, then the app's, then People
635    /// when the app records who works).
636    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    /// Sets the status line.
647    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    /// The status line.
653    pub fn status(&self) -> &SharedString {
654        &self.status
655    }
656
657    /// Sets the project named in the title bar (`None`: none open).
658    pub fn set_project(&mut self, project: Option<SharedString>, cx: &mut Context<Self>) {
659        self.project = project;
660        cx.notify();
661    }
662
663    /// The search, when open.
664    pub fn search(&self) -> Option<Entity<Search>> {
665        self.search.as_ref().map(|(s, _)| s.clone())
666    }
667
668    /// Opens the search over every command.
669    pub fn open_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
670        self.open_search_with(None, window, cx);
671    }
672
673    /// Opens the search over the commands `filter` accepts, titled `title` (Process ▸ "Find an
674    /// operation…": one kind of command); every command when `None`. Open already: closes it.
675    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                // Run once this update is over: the command may change the frame itself
694                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    /// The Settings section shown, when Settings is open (0 is Appearance).
709    pub fn settings_section(&self) -> Option<usize> {
710        self.settings
711    }
712
713    /// Opens Settings at `section` (0: Appearance, then the app's in order), or closes it.
714    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    /// Sets the look and tells the app.
723    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        // The general menus; narrow: one button holding them as submenus
731        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        // The app's views, one detented switcher; full width: with their names
765        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        // The shared workspaces: icons in the right corner
768        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        // Narrow and medium: the Panels drawer's button, when the workspace has side panes
781        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            // Compact: the icon only, where it runs in the tooltip
789            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        // Narrow: the layout toggles and the theme in one menu, as commands (checked when on)
793        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        // Who works: their name (compact: the icon, the name in the tooltip); a guest says so
804        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        // Compact and narrower: the project's name is left to the app's status bar
817        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        // GPUI clips to rectangles: the bars round their own corners inside a rounded frame
819        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            // Narrow: the menus scroll sideways rather than wrap
857            .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
979/// The People section's title.
980const PEOPLE: &str = "People";
981
982/// Who works: pick a person (or a guest), open People.
983fn people_commands(me: &WeakEntity<Shell>) -> Vec<CommandSpec> {
984    #[derive(serde::Deserialize, schemars::JsonSchema)]
985    struct UseArgs {
986        /// The person's name; none: a guest.
987        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
1010/// The frame's own commands.
1011fn 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    // Open… (and its key) only for an app that opens files: an app's own command keeps Ctrl+O otherwise
1043    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    // Views: Ctrl/⌘+1…9 in order; shared workspaces: their own keys
1071    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
1091/// The edge a press at `p` (window px) resizes, within [`RESIZE_BAND`] of a `size` window's edge.
1092pub 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
1110/// Whether the window draws its own rounded frame: client-side decorations on a floating window
1111/// (square when maximised, full screen or tiled).
1112pub 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        // Linux draws the frame itself (client-side decorations): no inset for a shadow margin
1124        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        // A wider window shows the side panes itself: the drawer closes
1130        if !fit.drawer() {
1131            self.drawer_open = false;
1132        }
1133        // The Panels drawer: the workspace's side panes over the body's left, a scrim beside them
1134        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            // The chrome under everything: the panes are cards on it
1167            .bg(color::chrome())
1168            .text_color(color::text())
1169            // Not a listener: a command may update the frame itself
1170            .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            // Over everything, and nothing under it takes a click meant for it
1198            .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            // No outline: the compositor's shadow sets a floating window apart
1203            .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}