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