items.rs

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