items.rs

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