items.rs

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