1use crate::{Autoscroll, Editor, Event, NavigationData, ToOffset, ToPoint as _};
2use anyhow::Result;
3use gpui::{
4 elements::*, AppContext, Entity, ModelHandle, RenderContext, Subscription, Task, View,
5 ViewContext, ViewHandle,
6};
7use language::{Bias, Buffer, Diagnostic, File as _};
8use project::{File, Project, ProjectEntryId, ProjectPath};
9use std::fmt::Write;
10use std::path::PathBuf;
11use text::{Point, Selection};
12use util::ResultExt;
13use workspace::{Item, ItemHandle, ItemNavHistory, ProjectItem, Settings, StatusItemView};
14
15impl Item for Editor {
16 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) {
17 if let Some(data) = data.downcast_ref::<NavigationData>() {
18 let buffer = self.buffer.read(cx).read(cx);
19 let offset = if buffer.can_resolve(&data.anchor) {
20 data.anchor.to_offset(&buffer)
21 } else {
22 buffer.clip_offset(data.offset, Bias::Left)
23 };
24
25 drop(buffer);
26 let nav_history = self.nav_history.take();
27 self.select_ranges([offset..offset], Some(Autoscroll::Fit), cx);
28 self.nav_history = nav_history;
29 }
30 }
31
32 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
33 let title = self.title(cx);
34 Label::new(title, style.label.clone()).boxed()
35 }
36
37 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
38 File::from_dyn(self.buffer().read(cx).file(cx)).map(|file| ProjectPath {
39 worktree_id: file.worktree_id(cx),
40 path: file.path().clone(),
41 })
42 }
43
44 fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
45 File::from_dyn(self.buffer().read(cx).file(cx)).and_then(|file| file.project_entry_id(cx))
46 }
47
48 fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
49 where
50 Self: Sized,
51 {
52 Some(self.clone(cx))
53 }
54
55 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
56 self.nav_history = Some(history);
57 }
58
59 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
60 let selection = self.newest_anchor_selection();
61 self.push_to_nav_history(selection.head(), None, cx);
62 }
63
64 fn is_dirty(&self, cx: &AppContext) -> bool {
65 self.buffer().read(cx).read(cx).is_dirty()
66 }
67
68 fn has_conflict(&self, cx: &AppContext) -> bool {
69 self.buffer().read(cx).read(cx).has_conflict()
70 }
71
72 fn can_save(&self, cx: &AppContext) -> bool {
73 !self.buffer().read(cx).is_singleton() || self.project_path(cx).is_some()
74 }
75
76 fn save(
77 &mut self,
78 project: ModelHandle<Project>,
79 cx: &mut ViewContext<Self>,
80 ) -> Task<Result<()>> {
81 let buffer = self.buffer().clone();
82 let buffers = buffer.read(cx).all_buffers();
83 let transaction = project.update(cx, |project, cx| project.format(buffers, true, cx));
84 cx.spawn(|this, mut cx| async move {
85 let transaction = transaction.await.log_err();
86 this.update(&mut cx, |editor, cx| {
87 editor.request_autoscroll(Autoscroll::Fit, cx)
88 });
89 buffer
90 .update(&mut cx, |buffer, cx| {
91 if let Some(transaction) = transaction {
92 if !buffer.is_singleton() {
93 buffer.push_transaction(&transaction.0);
94 }
95 }
96
97 buffer.save(cx)
98 })
99 .await?;
100 Ok(())
101 })
102 }
103
104 fn can_save_as(&self, cx: &AppContext) -> bool {
105 self.buffer().read(cx).is_singleton()
106 }
107
108 fn save_as(
109 &mut self,
110 project: ModelHandle<Project>,
111 abs_path: PathBuf,
112 cx: &mut ViewContext<Self>,
113 ) -> Task<Result<()>> {
114 let buffer = self
115 .buffer()
116 .read(cx)
117 .as_singleton()
118 .expect("cannot call save_as on an excerpt list")
119 .clone();
120
121 project.update(cx, |project, cx| {
122 project.save_buffer_as(buffer, abs_path, cx)
123 })
124 }
125
126 fn should_activate_item_on_event(event: &Event) -> bool {
127 matches!(event, Event::Activate)
128 }
129
130 fn should_close_item_on_event(event: &Event) -> bool {
131 matches!(event, Event::Closed)
132 }
133
134 fn should_update_tab_on_event(event: &Event) -> bool {
135 matches!(event, Event::Saved | Event::Dirtied | Event::TitleChanged)
136 }
137}
138
139impl ProjectItem for Editor {
140 type Item = Buffer;
141
142 fn for_project_item(
143 project: ModelHandle<Project>,
144 buffer: ModelHandle<Buffer>,
145 cx: &mut ViewContext<Self>,
146 ) -> Self {
147 Self::for_buffer(buffer, Some(project), cx)
148 }
149}
150
151pub struct CursorPosition {
152 position: Option<Point>,
153 selected_count: usize,
154 _observe_active_editor: Option<Subscription>,
155}
156
157impl CursorPosition {
158 pub fn new() -> Self {
159 Self {
160 position: None,
161 selected_count: 0,
162 _observe_active_editor: None,
163 }
164 }
165
166 fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
167 let editor = editor.read(cx);
168 let buffer = editor.buffer().read(cx).snapshot(cx);
169
170 self.selected_count = 0;
171 let mut last_selection: Option<Selection<usize>> = None;
172 for selection in editor.local_selections::<usize>(cx) {
173 self.selected_count += selection.end - selection.start;
174 if last_selection
175 .as_ref()
176 .map_or(true, |last_selection| selection.id > last_selection.id)
177 {
178 last_selection = Some(selection);
179 }
180 }
181 self.position = last_selection.map(|s| s.head().to_point(&buffer));
182
183 cx.notify();
184 }
185}
186
187impl Entity for CursorPosition {
188 type Event = ();
189}
190
191impl View for CursorPosition {
192 fn ui_name() -> &'static str {
193 "CursorPosition"
194 }
195
196 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
197 if let Some(position) = self.position {
198 let theme = &cx.global::<Settings>().theme.workspace.status_bar;
199 let mut text = format!("{},{}", position.row + 1, position.column + 1);
200 if self.selected_count > 0 {
201 write!(text, " ({} selected)", self.selected_count).unwrap();
202 }
203 Label::new(text, theme.cursor_position.clone()).boxed()
204 } else {
205 Empty::new().boxed()
206 }
207 }
208}
209
210impl StatusItemView for CursorPosition {
211 fn set_active_pane_item(
212 &mut self,
213 active_pane_item: Option<&dyn ItemHandle>,
214 cx: &mut ViewContext<Self>,
215 ) {
216 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
217 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
218 self.update_position(editor, cx);
219 } else {
220 self.position = None;
221 self._observe_active_editor = None;
222 }
223
224 cx.notify();
225 }
226}
227
228pub struct DiagnosticMessage {
229 diagnostic: Option<Diagnostic>,
230 _observe_active_editor: Option<Subscription>,
231}
232
233impl DiagnosticMessage {
234 pub fn new() -> Self {
235 Self {
236 diagnostic: None,
237 _observe_active_editor: None,
238 }
239 }
240
241 fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
242 let editor = editor.read(cx);
243 let buffer = editor.buffer().read(cx);
244 let cursor_position = editor
245 .newest_selection_with_snapshot::<usize>(&buffer.read(cx))
246 .head();
247 let new_diagnostic = buffer
248 .read(cx)
249 .diagnostics_in_range::<_, usize>(cursor_position..cursor_position, false)
250 .filter(|entry| !entry.range.is_empty())
251 .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
252 .map(|entry| entry.diagnostic);
253 if new_diagnostic != self.diagnostic {
254 self.diagnostic = new_diagnostic;
255 cx.notify();
256 }
257 }
258}
259
260impl Entity for DiagnosticMessage {
261 type Event = ();
262}
263
264impl View for DiagnosticMessage {
265 fn ui_name() -> &'static str {
266 "DiagnosticMessage"
267 }
268
269 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
270 if let Some(diagnostic) = &self.diagnostic {
271 let theme = &cx.global::<Settings>().theme.workspace.status_bar;
272 Label::new(
273 diagnostic.message.split('\n').next().unwrap().to_string(),
274 theme.diagnostic_message.clone(),
275 )
276 .boxed()
277 } else {
278 Empty::new().boxed()
279 }
280 }
281}
282
283impl StatusItemView for DiagnosticMessage {
284 fn set_active_pane_item(
285 &mut self,
286 active_pane_item: Option<&dyn ItemHandle>,
287 cx: &mut ViewContext<Self>,
288 ) {
289 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
290 self._observe_active_editor = Some(cx.observe(&editor, Self::update));
291 self.update(editor, cx);
292 } else {
293 self.diagnostic = Default::default();
294 self._observe_active_editor = None;
295 }
296 cx.notify();
297 }
298}