collab_titlebar_item.rs

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