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