items.rs

   1use crate::{
   2    display_map::ToDisplayPoint, link_go_to_definition::hide_link_definition,
   3    movement::surrounding_word, persistence::DB, scroll::ScrollAnchor, Anchor, Autoscroll, Editor,
   4    Event, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, NavigationData, ToPoint as _,
   5};
   6use anyhow::{anyhow, Context, Result};
   7use collections::HashSet;
   8use futures::future::try_join_all;
   9use gpui::{
  10    div, point, AnyElement, AppContext, AsyncAppContext, Entity, EntityId, EventEmitter,
  11    FocusHandle, Model, ParentElement, Pixels, SharedString, Styled, Subscription, Task, View,
  12    ViewContext, VisualContext, WeakView,
  13};
  14use language::{
  15    proto::serialize_anchor as serialize_text_anchor, Bias, Buffer, OffsetRangeExt, Point,
  16    SelectionGoal,
  17};
  18use project::{search::SearchQuery, FormatTrigger, Item as _, Project, ProjectPath};
  19use rpc::proto::{self, update_view, PeerId};
  20use smallvec::SmallVec;
  21use std::{
  22    borrow::Cow,
  23    cmp::{self, Ordering},
  24    iter,
  25    ops::Range,
  26    path::{Path, PathBuf},
  27    sync::Arc,
  28};
  29use text::Selection;
  30use theme::{ActiveTheme, Theme};
  31use util::{paths::PathExt, ResultExt, TryFutureExt};
  32use workspace::item::{BreadcrumbText, FollowEvent, FollowableEvents, FollowableItemHandle};
  33use workspace::{
  34    item::{FollowableItem, Item, ItemEvent, ItemHandle, ProjectItem},
  35    searchable::{Direction, SearchEvent, SearchableItem, SearchableItemHandle},
  36    ItemId, ItemNavHistory, Pane, ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
  37};
  38
  39pub const MAX_TAB_TITLE_LEN: usize = 24;
  40
  41impl FollowableEvents for Event {
  42    fn to_follow_event(&self) -> Option<workspace::item::FollowEvent> {
  43        match self {
  44            Event::Edited => Some(FollowEvent::Unfollow),
  45            Event::SelectionsChanged { local } | Event::ScrollPositionChanged { local, .. } => {
  46                if *local {
  47                    Some(FollowEvent::Unfollow)
  48                } else {
  49                    None
  50                }
  51            }
  52            _ => None,
  53        }
  54    }
  55}
  56
  57impl EventEmitter<ItemEvent> for Editor {}
  58
  59impl FollowableItem for Editor {
  60    type FollowableEvent = Event;
  61    fn remote_id(&self) -> Option<ViewId> {
  62        self.remote_id
  63    }
  64
  65    fn from_state_proto(
  66        pane: View<workspace::Pane>,
  67        workspace: View<Workspace>,
  68        remote_id: ViewId,
  69        state: &mut Option<proto::view::Variant>,
  70        cx: &mut AppContext,
  71    ) -> Option<Task<Result<View<Self>>>> {
  72        todo!()
  73    }
  74    //     let project = workspace.read(cx).project().to_owned();
  75    //     let Some(proto::view::Variant::Editor(_)) = state else {
  76    //         return None;
  77    //     };
  78    //     let Some(proto::view::Variant::Editor(state)) = state.take() else {
  79    //         unreachable!()
  80    //     };
  81
  82    //     let client = project.read(cx).client();
  83    //     let replica_id = project.read(cx).replica_id();
  84    //     let buffer_ids = state
  85    //         .excerpts
  86    //         .iter()
  87    //         .map(|excerpt| excerpt.buffer_id)
  88    //         .collect::<HashSet<_>>();
  89    //     let buffers = project.update(cx, |project, cx| {
  90    //         buffer_ids
  91    //             .iter()
  92    //             .map(|id| project.open_buffer_by_id(*id, cx))
  93    //             .collect::<Vec<_>>()
  94    //     });
  95
  96    //     let pane = pane.downgrade();
  97    //     Some(cx.spawn(|mut cx| async move {
  98    //         let mut buffers = futures::future::try_join_all(buffers).await?;
  99    //         let editor = pane.read_with(&cx, |pane, cx| {
 100    //             let mut editors = pane.items_of_type::<Self>();
 101    //             editors.find(|editor| {
 102    //                 let ids_match = editor.remote_id(&client, cx) == Some(remote_id);
 103    //                 let singleton_buffer_matches = state.singleton
 104    //                     && buffers.first()
 105    //                         == editor.read(cx).buffer.read(cx).as_singleton().as_ref();
 106    //                 ids_match || singleton_buffer_matches
 107    //             })
 108    //         })?;
 109
 110    //         let editor = if let Some(editor) = editor {
 111    //             editor
 112    //         } else {
 113    //             pane.update(&mut cx, |_, cx| {
 114    //                 let multibuffer = cx.add_model(|cx| {
 115    //                     let mut multibuffer;
 116    //                     if state.singleton && buffers.len() == 1 {
 117    //                         multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
 118    //                     } else {
 119    //                         multibuffer = MultiBuffer::new(replica_id);
 120    //                         let mut excerpts = state.excerpts.into_iter().peekable();
 121    //                         while let Some(excerpt) = excerpts.peek() {
 122    //                             let buffer_id = excerpt.buffer_id;
 123    //                             let buffer_excerpts = iter::from_fn(|| {
 124    //                                 let excerpt = excerpts.peek()?;
 125    //                                 (excerpt.buffer_id == buffer_id)
 126    //                                     .then(|| excerpts.next().unwrap())
 127    //                             });
 128    //                             let buffer =
 129    //                                 buffers.iter().find(|b| b.read(cx).remote_id() == buffer_id);
 130    //                             if let Some(buffer) = buffer {
 131    //                                 multibuffer.push_excerpts(
 132    //                                     buffer.clone(),
 133    //                                     buffer_excerpts.filter_map(deserialize_excerpt_range),
 134    //                                     cx,
 135    //                                 );
 136    //                             }
 137    //                         }
 138    //                     };
 139
 140    //                     if let Some(title) = &state.title {
 141    //                         multibuffer = multibuffer.with_title(title.clone())
 142    //                     }
 143
 144    //                     multibuffer
 145    //                 });
 146
 147    //                 cx.add_view(|cx| {
 148    //                     let mut editor =
 149    //                         Editor::for_multibuffer(multibuffer, Some(project.clone()), cx);
 150    //                     editor.remote_id = Some(remote_id);
 151    //                     editor
 152    //                 })
 153    //             })?
 154    //         };
 155
 156    //         update_editor_from_message(
 157    //             editor.downgrade(),
 158    //             project,
 159    //             proto::update_view::Editor {
 160    //                 selections: state.selections,
 161    //                 pending_selection: state.pending_selection,
 162    //                 scroll_top_anchor: state.scroll_top_anchor,
 163    //                 scroll_x: state.scroll_x,
 164    //                 scroll_y: state.scroll_y,
 165    //                 ..Default::default()
 166    //             },
 167    //             &mut cx,
 168    //         )
 169    //         .await?;
 170
 171    //         Ok(editor)
 172    //     }))
 173    // }
 174
 175    fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>) {
 176        self.leader_peer_id = leader_peer_id;
 177        if self.leader_peer_id.is_some() {
 178            self.buffer.update(cx, |buffer, cx| {
 179                buffer.remove_active_selections(cx);
 180            });
 181        } else if self.focus_handle.is_focused(cx) {
 182            self.buffer.update(cx, |buffer, cx| {
 183                buffer.set_active_selections(
 184                    &self.selections.disjoint_anchors(),
 185                    self.selections.line_mode,
 186                    self.cursor_shape,
 187                    cx,
 188                );
 189            });
 190        }
 191        cx.notify();
 192    }
 193
 194    fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
 195        let buffer = self.buffer.read(cx);
 196        let scroll_anchor = self.scroll_manager.anchor();
 197        let excerpts = buffer
 198            .read(cx)
 199            .excerpts()
 200            .map(|(id, buffer, range)| proto::Excerpt {
 201                id: id.to_proto(),
 202                buffer_id: buffer.remote_id(),
 203                context_start: Some(serialize_text_anchor(&range.context.start)),
 204                context_end: Some(serialize_text_anchor(&range.context.end)),
 205                primary_start: range
 206                    .primary
 207                    .as_ref()
 208                    .map(|range| serialize_text_anchor(&range.start)),
 209                primary_end: range
 210                    .primary
 211                    .as_ref()
 212                    .map(|range| serialize_text_anchor(&range.end)),
 213            })
 214            .collect();
 215
 216        Some(proto::view::Variant::Editor(proto::view::Editor {
 217            singleton: buffer.is_singleton(),
 218            title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
 219            excerpts,
 220            scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
 221            scroll_x: scroll_anchor.offset.x,
 222            scroll_y: scroll_anchor.offset.y,
 223            selections: self
 224                .selections
 225                .disjoint_anchors()
 226                .iter()
 227                .map(serialize_selection)
 228                .collect(),
 229            pending_selection: self
 230                .selections
 231                .pending_anchor()
 232                .as_ref()
 233                .map(serialize_selection),
 234        }))
 235    }
 236
 237    fn add_event_to_update_proto(
 238        &self,
 239        event: &Self::FollowableEvent,
 240        update: &mut Option<proto::update_view::Variant>,
 241        cx: &AppContext,
 242    ) -> bool {
 243        let update =
 244            update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
 245
 246        match update {
 247            proto::update_view::Variant::Editor(update) => match event {
 248                Event::ExcerptsAdded {
 249                    buffer,
 250                    predecessor,
 251                    excerpts,
 252                } => {
 253                    let buffer_id = buffer.read(cx).remote_id();
 254                    let mut excerpts = excerpts.iter();
 255                    if let Some((id, range)) = excerpts.next() {
 256                        update.inserted_excerpts.push(proto::ExcerptInsertion {
 257                            previous_excerpt_id: Some(predecessor.to_proto()),
 258                            excerpt: serialize_excerpt(buffer_id, id, range),
 259                        });
 260                        update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
 261                            proto::ExcerptInsertion {
 262                                previous_excerpt_id: None,
 263                                excerpt: serialize_excerpt(buffer_id, id, range),
 264                            }
 265                        }))
 266                    }
 267                    true
 268                }
 269                Event::ExcerptsRemoved { ids } => {
 270                    update
 271                        .deleted_excerpts
 272                        .extend(ids.iter().map(ExcerptId::to_proto));
 273                    true
 274                }
 275                Event::ScrollPositionChanged { .. } => {
 276                    let scroll_anchor = self.scroll_manager.anchor();
 277                    update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
 278                    update.scroll_x = scroll_anchor.offset.x;
 279                    update.scroll_y = scroll_anchor.offset.y;
 280                    true
 281                }
 282                Event::SelectionsChanged { .. } => {
 283                    update.selections = self
 284                        .selections
 285                        .disjoint_anchors()
 286                        .iter()
 287                        .map(serialize_selection)
 288                        .collect();
 289                    update.pending_selection = self
 290                        .selections
 291                        .pending_anchor()
 292                        .as_ref()
 293                        .map(serialize_selection);
 294                    true
 295                }
 296                _ => false,
 297            },
 298        }
 299    }
 300
 301    fn apply_update_proto(
 302        &mut self,
 303        project: &Model<Project>,
 304        message: update_view::Variant,
 305        cx: &mut ViewContext<Self>,
 306    ) -> Task<Result<()>> {
 307        let update_view::Variant::Editor(message) = message;
 308        let project = project.clone();
 309        cx.spawn(|this, mut cx| async move {
 310            update_editor_from_message(this, project, message, &mut cx).await
 311        })
 312    }
 313
 314    fn is_project_item(&self, _cx: &AppContext) -> bool {
 315        true
 316    }
 317}
 318
 319async fn update_editor_from_message(
 320    this: WeakView<Editor>,
 321    project: Model<Project>,
 322    message: proto::update_view::Editor,
 323    cx: &mut AsyncAppContext,
 324) -> Result<()> {
 325    todo!()
 326}
 327// Previous implementation of the above
 328//     // Open all of the buffers of which excerpts were added to the editor.
 329//     let inserted_excerpt_buffer_ids = message
 330//         .inserted_excerpts
 331//         .iter()
 332//         .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
 333//         .collect::<HashSet<_>>();
 334//     let inserted_excerpt_buffers = project.update(cx, |project, cx| {
 335//         inserted_excerpt_buffer_ids
 336//             .into_iter()
 337//             .map(|id| project.open_buffer_by_id(id, cx))
 338//             .collect::<Vec<_>>()
 339//     })?;
 340//     let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
 341
 342//     // Update the editor's excerpts.
 343//     this.update(cx, |editor, cx| {
 344//         editor.buffer.update(cx, |multibuffer, cx| {
 345//             let mut removed_excerpt_ids = message
 346//                 .deleted_excerpts
 347//                 .into_iter()
 348//                 .map(ExcerptId::from_proto)
 349//                 .collect::<Vec<_>>();
 350//             removed_excerpt_ids.sort_by({
 351//                 let multibuffer = multibuffer.read(cx);
 352//                 move |a, b| a.cmp(&b, &multibuffer)
 353//             });
 354
 355//             let mut insertions = message.inserted_excerpts.into_iter().peekable();
 356//             while let Some(insertion) = insertions.next() {
 357//                 let Some(excerpt) = insertion.excerpt else {
 358//                     continue;
 359//                 };
 360//                 let Some(previous_excerpt_id) = insertion.previous_excerpt_id else {
 361//                     continue;
 362//                 };
 363//                 let buffer_id = excerpt.buffer_id;
 364//                 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id) else {
 365//                     continue;
 366//                 };
 367
 368//                 let adjacent_excerpts = iter::from_fn(|| {
 369//                     let insertion = insertions.peek()?;
 370//                     if insertion.previous_excerpt_id.is_none()
 371//                         && insertion.excerpt.as_ref()?.buffer_id == buffer_id
 372//                     {
 373//                         insertions.next()?.excerpt
 374//                     } else {
 375//                         None
 376//                     }
 377//                 });
 378
 379//                 multibuffer.insert_excerpts_with_ids_after(
 380//                     ExcerptId::from_proto(previous_excerpt_id),
 381//                     buffer,
 382//                     [excerpt]
 383//                         .into_iter()
 384//                         .chain(adjacent_excerpts)
 385//                         .filter_map(|excerpt| {
 386//                             Some((
 387//                                 ExcerptId::from_proto(excerpt.id),
 388//                                 deserialize_excerpt_range(excerpt)?,
 389//                             ))
 390//                         }),
 391//                     cx,
 392//                 );
 393//             }
 394
 395//             multibuffer.remove_excerpts(removed_excerpt_ids, cx);
 396//         });
 397//     })?;
 398
 399//     // Deserialize the editor state.
 400//     let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {
 401//         let buffer = editor.buffer.read(cx).read(cx);
 402//         let selections = message
 403//             .selections
 404//             .into_iter()
 405//             .filter_map(|selection| deserialize_selection(&buffer, selection))
 406//             .collect::<Vec<_>>();
 407//         let pending_selection = message
 408//             .pending_selection
 409//             .and_then(|selection| deserialize_selection(&buffer, selection));
 410//         let scroll_top_anchor = message
 411//             .scroll_top_anchor
 412//             .and_then(|anchor| deserialize_anchor(&buffer, anchor));
 413//         anyhow::Ok((selections, pending_selection, scroll_top_anchor))
 414//     })??;
 415
 416//     // Wait until the buffer has received all of the operations referenced by
 417//     // the editor's new state.
 418//     this.update(cx, |editor, cx| {
 419//         editor.buffer.update(cx, |buffer, cx| {
 420//             buffer.wait_for_anchors(
 421//                 selections
 422//                     .iter()
 423//                     .chain(pending_selection.as_ref())
 424//                     .flat_map(|selection| [selection.start, selection.end])
 425//                     .chain(scroll_top_anchor),
 426//                 cx,
 427//             )
 428//         })
 429//     })?
 430//     .await?;
 431
 432//     // Update the editor's state.
 433//     this.update(cx, |editor, cx| {
 434//         if !selections.is_empty() || pending_selection.is_some() {
 435//             editor.set_selections_from_remote(selections, pending_selection, cx);
 436//             editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
 437//         } else if let Some(scroll_top_anchor) = scroll_top_anchor {
 438//             editor.set_scroll_anchor_remote(
 439//                 ScrollAnchor {
 440//                     anchor: scroll_top_anchor,
 441//                     offset: point(message.scroll_x, message.scroll_y),
 442//                 },
 443//                 cx,
 444//             );
 445//         }
 446//     })?;
 447//     Ok(())
 448// }
 449
 450fn serialize_excerpt(
 451    buffer_id: u64,
 452    id: &ExcerptId,
 453    range: &ExcerptRange<language::Anchor>,
 454) -> Option<proto::Excerpt> {
 455    Some(proto::Excerpt {
 456        id: id.to_proto(),
 457        buffer_id,
 458        context_start: Some(serialize_text_anchor(&range.context.start)),
 459        context_end: Some(serialize_text_anchor(&range.context.end)),
 460        primary_start: range
 461            .primary
 462            .as_ref()
 463            .map(|r| serialize_text_anchor(&r.start)),
 464        primary_end: range
 465            .primary
 466            .as_ref()
 467            .map(|r| serialize_text_anchor(&r.end)),
 468    })
 469}
 470
 471fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
 472    proto::Selection {
 473        id: selection.id as u64,
 474        start: Some(serialize_anchor(&selection.start)),
 475        end: Some(serialize_anchor(&selection.end)),
 476        reversed: selection.reversed,
 477    }
 478}
 479
 480fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
 481    proto::EditorAnchor {
 482        excerpt_id: anchor.excerpt_id.to_proto(),
 483        anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
 484    }
 485}
 486
 487fn deserialize_excerpt_range(excerpt: proto::Excerpt) -> Option<ExcerptRange<language::Anchor>> {
 488    let context = {
 489        let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
 490        let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
 491        start..end
 492    };
 493    let primary = excerpt
 494        .primary_start
 495        .zip(excerpt.primary_end)
 496        .and_then(|(start, end)| {
 497            let start = language::proto::deserialize_anchor(start)?;
 498            let end = language::proto::deserialize_anchor(end)?;
 499            Some(start..end)
 500        });
 501    Some(ExcerptRange { context, primary })
 502}
 503
 504fn deserialize_selection(
 505    buffer: &MultiBufferSnapshot,
 506    selection: proto::Selection,
 507) -> Option<Selection<Anchor>> {
 508    Some(Selection {
 509        id: selection.id as usize,
 510        start: deserialize_anchor(buffer, selection.start?)?,
 511        end: deserialize_anchor(buffer, selection.end?)?,
 512        reversed: selection.reversed,
 513        goal: SelectionGoal::None,
 514    })
 515}
 516
 517fn deserialize_anchor(buffer: &MultiBufferSnapshot, anchor: proto::EditorAnchor) -> Option<Anchor> {
 518    let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
 519    Some(Anchor {
 520        excerpt_id,
 521        text_anchor: language::proto::deserialize_anchor(anchor.anchor?)?,
 522        buffer_id: buffer.buffer_id_for_excerpt(excerpt_id),
 523    })
 524}
 525
 526impl Item for Editor {
 527    fn focus_handle(&self) -> FocusHandle {
 528        self.focus_handle.clone()
 529    }
 530
 531    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
 532        todo!();
 533        // if let Ok(data) = data.downcast::<NavigationData>() {
 534        //     let newest_selection = self.selections.newest::<Point>(cx);
 535        //     let buffer = self.buffer.read(cx).read(cx);
 536        //     let offset = if buffer.can_resolve(&data.cursor_anchor) {
 537        //         data.cursor_anchor.to_point(&buffer)
 538        //     } else {
 539        //         buffer.clip_point(data.cursor_position, Bias::Left)
 540        //     };
 541
 542        //     let mut scroll_anchor = data.scroll_anchor;
 543        //     if !buffer.can_resolve(&scroll_anchor.anchor) {
 544        //         scroll_anchor.anchor = buffer.anchor_before(
 545        //             buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
 546        //         );
 547        //     }
 548
 549        //     drop(buffer);
 550
 551        //     if newest_selection.head() == offset {
 552        //         false
 553        //     } else {
 554        //         let nav_history = self.nav_history.take();
 555        //         self.set_scroll_anchor(scroll_anchor, cx);
 556        //         self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 557        //             s.select_ranges([offset..offset])
 558        //         });
 559        //         self.nav_history = nav_history;
 560        //         true
 561        //     }
 562        // } else {
 563        //     false
 564        // }
 565    }
 566
 567    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
 568        let file_path = self
 569            .buffer()
 570            .read(cx)
 571            .as_singleton()?
 572            .read(cx)
 573            .file()
 574            .and_then(|f| f.as_local())?
 575            .abs_path(cx);
 576
 577        let file_path = file_path.compact().to_string_lossy().to_string();
 578
 579        Some(file_path.into())
 580    }
 581
 582    fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<SharedString> {
 583        let path = path_for_buffer(&self.buffer, detail, true, cx)?;
 584        Some(path.to_string_lossy().to_string().into())
 585    }
 586
 587    fn tab_content<T: 'static>(&self, detail: Option<usize>, cx: &AppContext) -> AnyElement<T> {
 588        let theme = cx.theme();
 589
 590        AnyElement::new(
 591            div()
 592                .flex()
 593                .flex_row()
 594                .items_center()
 595                .gap_2()
 596                .child(self.title(cx).to_string())
 597                .children(detail.and_then(|detail| {
 598                    let path = path_for_buffer(&self.buffer, detail, false, cx)?;
 599                    let description = path.to_string_lossy();
 600
 601                    Some(
 602                        div()
 603                            .text_color(theme.colors().text_muted)
 604                            .text_xs()
 605                            .child(util::truncate_and_trailoff(&description, MAX_TAB_TITLE_LEN)),
 606                    )
 607                })),
 608        )
 609    }
 610
 611    fn for_each_project_item(
 612        &self,
 613        cx: &AppContext,
 614        f: &mut dyn FnMut(EntityId, &dyn project::Item),
 615    ) {
 616        self.buffer
 617            .read(cx)
 618            .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
 619    }
 620
 621    fn is_singleton(&self, cx: &AppContext) -> bool {
 622        self.buffer.read(cx).is_singleton()
 623    }
 624
 625    fn clone_on_split(
 626        &self,
 627        _workspace_id: WorkspaceId,
 628        cx: &mut ViewContext<Self>,
 629    ) -> Option<View<Editor>>
 630    where
 631        Self: Sized,
 632    {
 633        Some(cx.build_view(|cx| self.clone(cx)))
 634    }
 635
 636    fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
 637        self.nav_history = Some(history);
 638    }
 639
 640    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 641        let selection = self.selections.newest_anchor();
 642        self.push_to_nav_history(selection.head(), None, cx);
 643    }
 644
 645    fn workspace_deactivated(&mut self, cx: &mut ViewContext<Self>) {
 646        hide_link_definition(self, cx);
 647        self.link_go_to_definition_state.last_trigger_point = None;
 648    }
 649
 650    fn is_dirty(&self, cx: &AppContext) -> bool {
 651        self.buffer().read(cx).read(cx).is_dirty()
 652    }
 653
 654    fn has_conflict(&self, cx: &AppContext) -> bool {
 655        self.buffer().read(cx).read(cx).has_conflict()
 656    }
 657
 658    fn can_save(&self, cx: &AppContext) -> bool {
 659        let buffer = &self.buffer().read(cx);
 660        if let Some(buffer) = buffer.as_singleton() {
 661            buffer.read(cx).project_path(cx).is_some()
 662        } else {
 663            true
 664        }
 665    }
 666
 667    fn save(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
 668        self.report_editor_event("save", None, cx);
 669        let format = self.perform_format(project.clone(), FormatTrigger::Save, cx);
 670        let buffers = self.buffer().clone().read(cx).all_buffers();
 671        cx.spawn(|_, mut cx| async move {
 672            format.await?;
 673
 674            if buffers.len() == 1 {
 675                project
 676                    .update(&mut cx, |project, cx| project.save_buffers(buffers, cx))?
 677                    .await?;
 678            } else {
 679                // For multi-buffers, only save those ones that contain changes. For clean buffers
 680                // we simulate saving by calling `Buffer::did_save`, so that language servers or
 681                // other downstream listeners of save events get notified.
 682                let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
 683                    buffer
 684                        .update(&mut cx, |buffer, _| {
 685                            buffer.is_dirty() || buffer.has_conflict()
 686                        })
 687                        .unwrap_or(false)
 688                });
 689
 690                project
 691                    .update(&mut cx, |project, cx| {
 692                        project.save_buffers(dirty_buffers, cx)
 693                    })?
 694                    .await?;
 695                for buffer in clean_buffers {
 696                    buffer.update(&mut cx, |buffer, cx| {
 697                        let version = buffer.saved_version().clone();
 698                        let fingerprint = buffer.saved_version_fingerprint();
 699                        let mtime = buffer.saved_mtime();
 700                        buffer.did_save(version, fingerprint, mtime, cx);
 701                    });
 702                }
 703            }
 704
 705            Ok(())
 706        })
 707    }
 708
 709    fn save_as(
 710        &mut self,
 711        project: Model<Project>,
 712        abs_path: PathBuf,
 713        cx: &mut ViewContext<Self>,
 714    ) -> Task<Result<()>> {
 715        let buffer = self
 716            .buffer()
 717            .read(cx)
 718            .as_singleton()
 719            .expect("cannot call save_as on an excerpt list");
 720
 721        let file_extension = abs_path
 722            .extension()
 723            .map(|a| a.to_string_lossy().to_string());
 724        self.report_editor_event("save", file_extension, cx);
 725
 726        project.update(cx, |project, cx| {
 727            project.save_buffer_as(buffer, abs_path, cx)
 728        })
 729    }
 730
 731    fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
 732        let buffer = self.buffer().clone();
 733        let buffers = self.buffer.read(cx).all_buffers();
 734        let reload_buffers =
 735            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
 736        cx.spawn(|this, mut cx| async move {
 737            let transaction = reload_buffers.log_err().await;
 738            this.update(&mut cx, |editor, cx| {
 739                editor.request_autoscroll(Autoscroll::fit(), cx)
 740            })?;
 741            buffer.update(&mut cx, |buffer, cx| {
 742                if let Some(transaction) = transaction {
 743                    if !buffer.is_singleton() {
 744                        buffer.push_transaction(&transaction.0, cx);
 745                    }
 746                }
 747            });
 748            Ok(())
 749        })
 750    }
 751
 752    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 753        Some(Box::new(handle.clone()))
 754    }
 755
 756    fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<gpui::Point<Pixels>> {
 757        self.pixel_position_of_newest_cursor
 758    }
 759
 760    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 761        ToolbarItemLocation::PrimaryLeft { flex: None }
 762    }
 763
 764    fn breadcrumbs(&self, variant: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 765        todo!();
 766        // let cursor = self.selections.newest_anchor().head();
 767        // let multibuffer = &self.buffer().read(cx);
 768        // let (buffer_id, symbols) =
 769        //     multibuffer.symbols_containing(cursor, Some(&theme.editor.syntax), cx)?;
 770        // let buffer = multibuffer.buffer(buffer_id)?;
 771
 772        // let buffer = buffer.read(cx);
 773        // let filename = buffer
 774        //     .snapshot()
 775        //     .resolve_file_path(
 776        //         cx,
 777        //         self.project
 778        //             .as_ref()
 779        //             .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 780        //             .unwrap_or_default(),
 781        //     )
 782        //     .map(|path| path.to_string_lossy().to_string())
 783        //     .unwrap_or_else(|| "untitled".to_string());
 784
 785        // let mut breadcrumbs = vec![BreadcrumbText {
 786        //     text: filename,
 787        //     highlights: None,
 788        // }];
 789        // breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
 790        //     text: symbol.text,
 791        //     highlights: Some(symbol.highlight_ranges),
 792        // }));
 793        // Some(breadcrumbs)
 794    }
 795
 796    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 797        let workspace_id = workspace.database_id();
 798        let item_id = cx.view().entity_id().as_u64() as ItemId;
 799        self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
 800
 801        fn serialize(
 802            buffer: Model<Buffer>,
 803            workspace_id: WorkspaceId,
 804            item_id: ItemId,
 805            cx: &mut AppContext,
 806        ) {
 807            if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
 808                let path = file.abs_path(cx);
 809
 810                cx.background_executor()
 811                    .spawn(async move {
 812                        DB.save_path(item_id, workspace_id, path.clone())
 813                            .await
 814                            .log_err()
 815                    })
 816                    .detach();
 817            }
 818        }
 819
 820        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 821            serialize(buffer.clone(), workspace_id, item_id, cx);
 822
 823            cx.subscribe(&buffer, |this, buffer, event, cx| {
 824                if let Some((_, workspace_id)) = this.workspace.as_ref() {
 825                    if let language::Event::FileHandleChanged = event {
 826                        serialize(
 827                            buffer,
 828                            *workspace_id,
 829                            cx.view().entity_id().as_u64() as ItemId,
 830                            cx,
 831                        );
 832                    }
 833                }
 834            })
 835            .detach();
 836        }
 837    }
 838
 839    fn serialized_item_kind() -> Option<&'static str> {
 840        Some("Editor")
 841    }
 842
 843    fn deserialize(
 844        project: Model<Project>,
 845        _workspace: WeakView<Workspace>,
 846        workspace_id: workspace::WorkspaceId,
 847        item_id: ItemId,
 848        cx: &mut ViewContext<Pane>,
 849    ) -> Task<Result<View<Self>>> {
 850        let project_item: Result<_> = project.update(cx, |project, cx| {
 851            // Look up the path with this key associated, create a self with that path
 852            let path = DB
 853                .get_path(item_id, workspace_id)?
 854                .context("No path stored for this editor")?;
 855
 856            let (worktree, path) = project
 857                .find_local_worktree(&path, cx)
 858                .with_context(|| format!("No worktree for path: {path:?}"))?;
 859            let project_path = ProjectPath {
 860                worktree_id: worktree.read(cx).id(),
 861                path: path.into(),
 862            };
 863
 864            Ok(project.open_path(project_path, cx))
 865        });
 866
 867        project_item
 868            .map(|project_item| {
 869                cx.spawn(|pane, mut cx| async move {
 870                    let (_, project_item) = project_item.await?;
 871                    let buffer = project_item
 872                        .downcast::<Buffer>()
 873                        .map_err(|_| anyhow!("Project item at stored path was not a buffer"))?;
 874                    Ok(pane.update(&mut cx, |_, cx| {
 875                        cx.build_view(|cx| {
 876                            let mut editor = Editor::for_buffer(buffer, Some(project), cx);
 877
 878                            editor.read_scroll_position_from_db(item_id, workspace_id, cx);
 879                            editor
 880                        })
 881                    })?)
 882                })
 883            })
 884            .unwrap_or_else(|error| Task::ready(Err(error)))
 885    }
 886}
 887
 888impl ProjectItem for Editor {
 889    type Item = Buffer;
 890
 891    fn for_project_item(
 892        project: Model<Project>,
 893        buffer: Model<Buffer>,
 894        cx: &mut ViewContext<Self>,
 895    ) -> Self {
 896        Self::for_buffer(buffer, Some(project), cx)
 897    }
 898}
 899
 900impl EventEmitter<SearchEvent> for Editor {}
 901
 902pub(crate) enum BufferSearchHighlights {}
 903impl SearchableItem for Editor {
 904    type Match = Range<Anchor>;
 905
 906    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
 907        todo!()
 908        // self.clear_background_highlights::<BufferSearchHighlights>(cx);
 909    }
 910
 911    fn update_matches(&mut self, matches: Vec<Range<Anchor>>, cx: &mut ViewContext<Self>) {
 912        todo!()
 913        // self.highlight_background::<BufferSearchHighlights>(
 914        //     matches,
 915        //     |theme| theme.search.match_background,
 916        //     cx,
 917        // );
 918    }
 919
 920    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
 921        let display_map = self.snapshot(cx).display_snapshot;
 922        let selection = self.selections.newest::<usize>(cx);
 923        if selection.start == selection.end {
 924            let point = selection.start.to_display_point(&display_map);
 925            let range = surrounding_word(&display_map, point);
 926            let range = range.start.to_offset(&display_map, Bias::Left)
 927                ..range.end.to_offset(&display_map, Bias::Right);
 928            let text: String = display_map.buffer_snapshot.text_for_range(range).collect();
 929            if text.trim().is_empty() {
 930                String::new()
 931            } else {
 932                text
 933            }
 934        } else {
 935            display_map
 936                .buffer_snapshot
 937                .text_for_range(selection.start..selection.end)
 938                .collect()
 939        }
 940    }
 941
 942    fn activate_match(
 943        &mut self,
 944        index: usize,
 945        matches: Vec<Range<Anchor>>,
 946        cx: &mut ViewContext<Self>,
 947    ) {
 948        todo!()
 949        // self.unfold_ranges([matches[index].clone()], false, true, cx);
 950        // let range = self.range_for_match(&matches[index]);
 951        // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 952        //     s.select_ranges([range]);
 953        // })
 954    }
 955
 956    fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 957        todo!()
 958        // self.unfold_ranges(matches.clone(), false, false, cx);
 959        // let mut ranges = Vec::new();
 960        // for m in &matches {
 961        //     ranges.push(self.range_for_match(&m))
 962        // }
 963        // self.change_selections(None, cx, |s| s.select_ranges(ranges));
 964    }
 965    fn replace(
 966        &mut self,
 967        identifier: &Self::Match,
 968        query: &SearchQuery,
 969        cx: &mut ViewContext<Self>,
 970    ) {
 971        let text = self.buffer.read(cx);
 972        let text = text.snapshot(cx);
 973        let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
 974        let text: Cow<_> = if text.len() == 1 {
 975            text.first().cloned().unwrap().into()
 976        } else {
 977            let joined_chunks = text.join("");
 978            joined_chunks.into()
 979        };
 980
 981        if let Some(replacement) = query.replacement_for(&text) {
 982            self.transact(cx, |this, cx| {
 983                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
 984            });
 985        }
 986    }
 987    fn match_index_for_direction(
 988        &mut self,
 989        matches: &Vec<Range<Anchor>>,
 990        current_index: usize,
 991        direction: Direction,
 992        count: usize,
 993        cx: &mut ViewContext<Self>,
 994    ) -> usize {
 995        let buffer = self.buffer().read(cx).snapshot(cx);
 996        let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
 997            self.selections.newest_anchor().head()
 998        } else {
 999            matches[current_index].start
1000        };
1001
1002        let mut count = count % matches.len();
1003        if count == 0 {
1004            return current_index;
1005        }
1006        match direction {
1007            Direction::Next => {
1008                if matches[current_index]
1009                    .start
1010                    .cmp(&current_index_position, &buffer)
1011                    .is_gt()
1012                {
1013                    count = count - 1
1014                }
1015
1016                (current_index + count) % matches.len()
1017            }
1018            Direction::Prev => {
1019                if matches[current_index]
1020                    .end
1021                    .cmp(&current_index_position, &buffer)
1022                    .is_lt()
1023                {
1024                    count = count - 1;
1025                }
1026
1027                if current_index >= count {
1028                    current_index - count
1029                } else {
1030                    matches.len() - (count - current_index)
1031                }
1032            }
1033        }
1034    }
1035
1036    fn find_matches(
1037        &mut self,
1038        query: Arc<project::search::SearchQuery>,
1039        cx: &mut ViewContext<Self>,
1040    ) -> Task<Vec<Range<Anchor>>> {
1041        let buffer = self.buffer().read(cx).snapshot(cx);
1042        cx.background_executor().spawn(async move {
1043            let mut ranges = Vec::new();
1044            if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
1045                ranges.extend(
1046                    query
1047                        .search(excerpt_buffer, None)
1048                        .await
1049                        .into_iter()
1050                        .map(|range| {
1051                            buffer.anchor_after(range.start)..buffer.anchor_before(range.end)
1052                        }),
1053                );
1054            } else {
1055                for excerpt in buffer.excerpt_boundaries_in_range(0..buffer.len()) {
1056                    let excerpt_range = excerpt.range.context.to_offset(&excerpt.buffer);
1057                    ranges.extend(
1058                        query
1059                            .search(&excerpt.buffer, Some(excerpt_range.clone()))
1060                            .await
1061                            .into_iter()
1062                            .map(|range| {
1063                                let start = excerpt
1064                                    .buffer
1065                                    .anchor_after(excerpt_range.start + range.start);
1066                                let end = excerpt
1067                                    .buffer
1068                                    .anchor_before(excerpt_range.start + range.end);
1069                                buffer.anchor_in_excerpt(excerpt.id.clone(), start)
1070                                    ..buffer.anchor_in_excerpt(excerpt.id.clone(), end)
1071                            }),
1072                    );
1073                }
1074            }
1075            ranges
1076        })
1077    }
1078
1079    fn active_match_index(
1080        &mut self,
1081        matches: Vec<Range<Anchor>>,
1082        cx: &mut ViewContext<Self>,
1083    ) -> Option<usize> {
1084        active_match_index(
1085            &matches,
1086            &self.selections.newest_anchor().head(),
1087            &self.buffer().read(cx).snapshot(cx),
1088        )
1089    }
1090}
1091
1092pub fn active_match_index(
1093    ranges: &[Range<Anchor>],
1094    cursor: &Anchor,
1095    buffer: &MultiBufferSnapshot,
1096) -> Option<usize> {
1097    if ranges.is_empty() {
1098        None
1099    } else {
1100        match ranges.binary_search_by(|probe| {
1101            if probe.end.cmp(cursor, &*buffer).is_lt() {
1102                Ordering::Less
1103            } else if probe.start.cmp(cursor, &*buffer).is_gt() {
1104                Ordering::Greater
1105            } else {
1106                Ordering::Equal
1107            }
1108        }) {
1109            Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1110        }
1111    }
1112}
1113
1114pub struct CursorPosition {
1115    position: Option<Point>,
1116    selected_count: usize,
1117    _observe_active_editor: Option<Subscription>,
1118}
1119
1120// impl Default for CursorPosition {
1121//     fn default() -> Self {
1122//         Self::new()
1123//     }
1124// }
1125
1126// impl CursorPosition {
1127//     pub fn new() -> Self {
1128//         Self {
1129//             position: None,
1130//             selected_count: 0,
1131//             _observe_active_editor: None,
1132//         }
1133//     }
1134
1135//     fn update_position(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
1136//         let editor = editor.read(cx);
1137//         let buffer = editor.buffer().read(cx).snapshot(cx);
1138
1139//         self.selected_count = 0;
1140//         let mut last_selection: Option<Selection<usize>> = None;
1141//         for selection in editor.selections.all::<usize>(cx) {
1142//             self.selected_count += selection.end - selection.start;
1143//             if last_selection
1144//                 .as_ref()
1145//                 .map_or(true, |last_selection| selection.id > last_selection.id)
1146//             {
1147//                 last_selection = Some(selection);
1148//             }
1149//         }
1150//         self.position = last_selection.map(|s| s.head().to_point(&buffer));
1151
1152//         cx.notify();
1153//     }
1154// }
1155
1156// impl Entity for CursorPosition {
1157//     type Event = ();
1158// }
1159
1160// impl View for CursorPosition {
1161//     fn ui_name() -> &'static str {
1162//         "CursorPosition"
1163//     }
1164
1165//     fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
1166//         if let Some(position) = self.position {
1167//             let theme = &theme::current(cx).workspace.status_bar;
1168//             let mut text = format!(
1169//                 "{}{FILE_ROW_COLUMN_DELIMITER}{}",
1170//                 position.row + 1,
1171//                 position.column + 1
1172//             );
1173//             if self.selected_count > 0 {
1174//                 write!(text, " ({} selected)", self.selected_count).unwrap();
1175//             }
1176//             Label::new(text, theme.cursor_position.clone()).into_any()
1177//         } else {
1178//             Empty::new().into_any()
1179//         }
1180//     }
1181// }
1182
1183// impl StatusItemView for CursorPosition {
1184//     fn set_active_pane_item(
1185//         &mut self,
1186//         active_pane_item: Option<&dyn ItemHandle>,
1187//         cx: &mut ViewContext<Self>,
1188//     ) {
1189//         if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
1190//             self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
1191//             self.update_position(editor, cx);
1192//         } else {
1193//             self.position = None;
1194//             self._observe_active_editor = None;
1195//         }
1196
1197//         cx.notify();
1198//     }
1199// }
1200
1201fn path_for_buffer<'a>(
1202    buffer: &Model<MultiBuffer>,
1203    height: usize,
1204    include_filename: bool,
1205    cx: &'a AppContext,
1206) -> Option<Cow<'a, Path>> {
1207    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1208    path_for_file(file.as_ref(), height, include_filename, cx)
1209}
1210
1211fn path_for_file<'a>(
1212    file: &'a dyn language::File,
1213    mut height: usize,
1214    include_filename: bool,
1215    cx: &'a AppContext,
1216) -> Option<Cow<'a, Path>> {
1217    // Ensure we always render at least the filename.
1218    height += 1;
1219
1220    let mut prefix = file.path().as_ref();
1221    while height > 0 {
1222        if let Some(parent) = prefix.parent() {
1223            prefix = parent;
1224            height -= 1;
1225        } else {
1226            break;
1227        }
1228    }
1229
1230    // Here we could have just always used `full_path`, but that is very
1231    // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1232    // traversed all the way up to the worktree's root.
1233    if height > 0 {
1234        let full_path = file.full_path(cx);
1235        if include_filename {
1236            Some(full_path.into())
1237        } else {
1238            Some(full_path.parent()?.to_path_buf().into())
1239        }
1240    } else {
1241        let mut path = file.path().strip_prefix(prefix).ok()?;
1242        if !include_filename {
1243            path = path.parent()?;
1244        }
1245        Some(path.into())
1246    }
1247}
1248
1249#[cfg(test)]
1250mod tests {
1251    use super::*;
1252    use gpui::AppContext;
1253    use std::{
1254        path::{Path, PathBuf},
1255        sync::Arc,
1256        time::SystemTime,
1257    };
1258
1259    #[gpui::test]
1260    fn test_path_for_file(cx: &mut AppContext) {
1261        let file = TestFile {
1262            path: Path::new("").into(),
1263            full_path: PathBuf::from(""),
1264        };
1265        assert_eq!(path_for_file(&file, 0, false, cx), None);
1266    }
1267
1268    struct TestFile {
1269        path: Arc<Path>,
1270        full_path: PathBuf,
1271    }
1272
1273    impl language::File for TestFile {
1274        fn path(&self) -> &Arc<Path> {
1275            &self.path
1276        }
1277
1278        fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
1279            self.full_path.clone()
1280        }
1281
1282        fn as_local(&self) -> Option<&dyn language::LocalFile> {
1283            unimplemented!()
1284        }
1285
1286        fn mtime(&self) -> SystemTime {
1287            unimplemented!()
1288        }
1289
1290        fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
1291            unimplemented!()
1292        }
1293
1294        fn worktree_id(&self) -> usize {
1295            0
1296        }
1297
1298        fn is_deleted(&self) -> bool {
1299            unimplemented!()
1300        }
1301
1302        fn as_any(&self) -> &dyn std::any::Any {
1303            unimplemented!()
1304        }
1305
1306        fn to_proto(&self) -> rpc::proto::File {
1307            unimplemented!()
1308        }
1309    }
1310}