items.rs

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