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