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 _,
  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, 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    time::Duration,
 24};
 25use text::{Point, Selection};
 26use util::TryFutureExt;
 27use workspace::{
 28    searchable::{Direction, SearchEvent, SearchableItem, SearchableItemHandle},
 29    FollowableItem, Item, ItemHandle, ItemNavHistory, ProjectItem, StatusItemView,
 30};
 31
 32pub const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
 33pub const MAX_TAB_TITLE_LEN: usize = 24;
 34
 35impl FollowableItem for Editor {
 36    fn from_state_proto(
 37        pane: ViewHandle<workspace::Pane>,
 38        project: ModelHandle<Project>,
 39        state: &mut Option<proto::view::Variant>,
 40        cx: &mut MutableAppContext,
 41    ) -> Option<Task<Result<ViewHandle<Self>>>> {
 42        let state = if matches!(state, Some(proto::view::Variant::Editor(_))) {
 43            if let Some(proto::view::Variant::Editor(state)) = state.take() {
 44                state
 45            } else {
 46                unreachable!()
 47            }
 48        } else {
 49            return None;
 50        };
 51
 52        let buffer = project.update(cx, |project, cx| {
 53            project.open_buffer_by_id(state.buffer_id, cx)
 54        });
 55        Some(cx.spawn(|mut cx| async move {
 56            let buffer = buffer.await?;
 57            let editor = pane
 58                .read_with(&cx, |pane, cx| {
 59                    pane.items_of_type::<Self>().find(|editor| {
 60                        editor.read(cx).buffer.read(cx).as_singleton().as_ref() == Some(&buffer)
 61                    })
 62                })
 63                .unwrap_or_else(|| {
 64                    pane.update(&mut cx, |_, cx| {
 65                        cx.add_view(|cx| Editor::for_buffer(buffer, Some(project), cx))
 66                    })
 67                });
 68            editor.update(&mut cx, |editor, cx| {
 69                let excerpt_id;
 70                let buffer_id;
 71                {
 72                    let buffer = editor.buffer.read(cx).read(cx);
 73                    let singleton = buffer.as_singleton().unwrap();
 74                    excerpt_id = singleton.0.clone();
 75                    buffer_id = singleton.1;
 76                }
 77                let selections = state
 78                    .selections
 79                    .into_iter()
 80                    .map(|selection| {
 81                        deserialize_selection(&excerpt_id, buffer_id, selection)
 82                            .ok_or_else(|| anyhow!("invalid selection"))
 83                    })
 84                    .collect::<Result<Vec<_>>>()?;
 85                if !selections.is_empty() {
 86                    editor.set_selections_from_remote(selections, cx);
 87                }
 88
 89                if let Some(anchor) = state.scroll_top_anchor {
 90                    editor.set_scroll_top_anchor(
 91                        Anchor {
 92                            buffer_id: Some(state.buffer_id as usize),
 93                            excerpt_id,
 94                            text_anchor: language::proto::deserialize_anchor(anchor)
 95                                .ok_or_else(|| anyhow!("invalid scroll top"))?,
 96                        },
 97                        vec2f(state.scroll_x, state.scroll_y),
 98                        cx,
 99                    );
100                }
101
102                Ok::<_, anyhow::Error>(())
103            })?;
104            Ok(editor)
105        }))
106    }
107
108    fn set_leader_replica_id(
109        &mut self,
110        leader_replica_id: Option<u16>,
111        cx: &mut ViewContext<Self>,
112    ) {
113        self.leader_replica_id = leader_replica_id;
114        if self.leader_replica_id.is_some() {
115            self.buffer.update(cx, |buffer, cx| {
116                buffer.remove_active_selections(cx);
117            });
118        } else {
119            self.buffer.update(cx, |buffer, cx| {
120                if self.focused {
121                    buffer.set_active_selections(
122                        &self.selections.disjoint_anchors(),
123                        self.selections.line_mode,
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        let buffer = self.buffer().clone();
409        let buffers = buffer.read(cx).all_buffers();
410        let mut timeout = cx.background().timer(FORMAT_TIMEOUT).fuse();
411        let format = project.update(cx, |project, cx| project.format(buffers, true, cx));
412        cx.spawn(|_, mut cx| async move {
413            let transaction = futures::select_biased! {
414                _ = timeout => {
415                    log::warn!("timed out waiting for formatting");
416                    None
417                }
418                transaction = format.log_err().fuse() => transaction,
419            };
420
421            buffer
422                .update(&mut cx, |buffer, cx| {
423                    if let Some(transaction) = transaction {
424                        if !buffer.is_singleton() {
425                            buffer.push_transaction(&transaction.0);
426                        }
427                    }
428
429                    buffer.save(cx)
430                })
431                .await?;
432            Ok(())
433        })
434    }
435
436    fn save_as(
437        &mut self,
438        project: ModelHandle<Project>,
439        abs_path: PathBuf,
440        cx: &mut ViewContext<Self>,
441    ) -> Task<Result<()>> {
442        let buffer = self
443            .buffer()
444            .read(cx)
445            .as_singleton()
446            .expect("cannot call save_as on an excerpt list");
447
448        project.update(cx, |project, cx| {
449            project.save_buffer_as(buffer, abs_path, cx)
450        })
451    }
452
453    fn reload(
454        &mut self,
455        project: ModelHandle<Project>,
456        cx: &mut ViewContext<Self>,
457    ) -> Task<Result<()>> {
458        let buffer = self.buffer().clone();
459        let buffers = self.buffer.read(cx).all_buffers();
460        let reload_buffers =
461            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
462        cx.spawn(|this, mut cx| async move {
463            let transaction = reload_buffers.log_err().await;
464            this.update(&mut cx, |editor, cx| {
465                editor.request_autoscroll(Autoscroll::Fit, cx)
466            });
467            buffer.update(&mut cx, |buffer, _| {
468                if let Some(transaction) = transaction {
469                    if !buffer.is_singleton() {
470                        buffer.push_transaction(&transaction.0);
471                    }
472                }
473            });
474            Ok(())
475        })
476    }
477
478    fn should_close_item_on_event(event: &Event) -> bool {
479        matches!(event, Event::Closed)
480    }
481
482    fn should_update_tab_on_event(event: &Event) -> bool {
483        matches!(
484            event,
485            Event::Saved | Event::DirtyChanged | Event::TitleChanged
486        )
487    }
488
489    fn is_edit_event(event: &Self::Event) -> bool {
490        matches!(event, Event::BufferEdited)
491    }
492
493    fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
494        Some(Box::new(handle.clone()))
495    }
496}
497
498impl ProjectItem for Editor {
499    type Item = Buffer;
500
501    fn for_project_item(
502        project: ModelHandle<Project>,
503        buffer: ModelHandle<Buffer>,
504        cx: &mut ViewContext<Self>,
505    ) -> Self {
506        Self::for_buffer(buffer, Some(project), cx)
507    }
508}
509
510enum BufferSearchHighlights {}
511impl SearchableItem for Editor {
512    type Match = Range<Anchor>;
513
514    fn to_search_event(event: &Self::Event) -> Option<SearchEvent> {
515        match event {
516            Event::BufferEdited => Some(SearchEvent::MatchesInvalidated),
517            Event::SelectionsChanged { .. } => Some(SearchEvent::ActiveMatchChanged),
518            _ => None,
519        }
520    }
521
522    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
523        self.clear_background_highlights::<BufferSearchHighlights>(cx);
524    }
525
526    fn update_matches(&mut self, matches: Vec<Range<Anchor>>, cx: &mut ViewContext<Self>) {
527        self.highlight_background::<BufferSearchHighlights>(
528            matches,
529            |theme| theme.search.match_background,
530            cx,
531        );
532    }
533
534    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
535        let display_map = self.snapshot(cx).display_snapshot;
536        let selection = self.selections.newest::<usize>(cx);
537        if selection.start == selection.end {
538            let point = selection.start.to_display_point(&display_map);
539            let range = surrounding_word(&display_map, point);
540            let range = range.start.to_offset(&display_map, Bias::Left)
541                ..range.end.to_offset(&display_map, Bias::Right);
542            let text: String = display_map.buffer_snapshot.text_for_range(range).collect();
543            if text.trim().is_empty() {
544                String::new()
545            } else {
546                text
547            }
548        } else {
549            display_map
550                .buffer_snapshot
551                .text_for_range(selection.start..selection.end)
552                .collect()
553        }
554    }
555
556    fn activate_match(
557        &mut self,
558        index: usize,
559        matches: Vec<Range<Anchor>>,
560        cx: &mut ViewContext<Self>,
561    ) {
562        self.unfold_ranges([matches[index].clone()], false, cx);
563        self.change_selections(Some(Autoscroll::Fit), cx, |s| {
564            s.select_ranges([matches[index].clone()])
565        });
566    }
567
568    fn match_index_for_direction(
569        &mut self,
570        matches: &Vec<Range<Anchor>>,
571        mut current_index: usize,
572        direction: Direction,
573        cx: &mut ViewContext<Self>,
574    ) -> usize {
575        let buffer = self.buffer().read(cx).snapshot(cx);
576        let cursor = self.selections.newest_anchor().head();
577        if matches[current_index].start.cmp(&cursor, &buffer).is_gt() {
578            if direction == Direction::Prev {
579                if current_index == 0 {
580                    current_index = matches.len() - 1;
581                } else {
582                    current_index -= 1;
583                }
584            }
585        } else if matches[current_index].end.cmp(&cursor, &buffer).is_lt() {
586            if direction == Direction::Next {
587                current_index = 0;
588            }
589        } else if direction == Direction::Prev {
590            if current_index == 0 {
591                current_index = matches.len() - 1;
592            } else {
593                current_index -= 1;
594            }
595        } else if direction == Direction::Next {
596            if current_index == matches.len() - 1 {
597                current_index = 0
598            } else {
599                current_index += 1;
600            }
601        };
602        current_index
603    }
604
605    fn find_matches(
606        &mut self,
607        query: project::search::SearchQuery,
608        cx: &mut ViewContext<Self>,
609    ) -> Task<Vec<Range<Anchor>>> {
610        let buffer = self.buffer().read(cx).snapshot(cx);
611        cx.background().spawn(async move {
612            let mut ranges = Vec::new();
613            if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
614                ranges.extend(
615                    query
616                        .search(excerpt_buffer.as_rope())
617                        .await
618                        .into_iter()
619                        .map(|range| {
620                            buffer.anchor_after(range.start)..buffer.anchor_before(range.end)
621                        }),
622                );
623            } else {
624                for excerpt in buffer.excerpt_boundaries_in_range(0..buffer.len()) {
625                    let excerpt_range = excerpt.range.context.to_offset(&excerpt.buffer);
626                    let rope = excerpt.buffer.as_rope().slice(excerpt_range.clone());
627                    ranges.extend(query.search(&rope).await.into_iter().map(|range| {
628                        let start = excerpt
629                            .buffer
630                            .anchor_after(excerpt_range.start + range.start);
631                        let end = excerpt
632                            .buffer
633                            .anchor_before(excerpt_range.start + range.end);
634                        buffer.anchor_in_excerpt(excerpt.id.clone(), start)
635                            ..buffer.anchor_in_excerpt(excerpt.id.clone(), end)
636                    }));
637                }
638            }
639            ranges
640        })
641    }
642
643    fn active_match_index(
644        &mut self,
645        matches: Vec<Range<Anchor>>,
646        cx: &mut ViewContext<Self>,
647    ) -> Option<usize> {
648        active_match_index(
649            &matches,
650            &self.selections.newest_anchor().head(),
651            &self.buffer().read(cx).snapshot(cx),
652        )
653    }
654}
655
656pub fn active_match_index(
657    ranges: &[Range<Anchor>],
658    cursor: &Anchor,
659    buffer: &MultiBufferSnapshot,
660) -> Option<usize> {
661    if ranges.is_empty() {
662        None
663    } else {
664        match ranges.binary_search_by(|probe| {
665            if probe.end.cmp(cursor, &*buffer).is_lt() {
666                Ordering::Less
667            } else if probe.start.cmp(cursor, &*buffer).is_gt() {
668                Ordering::Greater
669            } else {
670                Ordering::Equal
671            }
672        }) {
673            Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
674        }
675    }
676}
677
678pub struct CursorPosition {
679    position: Option<Point>,
680    selected_count: usize,
681    _observe_active_editor: Option<Subscription>,
682}
683
684impl Default for CursorPosition {
685    fn default() -> Self {
686        Self::new()
687    }
688}
689
690impl CursorPosition {
691    pub fn new() -> Self {
692        Self {
693            position: None,
694            selected_count: 0,
695            _observe_active_editor: None,
696        }
697    }
698
699    fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
700        let editor = editor.read(cx);
701        let buffer = editor.buffer().read(cx).snapshot(cx);
702
703        self.selected_count = 0;
704        let mut last_selection: Option<Selection<usize>> = None;
705        for selection in editor.selections.all::<usize>(cx) {
706            self.selected_count += selection.end - selection.start;
707            if last_selection
708                .as_ref()
709                .map_or(true, |last_selection| selection.id > last_selection.id)
710            {
711                last_selection = Some(selection);
712            }
713        }
714        self.position = last_selection.map(|s| s.head().to_point(&buffer));
715
716        cx.notify();
717    }
718}
719
720impl Entity for CursorPosition {
721    type Event = ();
722}
723
724impl View for CursorPosition {
725    fn ui_name() -> &'static str {
726        "CursorPosition"
727    }
728
729    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
730        if let Some(position) = self.position {
731            let theme = &cx.global::<Settings>().theme.workspace.status_bar;
732            let mut text = format!("{},{}", position.row + 1, position.column + 1);
733            if self.selected_count > 0 {
734                write!(text, " ({} selected)", self.selected_count).unwrap();
735            }
736            Label::new(text, theme.cursor_position.clone()).boxed()
737        } else {
738            Empty::new().boxed()
739        }
740    }
741}
742
743impl StatusItemView for CursorPosition {
744    fn set_active_pane_item(
745        &mut self,
746        active_pane_item: Option<&dyn ItemHandle>,
747        cx: &mut ViewContext<Self>,
748    ) {
749        if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
750            self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
751            self.update_position(editor, cx);
752        } else {
753            self.position = None;
754            self._observe_active_editor = None;
755        }
756
757        cx.notify();
758    }
759}
760
761fn path_for_buffer<'a>(
762    buffer: &ModelHandle<MultiBuffer>,
763    mut height: usize,
764    include_filename: bool,
765    cx: &'a AppContext,
766) -> Option<Cow<'a, Path>> {
767    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
768    // Ensure we always render at least the filename.
769    height += 1;
770
771    let mut prefix = file.path().as_ref();
772    while height > 0 {
773        if let Some(parent) = prefix.parent() {
774            prefix = parent;
775            height -= 1;
776        } else {
777            break;
778        }
779    }
780
781    // Here we could have just always used `full_path`, but that is very
782    // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
783    // traversed all the way up to the worktree's root.
784    if height > 0 {
785        let full_path = file.full_path(cx);
786        if include_filename {
787            Some(full_path.into())
788        } else {
789            Some(full_path.parent().unwrap().to_path_buf().into())
790        }
791    } else {
792        let mut path = file.path().strip_prefix(prefix).unwrap();
793        if !include_filename {
794            path = path.parent().unwrap();
795        }
796        Some(path.into())
797    }
798}