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