items.rs

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