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(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
224        let buffer = self.buffer().clone();
225        cx.spawn(|editor, mut cx| async move {
226            buffer
227                .update(&mut cx, |buffer, cx| buffer.format(cx).log_err())
228                .await;
229            editor.update(&mut cx, |editor, cx| {
230                editor.request_autoscroll(Autoscroll::Fit, cx)
231            });
232            buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
233            Ok(())
234        })
235    }
236
237    fn can_save_as(&self, cx: &AppContext) -> bool {
238        self.buffer().read(cx).is_singleton()
239    }
240
241    fn save_as(
242        &mut self,
243        project: ModelHandle<Project>,
244        abs_path: PathBuf,
245        cx: &mut ViewContext<Self>,
246    ) -> Task<Result<()>> {
247        let buffer = self
248            .buffer()
249            .read(cx)
250            .as_singleton()
251            .expect("cannot call save_as on an excerpt list")
252            .clone();
253
254        project.update(cx, |project, cx| {
255            project.save_buffer_as(buffer, abs_path, cx)
256        })
257    }
258
259    fn should_activate_item_on_event(event: &Event) -> bool {
260        matches!(event, Event::Activate)
261    }
262
263    fn should_close_item_on_event(event: &Event) -> bool {
264        matches!(event, Event::Closed)
265    }
266
267    fn should_update_tab_on_event(event: &Event) -> bool {
268        matches!(event, Event::Saved | Event::Dirtied | Event::TitleChanged)
269    }
270}
271
272pub struct CursorPosition {
273    position: Option<Point>,
274    selected_count: usize,
275    settings: watch::Receiver<Settings>,
276    _observe_active_editor: Option<Subscription>,
277}
278
279impl CursorPosition {
280    pub fn new(settings: watch::Receiver<Settings>) -> Self {
281        Self {
282            position: None,
283            selected_count: 0,
284            settings,
285            _observe_active_editor: None,
286        }
287    }
288
289    fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
290        let editor = editor.read(cx);
291        let buffer = editor.buffer().read(cx).snapshot(cx);
292
293        self.selected_count = 0;
294        let mut last_selection: Option<Selection<usize>> = None;
295        for selection in editor.local_selections::<usize>(cx) {
296            self.selected_count += selection.end - selection.start;
297            if last_selection
298                .as_ref()
299                .map_or(true, |last_selection| selection.id > last_selection.id)
300            {
301                last_selection = Some(selection);
302            }
303        }
304        self.position = last_selection.map(|s| s.head().to_point(&buffer));
305
306        cx.notify();
307    }
308}
309
310impl Entity for CursorPosition {
311    type Event = ();
312}
313
314impl View for CursorPosition {
315    fn ui_name() -> &'static str {
316        "CursorPosition"
317    }
318
319    fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
320        if let Some(position) = self.position {
321            let theme = &self.settings.borrow().theme.workspace.status_bar;
322            let mut text = format!("{},{}", position.row + 1, position.column + 1);
323            if self.selected_count > 0 {
324                write!(text, " ({} selected)", self.selected_count).unwrap();
325            }
326            Label::new(text, theme.cursor_position.clone()).boxed()
327        } else {
328            Empty::new().boxed()
329        }
330    }
331}
332
333impl StatusItemView for CursorPosition {
334    fn set_active_pane_item(
335        &mut self,
336        active_pane_item: Option<&dyn ItemViewHandle>,
337        cx: &mut ViewContext<Self>,
338    ) {
339        if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
340            self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
341            self.update_position(editor, cx);
342        } else {
343            self.position = None;
344            self._observe_active_editor = None;
345        }
346
347        cx.notify();
348    }
349}
350
351pub struct DiagnosticMessage {
352    settings: watch::Receiver<Settings>,
353    diagnostic: Option<Diagnostic>,
354    _observe_active_editor: Option<Subscription>,
355}
356
357impl DiagnosticMessage {
358    pub fn new(settings: watch::Receiver<Settings>) -> Self {
359        Self {
360            diagnostic: None,
361            settings,
362            _observe_active_editor: None,
363        }
364    }
365
366    fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
367        let editor = editor.read(cx);
368        let buffer = editor.buffer().read(cx);
369        let cursor_position = editor.newest_selection::<usize>(&buffer.read(cx)).head();
370        let new_diagnostic = buffer
371            .read(cx)
372            .diagnostics_in_range::<_, usize>(cursor_position..cursor_position)
373            .filter(|entry| !entry.range.is_empty())
374            .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
375            .map(|entry| entry.diagnostic);
376        if new_diagnostic != self.diagnostic {
377            self.diagnostic = new_diagnostic;
378            cx.notify();
379        }
380    }
381}
382
383impl Entity for DiagnosticMessage {
384    type Event = ();
385}
386
387impl View for DiagnosticMessage {
388    fn ui_name() -> &'static str {
389        "DiagnosticMessage"
390    }
391
392    fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
393        if let Some(diagnostic) = &self.diagnostic {
394            let theme = &self.settings.borrow().theme.workspace.status_bar;
395            Label::new(
396                diagnostic.message.lines().next().unwrap().to_string(),
397                theme.diagnostic_message.clone(),
398            )
399            .contained()
400            .with_margin_left(theme.item_spacing)
401            .boxed()
402        } else {
403            Empty::new().boxed()
404        }
405    }
406}
407
408impl StatusItemView for DiagnosticMessage {
409    fn set_active_pane_item(
410        &mut self,
411        active_pane_item: Option<&dyn ItemViewHandle>,
412        cx: &mut ViewContext<Self>,
413    ) {
414        if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
415            self._observe_active_editor = Some(cx.observe(&editor, Self::update));
416            self.update(editor, cx);
417        } else {
418            self.diagnostic = Default::default();
419            self._observe_active_editor = None;
420        }
421        cx.notify();
422    }
423}