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