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