items.rs

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