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