items.rs

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