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