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::TryFutureExt;
 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        let weak_buffer = buffer.downgrade();
 60        Box::new(cx.add_view(window_id, |cx| {
 61            let mut editor = Editor::for_buffer(
 62                buffer,
 63                crate::settings_builder(weak_buffer, workspace.settings()),
 64                Some(workspace.project().clone()),
 65                cx,
 66            );
 67            editor.nav_history = Some(ItemNavHistory::new(nav_history, &cx.handle()));
 68            editor
 69        }))
 70    }
 71
 72    fn boxed_clone(&self) -> Box<dyn ItemHandle> {
 73        Box::new(self.clone())
 74    }
 75
 76    fn to_any(&self) -> gpui::AnyModelHandle {
 77        self.0.clone().into()
 78    }
 79
 80    fn downgrade(&self) -> Box<dyn workspace::WeakItemHandle> {
 81        Box::new(WeakBufferItemHandle(self.0.downgrade()))
 82    }
 83
 84    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
 85        File::from_dyn(self.0.read(cx).file()).map(|f| ProjectPath {
 86            worktree_id: f.worktree_id(cx),
 87            path: f.path().clone(),
 88        })
 89    }
 90
 91    fn id(&self) -> usize {
 92        self.0.id()
 93    }
 94}
 95
 96impl ItemHandle for MultiBufferItemHandle {
 97    fn add_view(
 98        &self,
 99        window_id: usize,
100        workspace: &Workspace,
101        nav_history: Rc<RefCell<NavHistory>>,
102        cx: &mut MutableAppContext,
103    ) -> Box<dyn ItemViewHandle> {
104        let weak_buffer = self.0.downgrade();
105        Box::new(cx.add_view(window_id, |cx| {
106            let mut editor = Editor::for_buffer(
107                self.0.clone(),
108                crate::settings_builder(weak_buffer, workspace.settings()),
109                Some(workspace.project().clone()),
110                cx,
111            );
112            editor.nav_history = Some(ItemNavHistory::new(nav_history, &cx.handle()));
113            editor
114        }))
115    }
116
117    fn boxed_clone(&self) -> Box<dyn ItemHandle> {
118        Box::new(self.clone())
119    }
120
121    fn to_any(&self) -> gpui::AnyModelHandle {
122        self.0.clone().into()
123    }
124
125    fn downgrade(&self) -> Box<dyn WeakItemHandle> {
126        Box::new(WeakMultiBufferItemHandle(self.0.downgrade()))
127    }
128
129    fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
130        None
131    }
132
133    fn id(&self) -> usize {
134        self.0.id()
135    }
136}
137
138impl WeakItemHandle for WeakBufferItemHandle {
139    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
140        self.0
141            .upgrade(cx)
142            .map(|buffer| Box::new(BufferItemHandle(buffer)) as Box<dyn ItemHandle>)
143    }
144
145    fn id(&self) -> usize {
146        self.0.id()
147    }
148}
149
150impl WeakItemHandle for WeakMultiBufferItemHandle {
151    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
152        self.0
153            .upgrade(cx)
154            .map(|buffer| Box::new(MultiBufferItemHandle(buffer)) as Box<dyn ItemHandle>)
155    }
156
157    fn id(&self) -> usize {
158        self.0.id()
159    }
160}
161
162impl ItemView for Editor {
163    fn item_id(&self, cx: &AppContext) -> usize {
164        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
165            buffer.id()
166        } else {
167            self.buffer.id()
168        }
169    }
170
171    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) {
172        if let Some(data) = data.downcast_ref::<NavigationData>() {
173            let buffer = self.buffer.read(cx).read(cx);
174            let offset = if buffer.can_resolve(&data.anchor) {
175                data.anchor.to_offset(&buffer)
176            } else {
177                buffer.clip_offset(data.offset, Bias::Left)
178            };
179
180            drop(buffer);
181            let nav_history = self.nav_history.take();
182            self.select_ranges([offset..offset], Some(Autoscroll::Fit), cx);
183            self.nav_history = nav_history;
184        }
185    }
186
187    fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
188        let title = self.title(cx);
189        Label::new(title, style.label.clone()).boxed()
190    }
191
192    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
193        File::from_dyn(self.buffer().read(cx).file(cx)).map(|file| ProjectPath {
194            worktree_id: file.worktree_id(cx),
195            path: file.path().clone(),
196        })
197    }
198
199    fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
200    where
201        Self: Sized,
202    {
203        Some(self.clone(cx))
204    }
205
206    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
207        let selection = self.newest_anchor_selection();
208        self.push_to_nav_history(selection.head(), None, cx);
209    }
210
211    fn is_dirty(&self, cx: &AppContext) -> bool {
212        self.buffer().read(cx).read(cx).is_dirty()
213    }
214
215    fn has_conflict(&self, cx: &AppContext) -> bool {
216        self.buffer().read(cx).read(cx).has_conflict()
217    }
218
219    fn can_save(&self, cx: &AppContext) -> bool {
220        !self.buffer().read(cx).is_singleton() || self.project_path(cx).is_some()
221    }
222
223    fn save(
224        &mut self,
225        project: ModelHandle<Project>,
226        cx: &mut ViewContext<Self>,
227    ) -> Task<Result<()>> {
228        let buffer = self.buffer().clone();
229        cx.spawn(|editor, mut cx| async move {
230            buffer
231                .update(&mut cx, |buffer, cx| buffer.format(project, cx).log_err())
232                .await;
233            editor.update(&mut cx, |editor, cx| {
234                editor.request_autoscroll(Autoscroll::Fit, cx)
235            });
236            buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
237            Ok(())
238        })
239    }
240
241    fn can_save_as(&self, cx: &AppContext) -> bool {
242        self.buffer().read(cx).is_singleton()
243    }
244
245    fn save_as(
246        &mut self,
247        project: ModelHandle<Project>,
248        abs_path: PathBuf,
249        cx: &mut ViewContext<Self>,
250    ) -> Task<Result<()>> {
251        let buffer = self
252            .buffer()
253            .read(cx)
254            .as_singleton()
255            .expect("cannot call save_as on an excerpt list")
256            .clone();
257
258        project.update(cx, |project, cx| {
259            project.save_buffer_as(buffer, abs_path, cx)
260        })
261    }
262
263    fn should_activate_item_on_event(event: &Event) -> bool {
264        matches!(event, Event::Activate)
265    }
266
267    fn should_close_item_on_event(event: &Event) -> bool {
268        matches!(event, Event::Closed)
269    }
270
271    fn should_update_tab_on_event(event: &Event) -> bool {
272        matches!(event, Event::Saved | Event::Dirtied | Event::TitleChanged)
273    }
274}
275
276pub struct CursorPosition {
277    position: Option<Point>,
278    selected_count: usize,
279    settings: watch::Receiver<Settings>,
280    _observe_active_editor: Option<Subscription>,
281}
282
283impl CursorPosition {
284    pub fn new(settings: watch::Receiver<Settings>) -> Self {
285        Self {
286            position: None,
287            selected_count: 0,
288            settings,
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, _: &mut RenderContext<Self>) -> ElementBox {
324        if let Some(position) = self.position {
325            let theme = &self.settings.borrow().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    settings: watch::Receiver<Settings>,
357    diagnostic: Option<Diagnostic>,
358    _observe_active_editor: Option<Subscription>,
359}
360
361impl DiagnosticMessage {
362    pub fn new(settings: watch::Receiver<Settings>) -> Self {
363        Self {
364            diagnostic: None,
365            settings,
366            _observe_active_editor: None,
367        }
368    }
369
370    fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
371        let editor = editor.read(cx);
372        let buffer = editor.buffer().read(cx);
373        let cursor_position = editor.newest_selection::<usize>(&buffer.read(cx)).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, _: &mut RenderContext<Self>) -> ElementBox {
397        if let Some(diagnostic) = &self.diagnostic {
398            let theme = &self.settings.borrow().theme.workspace.status_bar;
399            Label::new(
400                diagnostic.message.split('\n').next().unwrap().to_string(),
401                theme.diagnostic_message.clone(),
402            )
403            .contained()
404            .with_margin_left(theme.item_spacing)
405            .boxed()
406        } else {
407            Empty::new().boxed()
408        }
409    }
410}
411
412impl StatusItemView for DiagnosticMessage {
413    fn set_active_pane_item(
414        &mut self,
415        active_pane_item: Option<&dyn ItemViewHandle>,
416        cx: &mut ViewContext<Self>,
417    ) {
418        if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
419            self._observe_active_editor = Some(cx.observe(&editor, Self::update));
420            self.update(editor, cx);
421        } else {
422            self.diagnostic = Default::default();
423            self._observe_active_editor = None;
424        }
425        cx.notify();
426    }
427}