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 project::{File, Project, ProjectPath};
  9use std::path::PathBuf;
 10use std::rc::Rc;
 11use std::{cell::RefCell, fmt::Write};
 12use text::{Point, Selection};
 13use util::ResultExt;
 14use workspace::{
 15    ItemHandle, ItemNavHistory, ItemView, ItemViewHandle, NavHistory, PathOpener, Settings,
 16    StatusItemView, WeakItemHandle, 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
 27#[derive(Clone)]
 28pub struct MultiBufferItemHandle(pub ModelHandle<MultiBuffer>);
 29
 30#[derive(Clone)]
 31struct WeakMultiBufferItemHandle(WeakModelHandle<MultiBuffer>);
 32
 33impl PathOpener for BufferOpener {
 34    fn open(
 35        &self,
 36        project: &mut Project,
 37        project_path: ProjectPath,
 38        cx: &mut ModelContext<Project>,
 39    ) -> Option<Task<Result<Box<dyn ItemHandle>>>> {
 40        let buffer = project.open_buffer(project_path, cx);
 41        let task = cx.spawn(|_, _| async move {
 42            let buffer = buffer.await?;
 43            Ok(Box::new(BufferItemHandle(buffer)) as Box<dyn ItemHandle>)
 44        });
 45        Some(task)
 46    }
 47}
 48
 49impl ItemHandle for BufferItemHandle {
 50    fn add_view(
 51        &self,
 52        window_id: usize,
 53        workspace: &Workspace,
 54        nav_history: Rc<RefCell<NavHistory>>,
 55        cx: &mut MutableAppContext,
 56    ) -> Box<dyn ItemViewHandle> {
 57        let buffer = cx.add_model(|cx| MultiBuffer::singleton(self.0.clone(), cx));
 58        Box::new(cx.add_view(window_id, |cx| {
 59            let mut editor = Editor::for_buffer(buffer, Some(workspace.project().clone()), cx);
 60            editor.nav_history = Some(ItemNavHistory::new(nav_history, &cx.handle()));
 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 ItemHandle for MultiBufferItemHandle {
 90    fn add_view(
 91        &self,
 92        window_id: usize,
 93        workspace: &Workspace,
 94        nav_history: Rc<RefCell<NavHistory>>,
 95        cx: &mut MutableAppContext,
 96    ) -> Box<dyn ItemViewHandle> {
 97        Box::new(cx.add_view(window_id, |cx| {
 98            let mut editor =
 99                Editor::for_buffer(self.0.clone(), Some(workspace.project().clone()), cx);
100            editor.nav_history = Some(ItemNavHistory::new(nav_history, &cx.handle()));
101            editor
102        }))
103    }
104
105    fn boxed_clone(&self) -> Box<dyn ItemHandle> {
106        Box::new(self.clone())
107    }
108
109    fn to_any(&self) -> gpui::AnyModelHandle {
110        self.0.clone().into()
111    }
112
113    fn downgrade(&self) -> Box<dyn WeakItemHandle> {
114        Box::new(WeakMultiBufferItemHandle(self.0.downgrade()))
115    }
116
117    fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
118        None
119    }
120
121    fn id(&self) -> usize {
122        self.0.id()
123    }
124}
125
126impl WeakItemHandle for WeakBufferItemHandle {
127    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
128        self.0
129            .upgrade(cx)
130            .map(|buffer| Box::new(BufferItemHandle(buffer)) as Box<dyn ItemHandle>)
131    }
132
133    fn id(&self) -> usize {
134        self.0.id()
135    }
136}
137
138impl WeakItemHandle for WeakMultiBufferItemHandle {
139    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
140        self.0
141            .upgrade(cx)
142            .map(|buffer| Box::new(MultiBufferItemHandle(buffer)) as Box<dyn ItemHandle>)
143    }
144
145    fn id(&self) -> usize {
146        self.0.id()
147    }
148}
149
150impl ItemView for Editor {
151    fn item(&self, cx: &AppContext) -> Box<dyn ItemHandle> {
152        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
153            Box::new(BufferItemHandle(buffer))
154        } else {
155            Box::new(MultiBufferItemHandle(self.buffer.clone()))
156        }
157    }
158
159    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) {
160        if let Some(data) = data.downcast_ref::<NavigationData>() {
161            let buffer = self.buffer.read(cx).read(cx);
162            let offset = if buffer.can_resolve(&data.anchor) {
163                data.anchor.to_offset(&buffer)
164            } else {
165                buffer.clip_offset(data.offset, Bias::Left)
166            };
167
168            drop(buffer);
169            let nav_history = self.nav_history.take();
170            self.select_ranges([offset..offset], Some(Autoscroll::Fit), cx);
171            self.nav_history = nav_history;
172        }
173    }
174
175    fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
176        let title = self.title(cx);
177        Label::new(title, style.label.clone()).boxed()
178    }
179
180    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
181        File::from_dyn(self.buffer().read(cx).file(cx)).map(|file| ProjectPath {
182            worktree_id: file.worktree_id(cx),
183            path: file.path().clone(),
184        })
185    }
186
187    fn clone_on_split(
188        &self,
189        nav_history: ItemNavHistory,
190        cx: &mut ViewContext<Self>,
191    ) -> Option<Self>
192    where
193        Self: Sized,
194    {
195        Some(self.clone(nav_history, cx))
196    }
197
198    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
199        let selection = self.newest_anchor_selection();
200        self.push_to_nav_history(selection.head(), None, cx);
201    }
202
203    fn is_dirty(&self, cx: &AppContext) -> bool {
204        self.buffer().read(cx).read(cx).is_dirty()
205    }
206
207    fn has_conflict(&self, cx: &AppContext) -> bool {
208        self.buffer().read(cx).read(cx).has_conflict()
209    }
210
211    fn can_save(&self, cx: &AppContext) -> bool {
212        !self.buffer().read(cx).is_singleton() || self.project_path(cx).is_some()
213    }
214
215    fn save(
216        &mut self,
217        project: ModelHandle<Project>,
218        cx: &mut ViewContext<Self>,
219    ) -> Task<Result<()>> {
220        let buffer = self.buffer().clone();
221        let buffers = buffer.read(cx).all_buffers();
222        let transaction = project.update(cx, |project, cx| project.format(buffers, true, cx));
223        cx.spawn(|this, mut cx| async move {
224            let transaction = transaction.await.log_err();
225            this.update(&mut cx, |editor, cx| {
226                editor.request_autoscroll(Autoscroll::Fit, cx)
227            });
228            buffer
229                .update(&mut cx, |buffer, cx| {
230                    if let Some(transaction) = transaction {
231                        if !buffer.is_singleton() {
232                            buffer.push_transaction(&transaction.0);
233                        }
234                    }
235
236                    buffer.save(cx)
237                })
238                .await?;
239            Ok(())
240        })
241    }
242
243    fn can_save_as(&self, cx: &AppContext) -> bool {
244        self.buffer().read(cx).is_singleton()
245    }
246
247    fn save_as(
248        &mut self,
249        project: ModelHandle<Project>,
250        abs_path: PathBuf,
251        cx: &mut ViewContext<Self>,
252    ) -> Task<Result<()>> {
253        let buffer = self
254            .buffer()
255            .read(cx)
256            .as_singleton()
257            .expect("cannot call save_as on an excerpt list")
258            .clone();
259
260        project.update(cx, |project, cx| {
261            project.save_buffer_as(buffer, abs_path, cx)
262        })
263    }
264
265    fn should_activate_item_on_event(event: &Event) -> bool {
266        matches!(event, Event::Activate)
267    }
268
269    fn should_close_item_on_event(event: &Event) -> bool {
270        matches!(event, Event::Closed)
271    }
272
273    fn should_update_tab_on_event(event: &Event) -> bool {
274        matches!(event, Event::Saved | Event::Dirtied | Event::TitleChanged)
275    }
276}
277
278pub struct CursorPosition {
279    position: Option<Point>,
280    selected_count: usize,
281    _observe_active_editor: Option<Subscription>,
282}
283
284impl CursorPosition {
285    pub fn new() -> Self {
286        Self {
287            position: None,
288            selected_count: 0,
289            _observe_active_editor: None,
290        }
291    }
292
293    fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
294        let editor = editor.read(cx);
295        let buffer = editor.buffer().read(cx).snapshot(cx);
296
297        self.selected_count = 0;
298        let mut last_selection: Option<Selection<usize>> = None;
299        for selection in editor.local_selections::<usize>(cx) {
300            self.selected_count += selection.end - selection.start;
301            if last_selection
302                .as_ref()
303                .map_or(true, |last_selection| selection.id > last_selection.id)
304            {
305                last_selection = Some(selection);
306            }
307        }
308        self.position = last_selection.map(|s| s.head().to_point(&buffer));
309
310        cx.notify();
311    }
312}
313
314impl Entity for CursorPosition {
315    type Event = ();
316}
317
318impl View for CursorPosition {
319    fn ui_name() -> &'static str {
320        "CursorPosition"
321    }
322
323    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
324        if let Some(position) = self.position {
325            let theme = &cx.app_state::<Settings>().theme.workspace.status_bar;
326            let mut text = format!("{},{}", position.row + 1, position.column + 1);
327            if self.selected_count > 0 {
328                write!(text, " ({} selected)", self.selected_count).unwrap();
329            }
330            Label::new(text, theme.cursor_position.clone()).boxed()
331        } else {
332            Empty::new().boxed()
333        }
334    }
335}
336
337impl StatusItemView for CursorPosition {
338    fn set_active_pane_item(
339        &mut self,
340        active_pane_item: Option<&dyn ItemViewHandle>,
341        cx: &mut ViewContext<Self>,
342    ) {
343        if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
344            self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
345            self.update_position(editor, cx);
346        } else {
347            self.position = None;
348            self._observe_active_editor = None;
349        }
350
351        cx.notify();
352    }
353}
354
355pub struct DiagnosticMessage {
356    diagnostic: Option<Diagnostic>,
357    _observe_active_editor: Option<Subscription>,
358}
359
360impl DiagnosticMessage {
361    pub fn new() -> Self {
362        Self {
363            diagnostic: None,
364            _observe_active_editor: None,
365        }
366    }
367
368    fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
369        let editor = editor.read(cx);
370        let buffer = editor.buffer().read(cx);
371        let cursor_position = editor
372            .newest_selection_with_snapshot::<usize>(&buffer.read(cx))
373            .head();
374        let new_diagnostic = buffer
375            .read(cx)
376            .diagnostics_in_range::<_, usize>(cursor_position..cursor_position)
377            .filter(|entry| !entry.range.is_empty())
378            .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
379            .map(|entry| entry.diagnostic);
380        if new_diagnostic != self.diagnostic {
381            self.diagnostic = new_diagnostic;
382            cx.notify();
383        }
384    }
385}
386
387impl Entity for DiagnosticMessage {
388    type Event = ();
389}
390
391impl View for DiagnosticMessage {
392    fn ui_name() -> &'static str {
393        "DiagnosticMessage"
394    }
395
396    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
397        if let Some(diagnostic) = &self.diagnostic {
398            let theme = &cx.app_state::<Settings>().theme.workspace.status_bar;
399            Label::new(
400                diagnostic.message.split('\n').next().unwrap().to_string(),
401                theme.diagnostic_message.clone(),
402            )
403            .boxed()
404        } else {
405            Empty::new().boxed()
406        }
407    }
408}
409
410impl StatusItemView for DiagnosticMessage {
411    fn set_active_pane_item(
412        &mut self,
413        active_pane_item: Option<&dyn ItemViewHandle>,
414        cx: &mut ViewContext<Self>,
415    ) {
416        if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
417            self._observe_active_editor = Some(cx.observe(&editor, Self::update));
418            self.update(editor, cx);
419        } else {
420            self.diagnostic = Default::default();
421            self._observe_active_editor = None;
422        }
423        cx.notify();
424    }
425}