1use crate::{Anchor, Autoscroll, Editor, Event, ExcerptId, NavigationData, ToPoint as _};
2use anyhow::{anyhow, Result};
3use futures::FutureExt;
4use gpui::{
5 elements::*, geometry::vector::vec2f, AppContext, Entity, ModelHandle, MutableAppContext,
6 RenderContext, Subscription, Task, View, ViewContext, ViewHandle,
7};
8use language::{Bias, Buffer, File as _, SelectionGoal};
9use project::{File, Project, ProjectEntryId, ProjectPath};
10use rpc::proto::{self, update_view};
11use settings::Settings;
12use std::{fmt::Write, path::PathBuf, time::Duration};
13use text::{Point, Selection};
14use util::TryFutureExt;
15use workspace::{FollowableItem, Item, ItemHandle, ItemNavHistory, ProjectItem, StatusItemView};
16
17pub const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
18
19impl FollowableItem for Editor {
20 fn from_state_proto(
21 pane: ViewHandle<workspace::Pane>,
22 project: ModelHandle<Project>,
23 state: &mut Option<proto::view::Variant>,
24 cx: &mut MutableAppContext,
25 ) -> Option<Task<Result<ViewHandle<Self>>>> {
26 let state = if matches!(state, Some(proto::view::Variant::Editor(_))) {
27 if let Some(proto::view::Variant::Editor(state)) = state.take() {
28 state
29 } else {
30 unreachable!()
31 }
32 } else {
33 return None;
34 };
35
36 let buffer = project.update(cx, |project, cx| {
37 project.open_buffer_by_id(state.buffer_id, cx)
38 });
39 Some(cx.spawn(|mut cx| async move {
40 let buffer = buffer.await?;
41 let editor = pane
42 .read_with(&cx, |pane, cx| {
43 pane.items_of_type::<Self>().find(|editor| {
44 editor.read(cx).buffer.read(cx).as_singleton().as_ref() == Some(&buffer)
45 })
46 })
47 .unwrap_or_else(|| {
48 cx.add_view(pane.window_id(), |cx| {
49 Editor::for_buffer(buffer, Some(project), cx)
50 })
51 });
52 editor.update(&mut cx, |editor, cx| {
53 let excerpt_id;
54 let buffer_id;
55 {
56 let buffer = editor.buffer.read(cx).read(cx);
57 let singleton = buffer.as_singleton().unwrap();
58 excerpt_id = singleton.0.clone();
59 buffer_id = singleton.1;
60 }
61 let selections = state
62 .selections
63 .into_iter()
64 .map(|selection| {
65 deserialize_selection(&excerpt_id, buffer_id, selection)
66 .ok_or_else(|| anyhow!("invalid selection"))
67 })
68 .collect::<Result<Vec<_>>>()?;
69 if !selections.is_empty() {
70 editor.set_selections_from_remote(selections.into(), cx);
71 }
72
73 if let Some(anchor) = state.scroll_top_anchor {
74 editor.set_scroll_top_anchor(
75 Anchor {
76 buffer_id: Some(state.buffer_id as usize),
77 excerpt_id: excerpt_id.clone(),
78 text_anchor: language::proto::deserialize_anchor(anchor)
79 .ok_or_else(|| anyhow!("invalid scroll top"))?,
80 },
81 vec2f(state.scroll_x, state.scroll_y),
82 cx,
83 );
84 }
85
86 Ok::<_, anyhow::Error>(())
87 })?;
88 Ok(editor)
89 }))
90 }
91
92 fn set_leader_replica_id(
93 &mut self,
94 leader_replica_id: Option<u16>,
95 cx: &mut ViewContext<Self>,
96 ) {
97 self.leader_replica_id = leader_replica_id;
98 if self.leader_replica_id.is_some() {
99 self.buffer.update(cx, |buffer, cx| {
100 buffer.remove_active_selections(cx);
101 });
102 } else {
103 self.buffer.update(cx, |buffer, cx| {
104 if self.focused {
105 buffer.set_active_selections(&self.selections, cx);
106 }
107 });
108 }
109 cx.notify();
110 }
111
112 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
113 let buffer_id = self.buffer.read(cx).as_singleton()?.read(cx).remote_id();
114 Some(proto::view::Variant::Editor(proto::view::Editor {
115 buffer_id,
116 scroll_top_anchor: Some(language::proto::serialize_anchor(
117 &self.scroll_top_anchor.text_anchor,
118 )),
119 scroll_x: self.scroll_position.x(),
120 scroll_y: self.scroll_position.y(),
121 selections: self.selections.iter().map(serialize_selection).collect(),
122 }))
123 }
124
125 fn add_event_to_update_proto(
126 &self,
127 event: &Self::Event,
128 update: &mut Option<proto::update_view::Variant>,
129 _: &AppContext,
130 ) -> bool {
131 let update =
132 update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
133
134 match update {
135 proto::update_view::Variant::Editor(update) => match event {
136 Event::ScrollPositionChanged { .. } => {
137 update.scroll_top_anchor = Some(language::proto::serialize_anchor(
138 &self.scroll_top_anchor.text_anchor,
139 ));
140 update.scroll_x = self.scroll_position.x();
141 update.scroll_y = self.scroll_position.y();
142 true
143 }
144 Event::SelectionsChanged { .. } => {
145 update.selections = self
146 .selections
147 .iter()
148 .chain(self.pending_selection.as_ref().map(|p| &p.selection))
149 .map(serialize_selection)
150 .collect();
151 true
152 }
153 _ => false,
154 },
155 }
156 }
157
158 fn apply_update_proto(
159 &mut self,
160 message: update_view::Variant,
161 cx: &mut ViewContext<Self>,
162 ) -> Result<()> {
163 match message {
164 update_view::Variant::Editor(message) => {
165 let buffer = self.buffer.read(cx);
166 let buffer = buffer.read(cx);
167 let (excerpt_id, buffer_id, _) = buffer.as_singleton().unwrap();
168 let excerpt_id = excerpt_id.clone();
169 drop(buffer);
170
171 let selections = message
172 .selections
173 .into_iter()
174 .filter_map(|selection| {
175 deserialize_selection(&excerpt_id, buffer_id, selection)
176 })
177 .collect::<Vec<_>>();
178
179 if !selections.is_empty() {
180 self.set_selections_from_remote(selections, cx);
181 self.request_autoscroll_remotely(Autoscroll::Newest, cx);
182 } else {
183 if let Some(anchor) = message.scroll_top_anchor {
184 self.set_scroll_top_anchor(
185 Anchor {
186 buffer_id: Some(buffer_id),
187 excerpt_id: excerpt_id.clone(),
188 text_anchor: language::proto::deserialize_anchor(anchor)
189 .ok_or_else(|| anyhow!("invalid scroll top"))?,
190 },
191 vec2f(message.scroll_x, message.scroll_y),
192 cx,
193 );
194 }
195 }
196 }
197 }
198 Ok(())
199 }
200
201 fn should_unfollow_on_event(event: &Self::Event, _: &AppContext) -> bool {
202 match event {
203 Event::Edited => true,
204 Event::SelectionsChanged { local } => *local,
205 Event::ScrollPositionChanged { local } => *local,
206 _ => false,
207 }
208 }
209}
210
211fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
212 proto::Selection {
213 id: selection.id as u64,
214 start: Some(language::proto::serialize_anchor(
215 &selection.start.text_anchor,
216 )),
217 end: Some(language::proto::serialize_anchor(
218 &selection.end.text_anchor,
219 )),
220 reversed: selection.reversed,
221 }
222}
223
224fn deserialize_selection(
225 excerpt_id: &ExcerptId,
226 buffer_id: usize,
227 selection: proto::Selection,
228) -> Option<Selection<Anchor>> {
229 Some(Selection {
230 id: selection.id as usize,
231 start: Anchor {
232 buffer_id: Some(buffer_id),
233 excerpt_id: excerpt_id.clone(),
234 text_anchor: language::proto::deserialize_anchor(selection.start?)?,
235 },
236 end: Anchor {
237 buffer_id: Some(buffer_id),
238 excerpt_id: excerpt_id.clone(),
239 text_anchor: language::proto::deserialize_anchor(selection.end?)?,
240 },
241 reversed: selection.reversed,
242 goal: SelectionGoal::None,
243 })
244}
245
246impl Item for Editor {
247 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
248 if let Ok(data) = data.downcast::<NavigationData>() {
249 let buffer = self.buffer.read(cx).read(cx);
250 let offset = if buffer.can_resolve(&data.cursor_anchor) {
251 data.cursor_anchor.to_point(&buffer)
252 } else {
253 buffer.clip_point(data.cursor_position, Bias::Left)
254 };
255 let newest_selection = self.newest_selection_with_snapshot::<Point>(&buffer);
256
257 let scroll_top_anchor = if buffer.can_resolve(&data.scroll_top_anchor) {
258 data.scroll_top_anchor
259 } else {
260 buffer.anchor_before(
261 buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
262 )
263 };
264
265 drop(buffer);
266
267 if newest_selection.head() == offset {
268 false
269 } else {
270 let nav_history = self.nav_history.take();
271 self.scroll_position = data.scroll_position;
272 self.scroll_top_anchor = scroll_top_anchor;
273 self.select_ranges([offset..offset], Some(Autoscroll::Fit), cx);
274 self.nav_history = nav_history;
275 true
276 }
277 } else {
278 false
279 }
280 }
281
282 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
283 let title = self.title(cx);
284 Label::new(title, style.label.clone()).boxed()
285 }
286
287 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
288 File::from_dyn(self.buffer().read(cx).file(cx)).map(|file| ProjectPath {
289 worktree_id: file.worktree_id(cx),
290 path: file.path().clone(),
291 })
292 }
293
294 fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
295 File::from_dyn(self.buffer().read(cx).file(cx)).and_then(|file| file.project_entry_id(cx))
296 }
297
298 fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
299 where
300 Self: Sized,
301 {
302 Some(self.clone(cx))
303 }
304
305 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
306 self.nav_history = Some(history);
307 }
308
309 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
310 let selection = self.newest_anchor_selection();
311 self.push_to_nav_history(selection.head(), None, cx);
312 }
313
314 fn is_dirty(&self, cx: &AppContext) -> bool {
315 self.buffer().read(cx).read(cx).is_dirty()
316 }
317
318 fn has_conflict(&self, cx: &AppContext) -> bool {
319 self.buffer().read(cx).read(cx).has_conflict()
320 }
321
322 fn can_save(&self, cx: &AppContext) -> bool {
323 !self.buffer().read(cx).is_singleton() || self.project_path(cx).is_some()
324 }
325
326 fn save(
327 &mut self,
328 project: ModelHandle<Project>,
329 cx: &mut ViewContext<Self>,
330 ) -> Task<Result<()>> {
331 let settings = cx.global::<Settings>();
332 let buffer = self.buffer().clone();
333 let mut buffers = buffer.read(cx).all_buffers();
334 buffers.retain(|buffer| {
335 let language_name = buffer.read(cx).language().map(|l| l.name());
336 settings.format_on_save(language_name.as_deref())
337 });
338 let mut timeout = cx.background().timer(FORMAT_TIMEOUT).fuse();
339 let format = project.update(cx, |project, cx| project.format(buffers, true, cx));
340 cx.spawn(|this, mut cx| async move {
341 let transaction = futures::select_biased! {
342 _ = timeout => {
343 log::warn!("timed out waiting for formatting");
344 None
345 }
346 transaction = format.log_err().fuse() => transaction,
347 };
348
349 this.update(&mut cx, |editor, cx| {
350 editor.request_autoscroll(Autoscroll::Fit, cx)
351 });
352 buffer
353 .update(&mut cx, |buffer, cx| {
354 if let Some(transaction) = transaction {
355 if !buffer.is_singleton() {
356 buffer.push_transaction(&transaction.0);
357 }
358 }
359
360 buffer.save(cx)
361 })
362 .await?;
363 Ok(())
364 })
365 }
366
367 fn can_save_as(&self, cx: &AppContext) -> bool {
368 self.buffer().read(cx).is_singleton()
369 }
370
371 fn save_as(
372 &mut self,
373 project: ModelHandle<Project>,
374 abs_path: PathBuf,
375 cx: &mut ViewContext<Self>,
376 ) -> Task<Result<()>> {
377 let buffer = self
378 .buffer()
379 .read(cx)
380 .as_singleton()
381 .expect("cannot call save_as on an excerpt list")
382 .clone();
383
384 project.update(cx, |project, cx| {
385 project.save_buffer_as(buffer, abs_path, cx)
386 })
387 }
388
389 fn reload(
390 &mut self,
391 project: ModelHandle<Project>,
392 cx: &mut ViewContext<Self>,
393 ) -> Task<Result<()>> {
394 let buffer = self.buffer().clone();
395 let buffers = self.buffer.read(cx).all_buffers();
396 let reload_buffers =
397 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
398 cx.spawn(|this, mut cx| async move {
399 let transaction = reload_buffers.log_err().await;
400 this.update(&mut cx, |editor, cx| {
401 editor.request_autoscroll(Autoscroll::Fit, cx)
402 });
403 buffer.update(&mut cx, |buffer, _| {
404 if let Some(transaction) = transaction {
405 if !buffer.is_singleton() {
406 buffer.push_transaction(&transaction.0);
407 }
408 }
409 });
410 Ok(())
411 })
412 }
413
414 fn should_activate_item_on_event(event: &Event) -> bool {
415 matches!(event, Event::Activate)
416 }
417
418 fn should_close_item_on_event(event: &Event) -> bool {
419 matches!(event, Event::Closed)
420 }
421
422 fn should_update_tab_on_event(event: &Event) -> bool {
423 matches!(event, Event::Saved | Event::Dirtied | Event::TitleChanged)
424 }
425}
426
427impl ProjectItem for Editor {
428 type Item = Buffer;
429
430 fn for_project_item(
431 project: ModelHandle<Project>,
432 buffer: ModelHandle<Buffer>,
433 cx: &mut ViewContext<Self>,
434 ) -> Self {
435 Self::for_buffer(buffer, Some(project), cx)
436 }
437}
438
439pub struct CursorPosition {
440 position: Option<Point>,
441 selected_count: usize,
442 _observe_active_editor: Option<Subscription>,
443}
444
445impl CursorPosition {
446 pub fn new() -> Self {
447 Self {
448 position: None,
449 selected_count: 0,
450 _observe_active_editor: None,
451 }
452 }
453
454 fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
455 let editor = editor.read(cx);
456 let buffer = editor.buffer().read(cx).snapshot(cx);
457
458 self.selected_count = 0;
459 let mut last_selection: Option<Selection<usize>> = None;
460 for selection in editor.local_selections::<usize>(cx) {
461 self.selected_count += selection.end - selection.start;
462 if last_selection
463 .as_ref()
464 .map_or(true, |last_selection| selection.id > last_selection.id)
465 {
466 last_selection = Some(selection);
467 }
468 }
469 self.position = last_selection.map(|s| s.head().to_point(&buffer));
470
471 cx.notify();
472 }
473}
474
475impl Entity for CursorPosition {
476 type Event = ();
477}
478
479impl View for CursorPosition {
480 fn ui_name() -> &'static str {
481 "CursorPosition"
482 }
483
484 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
485 if let Some(position) = self.position {
486 let theme = &cx.global::<Settings>().theme.workspace.status_bar;
487 let mut text = format!("{},{}", position.row + 1, position.column + 1);
488 if self.selected_count > 0 {
489 write!(text, " ({} selected)", self.selected_count).unwrap();
490 }
491 Label::new(text, theme.cursor_position.clone()).boxed()
492 } else {
493 Empty::new().boxed()
494 }
495 }
496}
497
498impl StatusItemView for CursorPosition {
499 fn set_active_pane_item(
500 &mut self,
501 active_pane_item: Option<&dyn ItemHandle>,
502 cx: &mut ViewContext<Self>,
503 ) {
504 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
505 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
506 self.update_position(editor, cx);
507 } else {
508 self.position = None;
509 self._observe_active_editor = None;
510 }
511
512 cx.notify();
513 }
514}