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.cursor_anchor) {
251                data.cursor_anchor.to_offset(&buffer)
252            } else {
253                buffer.clip_offset(data.cursor_offset, Bias::Left)
254            };
255            let newest_selection = self.newest_selection_with_snapshot::<usize>(&buffer);
256
257            let scroll_top_anchor = if buffer.can_resolve(&data.scroll_top_anchor) {
258                data.scroll_top_anchor.clone()
259            } else {
260                buffer.anchor_at(data.scroll_top_offset, Bias::Left)
261            };
262
263            drop(buffer);
264
265            if newest_selection.head() == offset {
266                false
267            } else {
268                let nav_history = self.nav_history.take();
269                self.scroll_position = data.scroll_position;
270                self.scroll_top_anchor = scroll_top_anchor;
271                self.select_ranges([offset..offset], Some(Autoscroll::Fit), cx);
272                self.nav_history = nav_history;
273                true
274            }
275        } else {
276            false
277        }
278    }
279
280    fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
281        let title = self.title(cx);
282        Label::new(title, style.label.clone()).boxed()
283    }
284
285    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
286        File::from_dyn(self.buffer().read(cx).file(cx)).map(|file| ProjectPath {
287            worktree_id: file.worktree_id(cx),
288            path: file.path().clone(),
289        })
290    }
291
292    fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
293        File::from_dyn(self.buffer().read(cx).file(cx)).and_then(|file| file.project_entry_id(cx))
294    }
295
296    fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
297    where
298        Self: Sized,
299    {
300        Some(self.clone(cx))
301    }
302
303    fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
304        self.nav_history = Some(history);
305    }
306
307    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
308        let selection = self.newest_anchor_selection();
309        self.push_to_nav_history(selection.head(), None, cx);
310    }
311
312    fn is_dirty(&self, cx: &AppContext) -> bool {
313        self.buffer().read(cx).read(cx).is_dirty()
314    }
315
316    fn has_conflict(&self, cx: &AppContext) -> bool {
317        self.buffer().read(cx).read(cx).has_conflict()
318    }
319
320    fn can_save(&self, cx: &AppContext) -> bool {
321        !self.buffer().read(cx).is_singleton() || self.project_path(cx).is_some()
322    }
323
324    fn save(
325        &mut self,
326        project: ModelHandle<Project>,
327        cx: &mut ViewContext<Self>,
328    ) -> Task<Result<()>> {
329        let buffer = self.buffer().clone();
330        let buffers = buffer.read(cx).all_buffers();
331        let mut timeout = cx.background().timer(FORMAT_TIMEOUT).fuse();
332        let format = project.update(cx, |project, cx| project.format(buffers, true, cx));
333        cx.spawn(|this, mut cx| async move {
334            let transaction = futures::select_biased! {
335                _ = timeout => {
336                    log::warn!("timed out waiting for formatting");
337                    None
338                }
339                transaction = format.log_err().fuse() => transaction,
340            };
341
342            this.update(&mut cx, |editor, cx| {
343                editor.request_autoscroll(Autoscroll::Fit, cx)
344            });
345            buffer
346                .update(&mut cx, |buffer, cx| {
347                    if let Some(transaction) = transaction {
348                        if !buffer.is_singleton() {
349                            buffer.push_transaction(&transaction.0);
350                        }
351                    }
352
353                    buffer.save(cx)
354                })
355                .await?;
356            Ok(())
357        })
358    }
359
360    fn can_save_as(&self, cx: &AppContext) -> bool {
361        self.buffer().read(cx).is_singleton()
362    }
363
364    fn save_as(
365        &mut self,
366        project: ModelHandle<Project>,
367        abs_path: PathBuf,
368        cx: &mut ViewContext<Self>,
369    ) -> Task<Result<()>> {
370        let buffer = self
371            .buffer()
372            .read(cx)
373            .as_singleton()
374            .expect("cannot call save_as on an excerpt list")
375            .clone();
376
377        project.update(cx, |project, cx| {
378            project.save_buffer_as(buffer, abs_path, cx)
379        })
380    }
381
382    fn reload(
383        &mut self,
384        project: ModelHandle<Project>,
385        cx: &mut ViewContext<Self>,
386    ) -> Task<Result<()>> {
387        let buffer = self.buffer().clone();
388        let buffers = self.buffer.read(cx).all_buffers();
389        let reload_buffers =
390            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
391        cx.spawn(|this, mut cx| async move {
392            let transaction = reload_buffers.log_err().await;
393            this.update(&mut cx, |editor, cx| {
394                editor.request_autoscroll(Autoscroll::Fit, cx)
395            });
396            buffer.update(&mut cx, |buffer, _| {
397                if let Some(transaction) = transaction {
398                    if !buffer.is_singleton() {
399                        buffer.push_transaction(&transaction.0);
400                    }
401                }
402            });
403            Ok(())
404        })
405    }
406
407    fn should_activate_item_on_event(event: &Event) -> bool {
408        matches!(event, Event::Activate)
409    }
410
411    fn should_close_item_on_event(event: &Event) -> bool {
412        matches!(event, Event::Closed)
413    }
414
415    fn should_update_tab_on_event(event: &Event) -> bool {
416        matches!(event, Event::Saved | Event::Dirtied | Event::TitleChanged)
417    }
418}
419
420impl ProjectItem for Editor {
421    type Item = Buffer;
422
423    fn for_project_item(
424        project: ModelHandle<Project>,
425        buffer: ModelHandle<Buffer>,
426        cx: &mut ViewContext<Self>,
427    ) -> Self {
428        Self::for_buffer(buffer, Some(project), cx)
429    }
430}
431
432pub struct CursorPosition {
433    position: Option<Point>,
434    selected_count: usize,
435    _observe_active_editor: Option<Subscription>,
436}
437
438impl CursorPosition {
439    pub fn new() -> Self {
440        Self {
441            position: None,
442            selected_count: 0,
443            _observe_active_editor: None,
444        }
445    }
446
447    fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
448        let editor = editor.read(cx);
449        let buffer = editor.buffer().read(cx).snapshot(cx);
450
451        self.selected_count = 0;
452        let mut last_selection: Option<Selection<usize>> = None;
453        for selection in editor.local_selections::<usize>(cx) {
454            self.selected_count += selection.end - selection.start;
455            if last_selection
456                .as_ref()
457                .map_or(true, |last_selection| selection.id > last_selection.id)
458            {
459                last_selection = Some(selection);
460            }
461        }
462        self.position = last_selection.map(|s| s.head().to_point(&buffer));
463
464        cx.notify();
465    }
466}
467
468impl Entity for CursorPosition {
469    type Event = ();
470}
471
472impl View for CursorPosition {
473    fn ui_name() -> &'static str {
474        "CursorPosition"
475    }
476
477    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
478        if let Some(position) = self.position {
479            let theme = &cx.global::<Settings>().theme.workspace.status_bar;
480            let mut text = format!("{},{}", position.row + 1, position.column + 1);
481            if self.selected_count > 0 {
482                write!(text, " ({} selected)", self.selected_count).unwrap();
483            }
484            Label::new(text, theme.cursor_position.clone()).boxed()
485        } else {
486            Empty::new().boxed()
487        }
488    }
489}
490
491impl StatusItemView for CursorPosition {
492    fn set_active_pane_item(
493        &mut self,
494        active_pane_item: Option<&dyn ItemHandle>,
495        cx: &mut ViewContext<Self>,
496    ) {
497        if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
498            self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
499            self.update_position(editor, cx);
500        } else {
501            self.position = None;
502            self._observe_active_editor = None;
503        }
504
505        cx.notify();
506    }
507}
508
509pub struct DiagnosticMessage {
510    diagnostic: Option<Diagnostic>,
511    _observe_active_editor: Option<Subscription>,
512}
513
514impl DiagnosticMessage {
515    pub fn new() -> Self {
516        Self {
517            diagnostic: None,
518            _observe_active_editor: None,
519        }
520    }
521
522    fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
523        let editor = editor.read(cx);
524        let buffer = editor.buffer().read(cx);
525        let cursor_position = editor
526            .newest_selection_with_snapshot::<usize>(&buffer.read(cx))
527            .head();
528        let new_diagnostic = buffer
529            .read(cx)
530            .diagnostics_in_range::<_, usize>(cursor_position..cursor_position, false)
531            .filter(|entry| !entry.range.is_empty())
532            .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
533            .map(|entry| entry.diagnostic);
534        if new_diagnostic != self.diagnostic {
535            self.diagnostic = new_diagnostic;
536            cx.notify();
537        }
538    }
539}
540
541impl Entity for DiagnosticMessage {
542    type Event = ();
543}
544
545impl View for DiagnosticMessage {
546    fn ui_name() -> &'static str {
547        "DiagnosticMessage"
548    }
549
550    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
551        if let Some(diagnostic) = &self.diagnostic {
552            let theme = &cx.global::<Settings>().theme.workspace.status_bar;
553            Label::new(
554                diagnostic.message.split('\n').next().unwrap().to_string(),
555                theme.diagnostic_message.clone(),
556            )
557            .boxed()
558        } else {
559            Empty::new().boxed()
560        }
561    }
562}
563
564impl StatusItemView for DiagnosticMessage {
565    fn set_active_pane_item(
566        &mut self,
567        active_pane_item: Option<&dyn ItemHandle>,
568        cx: &mut ViewContext<Self>,
569    ) {
570        if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
571            self._observe_active_editor = Some(cx.observe(&editor, Self::update));
572            self.update(editor, cx);
573        } else {
574            self.diagnostic = Default::default();
575            self._observe_active_editor = None;
576        }
577        cx.notify();
578    }
579}