collab_titlebar_item.rs

  1use crate::face_pile::FacePile;
  2use auto_update::AutoUpdateStatus;
  3use call::{ActiveCall, ParticipantLocation, Room};
  4use client::{proto::PeerId, Client, User, UserStore};
  5use gpui::{
  6    actions, canvas, div, point, px, Action, AnyElement, AppContext, Element, Hsla,
  7    InteractiveElement, IntoElement, Model, ParentElement, Path, Render,
  8    StatefulInteractiveElement, Styled, Subscription, View, ViewContext, VisualContext, WeakView,
  9    WindowBounds,
 10};
 11use project::{Project, RepositoryEntry};
 12use recent_projects::RecentProjects;
 13use rpc::proto;
 14use std::sync::Arc;
 15use theme::ActiveTheme;
 16use ui::{
 17    h_flex, popover_menu, prelude::*, Avatar, AvatarAudioStatusIndicator, Button, ButtonLike,
 18    ButtonStyle, ContextMenu, Icon, IconButton, IconName, TintColor, Tooltip,
 19};
 20use util::ResultExt;
 21use vcs_menu::{build_branch_list, BranchList, OpenRecent as ToggleVcsMenu};
 22use workspace::{notifications::NotifyResultExt, titlebar_height, Workspace};
 23
 24const MAX_PROJECT_NAME_LENGTH: usize = 40;
 25const MAX_BRANCH_NAME_LENGTH: usize = 40;
 26
 27actions!(
 28    collab,
 29    [
 30        ShareProject,
 31        UnshareProject,
 32        ToggleUserMenu,
 33        ToggleProjectMenu,
 34        SwitchBranch
 35    ]
 36);
 37
 38pub fn init(cx: &mut AppContext) {
 39    cx.observe_new_views(|workspace: &mut Workspace, cx| {
 40        let titlebar_item = cx.new_view(|cx| CollabTitlebarItem::new(workspace, cx));
 41        workspace.set_titlebar_item(titlebar_item.into(), cx)
 42    })
 43    .detach();
 44}
 45
 46pub struct CollabTitlebarItem {
 47    project: Model<Project>,
 48    user_store: Model<UserStore>,
 49    client: Arc<Client>,
 50    workspace: WeakView<Workspace>,
 51    _subscriptions: Vec<Subscription>,
 52}
 53
 54impl Render for CollabTitlebarItem {
 55    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 56        let room = ActiveCall::global(cx).read(cx).room().cloned();
 57        let current_user = self.user_store.read(cx).current_user();
 58        let client = self.client.clone();
 59        let project_id = self.project.read(cx).remote_id();
 60
 61        h_flex()
 62            .id("titlebar")
 63            .justify_between()
 64            .w_full()
 65            .h(titlebar_height(cx))
 66            .map(|this| {
 67                if matches!(cx.window_bounds(), WindowBounds::Fullscreen) {
 68                    this.pl_2()
 69                } else {
 70                    // Use pixels here instead of a rem-based size because the macOS traffic
 71                    // lights are a static size, and don't scale with the rest of the UI.
 72                    this.pl(px(80.))
 73                }
 74            })
 75            .bg(cx.theme().colors().title_bar_background)
 76            .on_click(|event, cx| {
 77                if event.up.click_count == 2 {
 78                    cx.zoom_window();
 79                }
 80            })
 81            // left side
 82            .child(
 83                h_flex()
 84                    .gap_1()
 85                    .children(self.render_project_host(cx))
 86                    .child(self.render_project_name(cx))
 87                    .child(div().pr_1().children(self.render_project_branch(cx)))
 88                    .when_some(
 89                        current_user.clone().zip(client.peer_id()).zip(room.clone()),
 90                        |this, ((current_user, peer_id), room)| {
 91                            let player_colors = cx.theme().players();
 92                            let room = room.read(cx);
 93                            let mut remote_participants =
 94                                room.remote_participants().values().collect::<Vec<_>>();
 95                            remote_participants.sort_by_key(|p| p.participant_index.0);
 96
 97                            let current_user_face_pile = self.render_collaborator(
 98                                &current_user,
 99                                peer_id,
100                                true,
101                                room.is_speaking(),
102                                room.is_muted(),
103                                &room,
104                                project_id,
105                                &current_user,
106                                cx,
107                            );
108
109                            this.children(current_user_face_pile.map(|face_pile| {
110                                v_flex()
111                                    .child(face_pile)
112                                    .child(render_color_ribbon(player_colors.local().cursor))
113                            }))
114                            .children(
115                                remote_participants.iter().filter_map(|collaborator| {
116                                    let is_present = project_id.map_or(false, |project_id| {
117                                        collaborator.location
118                                            == ParticipantLocation::SharedProject { project_id }
119                                    });
120
121                                    let face_pile = self.render_collaborator(
122                                        &collaborator.user,
123                                        collaborator.peer_id,
124                                        is_present,
125                                        collaborator.speaking,
126                                        collaborator.muted,
127                                        &room,
128                                        project_id,
129                                        &current_user,
130                                        cx,
131                                    )?;
132
133                                    Some(
134                                        v_flex()
135                                            .id(("collaborator", collaborator.user.id))
136                                            .child(face_pile)
137                                            .child(render_color_ribbon(
138                                                player_colors
139                                                    .color_for_participant(
140                                                        collaborator.participant_index.0,
141                                                    )
142                                                    .cursor,
143                                            ))
144                                            .cursor_pointer()
145                                            .on_click({
146                                                let peer_id = collaborator.peer_id;
147                                                cx.listener(move |this, _, cx| {
148                                                    this.workspace
149                                                        .update(cx, |workspace, cx| {
150                                                            workspace.follow(peer_id, cx);
151                                                        })
152                                                        .ok();
153                                                })
154                                            })
155                                            .tooltip({
156                                                let login = collaborator.user.github_login.clone();
157                                                move |cx| {
158                                                    Tooltip::text(format!("Follow {login}"), cx)
159                                                }
160                                            }),
161                                    )
162                                }),
163                            )
164                        },
165                    ),
166            )
167            // right side
168            .child(
169                h_flex()
170                    .gap_1()
171                    .pr_1()
172                    .when_some(room, |this, room| {
173                        let room = room.read(cx);
174                        let project = self.project.read(cx);
175                        let is_local = project.is_local();
176                        let is_shared = is_local && project.is_shared();
177                        let is_muted = room.is_muted();
178                        let is_deafened = room.is_deafened().unwrap_or(false);
179                        let is_screen_sharing = room.is_screen_sharing();
180                        let read_only = room.read_only();
181
182                        this.when(is_local && !read_only, |this| {
183                            this.child(
184                                Button::new(
185                                    "toggle_sharing",
186                                    if is_shared { "Unshare" } else { "Share" },
187                                )
188                                .tooltip(move |cx| {
189                                    Tooltip::text(
190                                        if is_shared {
191                                            "Stop sharing project with call participants"
192                                        } else {
193                                            "Share project with call participants"
194                                        },
195                                        cx,
196                                    )
197                                })
198                                .style(ButtonStyle::Subtle)
199                                .selected_style(ButtonStyle::Tinted(TintColor::Accent))
200                                .selected(is_shared)
201                                .label_size(LabelSize::Small)
202                                .on_click(cx.listener(
203                                    move |this, _, cx| {
204                                        if is_shared {
205                                            this.unshare_project(&Default::default(), cx);
206                                        } else {
207                                            this.share_project(&Default::default(), cx);
208                                        }
209                                    },
210                                )),
211                            )
212                        })
213                        .child(
214                            div()
215                                .child(
216                                    IconButton::new("leave-call", ui::IconName::Exit)
217                                        .style(ButtonStyle::Subtle)
218                                        .tooltip(|cx| Tooltip::text("Leave call", cx))
219                                        .icon_size(IconSize::Small)
220                                        .on_click(move |_, cx| {
221                                            ActiveCall::global(cx)
222                                                .update(cx, |call, cx| call.hang_up(cx))
223                                                .detach_and_log_err(cx);
224                                        }),
225                                )
226                                .pr_2(),
227                        )
228                        .when(!read_only, |this| {
229                            this.child(
230                                IconButton::new(
231                                    "mute-microphone",
232                                    if is_muted {
233                                        ui::IconName::MicMute
234                                    } else {
235                                        ui::IconName::Mic
236                                    },
237                                )
238                                .tooltip(move |cx| {
239                                    Tooltip::text(
240                                        if is_muted {
241                                            "Unmute microphone"
242                                        } else {
243                                            "Mute microphone"
244                                        },
245                                        cx,
246                                    )
247                                })
248                                .style(ButtonStyle::Subtle)
249                                .icon_size(IconSize::Small)
250                                .selected(is_muted)
251                                .selected_style(ButtonStyle::Tinted(TintColor::Negative))
252                                .on_click(move |_, cx| crate::toggle_mute(&Default::default(), cx)),
253                            )
254                        })
255                        .child(
256                            IconButton::new(
257                                "mute-sound",
258                                if is_deafened {
259                                    ui::IconName::AudioOff
260                                } else {
261                                    ui::IconName::AudioOn
262                                },
263                            )
264                            .style(ButtonStyle::Subtle)
265                            .selected_style(ButtonStyle::Tinted(TintColor::Negative))
266                            .icon_size(IconSize::Small)
267                            .selected(is_deafened)
268                            .tooltip(move |cx| {
269                                if !read_only {
270                                    Tooltip::with_meta(
271                                        "Deafen Audio",
272                                        None,
273                                        "Mic will be muted",
274                                        cx,
275                                    )
276                                } else {
277                                    Tooltip::text("Deafen Audio", cx)
278                                }
279                            })
280                            .on_click(move |_, cx| crate::toggle_deafen(&Default::default(), cx)),
281                        )
282                        .when(!read_only, |this| {
283                            this.child(
284                                IconButton::new("screen-share", ui::IconName::Screen)
285                                    .style(ButtonStyle::Subtle)
286                                    .icon_size(IconSize::Small)
287                                    .selected(is_screen_sharing)
288                                    .selected_style(ButtonStyle::Tinted(TintColor::Accent))
289                                    .tooltip(move |cx| {
290                                        Tooltip::text(
291                                            if is_screen_sharing {
292                                                "Stop Sharing Screen"
293                                            } else {
294                                                "Share Screen"
295                                            },
296                                            cx,
297                                        )
298                                    })
299                                    .on_click(move |_, cx| {
300                                        crate::toggle_screen_sharing(&Default::default(), cx)
301                                    }),
302                            )
303                        })
304                        .child(div().pr_2())
305                    })
306                    .map(|el| {
307                        let status = self.client.status();
308                        let status = &*status.borrow();
309                        if matches!(status, client::Status::Connected { .. }) {
310                            el.child(self.render_user_menu_button(cx))
311                        } else {
312                            el.children(self.render_connection_status(status, cx))
313                                .child(self.render_sign_in_button(cx))
314                                .child(self.render_user_menu_button(cx))
315                        }
316                    }),
317            )
318    }
319}
320
321fn render_color_ribbon(color: Hsla) -> gpui::Canvas {
322    canvas(move |bounds, cx| {
323        let height = bounds.size.height;
324        let horizontal_offset = height;
325        let vertical_offset = px(height.0 / 2.0);
326        let mut path = Path::new(bounds.lower_left());
327        path.curve_to(
328            bounds.origin + point(horizontal_offset, vertical_offset),
329            bounds.origin + point(px(0.0), vertical_offset),
330        );
331        path.line_to(bounds.upper_right() + point(-horizontal_offset, vertical_offset));
332        path.curve_to(
333            bounds.lower_right(),
334            bounds.upper_right() + point(px(0.0), vertical_offset),
335        );
336        path.line_to(bounds.lower_left());
337        cx.paint_path(path, color);
338    })
339    .h_1()
340    .w_full()
341}
342
343impl CollabTitlebarItem {
344    pub fn new(workspace: &Workspace, cx: &mut ViewContext<Self>) -> Self {
345        let project = workspace.project().clone();
346        let user_store = workspace.app_state().user_store.clone();
347        let client = workspace.app_state().client.clone();
348        let active_call = ActiveCall::global(cx);
349        let mut subscriptions = Vec::new();
350        subscriptions.push(
351            cx.observe(&workspace.weak_handle().upgrade().unwrap(), |_, _, cx| {
352                cx.notify()
353            }),
354        );
355        subscriptions.push(cx.observe(&project, |_, _, cx| cx.notify()));
356        subscriptions.push(cx.observe(&active_call, |this, _, cx| this.active_call_changed(cx)));
357        subscriptions.push(cx.observe_window_activation(Self::window_activation_changed));
358        subscriptions.push(cx.observe(&user_store, |_, _, cx| cx.notify()));
359
360        Self {
361            workspace: workspace.weak_handle(),
362            project,
363            user_store,
364            client,
365            _subscriptions: subscriptions,
366        }
367    }
368
369    // resolve if you are in a room -> render_project_owner
370    // render_project_owner -> resolve if you are in a room -> Option<foo>
371
372    pub fn render_project_host(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
373        let host = self.project.read(cx).host()?;
374        let host_user = self.user_store.read(cx).get_cached_user(host.user_id)?;
375        let participant_index = self
376            .user_store
377            .read(cx)
378            .participant_indices()
379            .get(&host_user.id)?;
380        Some(
381            Button::new("project_owner_trigger", host_user.github_login.clone())
382                .color(Color::Player(participant_index.0))
383                .style(ButtonStyle::Subtle)
384                .label_size(LabelSize::Small)
385                .tooltip(move |cx| {
386                    Tooltip::text(
387                        format!(
388                            "{} is sharing this project. Click to follow.",
389                            host_user.github_login.clone()
390                        ),
391                        cx,
392                    )
393                })
394                .on_click({
395                    let host_peer_id = host.peer_id.clone();
396                    cx.listener(move |this, _, cx| {
397                        this.workspace
398                            .update(cx, |workspace, cx| {
399                                workspace.follow(host_peer_id, cx);
400                            })
401                            .log_err();
402                    })
403                }),
404        )
405    }
406
407    pub fn render_project_name(&self, cx: &mut ViewContext<Self>) -> impl Element {
408        let name = {
409            let mut names = self.project.read(cx).visible_worktrees(cx).map(|worktree| {
410                let worktree = worktree.read(cx);
411                worktree.root_name()
412            });
413
414            names.next().unwrap_or("")
415        };
416
417        let name = util::truncate_and_trailoff(name, MAX_PROJECT_NAME_LENGTH);
418        let workspace = self.workspace.clone();
419        popover_menu("project_name_trigger")
420            .trigger(
421                Button::new("project_name_trigger", name)
422                    .style(ButtonStyle::Subtle)
423                    .label_size(LabelSize::Small)
424                    .tooltip(move |cx| Tooltip::text("Recent Projects", cx)),
425            )
426            .menu(move |cx| Some(Self::render_project_popover(workspace.clone(), cx)))
427    }
428
429    pub fn render_project_branch(&self, cx: &mut ViewContext<Self>) -> Option<impl Element> {
430        let entry = {
431            let mut names_and_branches =
432                self.project.read(cx).visible_worktrees(cx).map(|worktree| {
433                    let worktree = worktree.read(cx);
434                    worktree.root_git_entry()
435                });
436
437            names_and_branches.next().flatten()
438        };
439        let workspace = self.workspace.upgrade()?;
440        let branch_name = entry
441            .as_ref()
442            .and_then(RepositoryEntry::branch)
443            .map(|branch| util::truncate_and_trailoff(&branch, MAX_BRANCH_NAME_LENGTH))?;
444        Some(
445            popover_menu("project_branch_trigger")
446                .trigger(
447                    Button::new("project_branch_trigger", branch_name)
448                        .color(Color::Muted)
449                        .style(ButtonStyle::Subtle)
450                        .label_size(LabelSize::Small)
451                        .tooltip(move |cx| {
452                            Tooltip::with_meta(
453                                "Recent Branches",
454                                Some(&ToggleVcsMenu),
455                                "Local branches only",
456                                cx,
457                            )
458                        }),
459                )
460                .menu(move |cx| Self::render_vcs_popover(workspace.clone(), cx)),
461        )
462    }
463
464    fn render_collaborator(
465        &self,
466        user: &Arc<User>,
467        peer_id: PeerId,
468        is_present: bool,
469        is_speaking: bool,
470        is_muted: bool,
471        room: &Room,
472        project_id: Option<u64>,
473        current_user: &Arc<User>,
474        cx: &ViewContext<Self>,
475    ) -> Option<FacePile> {
476        if room.role_for_user(user.id) == Some(proto::ChannelRole::Guest) {
477            return None;
478        }
479
480        const FACEPILE_LIMIT: usize = 3;
481        let followers = project_id.map_or(&[] as &[_], |id| room.followers_for(peer_id, id));
482        let extra_count = followers.len().saturating_sub(FACEPILE_LIMIT);
483
484        let pile = FacePile::default()
485            .child(
486                Avatar::new(user.avatar_uri.clone())
487                    .grayscale(!is_present)
488                    .border_color(if is_speaking {
489                        cx.theme().status().info
490                    } else {
491                        // We draw the border in a transparent color rather to avoid
492                        // the layout shift that would come with adding/removing the border.
493                        gpui::transparent_black()
494                    })
495                    .when(is_muted, |avatar| {
496                        avatar.indicator(
497                            AvatarAudioStatusIndicator::new(ui::AudioStatus::Muted).tooltip({
498                                let github_login = user.github_login.clone();
499                                move |cx| Tooltip::text(format!("{} is muted", github_login), cx)
500                            }),
501                        )
502                    }),
503            )
504            .children(
505                followers
506                    .iter()
507                    .take(FACEPILE_LIMIT)
508                    .filter_map(|follower_peer_id| {
509                        let follower = room
510                            .remote_participants()
511                            .values()
512                            .find_map(|p| (p.peer_id == *follower_peer_id).then_some(&p.user))
513                            .or_else(|| {
514                                (self.client.peer_id() == Some(*follower_peer_id))
515                                    .then_some(current_user)
516                            })?
517                            .clone();
518
519                        Some(Avatar::new(follower.avatar_uri.clone()))
520                    }),
521            )
522            .children(if extra_count > 0 {
523                Some(
524                    div()
525                        .ml_1()
526                        .child(Label::new(format!("+{extra_count}")))
527                        .into_any_element(),
528                )
529            } else {
530                None
531            });
532
533        Some(pile)
534    }
535
536    fn window_activation_changed(&mut self, cx: &mut ViewContext<Self>) {
537        let project = if cx.is_window_active() {
538            Some(self.project.clone())
539        } else {
540            None
541        };
542        ActiveCall::global(cx)
543            .update(cx, |call, cx| call.set_location(project.as_ref(), cx))
544            .detach_and_log_err(cx);
545    }
546
547    fn active_call_changed(&mut self, cx: &mut ViewContext<Self>) {
548        cx.notify();
549    }
550
551    fn share_project(&mut self, _: &ShareProject, cx: &mut ViewContext<Self>) {
552        let active_call = ActiveCall::global(cx);
553        let project = self.project.clone();
554        active_call
555            .update(cx, |call, cx| call.share_project(project, cx))
556            .detach_and_log_err(cx);
557    }
558
559    fn unshare_project(&mut self, _: &UnshareProject, cx: &mut ViewContext<Self>) {
560        let active_call = ActiveCall::global(cx);
561        let project = self.project.clone();
562        active_call
563            .update(cx, |call, cx| call.unshare_project(project, cx))
564            .log_err();
565    }
566
567    pub fn render_vcs_popover(
568        workspace: View<Workspace>,
569        cx: &mut WindowContext<'_>,
570    ) -> Option<View<BranchList>> {
571        let view = build_branch_list(workspace, cx).log_err()?;
572        let focus_handle = view.focus_handle(cx);
573        cx.focus(&focus_handle);
574        Some(view)
575    }
576
577    pub fn render_project_popover(
578        workspace: WeakView<Workspace>,
579        cx: &mut WindowContext<'_>,
580    ) -> View<RecentProjects> {
581        let view = RecentProjects::open_popover(workspace, cx);
582
583        let focus_handle = view.focus_handle(cx);
584        cx.focus(&focus_handle);
585        view
586    }
587
588    fn render_connection_status(
589        &self,
590        status: &client::Status,
591        cx: &mut ViewContext<Self>,
592    ) -> Option<AnyElement> {
593        match status {
594            client::Status::ConnectionError
595            | client::Status::ConnectionLost
596            | client::Status::Reauthenticating { .. }
597            | client::Status::Reconnecting { .. }
598            | client::Status::ReconnectionError { .. } => Some(
599                div()
600                    .id("disconnected")
601                    .child(Icon::new(IconName::Disconnected).size(IconSize::Small))
602                    .tooltip(|cx| Tooltip::text("Disconnected", cx))
603                    .into_any_element(),
604            ),
605            client::Status::UpgradeRequired => {
606                let auto_updater = auto_update::AutoUpdater::get(cx);
607                let label = match auto_updater.map(|auto_update| auto_update.read(cx).status()) {
608                    Some(AutoUpdateStatus::Updated) => "Please restart Zed to Collaborate",
609                    Some(AutoUpdateStatus::Installing)
610                    | Some(AutoUpdateStatus::Downloading)
611                    | Some(AutoUpdateStatus::Checking) => "Updating...",
612                    Some(AutoUpdateStatus::Idle) | Some(AutoUpdateStatus::Errored) | None => {
613                        "Please update Zed to Collaborate"
614                    }
615                };
616
617                Some(
618                    Button::new("connection-status", label)
619                        .label_size(LabelSize::Small)
620                        .on_click(|_, cx| {
621                            if let Some(auto_updater) = auto_update::AutoUpdater::get(cx) {
622                                if auto_updater.read(cx).status() == AutoUpdateStatus::Updated {
623                                    workspace::restart(&Default::default(), cx);
624                                    return;
625                                }
626                            }
627                            auto_update::check(&Default::default(), cx);
628                        })
629                        .into_any_element(),
630                )
631            }
632            _ => None,
633        }
634    }
635
636    pub fn render_sign_in_button(&mut self, _: &mut ViewContext<Self>) -> Button {
637        let client = self.client.clone();
638        Button::new("sign_in", "Sign in")
639            .label_size(LabelSize::Small)
640            .on_click(move |_, cx| {
641                let client = client.clone();
642                cx.spawn(move |mut cx| async move {
643                    client
644                        .authenticate_and_connect(true, &cx)
645                        .await
646                        .notify_async_err(&mut cx);
647                })
648                .detach();
649            })
650    }
651
652    pub fn render_user_menu_button(&mut self, cx: &mut ViewContext<Self>) -> impl Element {
653        if let Some(user) = self.user_store.read(cx).current_user() {
654            popover_menu("user-menu")
655                .menu(|cx| {
656                    ContextMenu::build(cx, |menu, _| {
657                        menu.action("Settings", zed_actions::OpenSettings.boxed_clone())
658                            .action("Theme", theme_selector::Toggle.boxed_clone())
659                            .separator()
660                            .action("Share Feedback", feedback::GiveFeedback.boxed_clone())
661                            .action("Sign Out", client::SignOut.boxed_clone())
662                    })
663                    .into()
664                })
665                .trigger(
666                    ButtonLike::new("user-menu")
667                        .child(
668                            h_flex()
669                                .gap_0p5()
670                                .child(Avatar::new(user.avatar_uri.clone()))
671                                .child(Icon::new(IconName::ChevronDown).color(Color::Muted)),
672                        )
673                        .style(ButtonStyle::Subtle)
674                        .tooltip(move |cx| Tooltip::text("Toggle User Menu", cx)),
675                )
676                .anchor(gpui::AnchorCorner::TopRight)
677        } else {
678            popover_menu("user-menu")
679                .menu(|cx| {
680                    ContextMenu::build(cx, |menu, _| {
681                        menu.action("Settings", zed_actions::OpenSettings.boxed_clone())
682                            .action("Theme", theme_selector::Toggle.boxed_clone())
683                            .separator()
684                            .action("Share Feedback", feedback::GiveFeedback.boxed_clone())
685                    })
686                    .into()
687                })
688                .trigger(
689                    ButtonLike::new("user-menu")
690                        .child(
691                            h_flex()
692                                .gap_0p5()
693                                .child(Icon::new(IconName::ChevronDown).color(Color::Muted)),
694                        )
695                        .style(ButtonStyle::Subtle)
696                        .tooltip(move |cx| Tooltip::text("Toggle User Menu", cx)),
697                )
698        }
699    }
700}