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