1use crate::{
2 display_map::ToDisplayPoint, link_go_to_definition::hide_link_definition,
3 movement::surrounding_word, Anchor, Autoscroll, Editor, Event, ExcerptId, MultiBuffer,
4 MultiBufferSnapshot, NavigationData, ToPoint as _, FORMAT_TIMEOUT,
5};
6use anyhow::{anyhow, Result};
7use futures::FutureExt;
8use gpui::{
9 elements::*, geometry::vector::vec2f, AppContext, Entity, ModelHandle, MutableAppContext,
10 RenderContext, Subscription, Task, View, ViewContext, ViewHandle,
11};
12use language::{Bias, Buffer, File as _, OffsetRangeExt, Point, SelectionGoal};
13use project::{File, FormatTrigger, Project, ProjectEntryId, ProjectPath};
14use rpc::proto::{self, update_view};
15use settings::Settings;
16use smallvec::SmallVec;
17use std::{
18 borrow::Cow,
19 cmp::{self, Ordering},
20 fmt::Write,
21 ops::Range,
22 path::{Path, PathBuf},
23};
24use text::Selection;
25use util::TryFutureExt;
26use workspace::{
27 searchable::{Direction, SearchEvent, SearchableItem, SearchableItemHandle},
28 FollowableItem, Item, ItemEvent, ItemHandle, ItemNavHistory, ProjectItem, StatusItemView,
29 ToolbarItemLocation,
30};
31
32pub const MAX_TAB_TITLE_LEN: usize = 24;
33
34impl FollowableItem for Editor {
35 fn from_state_proto(
36 pane: ViewHandle<workspace::Pane>,
37 project: ModelHandle<Project>,
38 state: &mut Option<proto::view::Variant>,
39 cx: &mut MutableAppContext,
40 ) -> Option<Task<Result<ViewHandle<Self>>>> {
41 let state = if matches!(state, Some(proto::view::Variant::Editor(_))) {
42 if let Some(proto::view::Variant::Editor(state)) = state.take() {
43 state
44 } else {
45 unreachable!()
46 }
47 } else {
48 return None;
49 };
50
51 let buffer = project.update(cx, |project, cx| {
52 project.open_buffer_by_id(state.buffer_id, cx)
53 });
54 Some(cx.spawn(|mut cx| async move {
55 let buffer = buffer.await?;
56 let editor = pane
57 .read_with(&cx, |pane, cx| {
58 pane.items_of_type::<Self>().find(|editor| {
59 editor.read(cx).buffer.read(cx).as_singleton().as_ref() == Some(&buffer)
60 })
61 })
62 .unwrap_or_else(|| {
63 pane.update(&mut cx, |_, cx| {
64 cx.add_view(|cx| Editor::for_buffer(buffer, Some(project), cx))
65 })
66 });
67 editor.update(&mut cx, |editor, cx| {
68 let excerpt_id;
69 let buffer_id;
70 {
71 let buffer = editor.buffer.read(cx).read(cx);
72 let singleton = buffer.as_singleton().unwrap();
73 excerpt_id = singleton.0.clone();
74 buffer_id = singleton.1;
75 }
76 let selections = state
77 .selections
78 .into_iter()
79 .map(|selection| {
80 deserialize_selection(&excerpt_id, buffer_id, selection)
81 .ok_or_else(|| anyhow!("invalid selection"))
82 })
83 .collect::<Result<Vec<_>>>()?;
84 if !selections.is_empty() {
85 editor.set_selections_from_remote(selections, cx);
86 }
87
88 if let Some(anchor) = state.scroll_top_anchor {
89 editor.set_scroll_top_anchor(
90 Anchor {
91 buffer_id: Some(state.buffer_id as usize),
92 excerpt_id,
93 text_anchor: language::proto::deserialize_anchor(anchor)
94 .ok_or_else(|| anyhow!("invalid scroll top"))?,
95 },
96 vec2f(state.scroll_x, state.scroll_y),
97 cx,
98 );
99 }
100
101 Ok::<_, anyhow::Error>(())
102 })?;
103 Ok(editor)
104 }))
105 }
106
107 fn set_leader_replica_id(
108 &mut self,
109 leader_replica_id: Option<u16>,
110 cx: &mut ViewContext<Self>,
111 ) {
112 self.leader_replica_id = leader_replica_id;
113 if self.leader_replica_id.is_some() {
114 self.buffer.update(cx, |buffer, cx| {
115 buffer.remove_active_selections(cx);
116 });
117 } else {
118 self.buffer.update(cx, |buffer, cx| {
119 if self.focused {
120 buffer.set_active_selections(
121 &self.selections.disjoint_anchors(),
122 self.selections.line_mode,
123 self.cursor_shape,
124 cx,
125 );
126 }
127 });
128 }
129 cx.notify();
130 }
131
132 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
133 let buffer_id = self.buffer.read(cx).as_singleton()?.read(cx).remote_id();
134 Some(proto::view::Variant::Editor(proto::view::Editor {
135 buffer_id,
136 scroll_top_anchor: Some(language::proto::serialize_anchor(
137 &self.scroll_top_anchor.text_anchor,
138 )),
139 scroll_x: self.scroll_position.x(),
140 scroll_y: self.scroll_position.y(),
141 selections: self
142 .selections
143 .disjoint_anchors()
144 .iter()
145 .map(serialize_selection)
146 .collect(),
147 }))
148 }
149
150 fn add_event_to_update_proto(
151 &self,
152 event: &Self::Event,
153 update: &mut Option<proto::update_view::Variant>,
154 _: &AppContext,
155 ) -> bool {
156 let update =
157 update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
158
159 match update {
160 proto::update_view::Variant::Editor(update) => match event {
161 Event::ScrollPositionChanged { .. } => {
162 update.scroll_top_anchor = Some(language::proto::serialize_anchor(
163 &self.scroll_top_anchor.text_anchor,
164 ));
165 update.scroll_x = self.scroll_position.x();
166 update.scroll_y = self.scroll_position.y();
167 true
168 }
169 Event::SelectionsChanged { .. } => {
170 update.selections = self
171 .selections
172 .disjoint_anchors()
173 .iter()
174 .chain(self.selections.pending_anchor().as_ref())
175 .map(serialize_selection)
176 .collect();
177 true
178 }
179 _ => false,
180 },
181 }
182 }
183
184 fn apply_update_proto(
185 &mut self,
186 message: update_view::Variant,
187 cx: &mut ViewContext<Self>,
188 ) -> Result<()> {
189 match message {
190 update_view::Variant::Editor(message) => {
191 let buffer = self.buffer.read(cx);
192 let buffer = buffer.read(cx);
193 let (excerpt_id, buffer_id, _) = buffer.as_singleton().unwrap();
194 let excerpt_id = excerpt_id.clone();
195 drop(buffer);
196
197 let selections = message
198 .selections
199 .into_iter()
200 .filter_map(|selection| {
201 deserialize_selection(&excerpt_id, buffer_id, selection)
202 })
203 .collect::<Vec<_>>();
204
205 if !selections.is_empty() {
206 self.set_selections_from_remote(selections, cx);
207 self.request_autoscroll_remotely(Autoscroll::newest(), cx);
208 } else if let Some(anchor) = message.scroll_top_anchor {
209 self.set_scroll_top_anchor(
210 Anchor {
211 buffer_id: Some(buffer_id),
212 excerpt_id,
213 text_anchor: language::proto::deserialize_anchor(anchor)
214 .ok_or_else(|| anyhow!("invalid scroll top"))?,
215 },
216 vec2f(message.scroll_x, message.scroll_y),
217 cx,
218 );
219 }
220 }
221 }
222 Ok(())
223 }
224
225 fn should_unfollow_on_event(event: &Self::Event, _: &AppContext) -> bool {
226 match event {
227 Event::Edited => true,
228 Event::SelectionsChanged { local } => *local,
229 Event::ScrollPositionChanged { local } => *local,
230 _ => false,
231 }
232 }
233}
234
235fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
236 proto::Selection {
237 id: selection.id as u64,
238 start: Some(language::proto::serialize_anchor(
239 &selection.start.text_anchor,
240 )),
241 end: Some(language::proto::serialize_anchor(
242 &selection.end.text_anchor,
243 )),
244 reversed: selection.reversed,
245 }
246}
247
248fn deserialize_selection(
249 excerpt_id: &ExcerptId,
250 buffer_id: usize,
251 selection: proto::Selection,
252) -> Option<Selection<Anchor>> {
253 Some(Selection {
254 id: selection.id as usize,
255 start: Anchor {
256 buffer_id: Some(buffer_id),
257 excerpt_id: excerpt_id.clone(),
258 text_anchor: language::proto::deserialize_anchor(selection.start?)?,
259 },
260 end: Anchor {
261 buffer_id: Some(buffer_id),
262 excerpt_id: excerpt_id.clone(),
263 text_anchor: language::proto::deserialize_anchor(selection.end?)?,
264 },
265 reversed: selection.reversed,
266 goal: SelectionGoal::None,
267 })
268}
269
270impl Item for Editor {
271 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
272 if let Ok(data) = data.downcast::<NavigationData>() {
273 let newest_selection = self.selections.newest::<Point>(cx);
274 let buffer = self.buffer.read(cx).read(cx);
275 let offset = if buffer.can_resolve(&data.cursor_anchor) {
276 data.cursor_anchor.to_point(&buffer)
277 } else {
278 buffer.clip_point(data.cursor_position, Bias::Left)
279 };
280
281 let scroll_top_anchor = if buffer.can_resolve(&data.scroll_top_anchor) {
282 data.scroll_top_anchor
283 } else {
284 buffer.anchor_before(
285 buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
286 )
287 };
288
289 drop(buffer);
290
291 if newest_selection.head() == offset {
292 false
293 } else {
294 let nav_history = self.nav_history.take();
295 self.scroll_position = data.scroll_position;
296 self.scroll_top_anchor = scroll_top_anchor;
297 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
298 s.select_ranges([offset..offset])
299 });
300 self.nav_history = nav_history;
301 true
302 }
303 } else {
304 false
305 }
306 }
307
308 fn tab_description<'a>(&'a self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>> {
309 match path_for_buffer(&self.buffer, detail, true, cx)? {
310 Cow::Borrowed(path) => Some(path.to_string_lossy()),
311 Cow::Owned(path) => Some(path.to_string_lossy().to_string().into()),
312 }
313 }
314
315 fn tab_content(
316 &self,
317 detail: Option<usize>,
318 style: &theme::Tab,
319 cx: &AppContext,
320 ) -> ElementBox {
321 Flex::row()
322 .with_child(
323 Label::new(self.title(cx).into(), style.label.clone())
324 .aligned()
325 .boxed(),
326 )
327 .with_children(detail.and_then(|detail| {
328 let path = path_for_buffer(&self.buffer, detail, false, cx)?;
329 let description = path.to_string_lossy();
330 Some(
331 Label::new(
332 if description.len() > MAX_TAB_TITLE_LEN {
333 description[..MAX_TAB_TITLE_LEN].to_string() + "…"
334 } else {
335 description.into()
336 },
337 style.description.text.clone(),
338 )
339 .contained()
340 .with_style(style.description.container)
341 .aligned()
342 .boxed(),
343 )
344 }))
345 .boxed()
346 }
347
348 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
349 let buffer = self.buffer.read(cx).as_singleton()?;
350 let file = buffer.read(cx).file();
351 File::from_dyn(file).map(|file| ProjectPath {
352 worktree_id: file.worktree_id(cx),
353 path: file.path().clone(),
354 })
355 }
356
357 fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
358 self.buffer
359 .read(cx)
360 .files(cx)
361 .into_iter()
362 .filter_map(|file| File::from_dyn(Some(file))?.project_entry_id(cx))
363 .collect()
364 }
365
366 fn is_singleton(&self, cx: &AppContext) -> bool {
367 self.buffer.read(cx).is_singleton()
368 }
369
370 fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
371 where
372 Self: Sized,
373 {
374 Some(self.clone(cx))
375 }
376
377 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
378 self.nav_history = Some(history);
379 }
380
381 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
382 let selection = self.selections.newest_anchor();
383 self.push_to_nav_history(selection.head(), None, cx);
384 }
385
386 fn workspace_deactivated(&mut self, cx: &mut ViewContext<Self>) {
387 hide_link_definition(self, cx);
388 self.link_go_to_definition_state.last_mouse_location = None;
389 }
390
391 fn is_dirty(&self, cx: &AppContext) -> bool {
392 self.buffer().read(cx).read(cx).is_dirty()
393 }
394
395 fn has_conflict(&self, cx: &AppContext) -> bool {
396 self.buffer().read(cx).read(cx).has_conflict()
397 }
398
399 fn can_save(&self, cx: &AppContext) -> bool {
400 !self.buffer().read(cx).is_singleton() || self.project_path(cx).is_some()
401 }
402
403 fn save(
404 &mut self,
405 project: ModelHandle<Project>,
406 cx: &mut ViewContext<Self>,
407 ) -> Task<Result<()>> {
408 self.report_event("save editor", cx);
409
410 let buffer = self.buffer().clone();
411 let buffers = buffer.read(cx).all_buffers();
412 let mut timeout = cx.background().timer(FORMAT_TIMEOUT).fuse();
413 let format = project.update(cx, |project, cx| {
414 project.format(buffers, true, FormatTrigger::Save, cx)
415 });
416 cx.spawn(|_, mut cx| async move {
417 let transaction = futures::select_biased! {
418 _ = timeout => {
419 log::warn!("timed out waiting for formatting");
420 None
421 }
422 transaction = format.log_err().fuse() => transaction,
423 };
424
425 buffer
426 .update(&mut cx, |buffer, cx| {
427 if let Some(transaction) = transaction {
428 if !buffer.is_singleton() {
429 buffer.push_transaction(&transaction.0);
430 }
431 }
432
433 buffer.save(cx)
434 })
435 .await?;
436 Ok(())
437 })
438 }
439
440 fn save_as(
441 &mut self,
442 project: ModelHandle<Project>,
443 abs_path: PathBuf,
444 cx: &mut ViewContext<Self>,
445 ) -> Task<Result<()>> {
446 let buffer = self
447 .buffer()
448 .read(cx)
449 .as_singleton()
450 .expect("cannot call save_as on an excerpt list");
451
452 project.update(cx, |project, cx| {
453 project.save_buffer_as(buffer, abs_path, cx)
454 })
455 }
456
457 fn reload(
458 &mut self,
459 project: ModelHandle<Project>,
460 cx: &mut ViewContext<Self>,
461 ) -> Task<Result<()>> {
462 let buffer = self.buffer().clone();
463 let buffers = self.buffer.read(cx).all_buffers();
464 let reload_buffers =
465 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
466 cx.spawn(|this, mut cx| async move {
467 let transaction = reload_buffers.log_err().await;
468 this.update(&mut cx, |editor, cx| {
469 editor.request_autoscroll(Autoscroll::fit(), cx)
470 });
471 buffer.update(&mut cx, |buffer, _| {
472 if let Some(transaction) = transaction {
473 if !buffer.is_singleton() {
474 buffer.push_transaction(&transaction.0);
475 }
476 }
477 });
478 Ok(())
479 })
480 }
481
482 fn git_diff_recalc(
483 &mut self,
484 _project: ModelHandle<Project>,
485 cx: &mut ViewContext<Self>,
486 ) -> Task<Result<()>> {
487 self.buffer().update(cx, |multibuffer, cx| {
488 multibuffer.git_diff_recalc(cx);
489 });
490 Task::ready(Ok(()))
491 }
492
493 fn to_item_events(event: &Self::Event) -> Vec<workspace::ItemEvent> {
494 let mut result = Vec::new();
495 match event {
496 Event::Closed => result.push(ItemEvent::CloseItem),
497 Event::Saved | Event::TitleChanged => {
498 result.push(ItemEvent::UpdateTab);
499 result.push(ItemEvent::UpdateBreadcrumbs);
500 }
501 Event::Reparsed => {
502 result.push(ItemEvent::UpdateBreadcrumbs);
503 }
504 Event::SelectionsChanged { local } if *local => {
505 result.push(ItemEvent::UpdateBreadcrumbs);
506 }
507 Event::DirtyChanged => {
508 result.push(ItemEvent::UpdateTab);
509 }
510 Event::BufferEdited => {
511 result.push(ItemEvent::Edit);
512 result.push(ItemEvent::UpdateBreadcrumbs);
513 }
514 _ => {}
515 }
516 result
517 }
518
519 fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
520 Some(Box::new(handle.clone()))
521 }
522
523 fn breadcrumb_location(&self) -> ToolbarItemLocation {
524 ToolbarItemLocation::PrimaryLeft { flex: None }
525 }
526
527 fn breadcrumbs(&self, theme: &theme::Theme, cx: &AppContext) -> Option<Vec<ElementBox>> {
528 let cursor = self.selections.newest_anchor().head();
529 let multibuffer = &self.buffer().read(cx);
530 let (buffer_id, symbols) =
531 multibuffer.symbols_containing(cursor, Some(&theme.editor.syntax), cx)?;
532 let buffer = multibuffer.buffer(buffer_id)?;
533
534 let buffer = buffer.read(cx);
535 let filename = buffer
536 .snapshot()
537 .resolve_file_path(
538 cx,
539 self.project
540 .as_ref()
541 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
542 .unwrap_or_default(),
543 )
544 .map(|path| path.to_string_lossy().to_string())
545 .unwrap_or_else(|| "untitled".to_string());
546
547 let mut breadcrumbs = vec![Label::new(filename, theme.breadcrumbs.text.clone()).boxed()];
548 breadcrumbs.extend(symbols.into_iter().map(|symbol| {
549 Text::new(symbol.text, theme.breadcrumbs.text.clone())
550 .with_highlights(symbol.highlight_ranges)
551 .boxed()
552 }));
553 Some(breadcrumbs)
554 }
555}
556
557impl ProjectItem for Editor {
558 type Item = Buffer;
559
560 fn for_project_item(
561 project: ModelHandle<Project>,
562 buffer: ModelHandle<Buffer>,
563 cx: &mut ViewContext<Self>,
564 ) -> Self {
565 Self::for_buffer(buffer, Some(project), cx)
566 }
567}
568
569enum BufferSearchHighlights {}
570impl SearchableItem for Editor {
571 type Match = Range<Anchor>;
572
573 fn to_search_event(event: &Self::Event) -> Option<SearchEvent> {
574 match event {
575 Event::BufferEdited => Some(SearchEvent::MatchesInvalidated),
576 Event::SelectionsChanged { .. } => Some(SearchEvent::ActiveMatchChanged),
577 _ => None,
578 }
579 }
580
581 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
582 self.clear_background_highlights::<BufferSearchHighlights>(cx);
583 }
584
585 fn update_matches(&mut self, matches: Vec<Range<Anchor>>, cx: &mut ViewContext<Self>) {
586 self.highlight_background::<BufferSearchHighlights>(
587 matches,
588 |theme| theme.search.match_background,
589 cx,
590 );
591 }
592
593 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
594 let display_map = self.snapshot(cx).display_snapshot;
595 let selection = self.selections.newest::<usize>(cx);
596 if selection.start == selection.end {
597 let point = selection.start.to_display_point(&display_map);
598 let range = surrounding_word(&display_map, point);
599 let range = range.start.to_offset(&display_map, Bias::Left)
600 ..range.end.to_offset(&display_map, Bias::Right);
601 let text: String = display_map.buffer_snapshot.text_for_range(range).collect();
602 if text.trim().is_empty() {
603 String::new()
604 } else {
605 text
606 }
607 } else {
608 display_map
609 .buffer_snapshot
610 .text_for_range(selection.start..selection.end)
611 .collect()
612 }
613 }
614
615 fn activate_match(
616 &mut self,
617 index: usize,
618 matches: Vec<Range<Anchor>>,
619 cx: &mut ViewContext<Self>,
620 ) {
621 self.unfold_ranges([matches[index].clone()], false, cx);
622 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
623 s.select_ranges([matches[index].clone()])
624 });
625 }
626
627 fn match_index_for_direction(
628 &mut self,
629 matches: &Vec<Range<Anchor>>,
630 mut current_index: usize,
631 direction: Direction,
632 cx: &mut ViewContext<Self>,
633 ) -> usize {
634 let buffer = self.buffer().read(cx).snapshot(cx);
635 let cursor = self.selections.newest_anchor().head();
636 if matches[current_index].start.cmp(&cursor, &buffer).is_gt() {
637 if direction == Direction::Prev {
638 if current_index == 0 {
639 current_index = matches.len() - 1;
640 } else {
641 current_index -= 1;
642 }
643 }
644 } else if matches[current_index].end.cmp(&cursor, &buffer).is_lt() {
645 if direction == Direction::Next {
646 current_index = 0;
647 }
648 } else if direction == Direction::Prev {
649 if current_index == 0 {
650 current_index = matches.len() - 1;
651 } else {
652 current_index -= 1;
653 }
654 } else if direction == Direction::Next {
655 if current_index == matches.len() - 1 {
656 current_index = 0
657 } else {
658 current_index += 1;
659 }
660 };
661 current_index
662 }
663
664 fn find_matches(
665 &mut self,
666 query: project::search::SearchQuery,
667 cx: &mut ViewContext<Self>,
668 ) -> Task<Vec<Range<Anchor>>> {
669 let buffer = self.buffer().read(cx).snapshot(cx);
670 cx.background().spawn(async move {
671 let mut ranges = Vec::new();
672 if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
673 ranges.extend(
674 query
675 .search(excerpt_buffer.as_rope())
676 .await
677 .into_iter()
678 .map(|range| {
679 buffer.anchor_after(range.start)..buffer.anchor_before(range.end)
680 }),
681 );
682 } else {
683 for excerpt in buffer.excerpt_boundaries_in_range(0..buffer.len()) {
684 let excerpt_range = excerpt.range.context.to_offset(&excerpt.buffer);
685 let rope = excerpt.buffer.as_rope().slice(excerpt_range.clone());
686 ranges.extend(query.search(&rope).await.into_iter().map(|range| {
687 let start = excerpt
688 .buffer
689 .anchor_after(excerpt_range.start + range.start);
690 let end = excerpt
691 .buffer
692 .anchor_before(excerpt_range.start + range.end);
693 buffer.anchor_in_excerpt(excerpt.id.clone(), start)
694 ..buffer.anchor_in_excerpt(excerpt.id.clone(), end)
695 }));
696 }
697 }
698 ranges
699 })
700 }
701
702 fn active_match_index(
703 &mut self,
704 matches: Vec<Range<Anchor>>,
705 cx: &mut ViewContext<Self>,
706 ) -> Option<usize> {
707 active_match_index(
708 &matches,
709 &self.selections.newest_anchor().head(),
710 &self.buffer().read(cx).snapshot(cx),
711 )
712 }
713}
714
715pub fn active_match_index(
716 ranges: &[Range<Anchor>],
717 cursor: &Anchor,
718 buffer: &MultiBufferSnapshot,
719) -> Option<usize> {
720 if ranges.is_empty() {
721 None
722 } else {
723 match ranges.binary_search_by(|probe| {
724 if probe.end.cmp(cursor, &*buffer).is_lt() {
725 Ordering::Less
726 } else if probe.start.cmp(cursor, &*buffer).is_gt() {
727 Ordering::Greater
728 } else {
729 Ordering::Equal
730 }
731 }) {
732 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
733 }
734 }
735}
736
737pub struct CursorPosition {
738 position: Option<Point>,
739 selected_count: usize,
740 _observe_active_editor: Option<Subscription>,
741}
742
743impl Default for CursorPosition {
744 fn default() -> Self {
745 Self::new()
746 }
747}
748
749impl CursorPosition {
750 pub fn new() -> Self {
751 Self {
752 position: None,
753 selected_count: 0,
754 _observe_active_editor: None,
755 }
756 }
757
758 fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
759 let editor = editor.read(cx);
760 let buffer = editor.buffer().read(cx).snapshot(cx);
761
762 self.selected_count = 0;
763 let mut last_selection: Option<Selection<usize>> = None;
764 for selection in editor.selections.all::<usize>(cx) {
765 self.selected_count += selection.end - selection.start;
766 if last_selection
767 .as_ref()
768 .map_or(true, |last_selection| selection.id > last_selection.id)
769 {
770 last_selection = Some(selection);
771 }
772 }
773 self.position = last_selection.map(|s| s.head().to_point(&buffer));
774
775 cx.notify();
776 }
777}
778
779impl Entity for CursorPosition {
780 type Event = ();
781}
782
783impl View for CursorPosition {
784 fn ui_name() -> &'static str {
785 "CursorPosition"
786 }
787
788 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
789 if let Some(position) = self.position {
790 let theme = &cx.global::<Settings>().theme.workspace.status_bar;
791 let mut text = format!("{},{}", position.row + 1, position.column + 1);
792 if self.selected_count > 0 {
793 write!(text, " ({} selected)", self.selected_count).unwrap();
794 }
795 Label::new(text, theme.cursor_position.clone()).boxed()
796 } else {
797 Empty::new().boxed()
798 }
799 }
800}
801
802impl StatusItemView for CursorPosition {
803 fn set_active_pane_item(
804 &mut self,
805 active_pane_item: Option<&dyn ItemHandle>,
806 cx: &mut ViewContext<Self>,
807 ) {
808 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
809 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
810 self.update_position(editor, cx);
811 } else {
812 self.position = None;
813 self._observe_active_editor = None;
814 }
815
816 cx.notify();
817 }
818}
819
820fn path_for_buffer<'a>(
821 buffer: &ModelHandle<MultiBuffer>,
822 mut height: usize,
823 include_filename: bool,
824 cx: &'a AppContext,
825) -> Option<Cow<'a, Path>> {
826 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
827 // Ensure we always render at least the filename.
828 height += 1;
829
830 let mut prefix = file.path().as_ref();
831 while height > 0 {
832 if let Some(parent) = prefix.parent() {
833 prefix = parent;
834 height -= 1;
835 } else {
836 break;
837 }
838 }
839
840 // Here we could have just always used `full_path`, but that is very
841 // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
842 // traversed all the way up to the worktree's root.
843 if height > 0 {
844 let full_path = file.full_path(cx);
845 if include_filename {
846 Some(full_path.into())
847 } else {
848 Some(full_path.parent().unwrap().to_path_buf().into())
849 }
850 } else {
851 let mut path = file.path().strip_prefix(prefix).unwrap();
852 if !include_filename {
853 path = path.parent().unwrap();
854 }
855 Some(path.into())
856 }
857}