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 tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
106        let title = self.title(cx);
107        Label::new(title, style.label.clone()).boxed()
108    }
109
110    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
111        File::from_dyn(self.buffer().read(cx).file(cx)).map(|file| ProjectPath {
112            worktree_id: file.worktree_id(cx),
113            path: file.path().clone(),
114        })
115    }
116
117    fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
118    where
119        Self: Sized,
120    {
121        Some(self.clone(cx))
122    }
123
124    fn is_dirty(&self, cx: &AppContext) -> bool {
125        self.buffer().read(cx).read(cx).is_dirty()
126    }
127
128    fn has_conflict(&self, cx: &AppContext) -> bool {
129        self.buffer().read(cx).read(cx).has_conflict()
130    }
131
132    fn can_save(&self, cx: &AppContext) -> bool {
133        self.project_path(cx).is_some()
134    }
135
136    fn save(&mut self, cx: &mut ViewContext<Self>) -> Result<Task<Result<()>>> {
137        let buffer = self.buffer().clone();
138        Ok(cx.spawn(|editor, mut cx| async move {
139            buffer
140                .update(&mut cx, |buffer, cx| buffer.format(cx).log_err())
141                .await;
142            editor.update(&mut cx, |editor, cx| {
143                editor.request_autoscroll(Autoscroll::Fit, cx)
144            });
145            buffer
146                .update(&mut cx, |buffer, cx| buffer.save(cx))?
147                .await?;
148            Ok(())
149        }))
150    }
151
152    fn can_save_as(&self, _: &AppContext) -> bool {
153        true
154    }
155
156    fn save_as(
157        &mut self,
158        worktree: ModelHandle<Worktree>,
159        path: &Path,
160        cx: &mut ViewContext<Self>,
161    ) -> Task<Result<()>> {
162        let buffer = self
163            .buffer()
164            .read(cx)
165            .as_singleton()
166            .expect("cannot call save_as on an excerpt list")
167            .clone();
168
169        buffer.update(cx, |buffer, cx| {
170            let handle = cx.handle();
171            let text = buffer.as_rope().clone();
172            let version = buffer.version();
173
174            let save_as = worktree.update(cx, |worktree, cx| {
175                worktree
176                    .as_local_mut()
177                    .unwrap()
178                    .save_buffer_as(handle, path, text, cx)
179            });
180
181            cx.spawn(|buffer, mut cx| async move {
182                save_as.await.map(|new_file| {
183                    let (language, language_server) = worktree.update(&mut cx, |worktree, cx| {
184                        let worktree = worktree.as_local_mut().unwrap();
185                        let language = worktree
186                            .language_registry()
187                            .select_language(new_file.full_path())
188                            .cloned();
189                        let language_server = language
190                            .as_ref()
191                            .and_then(|language| worktree.register_language(language, cx));
192                        (language, language_server.clone())
193                    });
194
195                    buffer.update(&mut cx, |buffer, cx| {
196                        buffer.did_save(version, new_file.mtime, Some(Box::new(new_file)), cx);
197                        buffer.set_language(language, language_server, cx);
198                    });
199                })
200            })
201        })
202    }
203
204    fn should_activate_item_on_event(event: &Event) -> bool {
205        matches!(event, Event::Activate)
206    }
207
208    fn should_close_item_on_event(event: &Event) -> bool {
209        matches!(event, Event::Closed)
210    }
211
212    fn should_update_tab_on_event(event: &Event) -> bool {
213        matches!(event, Event::Saved | Event::Dirtied | Event::TitleChanged)
214    }
215}
216
217pub struct CursorPosition {
218    position: Option<Point>,
219    selected_count: usize,
220    settings: watch::Receiver<Settings>,
221    _observe_active_editor: Option<Subscription>,
222}
223
224impl CursorPosition {
225    pub fn new(settings: watch::Receiver<Settings>) -> Self {
226        Self {
227            position: None,
228            selected_count: 0,
229            settings,
230            _observe_active_editor: None,
231        }
232    }
233
234    fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
235        let editor = editor.read(cx);
236        let buffer = editor.buffer().read(cx).snapshot(cx);
237
238        self.selected_count = 0;
239        let mut last_selection: Option<Selection<usize>> = None;
240        for selection in editor.local_selections::<usize>(cx) {
241            self.selected_count += selection.end - selection.start;
242            if last_selection
243                .as_ref()
244                .map_or(true, |last_selection| selection.id > last_selection.id)
245            {
246                last_selection = Some(selection);
247            }
248        }
249        self.position = last_selection.map(|s| s.head().to_point(&buffer));
250
251        cx.notify();
252    }
253}
254
255impl Entity for CursorPosition {
256    type Event = ();
257}
258
259impl View for CursorPosition {
260    fn ui_name() -> &'static str {
261        "CursorPosition"
262    }
263
264    fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
265        if let Some(position) = self.position {
266            let theme = &self.settings.borrow().theme.workspace.status_bar;
267            let mut text = format!("{},{}", position.row + 1, position.column + 1);
268            if self.selected_count > 0 {
269                write!(text, " ({} selected)", self.selected_count).unwrap();
270            }
271            Label::new(text, theme.cursor_position.clone()).boxed()
272        } else {
273            Empty::new().boxed()
274        }
275    }
276}
277
278impl StatusItemView for CursorPosition {
279    fn set_active_pane_item(
280        &mut self,
281        active_pane_item: Option<&dyn ItemViewHandle>,
282        cx: &mut ViewContext<Self>,
283    ) {
284        if let Some(editor) = active_pane_item.and_then(|item| item.to_any().downcast::<Editor>()) {
285            self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
286            self.update_position(editor, cx);
287        } else {
288            self.position = None;
289            self._observe_active_editor = None;
290        }
291
292        cx.notify();
293    }
294}
295
296pub struct DiagnosticMessage {
297    settings: watch::Receiver<Settings>,
298    diagnostic: Option<Diagnostic>,
299    _observe_active_editor: Option<Subscription>,
300}
301
302impl DiagnosticMessage {
303    pub fn new(settings: watch::Receiver<Settings>) -> Self {
304        Self {
305            diagnostic: None,
306            settings,
307            _observe_active_editor: None,
308        }
309    }
310
311    fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
312        let editor = editor.read(cx);
313        let buffer = editor.buffer().read(cx);
314        let cursor_position = editor.newest_selection::<usize>(&buffer.read(cx)).head();
315        let new_diagnostic = buffer
316            .read(cx)
317            .diagnostics_in_range::<_, usize>(cursor_position..cursor_position)
318            .filter(|entry| !entry.range.is_empty())
319            .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
320            .map(|entry| entry.diagnostic);
321        if new_diagnostic != self.diagnostic {
322            self.diagnostic = new_diagnostic;
323            cx.notify();
324        }
325    }
326}
327
328impl Entity for DiagnosticMessage {
329    type Event = ();
330}
331
332impl View for DiagnosticMessage {
333    fn ui_name() -> &'static str {
334        "DiagnosticMessage"
335    }
336
337    fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
338        if let Some(diagnostic) = &self.diagnostic {
339            let theme = &self.settings.borrow().theme.workspace.status_bar;
340            Flex::row()
341                .with_child(
342                    Svg::new("icons/warning.svg")
343                        .with_color(theme.diagnostic_icon_color)
344                        .constrained()
345                        .with_height(theme.diagnostic_icon_size)
346                        .contained()
347                        .with_margin_right(theme.diagnostic_icon_spacing)
348                        .boxed(),
349                )
350                .with_child(
351                    Label::new(
352                        diagnostic.message.lines().next().unwrap().to_string(),
353                        theme.diagnostic_message.clone(),
354                    )
355                    .boxed(),
356                )
357                .boxed()
358        } else {
359            Empty::new().boxed()
360        }
361    }
362}
363
364impl StatusItemView for DiagnosticMessage {
365    fn set_active_pane_item(
366        &mut self,
367        active_pane_item: Option<&dyn ItemViewHandle>,
368        cx: &mut ViewContext<Self>,
369    ) {
370        if let Some(editor) = active_pane_item.and_then(|item| item.to_any().downcast::<Editor>()) {
371            self._observe_active_editor = Some(cx.observe(&editor, Self::update));
372            self.update(editor, cx);
373        } else {
374            self.diagnostic = Default::default();
375            self._observe_active_editor = None;
376        }
377        cx.notify();
378    }
379}