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
 28impl PathOpener for BufferOpener {
 29    fn open(
 30        &self,
 31        project: &mut Project,
 32        project_path: ProjectPath,
 33        cx: &mut ModelContext<Project>,
 34    ) -> Option<Task<Result<Box<dyn ItemHandle>>>> {
 35        let buffer = project.open_buffer(project_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<RefCell<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(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 WeakItemHandle for WeakBufferItemHandle {
 90    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
 91        self.0
 92            .upgrade(cx)
 93            .map(|buffer| Box::new(BufferItemHandle(buffer)) as Box<dyn ItemHandle>)
 94    }
 95
 96    fn id(&self) -> usize {
 97        self.0.id()
 98    }
 99}
100
101impl ItemView for Editor {
102    type ItemHandle = BufferItemHandle;
103
104    fn item_handle(&self, cx: &AppContext) -> Self::ItemHandle {
105        BufferItemHandle(self.buffer.read(cx).as_singleton().unwrap())
106    }
107
108    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) {
109        if let Some(data) = data.downcast_ref::<NavigationData>() {
110            let buffer = self.buffer.read(cx).read(cx);
111            let offset = if buffer.can_resolve(&data.anchor) {
112                data.anchor.to_offset(&buffer)
113            } else {
114                buffer.clip_offset(data.offset, Bias::Left)
115            };
116
117            drop(buffer);
118            let nav_history = self.nav_history.take();
119            self.select_ranges([offset..offset], Some(Autoscroll::Fit), cx);
120            self.nav_history = nav_history;
121        }
122    }
123
124    fn title(&self, cx: &AppContext) -> String {
125        let file = self.buffer().read(cx).file(cx);
126        if let Some(file) = file {
127            file.file_name(cx).to_string_lossy().into()
128        } else {
129            "untitled".into()
130        }
131    }
132
133    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
134        File::from_dyn(self.buffer().read(cx).file(cx)).map(|file| ProjectPath {
135            worktree_id: file.worktree_id(cx),
136            path: file.path().clone(),
137        })
138    }
139
140    fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
141    where
142        Self: Sized,
143    {
144        Some(self.clone(cx))
145    }
146
147    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
148        if let Some(selection) = self.newest_selection_internal() {
149            self.push_to_nav_history(selection.head(), None, cx);
150        }
151    }
152
153    fn is_dirty(&self, cx: &AppContext) -> bool {
154        self.buffer().read(cx).read(cx).is_dirty()
155    }
156
157    fn has_conflict(&self, cx: &AppContext) -> bool {
158        self.buffer().read(cx).read(cx).has_conflict()
159    }
160
161    fn can_save(&self, cx: &AppContext) -> bool {
162        self.project_path(cx).is_some()
163    }
164
165    fn save(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
166        let buffer = self.buffer().clone();
167        cx.spawn(|editor, mut cx| async move {
168            buffer
169                .update(&mut cx, |buffer, cx| buffer.format(cx).log_err())
170                .await;
171            editor.update(&mut cx, |editor, cx| {
172                editor.request_autoscroll(Autoscroll::Fit, cx)
173            });
174            buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).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.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.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}