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::TryFutureExt;
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 if let Some(selection) = self.newest_anchor_selection() {
208 self.push_to_nav_history(selection.head(), None, cx);
209 }
210 }
211
212 fn is_dirty(&self, cx: &AppContext) -> bool {
213 self.buffer().read(cx).read(cx).is_dirty()
214 }
215
216 fn has_conflict(&self, cx: &AppContext) -> bool {
217 self.buffer().read(cx).read(cx).has_conflict()
218 }
219
220 fn can_save(&self, cx: &AppContext) -> bool {
221 !self.buffer().read(cx).is_singleton() || self.project_path(cx).is_some()
222 }
223
224 fn save(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
225 let buffer = self.buffer().clone();
226 cx.spawn(|editor, mut cx| async move {
227 buffer
228 .update(&mut cx, |buffer, cx| buffer.format(cx).log_err())
229 .await;
230 editor.update(&mut cx, |editor, cx| {
231 editor.request_autoscroll(Autoscroll::Fit, cx)
232 });
233 buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
234 Ok(())
235 })
236 }
237
238 fn can_save_as(&self, cx: &AppContext) -> bool {
239 self.buffer().read(cx).is_singleton()
240 }
241
242 fn save_as(
243 &mut self,
244 project: ModelHandle<Project>,
245 abs_path: PathBuf,
246 cx: &mut ViewContext<Self>,
247 ) -> Task<Result<()>> {
248 let buffer = self
249 .buffer()
250 .read(cx)
251 .as_singleton()
252 .expect("cannot call save_as on an excerpt list")
253 .clone();
254
255 project.update(cx, |project, cx| {
256 project.save_buffer_as(buffer, abs_path, cx)
257 })
258 }
259
260 fn should_activate_item_on_event(event: &Event) -> bool {
261 matches!(event, Event::Activate)
262 }
263
264 fn should_close_item_on_event(event: &Event) -> bool {
265 matches!(event, Event::Closed)
266 }
267
268 fn should_update_tab_on_event(event: &Event) -> bool {
269 matches!(event, Event::Saved | Event::Dirtied | Event::TitleChanged)
270 }
271}
272
273pub struct CursorPosition {
274 position: Option<Point>,
275 selected_count: usize,
276 settings: watch::Receiver<Settings>,
277 _observe_active_editor: Option<Subscription>,
278}
279
280impl CursorPosition {
281 pub fn new(settings: watch::Receiver<Settings>) -> Self {
282 Self {
283 position: None,
284 selected_count: 0,
285 settings,
286 _observe_active_editor: None,
287 }
288 }
289
290 fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
291 let editor = editor.read(cx);
292 let buffer = editor.buffer().read(cx).snapshot(cx);
293
294 self.selected_count = 0;
295 let mut last_selection: Option<Selection<usize>> = None;
296 for selection in editor.local_selections::<usize>(cx) {
297 self.selected_count += selection.end - selection.start;
298 if last_selection
299 .as_ref()
300 .map_or(true, |last_selection| selection.id > last_selection.id)
301 {
302 last_selection = Some(selection);
303 }
304 }
305 self.position = last_selection.map(|s| s.head().to_point(&buffer));
306
307 cx.notify();
308 }
309}
310
311impl Entity for CursorPosition {
312 type Event = ();
313}
314
315impl View for CursorPosition {
316 fn ui_name() -> &'static str {
317 "CursorPosition"
318 }
319
320 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
321 if let Some(position) = self.position {
322 let theme = &self.settings.borrow().theme.workspace.status_bar;
323 let mut text = format!("{},{}", position.row + 1, position.column + 1);
324 if self.selected_count > 0 {
325 write!(text, " ({} selected)", self.selected_count).unwrap();
326 }
327 Label::new(text, theme.cursor_position.clone()).boxed()
328 } else {
329 Empty::new().boxed()
330 }
331 }
332}
333
334impl StatusItemView for CursorPosition {
335 fn set_active_pane_item(
336 &mut self,
337 active_pane_item: Option<&dyn ItemViewHandle>,
338 cx: &mut ViewContext<Self>,
339 ) {
340 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
341 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
342 self.update_position(editor, cx);
343 } else {
344 self.position = None;
345 self._observe_active_editor = None;
346 }
347
348 cx.notify();
349 }
350}
351
352pub struct DiagnosticMessage {
353 settings: watch::Receiver<Settings>,
354 diagnostic: Option<Diagnostic>,
355 _observe_active_editor: Option<Subscription>,
356}
357
358impl DiagnosticMessage {
359 pub fn new(settings: watch::Receiver<Settings>) -> Self {
360 Self {
361 diagnostic: None,
362 settings,
363 _observe_active_editor: None,
364 }
365 }
366
367 fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
368 let editor = editor.read(cx);
369 let buffer = editor.buffer().read(cx);
370 let cursor_position = editor.newest_selection::<usize>(&buffer.read(cx)).head();
371 let new_diagnostic = buffer
372 .read(cx)
373 .diagnostics_in_range::<_, usize>(cursor_position..cursor_position)
374 .filter(|entry| !entry.range.is_empty())
375 .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
376 .map(|entry| entry.diagnostic);
377 if new_diagnostic != self.diagnostic {
378 self.diagnostic = new_diagnostic;
379 cx.notify();
380 }
381 }
382}
383
384impl Entity for DiagnosticMessage {
385 type Event = ();
386}
387
388impl View for DiagnosticMessage {
389 fn ui_name() -> &'static str {
390 "DiagnosticMessage"
391 }
392
393 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
394 if let Some(diagnostic) = &self.diagnostic {
395 let theme = &self.settings.borrow().theme.workspace.status_bar;
396 Label::new(
397 diagnostic.message.lines().next().unwrap().to_string(),
398 theme.diagnostic_message.clone(),
399 )
400 .contained()
401 .with_margin_left(theme.item_spacing)
402 .boxed()
403 } else {
404 Empty::new().boxed()
405 }
406 }
407}
408
409impl StatusItemView for DiagnosticMessage {
410 fn set_active_pane_item(
411 &mut self,
412 active_pane_item: Option<&dyn ItemViewHandle>,
413 cx: &mut ViewContext<Self>,
414 ) {
415 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
416 self._observe_active_editor = Some(cx.observe(&editor, Self::update));
417 self.update(editor, cx);
418 } else {
419 self.diagnostic = Default::default();
420 self._observe_active_editor = None;
421 }
422 cx.notify();
423 }
424}