items.rs

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