items.rs

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