items.rs

   1use crate::{
   2    editor_settings::SeedQuerySetting,
   3    persistence::{SerializedEditor, DB},
   4    scroll::ScrollAnchor,
   5    Anchor, Autoscroll, Editor, EditorEvent, EditorSettings, ExcerptId, ExcerptRange, MultiBuffer,
   6    MultiBufferSnapshot, NavigationData, SearchWithinRange, ToPoint as _,
   7};
   8use anyhow::{anyhow, Context as _, Result};
   9use collections::HashSet;
  10use file_icons::FileIcons;
  11use futures::future::try_join_all;
  12use git::repository::GitFileStatus;
  13use gpui::{
  14    point, AnyElement, AppContext, AsyncWindowContext, Context, Entity, EntityId, EventEmitter,
  15    IntoElement, Model, ParentElement, Pixels, SharedString, Styled, Task, View, ViewContext,
  16    VisualContext, WeakView, WindowContext,
  17};
  18use language::{
  19    proto::serialize_anchor as serialize_text_anchor, Bias, Buffer, CharKind, Point, SelectionGoal,
  20};
  21use lsp::DiagnosticSeverity;
  22use multi_buffer::AnchorRangeExt;
  23use project::{
  24    lsp_store::FormatTrigger, project_settings::ProjectSettings, search::SearchQuery, Item as _,
  25    Project, ProjectPath,
  26};
  27use rpc::proto::{self, update_view, PeerId};
  28use settings::Settings;
  29use workspace::item::{Dedup, ItemSettings, SerializableItem, TabContentParams};
  30
  31use project::lsp_store::FormatTarget;
  32use std::{
  33    any::TypeId,
  34    borrow::Cow,
  35    cmp::{self, Ordering},
  36    iter,
  37    ops::Range,
  38    path::Path,
  39    sync::Arc,
  40};
  41use text::{BufferId, Selection};
  42use theme::{Theme, ThemeSettings};
  43use ui::{h_flex, prelude::*, IconDecorationKind, Label};
  44use util::{paths::PathExt, ResultExt, TryFutureExt};
  45use workspace::item::{BreadcrumbText, FollowEvent};
  46use workspace::{
  47    item::{FollowableItem, Item, ItemEvent, ProjectItem},
  48    searchable::{Direction, SearchEvent, SearchableItem, SearchableItemHandle},
  49    ItemId, ItemNavHistory, Pane, ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
  50};
  51
  52pub const MAX_TAB_TITLE_LEN: usize = 24;
  53
  54impl FollowableItem for Editor {
  55    fn remote_id(&self) -> Option<ViewId> {
  56        self.remote_id
  57    }
  58
  59    fn from_state_proto(
  60        workspace: View<Workspace>,
  61        remote_id: ViewId,
  62        state: &mut Option<proto::view::Variant>,
  63        cx: &mut WindowContext,
  64    ) -> Option<Task<Result<View<Self>>>> {
  65        let project = workspace.read(cx).project().to_owned();
  66        let Some(proto::view::Variant::Editor(_)) = state else {
  67            return None;
  68        };
  69        let Some(proto::view::Variant::Editor(state)) = state.take() else {
  70            unreachable!()
  71        };
  72
  73        let buffer_ids = state
  74            .excerpts
  75            .iter()
  76            .map(|excerpt| excerpt.buffer_id)
  77            .collect::<HashSet<_>>();
  78        let buffers = project.update(cx, |project, cx| {
  79            buffer_ids
  80                .iter()
  81                .map(|id| BufferId::new(*id).map(|id| project.open_buffer_by_id(id, cx)))
  82                .collect::<Result<Vec<_>>>()
  83        });
  84
  85        Some(cx.spawn(|mut cx| async move {
  86            let mut buffers = futures::future::try_join_all(buffers?)
  87                .await
  88                .debug_assert_ok("leaders don't share views for unshared buffers")?;
  89
  90            let editor = cx.update(|cx| {
  91                let multibuffer = cx.new_model(|cx| {
  92                    let mut multibuffer;
  93                    if state.singleton && buffers.len() == 1 {
  94                        multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
  95                    } else {
  96                        multibuffer = MultiBuffer::new(project.read(cx).capability());
  97                        let mut excerpts = state.excerpts.into_iter().peekable();
  98                        while let Some(excerpt) = excerpts.peek() {
  99                            let Ok(buffer_id) = BufferId::new(excerpt.buffer_id) else {
 100                                continue;
 101                            };
 102                            let buffer_excerpts = iter::from_fn(|| {
 103                                let excerpt = excerpts.peek()?;
 104                                (excerpt.buffer_id == u64::from(buffer_id))
 105                                    .then(|| excerpts.next().unwrap())
 106                            });
 107                            let buffer =
 108                                buffers.iter().find(|b| b.read(cx).remote_id() == buffer_id);
 109                            if let Some(buffer) = buffer {
 110                                multibuffer.push_excerpts(
 111                                    buffer.clone(),
 112                                    buffer_excerpts.filter_map(deserialize_excerpt_range),
 113                                    cx,
 114                                );
 115                            }
 116                        }
 117                    };
 118
 119                    if let Some(title) = &state.title {
 120                        multibuffer = multibuffer.with_title(title.clone())
 121                    }
 122
 123                    multibuffer
 124                });
 125
 126                cx.new_view(|cx| {
 127                    let mut editor =
 128                        Editor::for_multibuffer(multibuffer, Some(project.clone()), true, cx);
 129                    editor.remote_id = Some(remote_id);
 130                    editor
 131                })
 132            })?;
 133
 134            update_editor_from_message(
 135                editor.downgrade(),
 136                project,
 137                proto::update_view::Editor {
 138                    selections: state.selections,
 139                    pending_selection: state.pending_selection,
 140                    scroll_top_anchor: state.scroll_top_anchor,
 141                    scroll_x: state.scroll_x,
 142                    scroll_y: state.scroll_y,
 143                    ..Default::default()
 144                },
 145                &mut cx,
 146            )
 147            .await?;
 148
 149            Ok(editor)
 150        }))
 151    }
 152
 153    fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>) {
 154        self.leader_peer_id = leader_peer_id;
 155        if self.leader_peer_id.is_some() {
 156            self.buffer.update(cx, |buffer, cx| {
 157                buffer.remove_active_selections(cx);
 158            });
 159        } else if self.focus_handle.is_focused(cx) {
 160            self.buffer.update(cx, |buffer, cx| {
 161                buffer.set_active_selections(
 162                    &self.selections.disjoint_anchors(),
 163                    self.selections.line_mode,
 164                    self.cursor_shape,
 165                    cx,
 166                );
 167            });
 168        }
 169        cx.notify();
 170    }
 171
 172    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
 173        let buffer = self.buffer.read(cx);
 174        if buffer
 175            .as_singleton()
 176            .and_then(|buffer| buffer.read(cx).file())
 177            .map_or(false, |file| file.is_private())
 178        {
 179            return None;
 180        }
 181
 182        let scroll_anchor = self.scroll_manager.anchor();
 183        let excerpts = buffer
 184            .read(cx)
 185            .excerpts()
 186            .map(|(id, buffer, range)| proto::Excerpt {
 187                id: id.to_proto(),
 188                buffer_id: buffer.remote_id().into(),
 189                context_start: Some(serialize_text_anchor(&range.context.start)),
 190                context_end: Some(serialize_text_anchor(&range.context.end)),
 191                primary_start: range
 192                    .primary
 193                    .as_ref()
 194                    .map(|range| serialize_text_anchor(&range.start)),
 195                primary_end: range
 196                    .primary
 197                    .as_ref()
 198                    .map(|range| serialize_text_anchor(&range.end)),
 199            })
 200            .collect();
 201
 202        Some(proto::view::Variant::Editor(proto::view::Editor {
 203            singleton: buffer.is_singleton(),
 204            title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
 205            excerpts,
 206            scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
 207            scroll_x: scroll_anchor.offset.x,
 208            scroll_y: scroll_anchor.offset.y,
 209            selections: self
 210                .selections
 211                .disjoint_anchors()
 212                .iter()
 213                .map(serialize_selection)
 214                .collect(),
 215            pending_selection: self
 216                .selections
 217                .pending_anchor()
 218                .as_ref()
 219                .map(serialize_selection),
 220        }))
 221    }
 222
 223    fn to_follow_event(event: &EditorEvent) -> Option<workspace::item::FollowEvent> {
 224        match event {
 225            EditorEvent::Edited { .. } => Some(FollowEvent::Unfollow),
 226            EditorEvent::SelectionsChanged { local }
 227            | EditorEvent::ScrollPositionChanged { local, .. } => {
 228                if *local {
 229                    Some(FollowEvent::Unfollow)
 230                } else {
 231                    None
 232                }
 233            }
 234            _ => None,
 235        }
 236    }
 237
 238    fn add_event_to_update_proto(
 239        &self,
 240        event: &EditorEvent,
 241        update: &mut Option<proto::update_view::Variant>,
 242        cx: &WindowContext,
 243    ) -> bool {
 244        let update =
 245            update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
 246
 247        match update {
 248            proto::update_view::Variant::Editor(update) => match event {
 249                EditorEvent::ExcerptsAdded {
 250                    buffer,
 251                    predecessor,
 252                    excerpts,
 253                } => {
 254                    let buffer_id = buffer.read(cx).remote_id();
 255                    let mut excerpts = excerpts.iter();
 256                    if let Some((id, range)) = excerpts.next() {
 257                        update.inserted_excerpts.push(proto::ExcerptInsertion {
 258                            previous_excerpt_id: Some(predecessor.to_proto()),
 259                            excerpt: serialize_excerpt(buffer_id, id, range),
 260                        });
 261                        update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
 262                            proto::ExcerptInsertion {
 263                                previous_excerpt_id: None,
 264                                excerpt: serialize_excerpt(buffer_id, id, range),
 265                            }
 266                        }))
 267                    }
 268                    true
 269                }
 270                EditorEvent::ExcerptsRemoved { ids } => {
 271                    update
 272                        .deleted_excerpts
 273                        .extend(ids.iter().map(ExcerptId::to_proto));
 274                    true
 275                }
 276                EditorEvent::ScrollPositionChanged { autoscroll, .. } if !autoscroll => {
 277                    let scroll_anchor = self.scroll_manager.anchor();
 278                    update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
 279                    update.scroll_x = scroll_anchor.offset.x;
 280                    update.scroll_y = scroll_anchor.offset.y;
 281                    true
 282                }
 283                EditorEvent::SelectionsChanged { .. } => {
 284                    update.selections = self
 285                        .selections
 286                        .disjoint_anchors()
 287                        .iter()
 288                        .map(serialize_selection)
 289                        .collect();
 290                    update.pending_selection = self
 291                        .selections
 292                        .pending_anchor()
 293                        .as_ref()
 294                        .map(serialize_selection);
 295                    true
 296                }
 297                _ => false,
 298            },
 299        }
 300    }
 301
 302    fn apply_update_proto(
 303        &mut self,
 304        project: &Model<Project>,
 305        message: update_view::Variant,
 306        cx: &mut ViewContext<Self>,
 307    ) -> Task<Result<()>> {
 308        let update_view::Variant::Editor(message) = message;
 309        let project = project.clone();
 310        cx.spawn(|this, mut cx| async move {
 311            update_editor_from_message(this, project, message, &mut cx).await
 312        })
 313    }
 314
 315    fn is_project_item(&self, _cx: &WindowContext) -> bool {
 316        true
 317    }
 318
 319    fn dedup(&self, existing: &Self, cx: &WindowContext) -> Option<Dedup> {
 320        let self_singleton = self.buffer.read(cx).as_singleton()?;
 321        let other_singleton = existing.buffer.read(cx).as_singleton()?;
 322        if self_singleton == other_singleton {
 323            Some(Dedup::KeepExisting)
 324        } else {
 325            None
 326        }
 327    }
 328}
 329
 330async fn update_editor_from_message(
 331    this: WeakView<Editor>,
 332    project: Model<Project>,
 333    message: proto::update_view::Editor,
 334    cx: &mut AsyncWindowContext,
 335) -> Result<()> {
 336    // Open all of the buffers of which excerpts were added to the editor.
 337    let inserted_excerpt_buffer_ids = message
 338        .inserted_excerpts
 339        .iter()
 340        .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
 341        .collect::<HashSet<_>>();
 342    let inserted_excerpt_buffers = project.update(cx, |project, cx| {
 343        inserted_excerpt_buffer_ids
 344            .into_iter()
 345            .map(|id| BufferId::new(id).map(|id| project.open_buffer_by_id(id, cx)))
 346            .collect::<Result<Vec<_>>>()
 347    })??;
 348    let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
 349
 350    // Update the editor's excerpts.
 351    this.update(cx, |editor, cx| {
 352        editor.buffer.update(cx, |multibuffer, cx| {
 353            let mut removed_excerpt_ids = message
 354                .deleted_excerpts
 355                .into_iter()
 356                .map(ExcerptId::from_proto)
 357                .collect::<Vec<_>>();
 358            removed_excerpt_ids.sort_by({
 359                let multibuffer = multibuffer.read(cx);
 360                move |a, b| a.cmp(b, &multibuffer)
 361            });
 362
 363            let mut insertions = message.inserted_excerpts.into_iter().peekable();
 364            while let Some(insertion) = insertions.next() {
 365                let Some(excerpt) = insertion.excerpt else {
 366                    continue;
 367                };
 368                let Some(previous_excerpt_id) = insertion.previous_excerpt_id else {
 369                    continue;
 370                };
 371                let buffer_id = BufferId::new(excerpt.buffer_id)?;
 372                let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
 373                    continue;
 374                };
 375
 376                let adjacent_excerpts = iter::from_fn(|| {
 377                    let insertion = insertions.peek()?;
 378                    if insertion.previous_excerpt_id.is_none()
 379                        && insertion.excerpt.as_ref()?.buffer_id == u64::from(buffer_id)
 380                    {
 381                        insertions.next()?.excerpt
 382                    } else {
 383                        None
 384                    }
 385                });
 386
 387                multibuffer.insert_excerpts_with_ids_after(
 388                    ExcerptId::from_proto(previous_excerpt_id),
 389                    buffer,
 390                    [excerpt]
 391                        .into_iter()
 392                        .chain(adjacent_excerpts)
 393                        .filter_map(|excerpt| {
 394                            Some((
 395                                ExcerptId::from_proto(excerpt.id),
 396                                deserialize_excerpt_range(excerpt)?,
 397                            ))
 398                        }),
 399                    cx,
 400                );
 401            }
 402
 403            multibuffer.remove_excerpts(removed_excerpt_ids, cx);
 404            Result::<(), anyhow::Error>::Ok(())
 405        })
 406    })??;
 407
 408    // Deserialize the editor state.
 409    let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {
 410        let buffer = editor.buffer.read(cx).read(cx);
 411        let selections = message
 412            .selections
 413            .into_iter()
 414            .filter_map(|selection| deserialize_selection(&buffer, selection))
 415            .collect::<Vec<_>>();
 416        let pending_selection = message
 417            .pending_selection
 418            .and_then(|selection| deserialize_selection(&buffer, selection));
 419        let scroll_top_anchor = message
 420            .scroll_top_anchor
 421            .and_then(|anchor| deserialize_anchor(&buffer, anchor));
 422        anyhow::Ok((selections, pending_selection, scroll_top_anchor))
 423    })??;
 424
 425    // Wait until the buffer has received all of the operations referenced by
 426    // the editor's new state.
 427    this.update(cx, |editor, cx| {
 428        editor.buffer.update(cx, |buffer, cx| {
 429            buffer.wait_for_anchors(
 430                selections
 431                    .iter()
 432                    .chain(pending_selection.as_ref())
 433                    .flat_map(|selection| [selection.start, selection.end])
 434                    .chain(scroll_top_anchor),
 435                cx,
 436            )
 437        })
 438    })?
 439    .await?;
 440
 441    // Update the editor's state.
 442    this.update(cx, |editor, cx| {
 443        if !selections.is_empty() || pending_selection.is_some() {
 444            editor.set_selections_from_remote(selections, pending_selection, cx);
 445            editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
 446        } else if let Some(scroll_top_anchor) = scroll_top_anchor {
 447            editor.set_scroll_anchor_remote(
 448                ScrollAnchor {
 449                    anchor: scroll_top_anchor,
 450                    offset: point(message.scroll_x, message.scroll_y),
 451                },
 452                cx,
 453            );
 454        }
 455    })?;
 456    Ok(())
 457}
 458
 459fn serialize_excerpt(
 460    buffer_id: BufferId,
 461    id: &ExcerptId,
 462    range: &ExcerptRange<language::Anchor>,
 463) -> Option<proto::Excerpt> {
 464    Some(proto::Excerpt {
 465        id: id.to_proto(),
 466        buffer_id: buffer_id.into(),
 467        context_start: Some(serialize_text_anchor(&range.context.start)),
 468        context_end: Some(serialize_text_anchor(&range.context.end)),
 469        primary_start: range
 470            .primary
 471            .as_ref()
 472            .map(|r| serialize_text_anchor(&r.start)),
 473        primary_end: range
 474            .primary
 475            .as_ref()
 476            .map(|r| serialize_text_anchor(&r.end)),
 477    })
 478}
 479
 480fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
 481    proto::Selection {
 482        id: selection.id as u64,
 483        start: Some(serialize_anchor(&selection.start)),
 484        end: Some(serialize_anchor(&selection.end)),
 485        reversed: selection.reversed,
 486    }
 487}
 488
 489fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
 490    proto::EditorAnchor {
 491        excerpt_id: anchor.excerpt_id.to_proto(),
 492        anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
 493    }
 494}
 495
 496fn deserialize_excerpt_range(excerpt: proto::Excerpt) -> Option<ExcerptRange<language::Anchor>> {
 497    let context = {
 498        let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
 499        let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
 500        start..end
 501    };
 502    let primary = excerpt
 503        .primary_start
 504        .zip(excerpt.primary_end)
 505        .and_then(|(start, end)| {
 506            let start = language::proto::deserialize_anchor(start)?;
 507            let end = language::proto::deserialize_anchor(end)?;
 508            Some(start..end)
 509        });
 510    Some(ExcerptRange { context, primary })
 511}
 512
 513fn deserialize_selection(
 514    buffer: &MultiBufferSnapshot,
 515    selection: proto::Selection,
 516) -> Option<Selection<Anchor>> {
 517    Some(Selection {
 518        id: selection.id as usize,
 519        start: deserialize_anchor(buffer, selection.start?)?,
 520        end: deserialize_anchor(buffer, selection.end?)?,
 521        reversed: selection.reversed,
 522        goal: SelectionGoal::None,
 523    })
 524}
 525
 526fn deserialize_anchor(buffer: &MultiBufferSnapshot, anchor: proto::EditorAnchor) -> Option<Anchor> {
 527    let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
 528    Some(Anchor {
 529        excerpt_id,
 530        text_anchor: language::proto::deserialize_anchor(anchor.anchor?)?,
 531        buffer_id: buffer.buffer_id_for_excerpt(excerpt_id),
 532    })
 533}
 534
 535impl Item for Editor {
 536    type Event = EditorEvent;
 537
 538    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
 539        if let Ok(data) = data.downcast::<NavigationData>() {
 540            let newest_selection = self.selections.newest::<Point>(cx);
 541            let buffer = self.buffer.read(cx).read(cx);
 542            let offset = if buffer.can_resolve(&data.cursor_anchor) {
 543                data.cursor_anchor.to_point(&buffer)
 544            } else {
 545                buffer.clip_point(data.cursor_position, Bias::Left)
 546            };
 547
 548            let mut scroll_anchor = data.scroll_anchor;
 549            if !buffer.can_resolve(&scroll_anchor.anchor) {
 550                scroll_anchor.anchor = buffer.anchor_before(
 551                    buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
 552                );
 553            }
 554
 555            drop(buffer);
 556
 557            if newest_selection.head() == offset {
 558                false
 559            } else {
 560                let nav_history = self.nav_history.take();
 561                self.set_scroll_anchor(scroll_anchor, cx);
 562                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 563                    s.select_ranges([offset..offset])
 564                });
 565                self.nav_history = nav_history;
 566                true
 567            }
 568        } else {
 569            false
 570        }
 571    }
 572
 573    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
 574        let file_path = self
 575            .buffer()
 576            .read(cx)
 577            .as_singleton()?
 578            .read(cx)
 579            .file()
 580            .and_then(|f| f.as_local())?
 581            .abs_path(cx);
 582
 583        let file_path = file_path.compact().to_string_lossy().to_string();
 584
 585        Some(file_path.into())
 586    }
 587
 588    fn telemetry_event_text(&self) -> Option<&'static str> {
 589        None
 590    }
 591
 592    fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString> {
 593        let path = path_for_buffer(&self.buffer, detail, true, cx)?;
 594        Some(path.to_string_lossy().to_string().into())
 595    }
 596
 597    fn tab_icon(&self, cx: &WindowContext) -> Option<Icon> {
 598        ItemSettings::get_global(cx)
 599            .file_icons
 600            .then(|| {
 601                self.buffer
 602                    .read(cx)
 603                    .as_singleton()
 604                    .and_then(|buffer| buffer.read(cx).project_path(cx))
 605                    .and_then(|path| FileIcons::get_icon(path.path.as_ref(), cx))
 606            })
 607            .flatten()
 608            .map(Icon::from_path)
 609    }
 610
 611    fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
 612        let label_color = if ItemSettings::get_global(cx).git_status {
 613            self.buffer()
 614                .read(cx)
 615                .as_singleton()
 616                .and_then(|buffer| buffer.read(cx).project_path(cx))
 617                .and_then(|path| self.project.as_ref()?.read(cx).entry_for_path(&path, cx))
 618                .map(|entry| {
 619                    entry_git_aware_label_color(entry.git_status, entry.is_ignored, params.selected)
 620                })
 621                .unwrap_or_else(|| entry_label_color(params.selected))
 622        } else {
 623            entry_label_color(params.selected)
 624        };
 625
 626        let description = params.detail.and_then(|detail| {
 627            let path = path_for_buffer(&self.buffer, detail, false, cx)?;
 628            let description = path.to_string_lossy();
 629            let description = description.trim();
 630
 631            if description.is_empty() {
 632                return None;
 633            }
 634
 635            Some(util::truncate_and_trailoff(description, MAX_TAB_TITLE_LEN))
 636        });
 637
 638        h_flex()
 639            .gap_2()
 640            .child(
 641                Label::new(self.title(cx).to_string())
 642                    .color(label_color)
 643                    .italic(params.preview),
 644            )
 645            .when_some(description, |this, description| {
 646                this.child(
 647                    Label::new(description)
 648                        .size(LabelSize::XSmall)
 649                        .color(Color::Muted),
 650                )
 651            })
 652            .into_any_element()
 653    }
 654
 655    fn for_each_project_item(
 656        &self,
 657        cx: &AppContext,
 658        f: &mut dyn FnMut(EntityId, &dyn project::Item),
 659    ) {
 660        self.buffer
 661            .read(cx)
 662            .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
 663    }
 664
 665    fn is_singleton(&self, cx: &AppContext) -> bool {
 666        self.buffer.read(cx).is_singleton()
 667    }
 668
 669    fn clone_on_split(
 670        &self,
 671        _workspace_id: Option<WorkspaceId>,
 672        cx: &mut ViewContext<Self>,
 673    ) -> Option<View<Editor>>
 674    where
 675        Self: Sized,
 676    {
 677        Some(cx.new_view(|cx| self.clone(cx)))
 678    }
 679
 680    fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
 681        self.nav_history = Some(history);
 682    }
 683
 684    fn discarded(&self, _project: Model<Project>, cx: &mut ViewContext<Self>) {
 685        for buffer in self.buffer().clone().read(cx).all_buffers() {
 686            buffer.update(cx, |buffer, cx| buffer.discarded(cx))
 687        }
 688    }
 689
 690    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 691        let selection = self.selections.newest_anchor();
 692        self.push_to_nav_history(selection.head(), None, cx);
 693    }
 694
 695    fn workspace_deactivated(&mut self, cx: &mut ViewContext<Self>) {
 696        self.hide_hovered_link(cx);
 697    }
 698
 699    fn is_dirty(&self, cx: &AppContext) -> bool {
 700        self.buffer().read(cx).read(cx).is_dirty()
 701    }
 702
 703    fn has_conflict(&self, cx: &AppContext) -> bool {
 704        self.buffer().read(cx).read(cx).has_conflict()
 705    }
 706
 707    fn can_save(&self, cx: &AppContext) -> bool {
 708        let buffer = &self.buffer().read(cx);
 709        if let Some(buffer) = buffer.as_singleton() {
 710            buffer.read(cx).project_path(cx).is_some()
 711        } else {
 712            true
 713        }
 714    }
 715
 716    fn save(
 717        &mut self,
 718        format: bool,
 719        project: Model<Project>,
 720        cx: &mut ViewContext<Self>,
 721    ) -> Task<Result<()>> {
 722        self.report_editor_event("save", None, cx);
 723        let buffers = self.buffer().clone().read(cx).all_buffers();
 724        let buffers = buffers
 725            .into_iter()
 726            .map(|handle| handle.read(cx).diff_base_buffer().unwrap_or(handle.clone()))
 727            .collect::<HashSet<_>>();
 728        cx.spawn(|this, mut cx| async move {
 729            if format {
 730                this.update(&mut cx, |editor, cx| {
 731                    editor.perform_format(
 732                        project.clone(),
 733                        FormatTrigger::Save,
 734                        FormatTarget::Buffer,
 735                        cx,
 736                    )
 737                })?
 738                .await?;
 739            }
 740
 741            if buffers.len() == 1 {
 742                // Apply full save routine for singleton buffers, to allow to `touch` the file via the editor.
 743                project
 744                    .update(&mut cx, |project, cx| project.save_buffers(buffers, cx))?
 745                    .await?;
 746            } else {
 747                // For multi-buffers, only format and save the buffers with changes.
 748                // For clean buffers, we simulate saving by calling `Buffer::did_save`,
 749                // so that language servers or other downstream listeners of save events get notified.
 750                let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
 751                    buffer
 752                        .update(&mut cx, |buffer, _| {
 753                            buffer.is_dirty() || buffer.has_conflict()
 754                        })
 755                        .unwrap_or(false)
 756                });
 757
 758                project
 759                    .update(&mut cx, |project, cx| {
 760                        project.save_buffers(dirty_buffers, cx)
 761                    })?
 762                    .await?;
 763                for buffer in clean_buffers {
 764                    buffer
 765                        .update(&mut cx, |buffer, cx| {
 766                            let version = buffer.saved_version().clone();
 767                            let mtime = buffer.saved_mtime();
 768                            buffer.did_save(version, mtime, cx);
 769                        })
 770                        .ok();
 771                }
 772            }
 773
 774            Ok(())
 775        })
 776    }
 777
 778    fn save_as(
 779        &mut self,
 780        project: Model<Project>,
 781        path: ProjectPath,
 782        cx: &mut ViewContext<Self>,
 783    ) -> Task<Result<()>> {
 784        let buffer = self
 785            .buffer()
 786            .read(cx)
 787            .as_singleton()
 788            .expect("cannot call save_as on an excerpt list");
 789
 790        let file_extension = path
 791            .path
 792            .extension()
 793            .map(|a| a.to_string_lossy().to_string());
 794        self.report_editor_event("save", file_extension, cx);
 795
 796        project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
 797    }
 798
 799    fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
 800        let buffer = self.buffer().clone();
 801        let buffers = self.buffer.read(cx).all_buffers();
 802        let reload_buffers =
 803            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
 804        cx.spawn(|this, mut cx| async move {
 805            let transaction = reload_buffers.log_err().await;
 806            this.update(&mut cx, |editor, cx| {
 807                editor.request_autoscroll(Autoscroll::fit(), cx)
 808            })?;
 809            buffer
 810                .update(&mut cx, |buffer, cx| {
 811                    if let Some(transaction) = transaction {
 812                        if !buffer.is_singleton() {
 813                            buffer.push_transaction(&transaction.0, cx);
 814                        }
 815                    }
 816                })
 817                .ok();
 818            Ok(())
 819        })
 820    }
 821
 822    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 823        Some(Box::new(handle.clone()))
 824    }
 825
 826    fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<gpui::Point<Pixels>> {
 827        self.pixel_position_of_newest_cursor
 828    }
 829
 830    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 831        if self.show_breadcrumbs {
 832            ToolbarItemLocation::PrimaryLeft
 833        } else {
 834            ToolbarItemLocation::Hidden
 835        }
 836    }
 837
 838    fn breadcrumbs(&self, variant: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 839        let cursor = self.selections.newest_anchor().head();
 840        let multibuffer = &self.buffer().read(cx);
 841        let (buffer_id, symbols) =
 842            multibuffer.symbols_containing(cursor, Some(variant.syntax()), cx)?;
 843        let buffer = multibuffer.buffer(buffer_id)?;
 844
 845        let buffer = buffer.read(cx);
 846        let text = self.breadcrumb_header.clone().unwrap_or_else(|| {
 847            buffer
 848                .snapshot()
 849                .resolve_file_path(
 850                    cx,
 851                    self.project
 852                        .as_ref()
 853                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 854                        .unwrap_or_default(),
 855                )
 856                .map(|path| path.to_string_lossy().to_string())
 857                .unwrap_or_else(|| {
 858                    if multibuffer.is_singleton() {
 859                        multibuffer.title(cx).to_string()
 860                    } else {
 861                        "untitled".to_string()
 862                    }
 863                })
 864        });
 865
 866        let settings = ThemeSettings::get_global(cx);
 867
 868        let mut breadcrumbs = vec![BreadcrumbText {
 869            text,
 870            highlights: None,
 871            font: Some(settings.buffer_font.clone()),
 872        }];
 873
 874        breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
 875            text: symbol.text,
 876            highlights: Some(symbol.highlight_ranges),
 877            font: Some(settings.buffer_font.clone()),
 878        }));
 879        Some(breadcrumbs)
 880    }
 881
 882    fn added_to_workspace(&mut self, workspace: &mut Workspace, _: &mut ViewContext<Self>) {
 883        self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
 884    }
 885
 886    fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
 887        match event {
 888            EditorEvent::Closed => f(ItemEvent::CloseItem),
 889
 890            EditorEvent::Saved | EditorEvent::TitleChanged => {
 891                f(ItemEvent::UpdateTab);
 892                f(ItemEvent::UpdateBreadcrumbs);
 893            }
 894
 895            EditorEvent::Reparsed(_) => {
 896                f(ItemEvent::UpdateBreadcrumbs);
 897            }
 898
 899            EditorEvent::SelectionsChanged { local } if *local => {
 900                f(ItemEvent::UpdateBreadcrumbs);
 901            }
 902
 903            EditorEvent::DirtyChanged => {
 904                f(ItemEvent::UpdateTab);
 905            }
 906
 907            EditorEvent::BufferEdited => {
 908                f(ItemEvent::Edit);
 909                f(ItemEvent::UpdateBreadcrumbs);
 910            }
 911
 912            EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
 913                f(ItemEvent::Edit);
 914            }
 915
 916            _ => {}
 917        }
 918    }
 919
 920    fn preserve_preview(&self, cx: &AppContext) -> bool {
 921        self.buffer.read(cx).preserve_preview(cx)
 922    }
 923}
 924
 925impl SerializableItem for Editor {
 926    fn serialized_item_kind() -> &'static str {
 927        "Editor"
 928    }
 929
 930    fn cleanup(
 931        workspace_id: WorkspaceId,
 932        alive_items: Vec<ItemId>,
 933        cx: &mut WindowContext,
 934    ) -> Task<Result<()>> {
 935        cx.spawn(|_| DB.delete_unloaded_items(workspace_id, alive_items))
 936    }
 937
 938    fn deserialize(
 939        project: Model<Project>,
 940        workspace: WeakView<Workspace>,
 941        workspace_id: workspace::WorkspaceId,
 942        item_id: ItemId,
 943        cx: &mut ViewContext<Pane>,
 944    ) -> Task<Result<View<Self>>> {
 945        let serialized_editor = match DB
 946            .get_serialized_editor(item_id, workspace_id)
 947            .context("Failed to query editor state")
 948        {
 949            Ok(Some(serialized_editor)) => {
 950                if ProjectSettings::get_global(cx)
 951                    .session
 952                    .restore_unsaved_buffers
 953                {
 954                    serialized_editor
 955                } else {
 956                    SerializedEditor {
 957                        abs_path: serialized_editor.abs_path,
 958                        contents: None,
 959                        language: None,
 960                        mtime: None,
 961                    }
 962                }
 963            }
 964            Ok(None) => {
 965                return Task::ready(Err(anyhow!("No path or contents found for buffer")));
 966            }
 967            Err(error) => {
 968                return Task::ready(Err(error));
 969            }
 970        };
 971
 972        match serialized_editor {
 973            SerializedEditor {
 974                abs_path: None,
 975                contents: Some(contents),
 976                language,
 977                ..
 978            } => cx.spawn(|pane, mut cx| {
 979                let project = project.clone();
 980                async move {
 981                    let language = if let Some(language_name) = language {
 982                        let language_registry =
 983                            project.update(&mut cx, |project, _| project.languages().clone())?;
 984
 985                        // We don't fail here, because we'd rather not set the language if the name changed
 986                        // than fail to restore the buffer.
 987                        language_registry
 988                            .language_for_name(&language_name)
 989                            .await
 990                            .ok()
 991                    } else {
 992                        None
 993                    };
 994
 995                    // First create the empty buffer
 996                    let buffer = project
 997                        .update(&mut cx, |project, cx| project.create_buffer(cx))?
 998                        .await?;
 999
1000                    // Then set the text so that the dirty bit is set correctly
1001                    buffer.update(&mut cx, |buffer, cx| {
1002                        if let Some(language) = language {
1003                            buffer.set_language(Some(language), cx);
1004                        }
1005                        buffer.set_text(contents, cx);
1006                    })?;
1007
1008                    pane.update(&mut cx, |_, cx| {
1009                        cx.new_view(|cx| {
1010                            let mut editor = Editor::for_buffer(buffer, Some(project), cx);
1011
1012                            editor.read_scroll_position_from_db(item_id, workspace_id, cx);
1013                            editor
1014                        })
1015                    })
1016                }
1017            }),
1018            SerializedEditor {
1019                abs_path: Some(abs_path),
1020                contents,
1021                mtime,
1022                ..
1023            } => {
1024                let project_item = project.update(cx, |project, cx| {
1025                    let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1026                    let project_path = ProjectPath {
1027                        worktree_id: worktree.read(cx).id(),
1028                        path: path.into(),
1029                    };
1030                    Some(project.open_path(project_path, cx))
1031                });
1032
1033                match project_item {
1034                    Some(project_item) => {
1035                        cx.spawn(|pane, mut cx| async move {
1036                            let (_, project_item) = project_item.await?;
1037                            let buffer = project_item.downcast::<Buffer>().map_err(|_| {
1038                                anyhow!("Project item at stored path was not a buffer")
1039                            })?;
1040
1041                            // This is a bit wasteful: we're loading the whole buffer from
1042                            // disk and then overwrite the content.
1043                            // But for now, it keeps the implementation of the content serialization
1044                            // simple, because we don't have to persist all of the metadata that we get
1045                            // by loading the file (git diff base, ...).
1046                            if let Some(buffer_text) = contents {
1047                                buffer.update(&mut cx, |buffer, cx| {
1048                                    // If we did restore an mtime, we want to store it on the buffer
1049                                    // so that the next edit will mark the buffer as dirty/conflicted.
1050                                    if mtime.is_some() {
1051                                        buffer.did_reload(
1052                                            buffer.version(),
1053                                            buffer.line_ending(),
1054                                            mtime,
1055                                            cx,
1056                                        );
1057                                    }
1058                                    buffer.set_text(buffer_text, cx);
1059                                })?;
1060                            }
1061
1062                            pane.update(&mut cx, |_, cx| {
1063                                cx.new_view(|cx| {
1064                                    let mut editor = Editor::for_buffer(buffer, Some(project), cx);
1065
1066                                    editor.read_scroll_position_from_db(item_id, workspace_id, cx);
1067                                    editor
1068                                })
1069                            })
1070                        })
1071                    }
1072                    None => {
1073                        let open_by_abs_path = workspace.update(cx, |workspace, cx| {
1074                            workspace.open_abs_path(abs_path.clone(), false, cx)
1075                        });
1076                        cx.spawn(|_, mut cx| async move {
1077                            let editor = open_by_abs_path?.await?.downcast::<Editor>().with_context(|| format!("Failed to downcast to Editor after opening abs path {abs_path:?}"))?;
1078                            editor.update(&mut cx, |editor, cx| {
1079                                editor.read_scroll_position_from_db(item_id, workspace_id, cx);
1080                            })?;
1081                            Ok(editor)
1082                        })
1083                    }
1084                }
1085            }
1086            SerializedEditor {
1087                abs_path: None,
1088                contents: None,
1089                ..
1090            } => Task::ready(Err(anyhow!("No path or contents found for buffer"))),
1091        }
1092    }
1093
1094    fn serialize(
1095        &mut self,
1096        workspace: &mut Workspace,
1097        item_id: ItemId,
1098        closing: bool,
1099        cx: &mut ViewContext<Self>,
1100    ) -> Option<Task<Result<()>>> {
1101        let mut serialize_dirty_buffers = self.serialize_dirty_buffers;
1102
1103        let project = self.project.clone()?;
1104        if project.read(cx).visible_worktrees(cx).next().is_none() {
1105            // If we don't have a worktree, we don't serialize, because
1106            // projects without worktrees aren't deserialized.
1107            serialize_dirty_buffers = false;
1108        }
1109
1110        if closing && !serialize_dirty_buffers {
1111            return None;
1112        }
1113
1114        let workspace_id = workspace.database_id()?;
1115
1116        let buffer = self.buffer().read(cx).as_singleton()?;
1117
1118        let abs_path = buffer.read(cx).file().and_then(|file| {
1119            let worktree_id = file.worktree_id(cx);
1120            project
1121                .read(cx)
1122                .worktree_for_id(worktree_id, cx)
1123                .and_then(|worktree| worktree.read(cx).absolutize(&file.path()).ok())
1124                .or_else(|| {
1125                    let full_path = file.full_path(cx);
1126                    let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1127                    project.read(cx).absolute_path(&project_path, cx)
1128                })
1129        });
1130
1131        let is_dirty = buffer.read(cx).is_dirty();
1132        let mtime = buffer.read(cx).saved_mtime();
1133
1134        let snapshot = buffer.read(cx).snapshot();
1135
1136        Some(cx.spawn(|_this, cx| async move {
1137            cx.background_executor()
1138                .spawn(async move {
1139                    let (contents, language) = if serialize_dirty_buffers && is_dirty {
1140                        let contents = snapshot.text();
1141                        let language = snapshot.language().map(|lang| lang.name().to_string());
1142                        (Some(contents), language)
1143                    } else {
1144                        (None, None)
1145                    };
1146
1147                    let editor = SerializedEditor {
1148                        abs_path,
1149                        contents,
1150                        language,
1151                        mtime,
1152                    };
1153
1154                    DB.save_serialized_editor(item_id, workspace_id, editor)
1155                        .await
1156                        .context("failed to save serialized editor")
1157                })
1158                .await
1159                .context("failed to save contents of buffer")?;
1160
1161            Ok(())
1162        }))
1163    }
1164
1165    fn should_serialize(&self, event: &Self::Event) -> bool {
1166        matches!(
1167            event,
1168            EditorEvent::Saved | EditorEvent::DirtyChanged | EditorEvent::BufferEdited
1169        )
1170    }
1171}
1172
1173impl ProjectItem for Editor {
1174    type Item = Buffer;
1175
1176    fn for_project_item(
1177        project: Model<Project>,
1178        buffer: Model<Buffer>,
1179        cx: &mut ViewContext<Self>,
1180    ) -> Self {
1181        Self::for_buffer(buffer, Some(project), cx)
1182    }
1183}
1184
1185impl EventEmitter<SearchEvent> for Editor {}
1186
1187pub(crate) enum BufferSearchHighlights {}
1188impl SearchableItem for Editor {
1189    type Match = Range<Anchor>;
1190
1191    fn get_matches(&self, _: &mut WindowContext) -> Vec<Range<Anchor>> {
1192        self.background_highlights
1193            .get(&TypeId::of::<BufferSearchHighlights>())
1194            .map_or(Vec::new(), |(_color, ranges)| {
1195                ranges.iter().cloned().collect()
1196            })
1197    }
1198
1199    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
1200        if self
1201            .clear_background_highlights::<BufferSearchHighlights>(cx)
1202            .is_some()
1203        {
1204            cx.emit(SearchEvent::MatchesInvalidated);
1205        }
1206    }
1207
1208    fn update_matches(&mut self, matches: &[Range<Anchor>], cx: &mut ViewContext<Self>) {
1209        let existing_range = self
1210            .background_highlights
1211            .get(&TypeId::of::<BufferSearchHighlights>())
1212            .map(|(_, range)| range.as_ref());
1213        let updated = existing_range != Some(matches);
1214        self.highlight_background::<BufferSearchHighlights>(
1215            matches,
1216            |theme| theme.search_match_background,
1217            cx,
1218        );
1219        if updated {
1220            cx.emit(SearchEvent::MatchesInvalidated);
1221        }
1222    }
1223
1224    fn has_filtered_search_ranges(&mut self) -> bool {
1225        self.has_background_highlights::<SearchWithinRange>()
1226    }
1227
1228    fn toggle_filtered_search_ranges(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
1229        if self.has_filtered_search_ranges() {
1230            self.previous_search_ranges = self
1231                .clear_background_highlights::<SearchWithinRange>(cx)
1232                .map(|(_, ranges)| ranges)
1233        }
1234
1235        if !enabled {
1236            return;
1237        }
1238
1239        let ranges = self.selections.disjoint_anchor_ranges();
1240        if ranges.iter().any(|range| range.start != range.end) {
1241            self.set_search_within_ranges(&ranges, cx);
1242        } else if let Some(previous_search_ranges) = self.previous_search_ranges.take() {
1243            self.set_search_within_ranges(&previous_search_ranges, cx)
1244        }
1245    }
1246
1247    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
1248        let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1249        let snapshot = &self.snapshot(cx).buffer_snapshot;
1250        let selection = self.selections.newest::<usize>(cx);
1251
1252        match setting {
1253            SeedQuerySetting::Never => String::new(),
1254            SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1255                let text: String = snapshot
1256                    .text_for_range(selection.start..selection.end)
1257                    .collect();
1258                if text.contains('\n') {
1259                    String::new()
1260                } else {
1261                    text
1262                }
1263            }
1264            SeedQuerySetting::Selection => String::new(),
1265            SeedQuerySetting::Always => {
1266                let (range, kind) = snapshot.surrounding_word(selection.start, true);
1267                if kind == Some(CharKind::Word) {
1268                    let text: String = snapshot.text_for_range(range).collect();
1269                    if !text.trim().is_empty() {
1270                        return text;
1271                    }
1272                }
1273                String::new()
1274            }
1275        }
1276    }
1277
1278    fn activate_match(
1279        &mut self,
1280        index: usize,
1281        matches: &[Range<Anchor>],
1282        cx: &mut ViewContext<Self>,
1283    ) {
1284        self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1285        let range = self.range_for_match(&matches[index]);
1286        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
1287            s.select_ranges([range]);
1288        })
1289    }
1290
1291    fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
1292        self.unfold_ranges(matches, false, false, cx);
1293        let mut ranges = Vec::new();
1294        for m in matches {
1295            ranges.push(self.range_for_match(m))
1296        }
1297        self.change_selections(None, cx, |s| s.select_ranges(ranges));
1298    }
1299    fn replace(
1300        &mut self,
1301        identifier: &Self::Match,
1302        query: &SearchQuery,
1303        cx: &mut ViewContext<Self>,
1304    ) {
1305        let text = self.buffer.read(cx);
1306        let text = text.snapshot(cx);
1307        let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1308        let text: Cow<_> = if text.len() == 1 {
1309            text.first().cloned().unwrap().into()
1310        } else {
1311            let joined_chunks = text.join("");
1312            joined_chunks.into()
1313        };
1314
1315        if let Some(replacement) = query.replacement_for(&text) {
1316            self.transact(cx, |this, cx| {
1317                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1318            });
1319        }
1320    }
1321    fn replace_all(
1322        &mut self,
1323        matches: &mut dyn Iterator<Item = &Self::Match>,
1324        query: &SearchQuery,
1325        cx: &mut ViewContext<Self>,
1326    ) {
1327        let text = self.buffer.read(cx);
1328        let text = text.snapshot(cx);
1329        let mut edits = vec![];
1330        for m in matches {
1331            let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1332            let text: Cow<_> = if text.len() == 1 {
1333                text.first().cloned().unwrap().into()
1334            } else {
1335                let joined_chunks = text.join("");
1336                joined_chunks.into()
1337            };
1338
1339            if let Some(replacement) = query.replacement_for(&text) {
1340                edits.push((m.clone(), Arc::from(&*replacement)));
1341            }
1342        }
1343
1344        if !edits.is_empty() {
1345            self.transact(cx, |this, cx| {
1346                this.edit(edits, cx);
1347            });
1348        }
1349    }
1350    fn match_index_for_direction(
1351        &mut self,
1352        matches: &[Range<Anchor>],
1353        current_index: usize,
1354        direction: Direction,
1355        count: usize,
1356        cx: &mut ViewContext<Self>,
1357    ) -> usize {
1358        let buffer = self.buffer().read(cx).snapshot(cx);
1359        let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1360            self.selections.newest_anchor().head()
1361        } else {
1362            matches[current_index].start
1363        };
1364
1365        let mut count = count % matches.len();
1366        if count == 0 {
1367            return current_index;
1368        }
1369        match direction {
1370            Direction::Next => {
1371                if matches[current_index]
1372                    .start
1373                    .cmp(&current_index_position, &buffer)
1374                    .is_gt()
1375                {
1376                    count -= 1
1377                }
1378
1379                (current_index + count) % matches.len()
1380            }
1381            Direction::Prev => {
1382                if matches[current_index]
1383                    .end
1384                    .cmp(&current_index_position, &buffer)
1385                    .is_lt()
1386                {
1387                    count -= 1;
1388                }
1389
1390                if current_index >= count {
1391                    current_index - count
1392                } else {
1393                    matches.len() - (count - current_index)
1394                }
1395            }
1396        }
1397    }
1398
1399    fn find_matches(
1400        &mut self,
1401        query: Arc<project::search::SearchQuery>,
1402        cx: &mut ViewContext<Self>,
1403    ) -> Task<Vec<Range<Anchor>>> {
1404        let buffer = self.buffer().read(cx).snapshot(cx);
1405        let search_within_ranges = self
1406            .background_highlights
1407            .get(&TypeId::of::<SearchWithinRange>())
1408            .map_or(vec![], |(_color, ranges)| {
1409                ranges.iter().cloned().collect::<Vec<_>>()
1410            });
1411
1412        cx.background_executor().spawn(async move {
1413            let mut ranges = Vec::new();
1414
1415            if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
1416                let search_within_ranges = if search_within_ranges.is_empty() {
1417                    vec![None]
1418                } else {
1419                    search_within_ranges
1420                        .into_iter()
1421                        .map(|range| Some(range.to_offset(&buffer)))
1422                        .collect::<Vec<_>>()
1423                };
1424
1425                for range in search_within_ranges {
1426                    let buffer = &buffer;
1427                    ranges.extend(
1428                        query
1429                            .search(excerpt_buffer, range.clone())
1430                            .await
1431                            .into_iter()
1432                            .map(|matched_range| {
1433                                let offset = range.clone().map(|r| r.start).unwrap_or(0);
1434                                buffer.anchor_after(matched_range.start + offset)
1435                                    ..buffer.anchor_before(matched_range.end + offset)
1436                            }),
1437                    );
1438                }
1439            } else {
1440                let search_within_ranges = if search_within_ranges.is_empty() {
1441                    vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())]
1442                } else {
1443                    search_within_ranges
1444                };
1445
1446                for (excerpt_id, search_buffer, search_range) in
1447                    buffer.excerpts_in_ranges(search_within_ranges)
1448                {
1449                    if !search_range.is_empty() {
1450                        ranges.extend(
1451                            query
1452                                .search(search_buffer, Some(search_range.clone()))
1453                                .await
1454                                .into_iter()
1455                                .map(|match_range| {
1456                                    let start = search_buffer
1457                                        .anchor_after(search_range.start + match_range.start);
1458                                    let end = search_buffer
1459                                        .anchor_before(search_range.start + match_range.end);
1460                                    buffer.anchor_in_excerpt(excerpt_id, start).unwrap()
1461                                        ..buffer.anchor_in_excerpt(excerpt_id, end).unwrap()
1462                                }),
1463                        );
1464                    }
1465                }
1466            };
1467
1468            ranges
1469        })
1470    }
1471
1472    fn active_match_index(
1473        &mut self,
1474        matches: &[Range<Anchor>],
1475        cx: &mut ViewContext<Self>,
1476    ) -> Option<usize> {
1477        active_match_index(
1478            matches,
1479            &self.selections.newest_anchor().head(),
1480            &self.buffer().read(cx).snapshot(cx),
1481        )
1482    }
1483
1484    fn search_bar_visibility_changed(&mut self, _visible: bool, _cx: &mut ViewContext<Self>) {
1485        self.expect_bounds_change = self.last_bounds;
1486    }
1487}
1488
1489pub fn active_match_index(
1490    ranges: &[Range<Anchor>],
1491    cursor: &Anchor,
1492    buffer: &MultiBufferSnapshot,
1493) -> Option<usize> {
1494    if ranges.is_empty() {
1495        None
1496    } else {
1497        match ranges.binary_search_by(|probe| {
1498            if probe.end.cmp(cursor, buffer).is_lt() {
1499                Ordering::Less
1500            } else if probe.start.cmp(cursor, buffer).is_gt() {
1501                Ordering::Greater
1502            } else {
1503                Ordering::Equal
1504            }
1505        }) {
1506            Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1507        }
1508    }
1509}
1510
1511pub fn entry_label_color(selected: bool) -> Color {
1512    if selected {
1513        Color::Default
1514    } else {
1515        Color::Muted
1516    }
1517}
1518
1519pub fn entry_diagnostic_aware_icon_name_and_color(
1520    diagnostic_severity: Option<DiagnosticSeverity>,
1521) -> Option<(IconName, Color)> {
1522    match diagnostic_severity {
1523        Some(DiagnosticSeverity::ERROR) => Some((IconName::X, Color::Error)),
1524        Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1525        _ => None,
1526    }
1527}
1528
1529pub fn entry_diagnostic_aware_icon_decoration_and_color(
1530    diagnostic_severity: Option<DiagnosticSeverity>,
1531) -> Option<(IconDecorationKind, Color)> {
1532    match diagnostic_severity {
1533        Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1534        Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1535        _ => None,
1536    }
1537}
1538
1539pub fn entry_git_aware_label_color(
1540    git_status: Option<GitFileStatus>,
1541    ignored: bool,
1542    selected: bool,
1543) -> Color {
1544    if ignored {
1545        Color::Ignored
1546    } else {
1547        match git_status {
1548            Some(GitFileStatus::Added) => Color::Created,
1549            Some(GitFileStatus::Modified) => Color::Modified,
1550            Some(GitFileStatus::Conflict) => Color::Conflict,
1551            None => entry_label_color(selected),
1552        }
1553    }
1554}
1555
1556fn path_for_buffer<'a>(
1557    buffer: &Model<MultiBuffer>,
1558    height: usize,
1559    include_filename: bool,
1560    cx: &'a AppContext,
1561) -> Option<Cow<'a, Path>> {
1562    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1563    path_for_file(file.as_ref(), height, include_filename, cx)
1564}
1565
1566fn path_for_file<'a>(
1567    file: &'a dyn language::File,
1568    mut height: usize,
1569    include_filename: bool,
1570    cx: &'a AppContext,
1571) -> Option<Cow<'a, Path>> {
1572    // Ensure we always render at least the filename.
1573    height += 1;
1574
1575    let mut prefix = file.path().as_ref();
1576    while height > 0 {
1577        if let Some(parent) = prefix.parent() {
1578            prefix = parent;
1579            height -= 1;
1580        } else {
1581            break;
1582        }
1583    }
1584
1585    // Here we could have just always used `full_path`, but that is very
1586    // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1587    // traversed all the way up to the worktree's root.
1588    if height > 0 {
1589        let full_path = file.full_path(cx);
1590        if include_filename {
1591            Some(full_path.into())
1592        } else {
1593            Some(full_path.parent()?.to_path_buf().into())
1594        }
1595    } else {
1596        let mut path = file.path().strip_prefix(prefix).ok()?;
1597        if !include_filename {
1598            path = path.parent()?;
1599        }
1600        Some(path.into())
1601    }
1602}
1603
1604#[cfg(test)]
1605mod tests {
1606    use crate::editor_tests::init_test;
1607
1608    use super::*;
1609    use gpui::{AppContext, VisualTestContext};
1610    use language::{LanguageMatcher, TestFile};
1611    use project::FakeFs;
1612    use std::{
1613        path::{Path, PathBuf},
1614        time::SystemTime,
1615    };
1616
1617    #[gpui::test]
1618    fn test_path_for_file(cx: &mut AppContext) {
1619        let file = TestFile {
1620            path: Path::new("").into(),
1621            root_name: String::new(),
1622        };
1623        assert_eq!(path_for_file(&file, 0, false, cx), None);
1624    }
1625
1626    async fn deserialize_editor(
1627        item_id: ItemId,
1628        workspace_id: WorkspaceId,
1629        workspace: View<Workspace>,
1630        project: Model<Project>,
1631        cx: &mut VisualTestContext,
1632    ) -> View<Editor> {
1633        workspace
1634            .update(cx, |workspace, cx| {
1635                let pane = workspace.active_pane();
1636                pane.update(cx, |_, cx| {
1637                    Editor::deserialize(
1638                        project.clone(),
1639                        workspace.weak_handle(),
1640                        workspace_id,
1641                        item_id,
1642                        cx,
1643                    )
1644                })
1645            })
1646            .await
1647            .unwrap()
1648    }
1649
1650    fn rust_language() -> Arc<language::Language> {
1651        Arc::new(language::Language::new(
1652            language::LanguageConfig {
1653                name: "Rust".into(),
1654                matcher: LanguageMatcher {
1655                    path_suffixes: vec!["rs".to_string()],
1656                    ..Default::default()
1657                },
1658                ..Default::default()
1659            },
1660            Some(tree_sitter_rust::LANGUAGE.into()),
1661        ))
1662    }
1663
1664    #[gpui::test]
1665    async fn test_deserialize(cx: &mut gpui::TestAppContext) {
1666        init_test(cx, |_| {});
1667
1668        let now = SystemTime::now();
1669        let fs = FakeFs::new(cx.executor());
1670        fs.set_next_mtime(now);
1671        fs.insert_file("/file.rs", Default::default()).await;
1672
1673        // Test case 1: Deserialize with path and contents
1674        {
1675            let project = Project::test(fs.clone(), ["/file.rs".as_ref()], cx).await;
1676            let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
1677            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1678            let item_id = 1234 as ItemId;
1679
1680            let serialized_editor = SerializedEditor {
1681                abs_path: Some(PathBuf::from("/file.rs")),
1682                contents: Some("fn main() {}".to_string()),
1683                language: Some("Rust".to_string()),
1684                mtime: Some(now),
1685            };
1686
1687            DB.save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
1688                .await
1689                .unwrap();
1690
1691            let deserialized =
1692                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1693
1694            deserialized.update(cx, |editor, cx| {
1695                assert_eq!(editor.text(cx), "fn main() {}");
1696                assert!(editor.is_dirty(cx));
1697                assert!(!editor.has_conflict(cx));
1698                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1699                assert!(buffer.file().is_some());
1700            });
1701        }
1702
1703        // Test case 2: Deserialize with only path
1704        {
1705            let project = Project::test(fs.clone(), ["/file.rs".as_ref()], cx).await;
1706            let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
1707
1708            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1709
1710            let item_id = 5678 as ItemId;
1711            let serialized_editor = SerializedEditor {
1712                abs_path: Some(PathBuf::from("/file.rs")),
1713                contents: None,
1714                language: None,
1715                mtime: None,
1716            };
1717
1718            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1719                .await
1720                .unwrap();
1721
1722            let deserialized =
1723                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1724
1725            deserialized.update(cx, |editor, cx| {
1726                assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
1727                assert!(!editor.is_dirty(cx));
1728                assert!(!editor.has_conflict(cx));
1729
1730                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1731                assert!(buffer.file().is_some());
1732            });
1733        }
1734
1735        // Test case 3: Deserialize with no path (untitled buffer, with content and language)
1736        {
1737            let project = Project::test(fs.clone(), ["/file.rs".as_ref()], cx).await;
1738            // Add Rust to the language, so that we can restore the language of the buffer
1739            project.update(cx, |project, _| project.languages().add(rust_language()));
1740
1741            let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
1742
1743            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1744
1745            let item_id = 9012 as ItemId;
1746            let serialized_editor = SerializedEditor {
1747                abs_path: None,
1748                contents: Some("hello".to_string()),
1749                language: Some("Rust".to_string()),
1750                mtime: None,
1751            };
1752
1753            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1754                .await
1755                .unwrap();
1756
1757            let deserialized =
1758                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1759
1760            deserialized.update(cx, |editor, cx| {
1761                assert_eq!(editor.text(cx), "hello");
1762                assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
1763
1764                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1765                assert_eq!(
1766                    buffer.language().map(|lang| lang.name()),
1767                    Some("Rust".into())
1768                ); // Language should be set to Rust
1769                assert!(buffer.file().is_none()); // The buffer should not have an associated file
1770            });
1771        }
1772
1773        // Test case 4: Deserialize with path, content, and old mtime
1774        {
1775            let project = Project::test(fs.clone(), ["/file.rs".as_ref()], cx).await;
1776            let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
1777
1778            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1779
1780            let item_id = 9345 as ItemId;
1781            let old_mtime = now
1782                .checked_sub(std::time::Duration::from_secs(60 * 60 * 24))
1783                .unwrap();
1784            let serialized_editor = SerializedEditor {
1785                abs_path: Some(PathBuf::from("/file.rs")),
1786                contents: Some("fn main() {}".to_string()),
1787                language: Some("Rust".to_string()),
1788                mtime: Some(old_mtime),
1789            };
1790
1791            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1792                .await
1793                .unwrap();
1794
1795            let deserialized =
1796                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1797
1798            deserialized.update(cx, |editor, cx| {
1799                assert_eq!(editor.text(cx), "fn main() {}");
1800                assert!(editor.has_conflict(cx)); // The editor should have a conflict
1801            });
1802        }
1803    }
1804}