title_bar.rs

  1mod application_menu;
  2mod collab;
  3mod platforms;
  4mod window_controls;
  5
  6#[cfg(feature = "stories")]
  7mod stories;
  8
  9use crate::application_menu::ApplicationMenu;
 10use crate::platforms::{platform_linux, platform_mac, platform_windows};
 11use auto_update::AutoUpdateStatus;
 12use call::ActiveCall;
 13use client::{Client, UserStore};
 14use feature_flags::{FeatureFlagAppExt, ZedPro};
 15use gpui::{
 16    actions, div, px, Action, AnyElement, AppContext, Decorations, Element, InteractiveElement,
 17    Interactivity, IntoElement, Model, MouseButton, ParentElement, Render, Stateful,
 18    StatefulInteractiveElement, Styled, Subscription, View, ViewContext, VisualContext, WeakView,
 19};
 20use project::{Project, RepositoryEntry};
 21use recent_projects::{OpenRemote, RecentProjects, SshSettings};
 22use remote::SshConnectionOptions;
 23use rpc::proto::{self, DevServerStatus};
 24use settings::Settings;
 25use smallvec::SmallVec;
 26use std::sync::Arc;
 27use theme::ActiveTheme;
 28use ui::{
 29    h_flex, prelude::*, Avatar, Button, ButtonLike, ButtonStyle, ContextMenu, Icon, IconName,
 30    IconSize, IconWithIndicator, Indicator, PopoverMenu, Tooltip,
 31};
 32use util::{maybe, ResultExt};
 33use vcs_menu::{BranchList, OpenRecent as ToggleVcsMenu};
 34use workspace::{notifications::NotifyResultExt, Workspace};
 35
 36#[cfg(feature = "stories")]
 37pub use stories::*;
 38
 39const MAX_PROJECT_NAME_LENGTH: usize = 40;
 40const MAX_BRANCH_NAME_LENGTH: usize = 40;
 41
 42actions!(
 43    collab,
 44    [
 45        ShareProject,
 46        UnshareProject,
 47        ToggleUserMenu,
 48        ToggleProjectMenu,
 49        SwitchBranch
 50    ]
 51);
 52
 53pub fn init(cx: &mut AppContext) {
 54    cx.observe_new_views(|workspace: &mut Workspace, cx| {
 55        let item = cx.new_view(|cx| TitleBar::new("title-bar", workspace, cx));
 56        workspace.set_titlebar_item(item.into(), cx)
 57    })
 58    .detach();
 59}
 60
 61pub struct TitleBar {
 62    platform_style: PlatformStyle,
 63    content: Stateful<Div>,
 64    children: SmallVec<[AnyElement; 2]>,
 65    project: Model<Project>,
 66    user_store: Model<UserStore>,
 67    client: Arc<Client>,
 68    workspace: WeakView<Workspace>,
 69    should_move: bool,
 70    application_menu: Option<View<ApplicationMenu>>,
 71    _subscriptions: Vec<Subscription>,
 72}
 73
 74impl Render for TitleBar {
 75    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 76        let close_action = Box::new(workspace::CloseWindow);
 77        let height = Self::height(cx);
 78        let supported_controls = cx.window_controls();
 79        let decorations = cx.window_decorations();
 80        let titlebar_color = if cfg!(target_os = "linux") {
 81            if cx.is_window_active() && !self.should_move {
 82                cx.theme().colors().title_bar_background
 83            } else {
 84                cx.theme().colors().title_bar_inactive_background
 85            }
 86        } else {
 87            cx.theme().colors().title_bar_background
 88        };
 89
 90        h_flex()
 91            .id("titlebar")
 92            .w_full()
 93            .h(height)
 94            .map(|this| {
 95                if cx.is_fullscreen() {
 96                    this.pl_2()
 97                } else if self.platform_style == PlatformStyle::Mac {
 98                    this.pl(px(platform_mac::TRAFFIC_LIGHT_PADDING))
 99                } else {
100                    this.pl_2()
101                }
102            })
103            .map(|el| match decorations {
104                Decorations::Server => el,
105                Decorations::Client { tiling, .. } => el
106                    .when(!(tiling.top || tiling.right), |el| {
107                        el.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
108                    })
109                    .when(!(tiling.top || tiling.left), |el| {
110                        el.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
111                    })
112                    // this border is to avoid a transparent gap in the rounded corners
113                    .mt(px(-1.))
114                    .border(px(1.))
115                    .border_color(titlebar_color),
116            })
117            .bg(titlebar_color)
118            .content_stretch()
119            .child(
120                div()
121                    .id("titlebar-content")
122                    .flex()
123                    .flex_row()
124                    .justify_between()
125                    .w_full()
126                    // Note: On Windows the title bar behavior is handled by the platform implementation.
127                    .when(self.platform_style != PlatformStyle::Windows, |this| {
128                        this.on_click(|event, cx| {
129                            if event.up.click_count == 2 {
130                                cx.zoom_window();
131                            }
132                        })
133                    })
134                    .child(
135                        h_flex()
136                            .gap_1()
137                            .when_some(self.application_menu.clone(), |this, menu| this.child(menu))
138                            .children(self.render_project_host(cx))
139                            .child(self.render_project_name(cx))
140                            .children(self.render_project_branch(cx))
141                            .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation()),
142                    )
143                    .child(self.render_collaborator_list(cx))
144                    .child(
145                        h_flex()
146                            .gap_1()
147                            .pr_1()
148                            .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
149                            .children(self.render_call_controls(cx))
150                            .map(|el| {
151                                let status = self.client.status();
152                                let status = &*status.borrow();
153                                if matches!(status, client::Status::Connected { .. }) {
154                                    el.child(self.render_user_menu_button(cx))
155                                } else {
156                                    el.children(self.render_connection_status(status, cx))
157                                        .child(self.render_sign_in_button(cx))
158                                        .child(self.render_user_menu_button(cx))
159                                }
160                            }),
161                    ),
162            )
163            .when(!cx.is_fullscreen(), |title_bar| match self.platform_style {
164                PlatformStyle::Mac => title_bar,
165                PlatformStyle::Linux => {
166                    if matches!(decorations, Decorations::Client { .. }) {
167                        title_bar
168                            .child(platform_linux::LinuxWindowControls::new(close_action))
169                            .when(supported_controls.window_menu, |titlebar| {
170                                titlebar.on_mouse_down(gpui::MouseButton::Right, move |ev, cx| {
171                                    cx.show_window_menu(ev.position)
172                                })
173                            })
174                            .on_mouse_move(cx.listener(move |this, _ev, cx| {
175                                if this.should_move {
176                                    this.should_move = false;
177                                    cx.start_window_move();
178                                }
179                            }))
180                            .on_mouse_down_out(cx.listener(move |this, _ev, _cx| {
181                                this.should_move = false;
182                            }))
183                            .on_mouse_up(
184                                gpui::MouseButton::Left,
185                                cx.listener(move |this, _ev, _cx| {
186                                    this.should_move = false;
187                                }),
188                            )
189                            .on_mouse_down(
190                                gpui::MouseButton::Left,
191                                cx.listener(move |this, _ev, _cx| {
192                                    this.should_move = true;
193                                }),
194                            )
195                    } else {
196                        title_bar
197                    }
198                }
199                PlatformStyle::Windows => {
200                    title_bar.child(platform_windows::WindowsWindowControls::new(height))
201                }
202            })
203    }
204}
205
206impl TitleBar {
207    pub fn new(
208        id: impl Into<ElementId>,
209        workspace: &Workspace,
210        cx: &mut ViewContext<Self>,
211    ) -> Self {
212        let project = workspace.project().clone();
213        let user_store = workspace.app_state().user_store.clone();
214        let client = workspace.app_state().client.clone();
215        let active_call = ActiveCall::global(cx);
216
217        let platform_style = PlatformStyle::platform();
218        let application_menu = match platform_style {
219            PlatformStyle::Mac => None,
220            PlatformStyle::Linux | PlatformStyle::Windows => {
221                Some(cx.new_view(ApplicationMenu::new))
222            }
223        };
224
225        let mut subscriptions = Vec::new();
226        subscriptions.push(
227            cx.observe(&workspace.weak_handle().upgrade().unwrap(), |_, _, cx| {
228                cx.notify()
229            }),
230        );
231        subscriptions.push(cx.observe(&project, |_, _, cx| cx.notify()));
232        subscriptions.push(cx.observe(&active_call, |this, _, cx| this.active_call_changed(cx)));
233        subscriptions.push(cx.observe_window_activation(Self::window_activation_changed));
234        subscriptions.push(cx.observe(&user_store, |_, _, cx| cx.notify()));
235
236        Self {
237            platform_style,
238            content: div().id(id.into()),
239            children: SmallVec::new(),
240            application_menu,
241            workspace: workspace.weak_handle(),
242            should_move: false,
243            project,
244            user_store,
245            client,
246            _subscriptions: subscriptions,
247        }
248    }
249
250    #[cfg(not(target_os = "windows"))]
251    pub fn height(cx: &mut WindowContext) -> Pixels {
252        (1.75 * cx.rem_size()).max(px(34.))
253    }
254
255    #[cfg(target_os = "windows")]
256    pub fn height(_cx: &mut WindowContext) -> Pixels {
257        // todo(windows) instead of hard coded size report the actual size to the Windows platform API
258        px(32.)
259    }
260
261    /// Sets the platform style.
262    pub fn platform_style(mut self, style: PlatformStyle) -> Self {
263        self.platform_style = style;
264        self
265    }
266
267    fn render_ssh_project_host(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
268        let options = self.project.read(cx).ssh_connection_options(cx)?;
269        let host: SharedString = options.connection_string().into();
270
271        let nickname = maybe!({
272            SshSettings::get_global(cx)
273                .ssh_connections
274                .as_ref()?
275                .into_iter()
276                .find(|connection| SshConnectionOptions::from((*connection).clone()) == options)
277                .and_then(|connection| connection.nickname.clone())
278        })
279        .unwrap_or_else(|| host.clone());
280
281        let (indicator_color, meta) = match self.project.read(cx).ssh_connection_state(cx)? {
282            remote::ConnectionState::Connecting => (Color::Info, format!("Connecting to: {host}")),
283            remote::ConnectionState::Connected => (Color::Success, format!("Connected to: {host}")),
284            remote::ConnectionState::HeartbeatMissed => (
285                Color::Warning,
286                format!("Connection attempt to {host} missed. Retrying..."),
287            ),
288            remote::ConnectionState::Reconnecting => (
289                Color::Warning,
290                format!("Lost connection to {host}. Reconnecting..."),
291            ),
292            remote::ConnectionState::Disconnected => {
293                (Color::Error, format!("Disconnected from {host}"))
294            }
295        };
296
297        let icon_color = match self.project.read(cx).ssh_connection_state(cx)? {
298            remote::ConnectionState::Connecting => Color::Info,
299            remote::ConnectionState::Connected => Color::Default,
300            remote::ConnectionState::HeartbeatMissed => Color::Warning,
301            remote::ConnectionState::Reconnecting => Color::Warning,
302            remote::ConnectionState::Disconnected => Color::Error,
303        };
304
305        let meta = SharedString::from(meta);
306
307        Some(
308            ButtonLike::new("ssh-server-icon")
309                .child(
310                    IconWithIndicator::new(
311                        Icon::new(IconName::Server)
312                            .size(IconSize::XSmall)
313                            .color(icon_color),
314                        Some(Indicator::dot().color(indicator_color)),
315                    )
316                    .indicator_border_color(Some(cx.theme().colors().title_bar_background))
317                    .into_any_element(),
318                )
319                .child(
320                    div()
321                        .max_w_32()
322                        .overflow_hidden()
323                        .text_ellipsis()
324                        .child(Label::new(nickname.clone()).size(LabelSize::Small)),
325                )
326                .tooltip(move |cx| {
327                    Tooltip::with_meta("Remote Project", Some(&OpenRemote), meta.clone(), cx)
328                })
329                .on_click(|_, cx| {
330                    cx.dispatch_action(OpenRemote.boxed_clone());
331                })
332                .into_any_element(),
333        )
334    }
335
336    pub fn render_project_host(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
337        if let Some(dev_server) =
338            self.project
339                .read(cx)
340                .dev_server_project_id()
341                .and_then(|dev_server_project_id| {
342                    dev_server_projects::Store::global(cx)
343                        .read(cx)
344                        .dev_server_for_project(dev_server_project_id)
345                })
346        {
347            return Some(
348                ButtonLike::new("dev_server_trigger")
349                    .child(Indicator::dot().color(
350                        if dev_server.status == DevServerStatus::Online {
351                            Color::Created
352                        } else {
353                            Color::Disabled
354                        },
355                    ))
356                    .child(
357                        Label::new(dev_server.name.clone())
358                            .size(LabelSize::Small)
359                            .line_height_style(LineHeightStyle::UiLabel),
360                    )
361                    .tooltip(move |cx| Tooltip::text("Project is hosted on a dev server", cx))
362                    .on_click(cx.listener(|this, _, cx| {
363                        if let Some(workspace) = this.workspace.upgrade() {
364                            recent_projects::RemoteServerProjects::open(workspace, cx)
365                        }
366                    }))
367                    .into_any_element(),
368            );
369        }
370        if self.project.read(cx).is_via_ssh() {
371            return self.render_ssh_project_host(cx);
372        }
373
374        if self.project.read(cx).is_disconnected(cx) {
375            return Some(
376                Button::new("disconnected", "Disconnected")
377                    .disabled(true)
378                    .color(Color::Disabled)
379                    .style(ButtonStyle::Subtle)
380                    .label_size(LabelSize::Small)
381                    .into_any_element(),
382            );
383        }
384
385        let host = self.project.read(cx).host()?;
386        let host_user = self.user_store.read(cx).get_cached_user(host.user_id)?;
387        let participant_index = self
388            .user_store
389            .read(cx)
390            .participant_indices()
391            .get(&host_user.id)?;
392        Some(
393            Button::new("project_owner_trigger", host_user.github_login.clone())
394                .color(Color::Player(participant_index.0))
395                .style(ButtonStyle::Subtle)
396                .label_size(LabelSize::Small)
397                .tooltip(move |cx| {
398                    Tooltip::text(
399                        format!(
400                            "{} is sharing this project. Click to follow.",
401                            host_user.github_login.clone()
402                        ),
403                        cx,
404                    )
405                })
406                .on_click({
407                    let host_peer_id = host.peer_id;
408                    cx.listener(move |this, _, cx| {
409                        this.workspace
410                            .update(cx, |workspace, cx| {
411                                workspace.follow(host_peer_id, cx);
412                            })
413                            .log_err();
414                    })
415                })
416                .into_any_element(),
417        )
418    }
419
420    pub fn render_project_name(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
421        let name = {
422            let mut names = self.project.read(cx).visible_worktrees(cx).map(|worktree| {
423                let worktree = worktree.read(cx);
424                worktree.root_name()
425            });
426
427            names.next()
428        };
429        let is_project_selected = name.is_some();
430        let name = if let Some(name) = name {
431            util::truncate_and_trailoff(name, MAX_PROJECT_NAME_LENGTH)
432        } else {
433            "Open recent project".to_string()
434        };
435
436        let workspace = self.workspace.clone();
437        Button::new("project_name_trigger", name)
438            .when(!is_project_selected, |b| b.color(Color::Muted))
439            .style(ButtonStyle::Subtle)
440            .label_size(LabelSize::Small)
441            .tooltip(move |cx| {
442                Tooltip::for_action(
443                    "Recent Projects",
444                    &recent_projects::OpenRecent {
445                        create_new_window: false,
446                    },
447                    cx,
448                )
449            })
450            .on_click(cx.listener(move |_, _, cx| {
451                if let Some(workspace) = workspace.upgrade() {
452                    workspace.update(cx, |workspace, cx| {
453                        RecentProjects::open(workspace, false, cx);
454                    })
455                }
456            }))
457    }
458
459    pub fn render_project_branch(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
460        let entry = {
461            let mut names_and_branches =
462                self.project.read(cx).visible_worktrees(cx).map(|worktree| {
463                    let worktree = worktree.read(cx);
464                    worktree.root_git_entry()
465                });
466
467            names_and_branches.next().flatten()
468        };
469        let workspace = self.workspace.upgrade()?;
470        let branch_name = entry
471            .as_ref()
472            .and_then(RepositoryEntry::branch)
473            .map(|branch| util::truncate_and_trailoff(&branch, MAX_BRANCH_NAME_LENGTH))?;
474        Some(
475            Button::new("project_branch_trigger", branch_name)
476                .color(Color::Muted)
477                .style(ButtonStyle::Subtle)
478                .label_size(LabelSize::Small)
479                .tooltip(move |cx| {
480                    Tooltip::with_meta(
481                        "Recent Branches",
482                        Some(&ToggleVcsMenu),
483                        "Local branches only",
484                        cx,
485                    )
486                })
487                .on_click(move |_, cx| {
488                    let _ = workspace.update(cx, |this, cx| {
489                        BranchList::open(this, &Default::default(), cx)
490                    });
491                }),
492        )
493    }
494
495    fn window_activation_changed(&mut self, cx: &mut ViewContext<Self>) {
496        if cx.is_window_active() {
497            ActiveCall::global(cx)
498                .update(cx, |call, cx| call.set_location(Some(&self.project), cx))
499                .detach_and_log_err(cx);
500        } else if cx.active_window().is_none() {
501            ActiveCall::global(cx)
502                .update(cx, |call, cx| call.set_location(None, cx))
503                .detach_and_log_err(cx);
504        }
505        self.workspace
506            .update(cx, |workspace, cx| {
507                workspace.update_active_view_for_followers(cx);
508            })
509            .ok();
510    }
511
512    fn active_call_changed(&mut self, cx: &mut ViewContext<Self>) {
513        cx.notify();
514    }
515
516    fn share_project(&mut self, _: &ShareProject, cx: &mut ViewContext<Self>) {
517        let active_call = ActiveCall::global(cx);
518        let project = self.project.clone();
519        active_call
520            .update(cx, |call, cx| call.share_project(project, cx))
521            .detach_and_log_err(cx);
522    }
523
524    fn unshare_project(&mut self, _: &UnshareProject, cx: &mut ViewContext<Self>) {
525        let active_call = ActiveCall::global(cx);
526        let project = self.project.clone();
527        active_call
528            .update(cx, |call, cx| call.unshare_project(project, cx))
529            .log_err();
530    }
531
532    fn render_connection_status(
533        &self,
534        status: &client::Status,
535        cx: &mut ViewContext<Self>,
536    ) -> Option<AnyElement> {
537        match status {
538            client::Status::ConnectionError
539            | client::Status::ConnectionLost
540            | client::Status::Reauthenticating { .. }
541            | client::Status::Reconnecting { .. }
542            | client::Status::ReconnectionError { .. } => Some(
543                div()
544                    .id("disconnected")
545                    .child(Icon::new(IconName::Disconnected).size(IconSize::Small))
546                    .tooltip(|cx| Tooltip::text("Disconnected", cx))
547                    .into_any_element(),
548            ),
549            client::Status::UpgradeRequired => {
550                let auto_updater = auto_update::AutoUpdater::get(cx);
551                let label = match auto_updater.map(|auto_update| auto_update.read(cx).status()) {
552                    Some(AutoUpdateStatus::Updated { .. }) => "Please restart Zed to Collaborate",
553                    Some(AutoUpdateStatus::Installing)
554                    | Some(AutoUpdateStatus::Downloading)
555                    | Some(AutoUpdateStatus::Checking) => "Updating...",
556                    Some(AutoUpdateStatus::Idle) | Some(AutoUpdateStatus::Errored) | None => {
557                        "Please update Zed to Collaborate"
558                    }
559                };
560
561                Some(
562                    Button::new("connection-status", label)
563                        .label_size(LabelSize::Small)
564                        .on_click(|_, cx| {
565                            if let Some(auto_updater) = auto_update::AutoUpdater::get(cx) {
566                                if auto_updater.read(cx).status().is_updated() {
567                                    workspace::reload(&Default::default(), cx);
568                                    return;
569                                }
570                            }
571                            auto_update::check(&Default::default(), cx);
572                        })
573                        .into_any_element(),
574                )
575            }
576            _ => None,
577        }
578    }
579
580    pub fn render_sign_in_button(&mut self, _: &mut ViewContext<Self>) -> Button {
581        let client = self.client.clone();
582        Button::new("sign_in", "Sign in")
583            .label_size(LabelSize::Small)
584            .on_click(move |_, cx| {
585                let client = client.clone();
586                cx.spawn(move |mut cx| async move {
587                    client
588                        .authenticate_and_connect(true, &cx)
589                        .await
590                        .notify_async_err(&mut cx);
591                })
592                .detach();
593            })
594    }
595
596    pub fn render_user_menu_button(&mut self, cx: &mut ViewContext<Self>) -> impl Element {
597        let user_store = self.user_store.read(cx);
598        if let Some(user) = user_store.current_user() {
599            let plan = user_store.current_plan();
600            PopoverMenu::new("user-menu")
601                .menu(move |cx| {
602                    ContextMenu::build(cx, |menu, cx| {
603                        menu.when(cx.has_flag::<ZedPro>(), |menu| {
604                            menu.action(
605                                format!(
606                                    "Current Plan: {}",
607                                    match plan {
608                                        None => "",
609                                        Some(proto::Plan::Free) => "Free",
610                                        Some(proto::Plan::ZedPro) => "Pro",
611                                    }
612                                ),
613                                zed_actions::OpenAccountSettings.boxed_clone(),
614                            )
615                            .separator()
616                        })
617                        .action("Settings", zed_actions::OpenSettings.boxed_clone())
618                        .action("Key Bindings", Box::new(zed_actions::OpenKeymap))
619                        .action("Themes…", theme_selector::Toggle::default().boxed_clone())
620                        .action("Extensions", extensions_ui::Extensions.boxed_clone())
621                        .separator()
622                        .action("Sign Out", client::SignOut.boxed_clone())
623                    })
624                    .into()
625                })
626                .trigger(
627                    ButtonLike::new("user-menu")
628                        .child(
629                            h_flex()
630                                .gap_0p5()
631                                .child(Avatar::new(user.avatar_uri.clone()))
632                                .child(
633                                    Icon::new(IconName::ChevronDown)
634                                        .size(IconSize::Small)
635                                        .color(Color::Muted),
636                                ),
637                        )
638                        .style(ButtonStyle::Subtle)
639                        .tooltip(move |cx| Tooltip::text("Toggle User Menu", cx)),
640                )
641                .anchor(gpui::AnchorCorner::TopRight)
642        } else {
643            PopoverMenu::new("user-menu")
644                .menu(|cx| {
645                    ContextMenu::build(cx, |menu, _| {
646                        menu.action("Settings", zed_actions::OpenSettings.boxed_clone())
647                            .action("Key Bindings", Box::new(zed_actions::OpenKeymap))
648                            .action("Themes…", theme_selector::Toggle::default().boxed_clone())
649                            .action("Extensions", extensions_ui::Extensions.boxed_clone())
650                    })
651                    .into()
652                })
653                .trigger(
654                    ButtonLike::new("user-menu")
655                        .child(
656                            h_flex().gap_0p5().child(
657                                Icon::new(IconName::ChevronDown)
658                                    .size(IconSize::Small)
659                                    .color(Color::Muted),
660                            ),
661                        )
662                        .style(ButtonStyle::Subtle)
663                        .tooltip(move |cx| Tooltip::text("Toggle User Menu", cx)),
664                )
665        }
666    }
667}
668
669impl InteractiveElement for TitleBar {
670    fn interactivity(&mut self) -> &mut Interactivity {
671        self.content.interactivity()
672    }
673}
674
675impl StatefulInteractiveElement for TitleBar {}
676
677impl ParentElement for TitleBar {
678    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
679        self.children.extend(elements)
680    }
681}