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