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                                cx,
114                            ))
115                            .children(
116                                remote_participants.iter().filter_map(|collaborator| {
117                                    let is_present = project_id.map_or(false, |project_id| {
118                                        collaborator.location
119                                            == ParticipantLocation::SharedProject { project_id }
120                                    });
121
122                                    let face_pile = self.render_collaborator(
123                                        &collaborator.user,
124                                        collaborator.peer_id,
125                                        is_present,
126                                        collaborator.speaking,
127                                        collaborator.muted,
128                                        &room,
129                                        project_id,
130                                        &current_user,
131                                        cx,
132                                    )?;
133
134                                    Some(
135                                        v_stack()
136                                            .id(("collaborator", collaborator.user.id))
137                                            .child(face_pile)
138                                            .child(render_color_ribbon(
139                                                collaborator.participant_index,
140                                                player_colors,
141                                            ))
142                                            .cursor_pointer()
143                                            .on_click({
144                                                let peer_id = collaborator.peer_id;
145                                                cx.listener(move |this, _, cx| {
146                                                    this.workspace
147                                                        .update(cx, |workspace, cx| {
148                                                            workspace.follow(peer_id, cx);
149                                                        })
150                                                        .ok();
151                                                })
152                                            })
153                                            .tooltip({
154                                                let login = collaborator.user.github_login.clone();
155                                                move |cx| {
156                                                    Tooltip::text(format!("Follow {login}"), cx)
157                                                }
158                                            }),
159                                    )
160                                }),
161                            )
162                        },
163                    ),
164            )
165            // right side
166            .child(
167                h_stack()
168                    .gap_1()
169                    .pr_1()
170                    .when_some(room, |this, room| {
171                        let room = room.read(cx);
172                        let project = self.project.read(cx);
173                        let is_local = project.is_local();
174                        let is_shared = is_local && project.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.when(is_local, |this| {
180                            this.child(
181                                Button::new(
182                                    "toggle_sharing",
183                                    if is_shared { "Unshare" } else { "Share" },
184                                )
185                                .style(ButtonStyle::Subtle)
186                                .label_size(LabelSize::Small)
187                                .on_click(cx.listener(
188                                    move |this, _, cx| {
189                                        if is_shared {
190                                            this.unshare_project(&Default::default(), cx);
191                                        } else {
192                                            this.share_project(&Default::default(), cx);
193                                        }
194                                    },
195                                )),
196                            )
197                        })
198                        .child(
199                            IconButton::new("leave-call", ui::Icon::Exit)
200                                .style(ButtonStyle::Subtle)
201                                .icon_size(IconSize::Small)
202                                .on_click(move |_, cx| {
203                                    ActiveCall::global(cx)
204                                        .update(cx, |call, cx| call.hang_up(cx))
205                                        .detach_and_log_err(cx);
206                                }),
207                        )
208                        .child(
209                            IconButton::new(
210                                "mute-microphone",
211                                if is_muted {
212                                    ui::Icon::MicMute
213                                } else {
214                                    ui::Icon::Mic
215                                },
216                            )
217                            .style(ButtonStyle::Subtle)
218                            .icon_size(IconSize::Small)
219                            .selected(is_muted)
220                            .on_click(move |_, cx| crate::toggle_mute(&Default::default(), cx)),
221                        )
222                        .child(
223                            IconButton::new(
224                                "mute-sound",
225                                if is_deafened {
226                                    ui::Icon::AudioOff
227                                } else {
228                                    ui::Icon::AudioOn
229                                },
230                            )
231                            .style(ButtonStyle::Subtle)
232                            .icon_size(IconSize::Small)
233                            .selected(is_deafened)
234                            .tooltip(move |cx| {
235                                Tooltip::with_meta("Deafen Audio", None, "Mic will be muted", cx)
236                            })
237                            .on_click(move |_, cx| crate::toggle_mute(&Default::default(), cx)),
238                        )
239                        .child(
240                            IconButton::new("screen-share", ui::Icon::Screen)
241                                .style(ButtonStyle::Subtle)
242                                .icon_size(IconSize::Small)
243                                .selected(is_screen_sharing)
244                                .on_click(move |_, cx| {
245                                    crate::toggle_screen_sharing(&Default::default(), cx)
246                                }),
247                        )
248                    })
249                    .map(|el| {
250                        let status = self.client.status();
251                        let status = &*status.borrow();
252                        if matches!(status, client::Status::Connected { .. }) {
253                            el.child(self.render_user_menu_button(cx))
254                        } else {
255                            el.children(self.render_connection_status(status, cx))
256                                .child(self.render_sign_in_button(cx))
257                                .child(self.render_user_menu_button(cx))
258                        }
259                    }),
260            )
261    }
262}
263
264fn render_color_ribbon(participant_index: ParticipantIndex, colors: &PlayerColors) -> gpui::Canvas {
265    let color = colors.color_for_participant(participant_index.0).cursor;
266    canvas(move |bounds, cx| {
267        let mut path = Path::new(bounds.lower_left());
268        let height = bounds.size.height;
269        path.curve_to(bounds.origin + point(height, px(0.)), bounds.origin);
270        path.line_to(bounds.upper_right() - point(height, px(0.)));
271        path.curve_to(bounds.lower_right(), bounds.upper_right());
272        path.line_to(bounds.lower_left());
273        cx.paint_path(path, color);
274    })
275    .h_1()
276    .w_full()
277}
278
279impl CollabTitlebarItem {
280    pub fn new(workspace: &Workspace, cx: &mut ViewContext<Self>) -> Self {
281        let project = workspace.project().clone();
282        let user_store = workspace.app_state().user_store.clone();
283        let client = workspace.app_state().client.clone();
284        let active_call = ActiveCall::global(cx);
285        let mut subscriptions = Vec::new();
286        subscriptions.push(
287            cx.observe(&workspace.weak_handle().upgrade().unwrap(), |_, _, cx| {
288                cx.notify()
289            }),
290        );
291        subscriptions.push(cx.observe(&project, |_, _, cx| cx.notify()));
292        subscriptions.push(cx.observe(&active_call, |this, _, cx| this.active_call_changed(cx)));
293        subscriptions.push(cx.observe_window_activation(Self::window_activation_changed));
294        subscriptions.push(cx.observe(&user_store, |_, _, cx| cx.notify()));
295
296        Self {
297            workspace: workspace.weak_handle(),
298            project,
299            user_store,
300            client,
301            _subscriptions: subscriptions,
302        }
303    }
304
305    // resolve if you are in a room -> render_project_owner
306    // render_project_owner -> resolve if you are in a room -> Option<foo>
307
308    pub fn render_project_host(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
309        let host = self.project.read(cx).host()?;
310        let host_user = self.user_store.read(cx).get_cached_user(host.user_id)?;
311        let participant_index = self
312            .user_store
313            .read(cx)
314            .participant_indices()
315            .get(&host_user.id)?;
316        Some(
317            Button::new("project_owner_trigger", host_user.github_login.clone())
318                .color(Color::Player(participant_index.0))
319                .style(ButtonStyle::Subtle)
320                .label_size(LabelSize::Small)
321                .tooltip(move |cx| {
322                    Tooltip::text(
323                        format!(
324                            "{} is sharing this project. Click to follow.",
325                            host_user.github_login.clone()
326                        ),
327                        cx,
328                    )
329                })
330                .on_click({
331                    let host_peer_id = host.peer_id.clone();
332                    cx.listener(move |this, _, cx| {
333                        this.workspace
334                            .update(cx, |workspace, cx| {
335                                workspace.follow(host_peer_id, cx);
336                            })
337                            .log_err();
338                    })
339                }),
340        )
341    }
342
343    pub fn render_project_name(&self, cx: &mut ViewContext<Self>) -> impl Element {
344        let name = {
345            let mut names = self.project.read(cx).visible_worktrees(cx).map(|worktree| {
346                let worktree = worktree.read(cx);
347                worktree.root_name()
348            });
349
350            names.next().unwrap_or("")
351        };
352
353        let name = util::truncate_and_trailoff(name, MAX_PROJECT_NAME_LENGTH);
354        let workspace = self.workspace.clone();
355        popover_menu("project_name_trigger")
356            .trigger(
357                Button::new("project_name_trigger", name)
358                    .style(ButtonStyle::Subtle)
359                    .label_size(LabelSize::Small)
360                    .tooltip(move |cx| Tooltip::text("Recent Projects", cx)),
361            )
362            .menu(move |cx| Some(Self::render_project_popover(workspace.clone(), cx)))
363    }
364
365    pub fn render_project_branch(&self, cx: &mut ViewContext<Self>) -> Option<impl Element> {
366        let entry = {
367            let mut names_and_branches =
368                self.project.read(cx).visible_worktrees(cx).map(|worktree| {
369                    let worktree = worktree.read(cx);
370                    worktree.root_git_entry()
371                });
372
373            names_and_branches.next().flatten()
374        };
375        let workspace = self.workspace.upgrade()?;
376        let branch_name = entry
377            .as_ref()
378            .and_then(RepositoryEntry::branch)
379            .map(|branch| util::truncate_and_trailoff(&branch, MAX_BRANCH_NAME_LENGTH))?;
380        Some(
381            popover_menu("project_branch_trigger")
382                .trigger(
383                    Button::new("project_branch_trigger", branch_name)
384                        .color(Color::Muted)
385                        .style(ButtonStyle::Subtle)
386                        .label_size(LabelSize::Small)
387                        .tooltip(move |cx| {
388                            Tooltip::with_meta(
389                                "Recent Branches",
390                                Some(&ToggleVcsMenu),
391                                "Local branches only",
392                                cx,
393                            )
394                        }),
395                )
396                .menu(move |cx| Self::render_vcs_popover(workspace.clone(), cx)),
397        )
398    }
399
400    fn render_collaborator(
401        &self,
402        user: &Arc<User>,
403        peer_id: PeerId,
404        is_present: bool,
405        is_speaking: bool,
406        is_muted: bool,
407        room: &Room,
408        project_id: Option<u64>,
409        current_user: &Arc<User>,
410        cx: &ViewContext<Self>,
411    ) -> Option<FacePile> {
412        let followers = project_id.map_or(&[] as &[_], |id| room.followers_for(peer_id, id));
413
414        let pile = FacePile::default()
415            .child(
416                Avatar::new(user.avatar_uri.clone())
417                    .grayscale(!is_present)
418                    .border_color(if is_speaking {
419                        cx.theme().status().info_border
420                    } else if is_muted {
421                        cx.theme().status().error_border
422                    } else {
423                        Hsla::default()
424                    }),
425            )
426            .children(followers.iter().filter_map(|follower_peer_id| {
427                let follower = room
428                    .remote_participants()
429                    .values()
430                    .find_map(|p| (p.peer_id == *follower_peer_id).then_some(&p.user))
431                    .or_else(|| {
432                        (self.client.peer_id() == Some(*follower_peer_id)).then_some(current_user)
433                    })?
434                    .clone();
435
436                Some(Avatar::new(follower.avatar_uri.clone()))
437            }));
438
439        Some(pile)
440    }
441
442    fn window_activation_changed(&mut self, cx: &mut ViewContext<Self>) {
443        let project = if cx.is_window_active() {
444            Some(self.project.clone())
445        } else {
446            None
447        };
448        ActiveCall::global(cx)
449            .update(cx, |call, cx| call.set_location(project.as_ref(), cx))
450            .detach_and_log_err(cx);
451    }
452
453    fn active_call_changed(&mut self, cx: &mut ViewContext<Self>) {
454        cx.notify();
455    }
456
457    fn share_project(&mut self, _: &ShareProject, 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.share_project(project, cx))
462            .detach_and_log_err(cx);
463    }
464
465    fn unshare_project(&mut self, _: &UnshareProject, cx: &mut ViewContext<Self>) {
466        let active_call = ActiveCall::global(cx);
467        let project = self.project.clone();
468        active_call
469            .update(cx, |call, cx| call.unshare_project(project, cx))
470            .log_err();
471    }
472
473    pub fn render_vcs_popover(
474        workspace: View<Workspace>,
475        cx: &mut WindowContext<'_>,
476    ) -> Option<View<BranchList>> {
477        let view = build_branch_list(workspace, cx).log_err()?;
478        let focus_handle = view.focus_handle(cx);
479        cx.focus(&focus_handle);
480        Some(view)
481    }
482
483    pub fn render_project_popover(
484        workspace: WeakView<Workspace>,
485        cx: &mut WindowContext<'_>,
486    ) -> View<RecentProjects> {
487        let view = RecentProjects::open_popover(workspace, cx);
488
489        let focus_handle = view.focus_handle(cx);
490        cx.focus(&focus_handle);
491        view
492    }
493
494    fn render_connection_status(
495        &self,
496        status: &client::Status,
497        cx: &mut ViewContext<Self>,
498    ) -> Option<AnyElement> {
499        match status {
500            client::Status::ConnectionError
501            | client::Status::ConnectionLost
502            | client::Status::Reauthenticating { .. }
503            | client::Status::Reconnecting { .. }
504            | client::Status::ReconnectionError { .. } => Some(
505                div()
506                    .id("disconnected")
507                    .bg(gpui::red()) // todo!() @nate
508                    .child(IconElement::new(Icon::Disconnected))
509                    .tooltip(|cx| Tooltip::text("Disconnected", cx))
510                    .into_any_element(),
511            ),
512            client::Status::UpgradeRequired => {
513                let auto_updater = auto_update::AutoUpdater::get(cx);
514                let label = match auto_updater.map(|auto_update| auto_update.read(cx).status()) {
515                    Some(AutoUpdateStatus::Updated) => "Please restart Zed to Collaborate",
516                    Some(AutoUpdateStatus::Installing)
517                    | Some(AutoUpdateStatus::Downloading)
518                    | Some(AutoUpdateStatus::Checking) => "Updating...",
519                    Some(AutoUpdateStatus::Idle) | Some(AutoUpdateStatus::Errored) | None => {
520                        "Please update Zed to Collaborate"
521                    }
522                };
523
524                Some(
525                    div()
526                        .bg(gpui::red()) // todo!() @nate
527                        .child(Button::new("connection-status", label).on_click(|_, cx| {
528                            if let Some(auto_updater) = auto_update::AutoUpdater::get(cx) {
529                                if auto_updater.read(cx).status() == AutoUpdateStatus::Updated {
530                                    workspace::restart(&Default::default(), cx);
531                                    return;
532                                }
533                            }
534                            auto_update::check(&Default::default(), cx);
535                        }))
536                        .into_any_element(),
537                )
538            }
539            _ => None,
540        }
541    }
542
543    pub fn render_sign_in_button(&mut self, _: &mut ViewContext<Self>) -> Button {
544        let client = self.client.clone();
545        Button::new("sign_in", "Sign in").on_click(move |_, cx| {
546            let client = client.clone();
547            cx.spawn(move |mut cx| async move {
548                client
549                    .authenticate_and_connect(true, &cx)
550                    .await
551                    .notify_async_err(&mut cx);
552            })
553            .detach();
554        })
555    }
556
557    pub fn render_user_menu_button(&mut self, cx: &mut ViewContext<Self>) -> impl Element {
558        if let Some(user) = self.user_store.read(cx).current_user() {
559            popover_menu("user-menu")
560                .menu(|cx| {
561                    ContextMenu::build(cx, |menu, _| {
562                        menu.action("Settings", zed_actions::OpenSettings.boxed_clone())
563                            .action("Theme", theme_selector::Toggle.boxed_clone())
564                            .separator()
565                            .action("Share Feedback", feedback::GiveFeedback.boxed_clone())
566                            .action("Sign Out", client::SignOut.boxed_clone())
567                    })
568                    .into()
569                })
570                .trigger(
571                    ButtonLike::new("user-menu")
572                        .child(
573                            h_stack()
574                                .gap_0p5()
575                                .child(Avatar::new(user.avatar_uri.clone()))
576                                .child(IconElement::new(Icon::ChevronDown).color(Color::Muted)),
577                        )
578                        .style(ButtonStyle::Subtle)
579                        .tooltip(move |cx| Tooltip::text("Toggle User Menu", cx)),
580                )
581                .anchor(gpui::AnchorCorner::TopRight)
582        } else {
583            popover_menu("user-menu")
584                .menu(|cx| {
585                    ContextMenu::build(cx, |menu, _| {
586                        menu.action("Settings", zed_actions::OpenSettings.boxed_clone())
587                            .action("Theme", theme_selector::Toggle.boxed_clone())
588                            .separator()
589                            .action("Share Feedback", feedback::GiveFeedback.boxed_clone())
590                    })
591                    .into()
592                })
593                .trigger(
594                    ButtonLike::new("user-menu")
595                        .child(
596                            h_stack()
597                                .gap_0p5()
598                                .child(IconElement::new(Icon::ChevronDown).color(Color::Muted)),
599                        )
600                        .style(ButtonStyle::Subtle)
601                        .tooltip(move |cx| Tooltip::text("Toggle User Menu", cx)),
602                )
603        }
604    }
605}