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