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