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