channel_view.rs

  1use anyhow::Result;
  2use call::ActiveCall;
  3use channel::{Channel, ChannelBuffer, ChannelBufferEvent, ChannelStore};
  4use client::{
  5    ChannelId, Collaborator, ParticipantIndex,
  6    proto::{self, PeerId},
  7};
  8use collections::HashMap;
  9use editor::{
 10    CollaborationHub, DisplayPoint, Editor, EditorEvent, SelectionEffects,
 11    display_map::ToDisplayPoint, scroll::Autoscroll,
 12};
 13use gpui::{
 14    AnyView, App, ClipboardItem, Context, Entity, EventEmitter, Focusable, Pixels, Point, Render,
 15    Subscription, Task, VisualContext as _, WeakEntity, Window, actions,
 16};
 17use project::Project;
 18use rpc::proto::ChannelVisibility;
 19use std::{
 20    any::{Any, TypeId},
 21    sync::Arc,
 22};
 23use ui::prelude::*;
 24use util::ResultExt;
 25use workspace::{CollaboratorId, item::TabContentParams};
 26use workspace::{
 27    ItemNavHistory, Pane, SaveIntent, Toast, ViewId, Workspace, WorkspaceId,
 28    item::{FollowableItem, Item, ItemEvent, ItemHandle},
 29    searchable::SearchableItemHandle,
 30};
 31use workspace::{item::Dedup, notifications::NotificationId};
 32
 33actions!(
 34    collab,
 35    [
 36        /// Copies a link to the current position in the channel buffer.
 37        CopyLink
 38    ]
 39);
 40
 41pub fn init(cx: &mut App) {
 42    workspace::FollowableViewRegistry::register::<ChannelView>(cx)
 43}
 44
 45pub struct ChannelView {
 46    pub editor: Entity<Editor>,
 47    workspace: WeakEntity<Workspace>,
 48    project: Entity<Project>,
 49    channel_store: Entity<ChannelStore>,
 50    channel_buffer: Entity<ChannelBuffer>,
 51    remote_id: Option<ViewId>,
 52    _editor_event_subscription: Subscription,
 53    _reparse_subscription: Option<Subscription>,
 54}
 55
 56impl ChannelView {
 57    pub fn open(
 58        channel_id: ChannelId,
 59        link_position: Option<String>,
 60        workspace: Entity<Workspace>,
 61        window: &mut Window,
 62        cx: &mut App,
 63    ) -> Task<Result<Entity<Self>>> {
 64        let pane = workspace.read(cx).active_pane().clone();
 65        let channel_view = Self::open_in_pane(
 66            channel_id,
 67            link_position,
 68            pane.clone(),
 69            workspace,
 70            window,
 71            cx,
 72        );
 73        window.spawn(cx, async move |cx| {
 74            let channel_view = channel_view.await?;
 75            pane.update_in(cx, |pane, window, cx| {
 76                telemetry::event!(
 77                    "Channel Notes Opened",
 78                    channel_id,
 79                    room_id = ActiveCall::global(cx)
 80                        .read(cx)
 81                        .room()
 82                        .map(|r| r.read(cx).id())
 83                );
 84                pane.add_item(Box::new(channel_view.clone()), true, true, None, window, cx);
 85            })?;
 86            anyhow::Ok(channel_view)
 87        })
 88    }
 89
 90    pub fn open_in_pane(
 91        channel_id: ChannelId,
 92        link_position: Option<String>,
 93        pane: Entity<Pane>,
 94        workspace: Entity<Workspace>,
 95        window: &mut Window,
 96        cx: &mut App,
 97    ) -> Task<Result<Entity<Self>>> {
 98        let channel_view = Self::load(channel_id, workspace, window, cx);
 99        window.spawn(cx, async move |cx| {
100            let channel_view = channel_view.await?;
101
102            pane.update_in(cx, |pane, window, cx| {
103                let buffer_id = channel_view.read(cx).channel_buffer.read(cx).remote_id(cx);
104
105                let existing_view = pane
106                    .items_of_type::<Self>()
107                    .find(|view| view.read(cx).channel_buffer.read(cx).remote_id(cx) == buffer_id);
108
109                // If this channel buffer is already open in this pane, just return it.
110                if let Some(existing_view) = existing_view.clone()
111                    && existing_view.read(cx).channel_buffer == channel_view.read(cx).channel_buffer
112                {
113                    if let Some(link_position) = link_position {
114                        existing_view.update(cx, |channel_view, cx| {
115                            channel_view.focus_position_from_link(link_position, true, window, cx)
116                        });
117                    }
118                    return existing_view;
119                }
120
121                // If the pane contained a disconnected view for this channel buffer,
122                // replace that.
123                if let Some(existing_item) = existing_view
124                    && let Some(ix) = pane.index_for_item(&existing_item)
125                {
126                    pane.close_item_by_id(existing_item.entity_id(), SaveIntent::Skip, window, cx)
127                        .detach();
128                    pane.add_item(
129                        Box::new(channel_view.clone()),
130                        true,
131                        true,
132                        Some(ix),
133                        window,
134                        cx,
135                    );
136                }
137
138                if let Some(link_position) = link_position {
139                    channel_view.update(cx, |channel_view, cx| {
140                        channel_view.focus_position_from_link(link_position, true, window, cx)
141                    });
142                }
143
144                channel_view
145            })
146        })
147    }
148
149    pub fn load(
150        channel_id: ChannelId,
151        workspace: Entity<Workspace>,
152        window: &mut Window,
153        cx: &mut App,
154    ) -> Task<Result<Entity<Self>>> {
155        let weak_workspace = workspace.downgrade();
156        let workspace = workspace.read(cx);
157        let project = workspace.project().to_owned();
158        let channel_store = ChannelStore::global(cx);
159        let language_registry = workspace.app_state().languages.clone();
160        let markdown = language_registry.language_for_name("Markdown");
161        let channel_buffer =
162            channel_store.update(cx, |store, cx| store.open_channel_buffer(channel_id, cx));
163
164        window.spawn(cx, async move |cx| {
165            let channel_buffer = channel_buffer.await?;
166            let markdown = markdown.await.log_err();
167
168            channel_buffer.update(cx, |channel_buffer, cx| {
169                channel_buffer.buffer().update(cx, |buffer, cx| {
170                    buffer.set_language_registry(language_registry);
171                    let Some(markdown) = markdown else {
172                        return;
173                    };
174                    buffer.set_language(Some(markdown), cx);
175                })
176            })?;
177
178            cx.new_window_entity(|window, cx| {
179                let mut this = Self::new(
180                    project,
181                    weak_workspace,
182                    channel_store,
183                    channel_buffer,
184                    window,
185                    cx,
186                );
187                this.acknowledge_buffer_version(cx);
188                this
189            })
190        })
191    }
192
193    pub fn new(
194        project: Entity<Project>,
195        workspace: WeakEntity<Workspace>,
196        channel_store: Entity<ChannelStore>,
197        channel_buffer: Entity<ChannelBuffer>,
198        window: &mut Window,
199        cx: &mut Context<Self>,
200    ) -> Self {
201        let buffer = channel_buffer.read(cx).buffer();
202        let this = cx.entity().downgrade();
203        let editor = cx.new(|cx| {
204            let mut editor = Editor::for_buffer(buffer, None, window, cx);
205            editor.set_collaboration_hub(Box::new(ChannelBufferCollaborationHub(
206                channel_buffer.clone(),
207            )));
208            editor.set_custom_context_menu(move |_, position, window, cx| {
209                let this = this.clone();
210                Some(ui::ContextMenu::build(window, cx, move |menu, _, _| {
211                    menu.entry("Copy link to section", None, move |window, cx| {
212                        this.update(cx, |this, cx| {
213                            this.copy_link_for_position(position, window, cx)
214                        })
215                        .ok();
216                    })
217                }))
218            });
219            editor
220        });
221        let _editor_event_subscription =
222            cx.subscribe(&editor, |_, _, e: &EditorEvent, cx| cx.emit(e.clone()));
223
224        cx.subscribe_in(&channel_buffer, window, Self::handle_channel_buffer_event)
225            .detach();
226
227        Self {
228            editor,
229            workspace,
230            project,
231            channel_store,
232            channel_buffer,
233            remote_id: None,
234            _editor_event_subscription,
235            _reparse_subscription: None,
236        }
237    }
238
239    fn focus_position_from_link(
240        &mut self,
241        position: String,
242        first_attempt: bool,
243        window: &mut Window,
244        cx: &mut Context<Self>,
245    ) {
246        let position = Channel::slug(&position).to_lowercase();
247        let snapshot = self
248            .editor
249            .update(cx, |editor, cx| editor.snapshot(window, cx));
250
251        if let Some(outline) = snapshot.buffer_snapshot.outline(None)
252            && let Some(item) = outline
253                .items
254                .iter()
255                .find(|item| &Channel::slug(&item.text).to_lowercase() == &position)
256        {
257            self.editor.update(cx, |editor, cx| {
258                editor.change_selections(
259                    SelectionEffects::scroll(Autoscroll::focused()),
260                    window,
261                    cx,
262                    |s| s.replace_cursors_with(|map| vec![item.range.start.to_display_point(map)]),
263                )
264            });
265            return;
266        }
267
268        if !first_attempt {
269            return;
270        }
271        self._reparse_subscription = Some(cx.subscribe_in(
272            &self.editor,
273            window,
274            move |this, _, e: &EditorEvent, window, cx| {
275                match e {
276                    EditorEvent::Reparsed(_) => {
277                        this.focus_position_from_link(position.clone(), false, window, cx);
278                        this._reparse_subscription.take();
279                    }
280                    EditorEvent::Edited { .. } | EditorEvent::SelectionsChanged { local: true } => {
281                        this._reparse_subscription.take();
282                    }
283                    _ => {}
284                };
285            },
286        ));
287    }
288
289    fn copy_link(&mut self, _: &CopyLink, window: &mut Window, cx: &mut Context<Self>) {
290        let position = self
291            .editor
292            .update(cx, |editor, cx| editor.selections.newest_display(cx).start);
293        self.copy_link_for_position(position, window, cx)
294    }
295
296    fn copy_link_for_position(
297        &self,
298        position: DisplayPoint,
299        window: &mut Window,
300        cx: &mut Context<Self>,
301    ) {
302        let snapshot = self
303            .editor
304            .update(cx, |editor, cx| editor.snapshot(window, cx));
305
306        let mut closest_heading = None;
307
308        if let Some(outline) = snapshot.buffer_snapshot.outline(None) {
309            for item in outline.items {
310                if item.range.start.to_display_point(&snapshot) > position {
311                    break;
312                }
313                closest_heading = Some(item);
314            }
315        }
316
317        let Some(channel) = self.channel(cx) else {
318            return;
319        };
320
321        let link = channel.notes_link(closest_heading.map(|heading| heading.text), cx);
322        cx.write_to_clipboard(ClipboardItem::new_string(link));
323        self.workspace
324            .update(cx, |workspace, cx| {
325                struct CopyLinkForPositionToast;
326
327                workspace.show_toast(
328                    Toast::new(
329                        NotificationId::unique::<CopyLinkForPositionToast>(),
330                        "Link copied to clipboard",
331                    ),
332                    cx,
333                );
334            })
335            .ok();
336    }
337
338    pub fn channel(&self, cx: &App) -> Option<Arc<Channel>> {
339        self.channel_buffer.read(cx).channel(cx)
340    }
341
342    fn handle_channel_buffer_event(
343        &mut self,
344        _: &Entity<ChannelBuffer>,
345        event: &ChannelBufferEvent,
346        window: &mut Window,
347        cx: &mut Context<Self>,
348    ) {
349        match event {
350            ChannelBufferEvent::Disconnected => self.editor.update(cx, |editor, cx| {
351                editor.set_read_only(true);
352                cx.notify();
353            }),
354            ChannelBufferEvent::Connected => self.editor.update(cx, |editor, cx| {
355                editor.set_read_only(false);
356                cx.notify();
357            }),
358            ChannelBufferEvent::ChannelChanged => {
359                self.editor.update(cx, |_, cx| {
360                    cx.emit(editor::EditorEvent::TitleChanged);
361                    cx.notify()
362                });
363            }
364            ChannelBufferEvent::BufferEdited => {
365                if self.editor.read(cx).is_focused(window) {
366                    self.acknowledge_buffer_version(cx);
367                } else {
368                    self.channel_store.update(cx, |store, cx| {
369                        let channel_buffer = self.channel_buffer.read(cx);
370                        store.update_latest_notes_version(
371                            channel_buffer.channel_id,
372                            channel_buffer.epoch(),
373                            &channel_buffer.buffer().read(cx).version(),
374                            cx,
375                        )
376                    });
377                }
378            }
379            ChannelBufferEvent::CollaboratorsChanged => {}
380        }
381    }
382
383    fn acknowledge_buffer_version(&mut self, cx: &mut Context<ChannelView>) {
384        self.channel_store.update(cx, |store, cx| {
385            let channel_buffer = self.channel_buffer.read(cx);
386            store.acknowledge_notes_version(
387                channel_buffer.channel_id,
388                channel_buffer.epoch(),
389                &channel_buffer.buffer().read(cx).version(),
390                cx,
391            )
392        });
393        self.channel_buffer.update(cx, |buffer, cx| {
394            buffer.acknowledge_buffer_version(cx);
395        });
396    }
397
398    fn get_channel(&self, cx: &App) -> (SharedString, Option<SharedString>) {
399        if let Some(channel) = self.channel(cx) {
400            let status = match (
401                self.channel_buffer.read(cx).buffer().read(cx).read_only(),
402                self.channel_buffer.read(cx).is_connected(),
403            ) {
404                (false, true) => None,
405                (true, true) => Some("read-only"),
406                (_, false) => Some("disconnected"),
407            };
408
409            (channel.name.clone(), status.map(Into::into))
410        } else {
411            ("<unknown>".into(), Some("disconnected".into()))
412        }
413    }
414}
415
416impl EventEmitter<EditorEvent> for ChannelView {}
417
418impl Render for ChannelView {
419    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
420        div()
421            .size_full()
422            .on_action(cx.listener(Self::copy_link))
423            .child(self.editor.clone())
424    }
425}
426
427impl Focusable for ChannelView {
428    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
429        self.editor.read(cx).focus_handle(cx)
430    }
431}
432
433impl Item for ChannelView {
434    type Event = EditorEvent;
435
436    fn act_as_type<'a>(
437        &'a self,
438        type_id: TypeId,
439        self_handle: &'a Entity<Self>,
440        _: &'a App,
441    ) -> Option<AnyView> {
442        if type_id == TypeId::of::<Self>() {
443            Some(self_handle.to_any())
444        } else if type_id == TypeId::of::<Editor>() {
445            Some(self.editor.to_any())
446        } else {
447            None
448        }
449    }
450
451    fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
452        let channel = self.channel(cx)?;
453        let icon = match channel.visibility {
454            ChannelVisibility::Public => IconName::Public,
455            ChannelVisibility::Members => IconName::Hash,
456        };
457
458        Some(Icon::new(icon))
459    }
460
461    fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
462        let (name, status) = self.get_channel(cx);
463        if let Some(status) = status {
464            format!("{name} - {status}").into()
465        } else {
466            name
467        }
468    }
469
470    fn tab_content(&self, params: TabContentParams, _: &Window, cx: &App) -> gpui::AnyElement {
471        let (name, status) = self.get_channel(cx);
472        h_flex()
473            .gap_2()
474            .child(
475                Label::new(name)
476                    .color(params.text_color())
477                    .when(params.preview, |this| this.italic()),
478            )
479            .when_some(status, |element, status| {
480                element.child(
481                    Label::new(status)
482                        .size(LabelSize::XSmall)
483                        .color(Color::Muted),
484                )
485            })
486            .into_any_element()
487    }
488
489    fn telemetry_event_text(&self) -> Option<&'static str> {
490        None
491    }
492
493    fn clone_on_split(
494        &self,
495        _: Option<WorkspaceId>,
496        window: &mut Window,
497        cx: &mut Context<Self>,
498    ) -> Option<Entity<Self>> {
499        Some(cx.new(|cx| {
500            Self::new(
501                self.project.clone(),
502                self.workspace.clone(),
503                self.channel_store.clone(),
504                self.channel_buffer.clone(),
505                window,
506                cx,
507            )
508        }))
509    }
510
511    fn is_singleton(&self, _cx: &App) -> bool {
512        false
513    }
514
515    fn navigate(
516        &mut self,
517        data: Box<dyn Any>,
518        window: &mut Window,
519        cx: &mut Context<Self>,
520    ) -> bool {
521        self.editor
522            .update(cx, |editor, cx| editor.navigate(data, window, cx))
523    }
524
525    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
526        self.editor
527            .update(cx, |item, cx| item.deactivated(window, cx))
528    }
529
530    fn set_nav_history(
531        &mut self,
532        history: ItemNavHistory,
533        window: &mut Window,
534        cx: &mut Context<Self>,
535    ) {
536        self.editor.update(cx, |editor, cx| {
537            Item::set_nav_history(editor, history, window, cx)
538        })
539    }
540
541    fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
542        Some(Box::new(self.editor.clone()))
543    }
544
545    fn show_toolbar(&self) -> bool {
546        true
547    }
548
549    fn pixel_position_of_cursor(&self, cx: &App) -> Option<Point<Pixels>> {
550        self.editor.read(cx).pixel_position_of_cursor(cx)
551    }
552
553    fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
554        Editor::to_item_events(event, f)
555    }
556}
557
558impl FollowableItem for ChannelView {
559    fn remote_id(&self) -> Option<workspace::ViewId> {
560        self.remote_id
561    }
562
563    fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant> {
564        let channel_buffer = self.channel_buffer.read(cx);
565        if !channel_buffer.is_connected() {
566            return None;
567        }
568
569        Some(proto::view::Variant::ChannelView(
570            proto::view::ChannelView {
571                channel_id: channel_buffer.channel_id.0,
572                editor: if let Some(proto::view::Variant::Editor(proto)) =
573                    self.editor.read(cx).to_state_proto(window, cx)
574                {
575                    Some(proto)
576                } else {
577                    None
578                },
579            },
580        ))
581    }
582
583    fn from_state_proto(
584        workspace: Entity<workspace::Workspace>,
585        remote_id: workspace::ViewId,
586        state: &mut Option<proto::view::Variant>,
587        window: &mut Window,
588        cx: &mut App,
589    ) -> Option<gpui::Task<anyhow::Result<Entity<Self>>>> {
590        let Some(proto::view::Variant::ChannelView(_)) = state else {
591            return None;
592        };
593        let Some(proto::view::Variant::ChannelView(state)) = state.take() else {
594            unreachable!()
595        };
596
597        let open = ChannelView::load(ChannelId(state.channel_id), workspace, window, cx);
598
599        Some(window.spawn(cx, async move |cx| {
600            let this = open.await?;
601
602            let task = this.update_in(cx, |this, window, cx| {
603                this.remote_id = Some(remote_id);
604
605                if let Some(state) = state.editor {
606                    Some(this.editor.update(cx, |editor, cx| {
607                        editor.apply_update_proto(
608                            &this.project,
609                            proto::update_view::Variant::Editor(proto::update_view::Editor {
610                                selections: state.selections,
611                                pending_selection: state.pending_selection,
612                                scroll_top_anchor: state.scroll_top_anchor,
613                                scroll_x: state.scroll_x,
614                                scroll_y: state.scroll_y,
615                                ..Default::default()
616                            }),
617                            window,
618                            cx,
619                        )
620                    }))
621                } else {
622                    None
623                }
624            })?;
625
626            if let Some(task) = task {
627                task.await?;
628            }
629
630            Ok(this)
631        }))
632    }
633
634    fn add_event_to_update_proto(
635        &self,
636        event: &EditorEvent,
637        update: &mut Option<proto::update_view::Variant>,
638        window: &Window,
639        cx: &App,
640    ) -> bool {
641        self.editor
642            .read(cx)
643            .add_event_to_update_proto(event, update, window, cx)
644    }
645
646    fn apply_update_proto(
647        &mut self,
648        project: &Entity<Project>,
649        message: proto::update_view::Variant,
650        window: &mut Window,
651        cx: &mut Context<Self>,
652    ) -> gpui::Task<anyhow::Result<()>> {
653        self.editor.update(cx, |editor, cx| {
654            editor.apply_update_proto(project, message, window, cx)
655        })
656    }
657
658    fn set_leader_id(
659        &mut self,
660        leader_id: Option<CollaboratorId>,
661        window: &mut Window,
662        cx: &mut Context<Self>,
663    ) {
664        self.editor
665            .update(cx, |editor, cx| editor.set_leader_id(leader_id, window, cx))
666    }
667
668    fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
669        false
670    }
671
672    fn to_follow_event(event: &Self::Event) -> Option<workspace::item::FollowEvent> {
673        Editor::to_follow_event(event)
674    }
675
676    fn dedup(&self, existing: &Self, _: &Window, cx: &App) -> Option<Dedup> {
677        let existing = existing.channel_buffer.read(cx);
678        if self.channel_buffer.read(cx).channel_id == existing.channel_id {
679            if existing.is_connected() {
680                Some(Dedup::KeepExisting)
681            } else {
682                Some(Dedup::ReplaceExisting)
683            }
684        } else {
685            None
686        }
687    }
688}
689
690struct ChannelBufferCollaborationHub(Entity<ChannelBuffer>);
691
692impl CollaborationHub for ChannelBufferCollaborationHub {
693    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
694        self.0.read(cx).collaborators()
695    }
696
697    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
698        self.0.read(cx).user_store().read(cx).participant_indices()
699    }
700
701    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
702        let user_ids = self.collaborators(cx).values().map(|c| c.user_id);
703        self.0
704            .read(cx)
705            .user_store()
706            .read(cx)
707            .participant_names(user_ids, cx)
708    }
709}