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