items.rs

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