items.rs

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