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