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
262            .selections::<usize>(cx)
263            .max_by_key(|selection| selection.id)
264            .unwrap()
265            .head();
266        let new_diagnostic = editor
267            .buffer()
268            .read(cx)
269            .diagnostics_in_range::<usize, usize>(cursor_position..cursor_position)
270            .min_by_key(|(range, diagnostic)| (diagnostic.severity, range.len()))
271            .map(|(_, diagnostic)| diagnostic.clone());
272        if new_diagnostic != self.diagnostic {
273            self.diagnostic = new_diagnostic;
274            cx.notify();
275        }
276    }
277}
278
279impl Entity for DiagnosticMessage {
280    type Event = ();
281}
282
283impl View for DiagnosticMessage {
284    fn ui_name() -> &'static str {
285        "DiagnosticMessage"
286    }
287
288    fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
289        if let Some(diagnostic) = &self.diagnostic {
290            let theme = &self.settings.borrow().theme.workspace.status_bar;
291            Flex::row()
292                .with_child(
293                    Svg::new("icons/warning.svg")
294                        .with_color(theme.diagnostic_icon_color)
295                        .constrained()
296                        .with_height(theme.diagnostic_icon_size)
297                        .contained()
298                        .with_margin_right(theme.diagnostic_icon_spacing)
299                        .boxed(),
300                )
301                .with_child(
302                    Label::new(
303                        diagnostic.message.replace('\n', " "),
304                        theme.diagnostic_message.clone(),
305                    )
306                    .boxed(),
307                )
308                .boxed()
309        } else {
310            Empty::new().boxed()
311        }
312    }
313}
314
315impl StatusItemView for DiagnosticMessage {
316    fn set_active_pane_item(
317        &mut self,
318        active_pane_item: Option<&dyn crate::ItemViewHandle>,
319        cx: &mut ViewContext<Self>,
320    ) {
321        if let Some(editor) = active_pane_item.and_then(|item| item.to_any().downcast::<Editor>()) {
322            self._observe_active_editor = Some(cx.observe(&editor, Self::update));
323            self.update(editor, cx);
324        } else {
325            self.diagnostic = Default::default();
326            self._observe_active_editor = None;
327        }
328        cx.notify();
329    }
330}