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