items.rs

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