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