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