items.rs

  1use crate::{Autoscroll, Editor, Event, NavigationData, ToOffset, ToPoint as _};
  2use anyhow::Result;
  3use gpui::{
  4    elements::*, AppContext, Entity, ModelHandle, RenderContext, Subscription, Task, View,
  5    ViewContext, ViewHandle,
  6};
  7use language::{Bias, Buffer, Diagnostic, File as _};
  8use project::{File, Project, ProjectPath};
  9use std::fmt::Write;
 10use std::path::PathBuf;
 11use text::{Point, Selection};
 12use util::ResultExt;
 13use workspace::{Item, ItemHandle, ItemNavHistory, ProjectItem, Settings, StatusItemView};
 14
 15impl Item for Editor {
 16    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) {
 17        if let Some(data) = data.downcast_ref::<NavigationData>() {
 18            let buffer = self.buffer.read(cx).read(cx);
 19            let offset = if buffer.can_resolve(&data.anchor) {
 20                data.anchor.to_offset(&buffer)
 21            } else {
 22                buffer.clip_offset(data.offset, Bias::Left)
 23            };
 24
 25            drop(buffer);
 26            let nav_history = self.nav_history.take();
 27            self.select_ranges([offset..offset], Some(Autoscroll::Fit), cx);
 28            self.nav_history = nav_history;
 29        }
 30    }
 31
 32    fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
 33        let title = self.title(cx);
 34        Label::new(title, style.label.clone()).boxed()
 35    }
 36
 37    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
 38        File::from_dyn(self.buffer().read(cx).file(cx)).map(|file| ProjectPath {
 39            worktree_id: file.worktree_id(cx),
 40            path: file.path().clone(),
 41        })
 42    }
 43
 44    fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
 45    where
 46        Self: Sized,
 47    {
 48        Some(self.clone(cx))
 49    }
 50
 51    fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
 52        self.nav_history = Some(history);
 53    }
 54
 55    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 56        let selection = self.newest_anchor_selection();
 57        self.push_to_nav_history(selection.head(), None, cx);
 58    }
 59
 60    fn is_dirty(&self, cx: &AppContext) -> bool {
 61        self.buffer().read(cx).read(cx).is_dirty()
 62    }
 63
 64    fn has_conflict(&self, cx: &AppContext) -> bool {
 65        self.buffer().read(cx).read(cx).has_conflict()
 66    }
 67
 68    fn can_save(&self, cx: &AppContext) -> bool {
 69        !self.buffer().read(cx).is_singleton() || self.project_path(cx).is_some()
 70    }
 71
 72    fn save(
 73        &mut self,
 74        project: ModelHandle<Project>,
 75        cx: &mut ViewContext<Self>,
 76    ) -> Task<Result<()>> {
 77        let buffer = self.buffer().clone();
 78        let buffers = buffer.read(cx).all_buffers();
 79        let transaction = project.update(cx, |project, cx| project.format(buffers, true, cx));
 80        cx.spawn(|this, mut cx| async move {
 81            let transaction = transaction.await.log_err();
 82            this.update(&mut cx, |editor, cx| {
 83                editor.request_autoscroll(Autoscroll::Fit, cx)
 84            });
 85            buffer
 86                .update(&mut cx, |buffer, cx| {
 87                    if let Some(transaction) = transaction {
 88                        if !buffer.is_singleton() {
 89                            buffer.push_transaction(&transaction.0);
 90                        }
 91                    }
 92
 93                    buffer.save(cx)
 94                })
 95                .await?;
 96            Ok(())
 97        })
 98    }
 99
100    fn can_save_as(&self, cx: &AppContext) -> bool {
101        self.buffer().read(cx).is_singleton()
102    }
103
104    fn save_as(
105        &mut self,
106        project: ModelHandle<Project>,
107        abs_path: PathBuf,
108        cx: &mut ViewContext<Self>,
109    ) -> Task<Result<()>> {
110        let buffer = self
111            .buffer()
112            .read(cx)
113            .as_singleton()
114            .expect("cannot call save_as on an excerpt list")
115            .clone();
116
117        project.update(cx, |project, cx| {
118            project.save_buffer_as(buffer, abs_path, cx)
119        })
120    }
121
122    fn should_activate_item_on_event(event: &Event) -> bool {
123        matches!(event, Event::Activate)
124    }
125
126    fn should_close_item_on_event(event: &Event) -> bool {
127        matches!(event, Event::Closed)
128    }
129
130    fn should_update_tab_on_event(event: &Event) -> bool {
131        matches!(event, Event::Saved | Event::Dirtied | Event::TitleChanged)
132    }
133}
134
135impl ProjectItem for Editor {
136    type Item = Buffer;
137
138    fn for_project_item(
139        project: ModelHandle<Project>,
140        buffer: ModelHandle<Buffer>,
141        cx: &mut ViewContext<Self>,
142    ) -> Self {
143        Self::for_buffer(buffer, Some(project), cx)
144    }
145}
146
147pub struct CursorPosition {
148    position: Option<Point>,
149    selected_count: usize,
150    _observe_active_editor: Option<Subscription>,
151}
152
153impl CursorPosition {
154    pub fn new() -> Self {
155        Self {
156            position: None,
157            selected_count: 0,
158            _observe_active_editor: None,
159        }
160    }
161
162    fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
163        let editor = editor.read(cx);
164        let buffer = editor.buffer().read(cx).snapshot(cx);
165
166        self.selected_count = 0;
167        let mut last_selection: Option<Selection<usize>> = None;
168        for selection in editor.local_selections::<usize>(cx) {
169            self.selected_count += selection.end - selection.start;
170            if last_selection
171                .as_ref()
172                .map_or(true, |last_selection| selection.id > last_selection.id)
173            {
174                last_selection = Some(selection);
175            }
176        }
177        self.position = last_selection.map(|s| s.head().to_point(&buffer));
178
179        cx.notify();
180    }
181}
182
183impl Entity for CursorPosition {
184    type Event = ();
185}
186
187impl View for CursorPosition {
188    fn ui_name() -> &'static str {
189        "CursorPosition"
190    }
191
192    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
193        if let Some(position) = self.position {
194            let theme = &cx.global::<Settings>().theme.workspace.status_bar;
195            let mut text = format!("{},{}", position.row + 1, position.column + 1);
196            if self.selected_count > 0 {
197                write!(text, " ({} selected)", self.selected_count).unwrap();
198            }
199            Label::new(text, theme.cursor_position.clone()).boxed()
200        } else {
201            Empty::new().boxed()
202        }
203    }
204}
205
206impl StatusItemView for CursorPosition {
207    fn set_active_pane_item(
208        &mut self,
209        active_pane_item: Option<&dyn ItemHandle>,
210        cx: &mut ViewContext<Self>,
211    ) {
212        if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
213            self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
214            self.update_position(editor, cx);
215        } else {
216            self.position = None;
217            self._observe_active_editor = None;
218        }
219
220        cx.notify();
221    }
222}
223
224pub struct DiagnosticMessage {
225    diagnostic: Option<Diagnostic>,
226    _observe_active_editor: Option<Subscription>,
227}
228
229impl DiagnosticMessage {
230    pub fn new() -> Self {
231        Self {
232            diagnostic: None,
233            _observe_active_editor: None,
234        }
235    }
236
237    fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
238        let editor = editor.read(cx);
239        let buffer = editor.buffer().read(cx);
240        let cursor_position = editor
241            .newest_selection_with_snapshot::<usize>(&buffer.read(cx))
242            .head();
243        let new_diagnostic = buffer
244            .read(cx)
245            .diagnostics_in_range::<_, usize>(cursor_position..cursor_position, false)
246            .filter(|entry| !entry.range.is_empty())
247            .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
248            .map(|entry| entry.diagnostic);
249        if new_diagnostic != self.diagnostic {
250            self.diagnostic = new_diagnostic;
251            cx.notify();
252        }
253    }
254}
255
256impl Entity for DiagnosticMessage {
257    type Event = ();
258}
259
260impl View for DiagnosticMessage {
261    fn ui_name() -> &'static str {
262        "DiagnosticMessage"
263    }
264
265    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
266        if let Some(diagnostic) = &self.diagnostic {
267            let theme = &cx.global::<Settings>().theme.workspace.status_bar;
268            Label::new(
269                diagnostic.message.split('\n').next().unwrap().to_string(),
270                theme.diagnostic_message.clone(),
271            )
272            .boxed()
273        } else {
274            Empty::new().boxed()
275        }
276    }
277}
278
279impl StatusItemView for DiagnosticMessage {
280    fn set_active_pane_item(
281        &mut self,
282        active_pane_item: Option<&dyn ItemHandle>,
283        cx: &mut ViewContext<Self>,
284    ) {
285        if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
286            self._observe_active_editor = Some(cx.observe(&editor, Self::update));
287            self.update(editor, cx);
288        } else {
289            self.diagnostic = Default::default();
290            self._observe_active_editor = None;
291        }
292        cx.notify();
293    }
294}