items.rs

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