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};
  8use postage::watch;
  9use project::worktree::File;
 10use project::{Project, ProjectEntry, ProjectPath, Worktree};
 11use std::rc::Rc;
 12use std::{fmt::Write, path::PathBuf};
 13use text::{Point, Selection};
 14use util::TryFutureExt;
 15use workspace::{
 16    ItemHandle, ItemView, ItemViewHandle, NavHistory, 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        nav_history: Rc<NavHistory>,
 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.nav_history = Some(nav_history);
 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_entry(&self, cx: &AppContext) -> Option<ProjectEntry> {
 78        File::from_dyn(self.0.read(cx).file()).and_then(|f| f.project_entry(cx))
 79    }
 80
 81    fn id(&self) -> usize {
 82        self.0.id()
 83    }
 84}
 85
 86impl WeakItemHandle for WeakBufferItemHandle {
 87    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
 88        self.0
 89            .upgrade(cx)
 90            .map(|buffer| Box::new(BufferItemHandle(buffer)) as Box<dyn ItemHandle>)
 91    }
 92
 93    fn id(&self) -> usize {
 94        self.0.id()
 95    }
 96}
 97
 98impl ItemView for Editor {
 99    type ItemHandle = BufferItemHandle;
100
101    fn item_handle(&self, cx: &AppContext) -> Self::ItemHandle {
102        BufferItemHandle(self.buffer.read(cx).as_singleton().unwrap())
103    }
104
105    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) {
106        if let Some(data) = data.downcast_ref::<NavigationData>() {
107            let buffer = self.buffer.read(cx).read(cx);
108            let offset = if buffer.can_resolve(&data.anchor) {
109                data.anchor.to_offset(&buffer)
110            } else {
111                buffer.clip_offset(data.offset, Bias::Left)
112            };
113
114            drop(buffer);
115            let nav_history = self.nav_history.take();
116            self.select_ranges([offset..offset], Some(Autoscroll::Fit), cx);
117            self.nav_history = nav_history;
118        }
119    }
120
121    fn title(&self, cx: &AppContext) -> String {
122        let filename = self
123            .buffer()
124            .read(cx)
125            .file(cx)
126            .and_then(|file| file.file_name());
127        if let Some(name) = filename {
128            name.to_string_lossy().into()
129        } else {
130            "untitled".into()
131        }
132    }
133
134    fn project_entry(&self, cx: &AppContext) -> Option<ProjectEntry> {
135        File::from_dyn(self.buffer().read(cx).file(cx)).and_then(|file| file.project_entry(cx))
136    }
137
138    fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
139    where
140        Self: Sized,
141    {
142        Some(self.clone(cx))
143    }
144
145    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
146        if let Some(selection) = self.newest_selection_internal() {
147            self.push_to_nav_history(selection.head(), None, cx);
148        }
149    }
150
151    fn is_dirty(&self, cx: &AppContext) -> bool {
152        self.buffer().read(cx).read(cx).is_dirty()
153    }
154
155    fn has_conflict(&self, cx: &AppContext) -> bool {
156        self.buffer().read(cx).read(cx).has_conflict()
157    }
158
159    fn can_save(&self, cx: &AppContext) -> bool {
160        self.project_entry(cx).is_some()
161    }
162
163    fn save(&mut self, cx: &mut ViewContext<Self>) -> Result<Task<Result<()>>> {
164        let buffer = self.buffer().clone();
165        Ok(cx.spawn(|editor, mut cx| async move {
166            buffer
167                .update(&mut cx, |buffer, cx| buffer.format(cx).log_err())
168                .await;
169            editor.update(&mut cx, |editor, cx| {
170                editor.request_autoscroll(Autoscroll::Fit, cx)
171            });
172            buffer
173                .update(&mut cx, |buffer, cx| buffer.save(cx))?
174                .await?;
175            Ok(())
176        }))
177    }
178
179    fn can_save_as(&self, _: &AppContext) -> bool {
180        true
181    }
182
183    fn save_as(
184        &mut self,
185        project: ModelHandle<Project>,
186        abs_path: PathBuf,
187        cx: &mut ViewContext<Self>,
188    ) -> Task<Result<()>> {
189        let buffer = self
190            .buffer()
191            .read(cx)
192            .as_singleton()
193            .expect("cannot call save_as on an excerpt list")
194            .clone();
195
196        project.update(cx, |project, cx| {
197            project.save_buffer_as(buffer, &abs_path, cx)
198        })
199    }
200
201    fn should_activate_item_on_event(event: &Event) -> bool {
202        matches!(event, Event::Activate)
203    }
204
205    fn should_close_item_on_event(event: &Event) -> bool {
206        matches!(event, Event::Closed)
207    }
208
209    fn should_update_tab_on_event(event: &Event) -> bool {
210        matches!(
211            event,
212            Event::Saved | Event::Dirtied | Event::FileHandleChanged
213        )
214    }
215}
216
217pub struct CursorPosition {
218    position: Option<Point>,
219    selected_count: usize,
220    settings: watch::Receiver<Settings>,
221    _observe_active_editor: Option<Subscription>,
222}
223
224impl CursorPosition {
225    pub fn new(settings: watch::Receiver<Settings>) -> Self {
226        Self {
227            position: None,
228            selected_count: 0,
229            settings,
230            _observe_active_editor: None,
231        }
232    }
233
234    fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
235        let editor = editor.read(cx);
236        let buffer = editor.buffer().read(cx).snapshot(cx);
237
238        self.selected_count = 0;
239        let mut last_selection: Option<Selection<usize>> = None;
240        for selection in editor.local_selections::<usize>(cx) {
241            self.selected_count += selection.end - selection.start;
242            if last_selection
243                .as_ref()
244                .map_or(true, |last_selection| selection.id > last_selection.id)
245            {
246                last_selection = Some(selection);
247            }
248        }
249        self.position = last_selection.map(|s| s.head().to_point(&buffer));
250
251        cx.notify();
252    }
253}
254
255impl Entity for CursorPosition {
256    type Event = ();
257}
258
259impl View for CursorPosition {
260    fn ui_name() -> &'static str {
261        "CursorPosition"
262    }
263
264    fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
265        if let Some(position) = self.position {
266            let theme = &self.settings.borrow().theme.workspace.status_bar;
267            let mut text = format!("{},{}", position.row + 1, position.column + 1);
268            if self.selected_count > 0 {
269                write!(text, " ({} selected)", self.selected_count).unwrap();
270            }
271            Label::new(text, theme.cursor_position.clone()).boxed()
272        } else {
273            Empty::new().boxed()
274        }
275    }
276}
277
278impl StatusItemView for CursorPosition {
279    fn set_active_pane_item(
280        &mut self,
281        active_pane_item: Option<&dyn ItemViewHandle>,
282        cx: &mut ViewContext<Self>,
283    ) {
284        if let Some(editor) = active_pane_item.and_then(|item| item.to_any().downcast::<Editor>()) {
285            self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
286            self.update_position(editor, cx);
287        } else {
288            self.position = None;
289            self._observe_active_editor = None;
290        }
291
292        cx.notify();
293    }
294}
295
296pub struct DiagnosticMessage {
297    settings: watch::Receiver<Settings>,
298    diagnostic: Option<Diagnostic>,
299    _observe_active_editor: Option<Subscription>,
300}
301
302impl DiagnosticMessage {
303    pub fn new(settings: watch::Receiver<Settings>) -> Self {
304        Self {
305            diagnostic: None,
306            settings,
307            _observe_active_editor: None,
308        }
309    }
310
311    fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
312        let editor = editor.read(cx);
313        let buffer = editor.buffer().read(cx);
314        let cursor_position = editor.newest_selection::<usize>(&buffer.read(cx)).head();
315        let new_diagnostic = buffer
316            .read(cx)
317            .diagnostics_in_range::<_, usize>(cursor_position..cursor_position)
318            .filter(|entry| !entry.range.is_empty())
319            .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
320            .map(|entry| entry.diagnostic);
321        if new_diagnostic != self.diagnostic {
322            self.diagnostic = new_diagnostic;
323            cx.notify();
324        }
325    }
326}
327
328impl Entity for DiagnosticMessage {
329    type Event = ();
330}
331
332impl View for DiagnosticMessage {
333    fn ui_name() -> &'static str {
334        "DiagnosticMessage"
335    }
336
337    fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
338        if let Some(diagnostic) = &self.diagnostic {
339            let theme = &self.settings.borrow().theme.workspace.status_bar;
340            Flex::row()
341                .with_child(
342                    Svg::new("icons/warning.svg")
343                        .with_color(theme.diagnostic_icon_color)
344                        .constrained()
345                        .with_height(theme.diagnostic_icon_size)
346                        .contained()
347                        .with_margin_right(theme.diagnostic_icon_spacing)
348                        .boxed(),
349                )
350                .with_child(
351                    Label::new(
352                        diagnostic.message.lines().next().unwrap().to_string(),
353                        theme.diagnostic_message.clone(),
354                    )
355                    .boxed(),
356                )
357                .boxed()
358        } else {
359            Empty::new().boxed()
360        }
361    }
362}
363
364impl StatusItemView for DiagnosticMessage {
365    fn set_active_pane_item(
366        &mut self,
367        active_pane_item: Option<&dyn ItemViewHandle>,
368        cx: &mut ViewContext<Self>,
369    ) {
370        if let Some(editor) = active_pane_item.and_then(|item| item.to_any().downcast::<Editor>()) {
371            self._observe_active_editor = Some(cx.observe(&editor, Self::update));
372            self.update(editor, cx);
373        } else {
374            self.diagnostic = Default::default();
375            self._observe_active_editor = None;
376        }
377        cx.notify();
378    }
379}