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