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