items.rs

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