items.rs

  1use crate::{Editor, EditorSettings, Event};
  2use anyhow::Result;
  3use gpui::{
  4    elements::*, fonts::TextStyle, AppContext, Entity, ModelContext, ModelHandle,
  5    MutableAppContext, RenderContext, Subscription, Task, View, ViewContext, ViewHandle,
  6    WeakModelHandle,
  7};
  8use language::{Buffer, Diagnostic, File as _};
  9use postage::watch;
 10use project::{ProjectPath, Worktree};
 11use std::fmt::Write;
 12use std::path::Path;
 13use text::{Point, Selection, ToPoint};
 14use workspace::{
 15    settings, EntryOpener, ItemHandle, ItemView, ItemViewHandle, Settings, StatusItemView,
 16    WeakItemHandle,
 17};
 18
 19pub struct BufferOpener;
 20
 21#[derive(Clone)]
 22pub struct BufferItemHandle(pub ModelHandle<Buffer>);
 23
 24#[derive(Clone)]
 25struct WeakBufferItemHandle(WeakModelHandle<Buffer>);
 26
 27impl EntryOpener for BufferOpener {
 28    fn open(
 29        &self,
 30        worktree: &mut Worktree,
 31        project_path: ProjectPath,
 32        cx: &mut ModelContext<Worktree>,
 33    ) -> Option<Task<Result<Box<dyn ItemHandle>>>> {
 34        let buffer = worktree.open_buffer(project_path.path, cx);
 35        let task = cx.spawn(|_, _| async move {
 36            buffer
 37                .await
 38                .map(|buffer| 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        settings: watch::Receiver<Settings>,
 49        cx: &mut MutableAppContext,
 50    ) -> Box<dyn ItemViewHandle> {
 51        let buffer = self.0.downgrade();
 52        Box::new(cx.add_view(window_id, |cx| {
 53            Editor::for_buffer(
 54                self.0.clone(),
 55                move |cx| {
 56                    let settings = settings.borrow();
 57                    let font_cache = cx.font_cache();
 58                    let font_family_id = settings.buffer_font_family;
 59                    let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
 60                    let font_properties = Default::default();
 61                    let font_id = font_cache
 62                        .select_font(font_family_id, &font_properties)
 63                        .unwrap();
 64                    let font_size = settings.buffer_font_size;
 65
 66                    let mut theme = settings.theme.editor.clone();
 67                    theme.text = TextStyle {
 68                        color: theme.text.color,
 69                        font_family_name,
 70                        font_family_id,
 71                        font_id,
 72                        font_size,
 73                        font_properties,
 74                        underline: None,
 75                    };
 76                    let language = buffer.upgrade(cx).and_then(|buf| buf.read(cx).language());
 77                    let soft_wrap = match settings.soft_wrap(language) {
 78                        settings::SoftWrap::None => crate::SoftWrap::None,
 79                        settings::SoftWrap::EditorWidth => crate::SoftWrap::EditorWidth,
 80                        settings::SoftWrap::PreferredLineLength => crate::SoftWrap::Column(
 81                            settings.preferred_line_length(language).saturating_sub(1),
 82                        ),
 83                    };
 84
 85                    EditorSettings {
 86                        tab_size: settings.tab_size,
 87                        soft_wrap,
 88                        style: theme,
 89                    }
 90                },
 91                cx,
 92            )
 93        }))
 94    }
 95
 96    fn boxed_clone(&self) -> Box<dyn ItemHandle> {
 97        Box::new(self.clone())
 98    }
 99
100    fn downgrade(&self) -> Box<dyn workspace::WeakItemHandle> {
101        Box::new(WeakBufferItemHandle(self.0.downgrade()))
102    }
103
104    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
105        self.0.read(cx).file().map(|f| ProjectPath {
106            worktree_id: f.worktree_id(),
107            path: f.path().clone(),
108        })
109    }
110}
111
112impl WeakItemHandle for WeakBufferItemHandle {
113    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
114        self.0
115            .upgrade(cx)
116            .map(|buffer| Box::new(BufferItemHandle(buffer)) as Box<dyn ItemHandle>)
117    }
118}
119
120impl ItemView for Editor {
121    fn should_activate_item_on_event(event: &Event) -> bool {
122        matches!(event, Event::Activate)
123    }
124
125    fn should_close_item_on_event(event: &Event) -> bool {
126        matches!(event, Event::Closed)
127    }
128
129    fn should_update_tab_on_event(event: &Event) -> bool {
130        matches!(
131            event,
132            Event::Saved | Event::Dirtied | Event::FileHandleChanged
133        )
134    }
135
136    fn title(&self, cx: &AppContext) -> String {
137        let filename = self
138            .buffer()
139            .read(cx)
140            .file()
141            .and_then(|file| file.file_name());
142        if let Some(name) = filename {
143            name.to_string_lossy().into()
144        } else {
145            "untitled".into()
146        }
147    }
148
149    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
150        self.buffer().read(cx).file().map(|file| ProjectPath {
151            worktree_id: file.worktree_id(),
152            path: file.path().clone(),
153        })
154    }
155
156    fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
157    where
158        Self: Sized,
159    {
160        Some(self.clone(cx))
161    }
162
163    fn save(&mut self, cx: &mut ViewContext<Self>) -> Result<Task<Result<()>>> {
164        let save = self.buffer().update(cx, |b, cx| b.save(cx))?;
165        Ok(cx.spawn(|_, _| async move {
166            save.await?;
167            Ok(())
168        }))
169    }
170
171    fn save_as(
172        &mut self,
173        worktree: ModelHandle<Worktree>,
174        path: &Path,
175        cx: &mut ViewContext<Self>,
176    ) -> Task<Result<()>> {
177        self.buffer().update(cx, |buffer, cx| {
178            let handle = cx.handle();
179            let text = buffer.as_rope().clone();
180            let version = buffer.version();
181
182            let save_as = worktree.update(cx, |worktree, cx| {
183                worktree
184                    .as_local_mut()
185                    .unwrap()
186                    .save_buffer_as(handle, path, text, cx)
187            });
188
189            cx.spawn(|buffer, mut cx| async move {
190                save_as.await.map(|new_file| {
191                    let (language, language_server) = worktree.update(&mut cx, |worktree, cx| {
192                        let worktree = worktree.as_local_mut().unwrap();
193                        let language = worktree
194                            .languages()
195                            .select_language(new_file.full_path())
196                            .cloned();
197                        let language_server = language
198                            .as_ref()
199                            .and_then(|language| worktree.ensure_language_server(language, cx));
200                        (language, language_server.clone())
201                    });
202
203                    buffer.update(&mut cx, |buffer, cx| {
204                        buffer.did_save(version, new_file.mtime, Some(Box::new(new_file)), cx);
205                        buffer.set_language(language, language_server, cx);
206                    });
207                })
208            })
209        })
210    }
211
212    fn is_dirty(&self, cx: &AppContext) -> bool {
213        self.buffer().read(cx).is_dirty()
214    }
215
216    fn has_conflict(&self, cx: &AppContext) -> bool {
217        self.buffer().read(cx).has_conflict()
218    }
219}
220
221pub struct CursorPosition {
222    position: Option<Point>,
223    selected_count: usize,
224    settings: watch::Receiver<Settings>,
225    _observe_active_editor: Option<Subscription>,
226}
227
228impl CursorPosition {
229    pub fn new(settings: watch::Receiver<Settings>) -> Self {
230        Self {
231            position: None,
232            selected_count: 0,
233            settings,
234            _observe_active_editor: None,
235        }
236    }
237
238    fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
239        let editor = editor.read(cx);
240        let buffer = editor.buffer().read(cx);
241
242        self.selected_count = 0;
243        let mut last_selection: Option<Selection<usize>> = None;
244        for selection in editor.selections::<usize>(cx) {
245            self.selected_count += selection.end - selection.start;
246            if last_selection
247                .as_ref()
248                .map_or(true, |last_selection| selection.id > last_selection.id)
249            {
250                last_selection = Some(selection);
251            }
252        }
253        self.position = last_selection.map(|s| s.head().to_point(buffer));
254
255        cx.notify();
256    }
257}
258
259impl Entity for CursorPosition {
260    type Event = ();
261}
262
263impl View for CursorPosition {
264    fn ui_name() -> &'static str {
265        "CursorPosition"
266    }
267
268    fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
269        if let Some(position) = self.position {
270            let theme = &self.settings.borrow().theme.workspace.status_bar;
271            let mut text = format!("{},{}", position.row + 1, position.column + 1);
272            if self.selected_count > 0 {
273                write!(text, " ({} selected)", self.selected_count).unwrap();
274            }
275            Label::new(text, theme.cursor_position.clone()).boxed()
276        } else {
277            Empty::new().boxed()
278        }
279    }
280}
281
282impl StatusItemView for CursorPosition {
283    fn set_active_pane_item(
284        &mut self,
285        active_pane_item: Option<&dyn ItemViewHandle>,
286        cx: &mut ViewContext<Self>,
287    ) {
288        if let Some(editor) = active_pane_item.and_then(|item| item.to_any().downcast::<Editor>()) {
289            self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
290            self.update_position(editor, cx);
291        } else {
292            self.position = None;
293            self._observe_active_editor = None;
294        }
295
296        cx.notify();
297    }
298}
299
300pub struct DiagnosticMessage {
301    settings: watch::Receiver<Settings>,
302    diagnostic: Option<Diagnostic>,
303    _observe_active_editor: Option<Subscription>,
304}
305
306impl DiagnosticMessage {
307    pub fn new(settings: watch::Receiver<Settings>) -> Self {
308        Self {
309            diagnostic: None,
310            settings,
311            _observe_active_editor: None,
312        }
313    }
314
315    fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
316        let editor = editor.read(cx);
317        let cursor_position = editor.newest_selection(cx).head();
318        let new_diagnostic = editor
319            .buffer()
320            .read(cx)
321            .diagnostics_in_range::<usize, usize>(cursor_position..cursor_position)
322            .filter(|(range, _)| !range.is_empty())
323            .min_by_key(|(range, diagnostic)| (diagnostic.severity, range.len()))
324            .map(|(_, diagnostic)| diagnostic.clone());
325        if new_diagnostic != self.diagnostic {
326            self.diagnostic = new_diagnostic;
327            cx.notify();
328        }
329    }
330}
331
332impl Entity for DiagnosticMessage {
333    type Event = ();
334}
335
336impl View for DiagnosticMessage {
337    fn ui_name() -> &'static str {
338        "DiagnosticMessage"
339    }
340
341    fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
342        if let Some(diagnostic) = &self.diagnostic {
343            let theme = &self.settings.borrow().theme.workspace.status_bar;
344            Flex::row()
345                .with_child(
346                    Svg::new("icons/warning.svg")
347                        .with_color(theme.diagnostic_icon_color)
348                        .constrained()
349                        .with_height(theme.diagnostic_icon_size)
350                        .contained()
351                        .with_margin_right(theme.diagnostic_icon_spacing)
352                        .boxed(),
353                )
354                .with_child(
355                    Label::new(
356                        diagnostic.message.lines().next().unwrap().to_string(),
357                        theme.diagnostic_message.clone(),
358                    )
359                    .boxed(),
360                )
361                .boxed()
362        } else {
363            Empty::new().boxed()
364        }
365    }
366}
367
368impl StatusItemView for DiagnosticMessage {
369    fn set_active_pane_item(
370        &mut self,
371        active_pane_item: Option<&dyn ItemViewHandle>,
372        cx: &mut ViewContext<Self>,
373    ) {
374        if let Some(editor) = active_pane_item.and_then(|item| item.to_any().downcast::<Editor>()) {
375            self._observe_active_editor = Some(cx.observe(&editor, Self::update));
376            self.update(editor, cx);
377        } else {
378            self.diagnostic = Default::default();
379            self._observe_active_editor = None;
380        }
381        cx.notify();
382    }
383}