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