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