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