items.rs

  1use crate::{
  2    link_go_to_definition::hide_link_definition, Anchor, Autoscroll, Editor, Event, ExcerptId,
  3    MultiBuffer, NavigationData, ToPoint as _,
  4};
  5use anyhow::{anyhow, Result};
  6use futures::FutureExt;
  7use gpui::{
  8    elements::*, geometry::vector::vec2f, AppContext, Entity, ModelHandle, MutableAppContext,
  9    RenderContext, Subscription, Task, View, ViewContext, ViewHandle,
 10};
 11use language::{Bias, Buffer, File as _, SelectionGoal};
 12use project::{File, Project, ProjectEntryId, ProjectPath};
 13use rpc::proto::{self, update_view};
 14use settings::Settings;
 15use smallvec::SmallVec;
 16use std::{
 17    borrow::Cow,
 18    fmt::Write,
 19    path::{Path, PathBuf},
 20    time::Duration,
 21};
 22use text::{Point, Selection};
 23use util::TryFutureExt;
 24use workspace::{FollowableItem, Item, ItemHandle, ItemNavHistory, ProjectItem, StatusItemView};
 25
 26pub const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
 27pub const MAX_TAB_TITLE_LEN: usize = 24;
 28
 29impl FollowableItem for Editor {
 30    fn from_state_proto(
 31        pane: ViewHandle<workspace::Pane>,
 32        project: ModelHandle<Project>,
 33        state: &mut Option<proto::view::Variant>,
 34        cx: &mut MutableAppContext,
 35    ) -> Option<Task<Result<ViewHandle<Self>>>> {
 36        let state = if matches!(state, Some(proto::view::Variant::Editor(_))) {
 37            if let Some(proto::view::Variant::Editor(state)) = state.take() {
 38                state
 39            } else {
 40                unreachable!()
 41            }
 42        } else {
 43            return None;
 44        };
 45
 46        let buffer = project.update(cx, |project, cx| {
 47            project.open_buffer_by_id(state.buffer_id, cx)
 48        });
 49        Some(cx.spawn(|mut cx| async move {
 50            let buffer = buffer.await?;
 51            let editor = pane
 52                .read_with(&cx, |pane, cx| {
 53                    pane.items_of_type::<Self>().find(|editor| {
 54                        editor.read(cx).buffer.read(cx).as_singleton().as_ref() == Some(&buffer)
 55                    })
 56                })
 57                .unwrap_or_else(|| {
 58                    pane.update(&mut cx, |_, cx| {
 59                        cx.add_view(|cx| Editor::for_buffer(buffer, Some(project), cx))
 60                    })
 61                });
 62            editor.update(&mut cx, |editor, cx| {
 63                let excerpt_id;
 64                let buffer_id;
 65                {
 66                    let buffer = editor.buffer.read(cx).read(cx);
 67                    let singleton = buffer.as_singleton().unwrap();
 68                    excerpt_id = singleton.0.clone();
 69                    buffer_id = singleton.1;
 70                }
 71                let selections = state
 72                    .selections
 73                    .into_iter()
 74                    .map(|selection| {
 75                        deserialize_selection(&excerpt_id, buffer_id, selection)
 76                            .ok_or_else(|| anyhow!("invalid selection"))
 77                    })
 78                    .collect::<Result<Vec<_>>>()?;
 79                if !selections.is_empty() {
 80                    editor.set_selections_from_remote(selections, cx);
 81                }
 82
 83                if let Some(anchor) = state.scroll_top_anchor {
 84                    editor.set_scroll_top_anchor(
 85                        Anchor {
 86                            buffer_id: Some(state.buffer_id as usize),
 87                            excerpt_id,
 88                            text_anchor: language::proto::deserialize_anchor(anchor)
 89                                .ok_or_else(|| anyhow!("invalid scroll top"))?,
 90                        },
 91                        vec2f(state.scroll_x, state.scroll_y),
 92                        cx,
 93                    );
 94                }
 95
 96                Ok::<_, anyhow::Error>(())
 97            })?;
 98            Ok(editor)
 99        }))
100    }
101
102    fn set_leader_replica_id(
103        &mut self,
104        leader_replica_id: Option<u16>,
105        cx: &mut ViewContext<Self>,
106    ) {
107        self.leader_replica_id = leader_replica_id;
108        if self.leader_replica_id.is_some() {
109            self.buffer.update(cx, |buffer, cx| {
110                buffer.remove_active_selections(cx);
111            });
112        } else {
113            self.buffer.update(cx, |buffer, cx| {
114                if self.focused {
115                    buffer.set_active_selections(
116                        &self.selections.disjoint_anchors(),
117                        self.selections.line_mode,
118                        cx,
119                    );
120                }
121            });
122        }
123        cx.notify();
124    }
125
126    fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
127        let buffer_id = self.buffer.read(cx).as_singleton()?.read(cx).remote_id();
128        Some(proto::view::Variant::Editor(proto::view::Editor {
129            buffer_id,
130            scroll_top_anchor: Some(language::proto::serialize_anchor(
131                &self.scroll_top_anchor.text_anchor,
132            )),
133            scroll_x: self.scroll_position.x(),
134            scroll_y: self.scroll_position.y(),
135            selections: self
136                .selections
137                .disjoint_anchors()
138                .iter()
139                .map(serialize_selection)
140                .collect(),
141        }))
142    }
143
144    fn add_event_to_update_proto(
145        &self,
146        event: &Self::Event,
147        update: &mut Option<proto::update_view::Variant>,
148        _: &AppContext,
149    ) -> bool {
150        let update =
151            update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
152
153        match update {
154            proto::update_view::Variant::Editor(update) => match event {
155                Event::ScrollPositionChanged { .. } => {
156                    update.scroll_top_anchor = Some(language::proto::serialize_anchor(
157                        &self.scroll_top_anchor.text_anchor,
158                    ));
159                    update.scroll_x = self.scroll_position.x();
160                    update.scroll_y = self.scroll_position.y();
161                    true
162                }
163                Event::SelectionsChanged { .. } => {
164                    update.selections = self
165                        .selections
166                        .disjoint_anchors()
167                        .iter()
168                        .chain(self.selections.pending_anchor().as_ref())
169                        .map(serialize_selection)
170                        .collect();
171                    true
172                }
173                _ => false,
174            },
175        }
176    }
177
178    fn apply_update_proto(
179        &mut self,
180        message: update_view::Variant,
181        cx: &mut ViewContext<Self>,
182    ) -> Result<()> {
183        match message {
184            update_view::Variant::Editor(message) => {
185                let buffer = self.buffer.read(cx);
186                let buffer = buffer.read(cx);
187                let (excerpt_id, buffer_id, _) = buffer.as_singleton().unwrap();
188                let excerpt_id = excerpt_id.clone();
189                drop(buffer);
190
191                let selections = message
192                    .selections
193                    .into_iter()
194                    .filter_map(|selection| {
195                        deserialize_selection(&excerpt_id, buffer_id, selection)
196                    })
197                    .collect::<Vec<_>>();
198
199                if !selections.is_empty() {
200                    self.set_selections_from_remote(selections, cx);
201                    self.request_autoscroll_remotely(Autoscroll::Newest, cx);
202                } else if let Some(anchor) = message.scroll_top_anchor {
203                    self.set_scroll_top_anchor(
204                        Anchor {
205                            buffer_id: Some(buffer_id),
206                            excerpt_id,
207                            text_anchor: language::proto::deserialize_anchor(anchor)
208                                .ok_or_else(|| anyhow!("invalid scroll top"))?,
209                        },
210                        vec2f(message.scroll_x, message.scroll_y),
211                        cx,
212                    );
213                }
214            }
215        }
216        Ok(())
217    }
218
219    fn should_unfollow_on_event(event: &Self::Event, _: &AppContext) -> bool {
220        match event {
221            Event::Edited => true,
222            Event::SelectionsChanged { local } => *local,
223            Event::ScrollPositionChanged { local } => *local,
224            _ => false,
225        }
226    }
227}
228
229fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
230    proto::Selection {
231        id: selection.id as u64,
232        start: Some(language::proto::serialize_anchor(
233            &selection.start.text_anchor,
234        )),
235        end: Some(language::proto::serialize_anchor(
236            &selection.end.text_anchor,
237        )),
238        reversed: selection.reversed,
239    }
240}
241
242fn deserialize_selection(
243    excerpt_id: &ExcerptId,
244    buffer_id: usize,
245    selection: proto::Selection,
246) -> Option<Selection<Anchor>> {
247    Some(Selection {
248        id: selection.id as usize,
249        start: Anchor {
250            buffer_id: Some(buffer_id),
251            excerpt_id: excerpt_id.clone(),
252            text_anchor: language::proto::deserialize_anchor(selection.start?)?,
253        },
254        end: Anchor {
255            buffer_id: Some(buffer_id),
256            excerpt_id: excerpt_id.clone(),
257            text_anchor: language::proto::deserialize_anchor(selection.end?)?,
258        },
259        reversed: selection.reversed,
260        goal: SelectionGoal::None,
261    })
262}
263
264impl Item for Editor {
265    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
266        if let Ok(data) = data.downcast::<NavigationData>() {
267            let newest_selection = self.selections.newest::<Point>(cx);
268            let buffer = self.buffer.read(cx).read(cx);
269            let offset = if buffer.can_resolve(&data.cursor_anchor) {
270                data.cursor_anchor.to_point(&buffer)
271            } else {
272                buffer.clip_point(data.cursor_position, Bias::Left)
273            };
274
275            let scroll_top_anchor = if buffer.can_resolve(&data.scroll_top_anchor) {
276                data.scroll_top_anchor
277            } else {
278                buffer.anchor_before(
279                    buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
280                )
281            };
282
283            drop(buffer);
284
285            if newest_selection.head() == offset {
286                false
287            } else {
288                let nav_history = self.nav_history.take();
289                self.scroll_position = data.scroll_position;
290                self.scroll_top_anchor = scroll_top_anchor;
291                self.change_selections(Some(Autoscroll::Fit), cx, |s| {
292                    s.select_ranges([offset..offset])
293                });
294                self.nav_history = nav_history;
295                true
296            }
297        } else {
298            false
299        }
300    }
301
302    fn tab_description<'a>(&'a self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>> {
303        match path_for_buffer(&self.buffer, detail, true, cx)? {
304            Cow::Borrowed(path) => Some(path.to_string_lossy()),
305            Cow::Owned(path) => Some(path.to_string_lossy().to_string().into()),
306        }
307    }
308
309    fn tab_content(
310        &self,
311        detail: Option<usize>,
312        style: &theme::Tab,
313        cx: &AppContext,
314    ) -> ElementBox {
315        Flex::row()
316            .with_child(
317                Label::new(self.title(cx).into(), style.label.clone())
318                    .aligned()
319                    .boxed(),
320            )
321            .with_children(detail.and_then(|detail| {
322                let path = path_for_buffer(&self.buffer, detail, false, cx)?;
323                let description = path.to_string_lossy();
324                Some(
325                    Label::new(
326                        if description.len() > MAX_TAB_TITLE_LEN {
327                            description[..MAX_TAB_TITLE_LEN].to_string() + ""
328                        } else {
329                            description.into()
330                        },
331                        style.description.text.clone(),
332                    )
333                    .contained()
334                    .with_style(style.description.container)
335                    .aligned()
336                    .boxed(),
337                )
338            }))
339            .boxed()
340    }
341
342    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
343        let buffer = self.buffer.read(cx).as_singleton()?;
344        let file = buffer.read(cx).file();
345        File::from_dyn(file).map(|file| ProjectPath {
346            worktree_id: file.worktree_id(cx),
347            path: file.path().clone(),
348        })
349    }
350
351    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
352        self.buffer
353            .read(cx)
354            .files(cx)
355            .into_iter()
356            .filter_map(|file| File::from_dyn(Some(file))?.project_entry_id(cx))
357            .collect()
358    }
359
360    fn is_singleton(&self, cx: &AppContext) -> bool {
361        self.buffer.read(cx).is_singleton()
362    }
363
364    fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
365    where
366        Self: Sized,
367    {
368        Some(self.clone(cx))
369    }
370
371    fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
372        self.nav_history = Some(history);
373    }
374
375    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
376        let selection = self.selections.newest_anchor();
377        self.push_to_nav_history(selection.head(), None, cx);
378    }
379
380    fn workspace_deactivated(&mut self, cx: &mut ViewContext<Self>) {
381        hide_link_definition(self, cx);
382        self.link_go_to_definition_state.last_mouse_location = None;
383    }
384
385    fn is_dirty(&self, cx: &AppContext) -> bool {
386        self.buffer().read(cx).read(cx).is_dirty()
387    }
388
389    fn has_conflict(&self, cx: &AppContext) -> bool {
390        self.buffer().read(cx).read(cx).has_conflict()
391    }
392
393    fn can_save(&self, cx: &AppContext) -> bool {
394        !self.buffer().read(cx).is_singleton() || self.project_path(cx).is_some()
395    }
396
397    fn save(
398        &mut self,
399        project: ModelHandle<Project>,
400        cx: &mut ViewContext<Self>,
401    ) -> Task<Result<()>> {
402        let buffer = self.buffer().clone();
403        let buffers = buffer.read(cx).all_buffers();
404        let mut timeout = cx.background().timer(FORMAT_TIMEOUT).fuse();
405        let format = project.update(cx, |project, cx| project.format(buffers, true, cx));
406        cx.spawn(|_, mut cx| async move {
407            let transaction = futures::select_biased! {
408                _ = timeout => {
409                    log::warn!("timed out waiting for formatting");
410                    None
411                }
412                transaction = format.log_err().fuse() => transaction,
413            };
414
415            buffer
416                .update(&mut cx, |buffer, cx| {
417                    if let Some(transaction) = transaction {
418                        if !buffer.is_singleton() {
419                            buffer.push_transaction(&transaction.0);
420                        }
421                    }
422
423                    buffer.save(cx)
424                })
425                .await?;
426            Ok(())
427        })
428    }
429
430    fn save_as(
431        &mut self,
432        project: ModelHandle<Project>,
433        abs_path: PathBuf,
434        cx: &mut ViewContext<Self>,
435    ) -> Task<Result<()>> {
436        let buffer = self
437            .buffer()
438            .read(cx)
439            .as_singleton()
440            .expect("cannot call save_as on an excerpt list");
441
442        project.update(cx, |project, cx| {
443            project.save_buffer_as(buffer, abs_path, cx)
444        })
445    }
446
447    fn reload(
448        &mut self,
449        project: ModelHandle<Project>,
450        cx: &mut ViewContext<Self>,
451    ) -> Task<Result<()>> {
452        let buffer = self.buffer().clone();
453        let buffers = self.buffer.read(cx).all_buffers();
454        let reload_buffers =
455            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
456        cx.spawn(|this, mut cx| async move {
457            let transaction = reload_buffers.log_err().await;
458            this.update(&mut cx, |editor, cx| {
459                editor.request_autoscroll(Autoscroll::Fit, cx)
460            });
461            buffer.update(&mut cx, |buffer, _| {
462                if let Some(transaction) = transaction {
463                    if !buffer.is_singleton() {
464                        buffer.push_transaction(&transaction.0);
465                    }
466                }
467            });
468            Ok(())
469        })
470    }
471
472    fn should_close_item_on_event(event: &Event) -> bool {
473        matches!(event, Event::Closed)
474    }
475
476    fn should_update_tab_on_event(event: &Event) -> bool {
477        matches!(
478            event,
479            Event::Saved | Event::DirtyChanged | Event::TitleChanged
480        )
481    }
482
483    fn is_edit_event(event: &Self::Event) -> bool {
484        matches!(event, Event::BufferEdited)
485    }
486}
487
488impl ProjectItem for Editor {
489    type Item = Buffer;
490
491    fn for_project_item(
492        project: ModelHandle<Project>,
493        buffer: ModelHandle<Buffer>,
494        cx: &mut ViewContext<Self>,
495    ) -> Self {
496        Self::for_buffer(buffer, Some(project), cx)
497    }
498}
499
500pub struct CursorPosition {
501    position: Option<Point>,
502    selected_count: usize,
503    _observe_active_editor: Option<Subscription>,
504}
505
506impl Default for CursorPosition {
507    fn default() -> Self {
508        Self::new()
509    }
510}
511
512impl CursorPosition {
513    pub fn new() -> Self {
514        Self {
515            position: None,
516            selected_count: 0,
517            _observe_active_editor: None,
518        }
519    }
520
521    fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
522        let editor = editor.read(cx);
523        let buffer = editor.buffer().read(cx).snapshot(cx);
524
525        self.selected_count = 0;
526        let mut last_selection: Option<Selection<usize>> = None;
527        for selection in editor.selections.all::<usize>(cx) {
528            self.selected_count += selection.end - selection.start;
529            if last_selection
530                .as_ref()
531                .map_or(true, |last_selection| selection.id > last_selection.id)
532            {
533                last_selection = Some(selection);
534            }
535        }
536        self.position = last_selection.map(|s| s.head().to_point(&buffer));
537
538        cx.notify();
539    }
540}
541
542impl Entity for CursorPosition {
543    type Event = ();
544}
545
546impl View for CursorPosition {
547    fn ui_name() -> &'static str {
548        "CursorPosition"
549    }
550
551    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
552        if let Some(position) = self.position {
553            let theme = &cx.global::<Settings>().theme.workspace.status_bar;
554            let mut text = format!("{},{}", position.row + 1, position.column + 1);
555            if self.selected_count > 0 {
556                write!(text, " ({} selected)", self.selected_count).unwrap();
557            }
558            Label::new(text, theme.cursor_position.clone()).boxed()
559        } else {
560            Empty::new().boxed()
561        }
562    }
563}
564
565impl StatusItemView for CursorPosition {
566    fn set_active_pane_item(
567        &mut self,
568        active_pane_item: Option<&dyn ItemHandle>,
569        cx: &mut ViewContext<Self>,
570    ) {
571        if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
572            self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
573            self.update_position(editor, cx);
574        } else {
575            self.position = None;
576            self._observe_active_editor = None;
577        }
578
579        cx.notify();
580    }
581}
582
583fn path_for_buffer<'a>(
584    buffer: &ModelHandle<MultiBuffer>,
585    mut height: usize,
586    include_filename: bool,
587    cx: &'a AppContext,
588) -> Option<Cow<'a, Path>> {
589    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
590    // Ensure we always render at least the filename.
591    height += 1;
592
593    let mut prefix = file.path().as_ref();
594    while height > 0 {
595        if let Some(parent) = prefix.parent() {
596            prefix = parent;
597            height -= 1;
598        } else {
599            break;
600        }
601    }
602
603    // Here we could have just always used `full_path`, but that is very
604    // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
605    // traversed all the way up to the worktree's root.
606    if height > 0 {
607        let full_path = file.full_path(cx);
608        if include_filename {
609            Some(full_path.into())
610        } else {
611            Some(full_path.parent().unwrap().to_path_buf().into())
612        }
613    } else {
614        let mut path = file.path().strip_prefix(prefix).unwrap();
615        if !include_filename {
616            path = path.parent().unwrap();
617        }
618        Some(path.into())
619    }
620}