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