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