items.rs

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