items.rs

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