items.rs

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