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