items.rs

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