items.rs

  1use super::{Item, ItemView};
  2use crate::{status_bar::StatusItemView, Settings};
  3use anyhow::Result;
  4use buffer::{Point, Selection, ToPoint};
  5use editor::{Editor, EditorSettings, Event};
  6use gpui::{
  7    elements::*, fonts::TextStyle, AppContext, Entity, ModelHandle, RenderContext, Subscription,
  8    Task, View, ViewContext, ViewHandle,
  9};
 10use language::{Buffer, Diagnostic, File as _};
 11use postage::watch;
 12use project::{ProjectPath, Worktree};
 13use std::fmt::Write;
 14use std::path::Path;
 15
 16impl Item for Buffer {
 17    type View = Editor;
 18
 19    fn build_view(
 20        handle: ModelHandle<Self>,
 21        settings: watch::Receiver<Settings>,
 22        cx: &mut ViewContext<Self::View>,
 23    ) -> Self::View {
 24        Editor::for_buffer(
 25            handle,
 26            move |cx| {
 27                let settings = settings.borrow();
 28                let font_cache = cx.font_cache();
 29                let font_family_id = settings.buffer_font_family;
 30                let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
 31                let font_properties = Default::default();
 32                let font_id = font_cache
 33                    .select_font(font_family_id, &font_properties)
 34                    .unwrap();
 35                let font_size = settings.buffer_font_size;
 36
 37                let mut theme = settings.theme.editor.clone();
 38                theme.text = TextStyle {
 39                    color: theme.text.color,
 40                    font_family_name,
 41                    font_family_id,
 42                    font_id,
 43                    font_size,
 44                    font_properties,
 45                    underline: None,
 46                };
 47                EditorSettings {
 48                    tab_size: settings.tab_size,
 49                    style: theme,
 50                }
 51            },
 52            cx,
 53        )
 54    }
 55
 56    fn project_path(&self) -> Option<ProjectPath> {
 57        self.file().map(|f| ProjectPath {
 58            worktree_id: f.worktree_id(),
 59            path: f.path().clone(),
 60        })
 61    }
 62}
 63
 64impl ItemView for Editor {
 65    fn should_activate_item_on_event(event: &Event) -> bool {
 66        matches!(event, Event::Activate)
 67    }
 68
 69    fn should_close_item_on_event(event: &Event) -> bool {
 70        matches!(event, Event::Closed)
 71    }
 72
 73    fn should_update_tab_on_event(event: &Event) -> bool {
 74        matches!(
 75            event,
 76            Event::Saved | Event::Dirtied | Event::FileHandleChanged
 77        )
 78    }
 79
 80    fn title(&self, cx: &AppContext) -> String {
 81        let filename = self
 82            .buffer()
 83            .read(cx)
 84            .file()
 85            .and_then(|file| file.file_name());
 86        if let Some(name) = filename {
 87            name.to_string_lossy().into()
 88        } else {
 89            "untitled".into()
 90        }
 91    }
 92
 93    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
 94        self.buffer().read(cx).file().map(|file| ProjectPath {
 95            worktree_id: file.worktree_id(),
 96            path: file.path().clone(),
 97        })
 98    }
 99
100    fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
101    where
102        Self: Sized,
103    {
104        Some(self.clone(cx))
105    }
106
107    fn save(&mut self, cx: &mut ViewContext<Self>) -> Result<Task<Result<()>>> {
108        let save = self.buffer().update(cx, |b, cx| b.save(cx))?;
109        Ok(cx.spawn(|_, _| async move {
110            save.await?;
111            Ok(())
112        }))
113    }
114
115    fn save_as(
116        &mut self,
117        worktree: ModelHandle<Worktree>,
118        path: &Path,
119        cx: &mut ViewContext<Self>,
120    ) -> Task<Result<()>> {
121        self.buffer().update(cx, |buffer, cx| {
122            let handle = cx.handle();
123            let text = buffer.as_rope().clone();
124            let version = buffer.version();
125
126            let save_as = worktree.update(cx, |worktree, cx| {
127                worktree
128                    .as_local_mut()
129                    .unwrap()
130                    .save_buffer_as(handle, path, text, cx)
131            });
132
133            cx.spawn(|buffer, mut cx| async move {
134                save_as.await.map(|new_file| {
135                    let (language, language_server) = worktree.update(&mut cx, |worktree, cx| {
136                        let worktree = worktree.as_local_mut().unwrap();
137                        let language = worktree
138                            .languages()
139                            .select_language(new_file.full_path())
140                            .cloned();
141                        let language_server = language
142                            .as_ref()
143                            .and_then(|language| worktree.ensure_language_server(language, cx));
144                        (language, language_server.clone())
145                    });
146
147                    buffer.update(&mut cx, |buffer, cx| {
148                        buffer.did_save(version, new_file.mtime, Some(Box::new(new_file)), cx);
149                        buffer.set_language(language, language_server, cx);
150                    });
151                })
152            })
153        })
154    }
155
156    fn is_dirty(&self, cx: &AppContext) -> bool {
157        self.buffer().read(cx).is_dirty()
158    }
159
160    fn has_conflict(&self, cx: &AppContext) -> bool {
161        self.buffer().read(cx).has_conflict()
162    }
163}
164
165pub struct CursorPosition {
166    position: Option<Point>,
167    selected_count: usize,
168    settings: watch::Receiver<Settings>,
169    _observe_active_editor: Option<Subscription>,
170}
171
172impl CursorPosition {
173    pub fn new(settings: watch::Receiver<Settings>) -> Self {
174        Self {
175            position: None,
176            selected_count: 0,
177            settings,
178            _observe_active_editor: None,
179        }
180    }
181
182    fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
183        let editor = editor.read(cx);
184        let buffer = editor.buffer().read(cx);
185
186        self.selected_count = 0;
187        let mut last_selection: Option<Selection<usize>> = None;
188        for selection in editor.selections::<usize>(cx) {
189            self.selected_count += selection.end - selection.start;
190            if last_selection
191                .as_ref()
192                .map_or(true, |last_selection| selection.id > last_selection.id)
193            {
194                last_selection = Some(selection);
195            }
196        }
197        self.position = last_selection.map(|s| s.head().to_point(buffer));
198
199        cx.notify();
200    }
201}
202
203impl Entity for CursorPosition {
204    type Event = ();
205}
206
207impl View for CursorPosition {
208    fn ui_name() -> &'static str {
209        "CursorPosition"
210    }
211
212    fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
213        if let Some(position) = self.position {
214            let theme = &self.settings.borrow().theme.workspace.status_bar;
215            let mut text = format!("{},{}", position.row + 1, position.column + 1);
216            if self.selected_count > 0 {
217                write!(text, " ({} selected)", self.selected_count).unwrap();
218            }
219            Label::new(text, theme.cursor_position.clone()).boxed()
220        } else {
221            Empty::new().boxed()
222        }
223    }
224}
225
226impl StatusItemView for CursorPosition {
227    fn set_active_pane_item(
228        &mut self,
229        active_pane_item: Option<&dyn crate::ItemViewHandle>,
230        cx: &mut ViewContext<Self>,
231    ) {
232        if let Some(editor) = active_pane_item.and_then(|item| item.to_any().downcast::<Editor>()) {
233            self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
234            self.update_position(editor, cx);
235        } else {
236            self.position = None;
237            self._observe_active_editor = None;
238        }
239
240        cx.notify();
241    }
242}
243
244pub struct DiagnosticMessage {
245    settings: watch::Receiver<Settings>,
246    diagnostic: Option<Diagnostic>,
247    _observe_active_editor: Option<Subscription>,
248}
249
250impl DiagnosticMessage {
251    pub fn new(settings: watch::Receiver<Settings>) -> Self {
252        Self {
253            diagnostic: None,
254            settings,
255            _observe_active_editor: None,
256        }
257    }
258
259    fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
260        let editor = editor.read(cx);
261        let cursor_position = editor.newest_selection(cx).head();
262        let new_diagnostic = editor
263            .buffer()
264            .read(cx)
265            .diagnostics_in_range::<usize, usize>(cursor_position..cursor_position)
266            .filter(|(range, _)| !range.is_empty())
267            .min_by_key(|(range, diagnostic)| (diagnostic.severity, range.len()))
268            .map(|(_, diagnostic)| diagnostic.clone());
269        if new_diagnostic != self.diagnostic {
270            self.diagnostic = new_diagnostic;
271            cx.notify();
272        }
273    }
274}
275
276impl Entity for DiagnosticMessage {
277    type Event = ();
278}
279
280impl View for DiagnosticMessage {
281    fn ui_name() -> &'static str {
282        "DiagnosticMessage"
283    }
284
285    fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
286        if let Some(diagnostic) = &self.diagnostic {
287            let theme = &self.settings.borrow().theme.workspace.status_bar;
288            Flex::row()
289                .with_child(
290                    Svg::new("icons/warning.svg")
291                        .with_color(theme.diagnostic_icon_color)
292                        .constrained()
293                        .with_height(theme.diagnostic_icon_size)
294                        .contained()
295                        .with_margin_right(theme.diagnostic_icon_spacing)
296                        .boxed(),
297                )
298                .with_child(
299                    Label::new(
300                        diagnostic.message.lines().next().unwrap().to_string(),
301                        theme.diagnostic_message.clone(),
302                    )
303                    .boxed(),
304                )
305                .boxed()
306        } else {
307            Empty::new().boxed()
308        }
309    }
310}
311
312impl StatusItemView for DiagnosticMessage {
313    fn set_active_pane_item(
314        &mut self,
315        active_pane_item: Option<&dyn crate::ItemViewHandle>,
316        cx: &mut ViewContext<Self>,
317    ) {
318        if let Some(editor) = active_pane_item.and_then(|item| item.to_any().downcast::<Editor>()) {
319            self._observe_active_editor = Some(cx.observe(&editor, Self::update));
320            self.update(editor, cx);
321        } else {
322            self.diagnostic = Default::default();
323            self._observe_active_editor = None;
324        }
325        cx.notify();
326    }
327}