items.rs

   1use crate::{
   2    editor_settings::SeedQuerySetting, persistence::DB, scroll::ScrollAnchor, Anchor, Autoscroll,
   3    Editor, EditorEvent, EditorSettings, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot,
   4    NavigationData, ToPoint as _,
   5};
   6use anyhow::{anyhow, Context as _, Result};
   7use collections::HashSet;
   8use futures::future::try_join_all;
   9use gpui::{
  10    point, AnyElement, AppContext, AsyncWindowContext, Context, Entity, EntityId, EventEmitter,
  11    IntoElement, Model, ParentElement, Pixels, SharedString, Styled, Task, View, ViewContext,
  12    VisualContext, WeakView, WindowContext,
  13};
  14use language::{
  15    proto::serialize_anchor as serialize_text_anchor, Bias, Buffer, CharKind, OffsetRangeExt,
  16    Point, SelectionGoal,
  17};
  18use project::repository::GitFileStatus;
  19use project::{search::SearchQuery, FormatTrigger, Item as _, Project, ProjectPath};
  20use rpc::proto::{self, update_view, PeerId};
  21use settings::Settings;
  22use workspace::item::ItemSettings;
  23
  24use std::{
  25    borrow::Cow,
  26    cmp::{self, Ordering},
  27    iter,
  28    ops::Range,
  29    path::{Path, PathBuf},
  30    sync::Arc,
  31};
  32use text::{BufferId, Selection};
  33use theme::Theme;
  34use ui::{h_flex, prelude::*, Label};
  35use util::{paths::PathExt, ResultExt, TryFutureExt};
  36use workspace::item::{BreadcrumbText, FollowEvent, FollowableItemHandle};
  37use workspace::{
  38    item::{FollowableItem, Item, ItemEvent, ItemHandle, ProjectItem},
  39    searchable::{Direction, SearchEvent, SearchableItem, SearchableItemHandle},
  40    ItemId, ItemNavHistory, Pane, ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
  41};
  42
  43pub const MAX_TAB_TITLE_LEN: usize = 24;
  44
  45impl FollowableItem for Editor {
  46    fn remote_id(&self) -> Option<ViewId> {
  47        self.remote_id
  48    }
  49
  50    fn from_state_proto(
  51        pane: View<workspace::Pane>,
  52        workspace: View<Workspace>,
  53        remote_id: ViewId,
  54        state: &mut Option<proto::view::Variant>,
  55        cx: &mut WindowContext,
  56    ) -> Option<Task<Result<View<Self>>>> {
  57        let project = workspace.read(cx).project().to_owned();
  58        let Some(proto::view::Variant::Editor(_)) = state else {
  59            return None;
  60        };
  61        let Some(proto::view::Variant::Editor(state)) = state.take() else {
  62            unreachable!()
  63        };
  64
  65        let client = project.read(cx).client();
  66        let replica_id = project.read(cx).replica_id();
  67        let buffer_ids = state
  68            .excerpts
  69            .iter()
  70            .map(|excerpt| excerpt.buffer_id)
  71            .collect::<HashSet<_>>();
  72        let buffers = project.update(cx, |project, cx| {
  73            buffer_ids
  74                .iter()
  75                .map(|id| BufferId::new(*id).map(|id| project.open_buffer_by_id(id, cx)))
  76                .collect::<Result<Vec<_>>>()
  77        });
  78
  79        let pane = pane.downgrade();
  80        Some(cx.spawn(|mut cx| async move {
  81            let mut buffers = futures::future::try_join_all(buffers?)
  82                .await
  83                .debug_assert_ok("leaders don't share views for unshared buffers")?;
  84            let editor = pane.update(&mut cx, |pane, cx| {
  85                let mut editors = pane.items_of_type::<Self>();
  86                editors.find(|editor| {
  87                    let ids_match = editor.remote_id(&client, cx) == Some(remote_id);
  88                    let singleton_buffer_matches = state.singleton
  89                        && buffers.first()
  90                            == editor.read(cx).buffer.read(cx).as_singleton().as_ref();
  91                    ids_match || singleton_buffer_matches
  92                })
  93            })?;
  94
  95            let editor = if let Some(editor) = editor {
  96                editor
  97            } else {
  98                pane.update(&mut cx, |_, cx| {
  99                    let multibuffer = cx.new_model(|cx| {
 100                        let mut multibuffer;
 101                        if state.singleton && buffers.len() == 1 {
 102                            multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
 103                        } else {
 104                            multibuffer =
 105                                MultiBuffer::new(replica_id, project.read(cx).capability());
 106                            let mut excerpts = state.excerpts.into_iter().peekable();
 107                            while let Some(excerpt) = excerpts.peek() {
 108                                let Ok(buffer_id) = BufferId::new(excerpt.buffer_id) else {
 109                                    continue;
 110                                };
 111                                let buffer_excerpts = iter::from_fn(|| {
 112                                    let excerpt = excerpts.peek()?;
 113                                    (excerpt.buffer_id == u64::from(buffer_id))
 114                                        .then(|| excerpts.next().unwrap())
 115                                });
 116                                let buffer =
 117                                    buffers.iter().find(|b| b.read(cx).remote_id() == buffer_id);
 118                                if let Some(buffer) = buffer {
 119                                    multibuffer.push_excerpts(
 120                                        buffer.clone(),
 121                                        buffer_excerpts.filter_map(deserialize_excerpt_range),
 122                                        cx,
 123                                    );
 124                                }
 125                            }
 126                        };
 127
 128                        if let Some(title) = &state.title {
 129                            multibuffer = multibuffer.with_title(title.clone())
 130                        }
 131
 132                        multibuffer
 133                    });
 134
 135                    cx.new_view(|cx| {
 136                        let mut editor =
 137                            Editor::for_multibuffer(multibuffer, Some(project.clone()), cx);
 138                        editor.remote_id = Some(remote_id);
 139                        editor
 140                    })
 141                })?
 142            };
 143
 144            update_editor_from_message(
 145                editor.downgrade(),
 146                project,
 147                proto::update_view::Editor {
 148                    selections: state.selections,
 149                    pending_selection: state.pending_selection,
 150                    scroll_top_anchor: state.scroll_top_anchor,
 151                    scroll_x: state.scroll_x,
 152                    scroll_y: state.scroll_y,
 153                    ..Default::default()
 154                },
 155                &mut cx,
 156            )
 157            .await?;
 158
 159            Ok(editor)
 160        }))
 161    }
 162
 163    fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>) {
 164        self.leader_peer_id = leader_peer_id;
 165        if self.leader_peer_id.is_some() {
 166            self.buffer.update(cx, |buffer, cx| {
 167                buffer.remove_active_selections(cx);
 168            });
 169        } else if self.focus_handle.is_focused(cx) {
 170            self.buffer.update(cx, |buffer, cx| {
 171                buffer.set_active_selections(
 172                    &self.selections.disjoint_anchors(),
 173                    self.selections.line_mode,
 174                    self.cursor_shape,
 175                    cx,
 176                );
 177            });
 178        }
 179        cx.notify();
 180    }
 181
 182    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
 183        let buffer = self.buffer.read(cx);
 184        if buffer
 185            .as_singleton()
 186            .and_then(|buffer| buffer.read(cx).file())
 187            .map_or(false, |file| file.is_private())
 188        {
 189            return None;
 190        }
 191
 192        let scroll_anchor = self.scroll_manager.anchor();
 193        let excerpts = buffer
 194            .read(cx)
 195            .excerpts()
 196            .map(|(id, buffer, range)| proto::Excerpt {
 197                id: id.to_proto(),
 198                buffer_id: buffer.remote_id().into(),
 199                context_start: Some(serialize_text_anchor(&range.context.start)),
 200                context_end: Some(serialize_text_anchor(&range.context.end)),
 201                primary_start: range
 202                    .primary
 203                    .as_ref()
 204                    .map(|range| serialize_text_anchor(&range.start)),
 205                primary_end: range
 206                    .primary
 207                    .as_ref()
 208                    .map(|range| serialize_text_anchor(&range.end)),
 209            })
 210            .collect();
 211
 212        Some(proto::view::Variant::Editor(proto::view::Editor {
 213            singleton: buffer.is_singleton(),
 214            title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
 215            excerpts,
 216            scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
 217            scroll_x: scroll_anchor.offset.x,
 218            scroll_y: scroll_anchor.offset.y,
 219            selections: self
 220                .selections
 221                .disjoint_anchors()
 222                .iter()
 223                .map(serialize_selection)
 224                .collect(),
 225            pending_selection: self
 226                .selections
 227                .pending_anchor()
 228                .as_ref()
 229                .map(serialize_selection),
 230        }))
 231    }
 232
 233    fn to_follow_event(event: &EditorEvent) -> Option<workspace::item::FollowEvent> {
 234        match event {
 235            EditorEvent::Edited => Some(FollowEvent::Unfollow),
 236            EditorEvent::SelectionsChanged { local }
 237            | EditorEvent::ScrollPositionChanged { local, .. } => {
 238                if *local {
 239                    Some(FollowEvent::Unfollow)
 240                } else {
 241                    None
 242                }
 243            }
 244            _ => None,
 245        }
 246    }
 247
 248    fn add_event_to_update_proto(
 249        &self,
 250        event: &EditorEvent,
 251        update: &mut Option<proto::update_view::Variant>,
 252        cx: &WindowContext,
 253    ) -> bool {
 254        let update =
 255            update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
 256
 257        match update {
 258            proto::update_view::Variant::Editor(update) => match event {
 259                EditorEvent::ExcerptsAdded {
 260                    buffer,
 261                    predecessor,
 262                    excerpts,
 263                } => {
 264                    let buffer_id = buffer.read(cx).remote_id();
 265                    let mut excerpts = excerpts.iter();
 266                    if let Some((id, range)) = excerpts.next() {
 267                        update.inserted_excerpts.push(proto::ExcerptInsertion {
 268                            previous_excerpt_id: Some(predecessor.to_proto()),
 269                            excerpt: serialize_excerpt(buffer_id, id, range),
 270                        });
 271                        update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
 272                            proto::ExcerptInsertion {
 273                                previous_excerpt_id: None,
 274                                excerpt: serialize_excerpt(buffer_id, id, range),
 275                            }
 276                        }))
 277                    }
 278                    true
 279                }
 280                EditorEvent::ExcerptsRemoved { ids } => {
 281                    update
 282                        .deleted_excerpts
 283                        .extend(ids.iter().map(ExcerptId::to_proto));
 284                    true
 285                }
 286                EditorEvent::ScrollPositionChanged { autoscroll, .. } if !autoscroll => {
 287                    let scroll_anchor = self.scroll_manager.anchor();
 288                    update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
 289                    update.scroll_x = scroll_anchor.offset.x;
 290                    update.scroll_y = scroll_anchor.offset.y;
 291                    true
 292                }
 293                EditorEvent::SelectionsChanged { .. } => {
 294                    update.selections = self
 295                        .selections
 296                        .disjoint_anchors()
 297                        .iter()
 298                        .map(serialize_selection)
 299                        .collect();
 300                    update.pending_selection = self
 301                        .selections
 302                        .pending_anchor()
 303                        .as_ref()
 304                        .map(serialize_selection);
 305                    true
 306                }
 307                _ => false,
 308            },
 309        }
 310    }
 311
 312    fn apply_update_proto(
 313        &mut self,
 314        project: &Model<Project>,
 315        message: update_view::Variant,
 316        cx: &mut ViewContext<Self>,
 317    ) -> Task<Result<()>> {
 318        let update_view::Variant::Editor(message) = message;
 319        let project = project.clone();
 320        cx.spawn(|this, mut cx| async move {
 321            update_editor_from_message(this, project, message, &mut cx).await
 322        })
 323    }
 324
 325    fn is_project_item(&self, _cx: &WindowContext) -> bool {
 326        true
 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) 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_content(&self, detail: Option<usize>, selected: bool, cx: &WindowContext) -> AnyElement {
 598        let git_status = if ItemSettings::get_global(cx).git_status {
 599            self.buffer()
 600                .read(cx)
 601                .as_singleton()
 602                .and_then(|buffer| buffer.read(cx).project_path(cx))
 603                .and_then(|path| self.project.as_ref()?.read(cx).entry_for_path(&path, cx))
 604                .and_then(|entry| entry.git_status())
 605        } else {
 606            None
 607        };
 608        let label_color = match git_status {
 609            Some(GitFileStatus::Added) => Color::Created,
 610            Some(GitFileStatus::Modified) => Color::Modified,
 611            Some(GitFileStatus::Conflict) => Color::Conflict,
 612            None => {
 613                if selected {
 614                    Color::Default
 615                } else {
 616                    Color::Muted
 617                }
 618            }
 619        };
 620
 621        let description = detail.and_then(|detail| {
 622            let path = path_for_buffer(&self.buffer, detail, false, cx)?;
 623            let description = path.to_string_lossy();
 624            let description = description.trim();
 625
 626            if description.is_empty() {
 627                return None;
 628            }
 629
 630            Some(util::truncate_and_trailoff(&description, MAX_TAB_TITLE_LEN))
 631        });
 632
 633        h_flex()
 634            .gap_2()
 635            .child(Label::new(self.title(cx).to_string()).color(label_color))
 636            .when_some(description, |this, description| {
 637                this.child(
 638                    Label::new(description)
 639                        .size(LabelSize::XSmall)
 640                        .color(Color::Muted),
 641                )
 642            })
 643            .into_any_element()
 644    }
 645
 646    fn for_each_project_item(
 647        &self,
 648        cx: &AppContext,
 649        f: &mut dyn FnMut(EntityId, &dyn project::Item),
 650    ) {
 651        self.buffer
 652            .read(cx)
 653            .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
 654    }
 655
 656    fn is_singleton(&self, cx: &AppContext) -> bool {
 657        self.buffer.read(cx).is_singleton()
 658    }
 659
 660    fn clone_on_split(
 661        &self,
 662        _workspace_id: WorkspaceId,
 663        cx: &mut ViewContext<Self>,
 664    ) -> Option<View<Editor>>
 665    where
 666        Self: Sized,
 667    {
 668        Some(cx.new_view(|cx| self.clone(cx)))
 669    }
 670
 671    fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
 672        self.nav_history = Some(history);
 673    }
 674
 675    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 676        let selection = self.selections.newest_anchor();
 677        self.push_to_nav_history(selection.head(), None, cx);
 678    }
 679
 680    fn workspace_deactivated(&mut self, cx: &mut ViewContext<Self>) {
 681        self.hide_hovered_link(cx);
 682    }
 683
 684    fn is_dirty(&self, cx: &AppContext) -> bool {
 685        self.buffer().read(cx).read(cx).is_dirty()
 686    }
 687
 688    fn has_conflict(&self, cx: &AppContext) -> bool {
 689        self.buffer().read(cx).read(cx).has_conflict()
 690    }
 691
 692    fn can_save(&self, cx: &AppContext) -> bool {
 693        let buffer = &self.buffer().read(cx);
 694        if let Some(buffer) = buffer.as_singleton() {
 695            buffer.read(cx).project_path(cx).is_some()
 696        } else {
 697            true
 698        }
 699    }
 700
 701    fn save(
 702        &mut self,
 703        format: bool,
 704        project: Model<Project>,
 705        cx: &mut ViewContext<Self>,
 706    ) -> Task<Result<()>> {
 707        self.report_editor_event("save", None, cx);
 708        let buffers = self.buffer().clone().read(cx).all_buffers();
 709        cx.spawn(|this, mut cx| async move {
 710            if format {
 711                this.update(&mut cx, |this, cx| {
 712                    this.perform_format(project.clone(), FormatTrigger::Save, cx)
 713                })?
 714                .await?;
 715            }
 716
 717            if buffers.len() == 1 {
 718                project
 719                    .update(&mut cx, |project, cx| project.save_buffers(buffers, cx))?
 720                    .await?;
 721            } else {
 722                // For multi-buffers, only save those ones that contain changes. For clean buffers
 723                // we simulate saving by calling `Buffer::did_save`, so that language servers or
 724                // other downstream listeners of save events get notified.
 725                let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
 726                    buffer
 727                        .update(&mut cx, |buffer, _| {
 728                            buffer.is_dirty() || buffer.has_conflict()
 729                        })
 730                        .unwrap_or(false)
 731                });
 732
 733                project
 734                    .update(&mut cx, |project, cx| {
 735                        project.save_buffers(dirty_buffers, cx)
 736                    })?
 737                    .await?;
 738                for buffer in clean_buffers {
 739                    buffer
 740                        .update(&mut cx, |buffer, cx| {
 741                            let version = buffer.saved_version().clone();
 742                            let fingerprint = buffer.saved_version_fingerprint();
 743                            let mtime = buffer.saved_mtime();
 744                            buffer.did_save(version, fingerprint, mtime, cx);
 745                        })
 746                        .ok();
 747                }
 748            }
 749
 750            Ok(())
 751        })
 752    }
 753
 754    fn save_as(
 755        &mut self,
 756        project: Model<Project>,
 757        abs_path: PathBuf,
 758        cx: &mut ViewContext<Self>,
 759    ) -> Task<Result<()>> {
 760        let buffer = self
 761            .buffer()
 762            .read(cx)
 763            .as_singleton()
 764            .expect("cannot call save_as on an excerpt list");
 765
 766        let file_extension = abs_path
 767            .extension()
 768            .map(|a| a.to_string_lossy().to_string());
 769        self.report_editor_event("save", file_extension, cx);
 770
 771        project.update(cx, |project, cx| {
 772            project.save_buffer_as(buffer, abs_path, cx)
 773        })
 774    }
 775
 776    fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
 777        let buffer = self.buffer().clone();
 778        let buffers = self.buffer.read(cx).all_buffers();
 779        let reload_buffers =
 780            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
 781        cx.spawn(|this, mut cx| async move {
 782            let transaction = reload_buffers.log_err().await;
 783            this.update(&mut cx, |editor, cx| {
 784                editor.request_autoscroll(Autoscroll::fit(), cx)
 785            })?;
 786            buffer
 787                .update(&mut cx, |buffer, cx| {
 788                    if let Some(transaction) = transaction {
 789                        if !buffer.is_singleton() {
 790                            buffer.push_transaction(&transaction.0, cx);
 791                        }
 792                    }
 793                })
 794                .ok();
 795            Ok(())
 796        })
 797    }
 798
 799    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 800        Some(Box::new(handle.clone()))
 801    }
 802
 803    fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<gpui::Point<Pixels>> {
 804        self.pixel_position_of_newest_cursor
 805    }
 806
 807    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 808        if self.show_breadcrumbs {
 809            ToolbarItemLocation::PrimaryLeft
 810        } else {
 811            ToolbarItemLocation::Hidden
 812        }
 813    }
 814
 815    fn breadcrumbs(&self, variant: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 816        let cursor = self.selections.newest_anchor().head();
 817        let multibuffer = &self.buffer().read(cx);
 818        let (buffer_id, symbols) =
 819            multibuffer.symbols_containing(cursor, Some(&variant.syntax()), cx)?;
 820        let buffer = multibuffer.buffer(buffer_id)?;
 821
 822        let buffer = buffer.read(cx);
 823        let filename = buffer
 824            .snapshot()
 825            .resolve_file_path(
 826                cx,
 827                self.project
 828                    .as_ref()
 829                    .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 830                    .unwrap_or_default(),
 831            )
 832            .map(|path| path.to_string_lossy().to_string())
 833            .unwrap_or_else(|| "untitled".to_string());
 834
 835        let mut breadcrumbs = vec![BreadcrumbText {
 836            text: filename,
 837            highlights: None,
 838        }];
 839        breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
 840            text: symbol.text,
 841            highlights: Some(symbol.highlight_ranges),
 842        }));
 843        Some(breadcrumbs)
 844    }
 845
 846    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 847        let workspace_id = workspace.database_id();
 848        let item_id = cx.view().item_id().as_u64() as ItemId;
 849        self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
 850
 851        fn serialize(
 852            buffer: Model<Buffer>,
 853            workspace_id: WorkspaceId,
 854            item_id: ItemId,
 855            cx: &mut AppContext,
 856        ) {
 857            if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
 858                let path = file.abs_path(cx);
 859
 860                cx.background_executor()
 861                    .spawn(async move {
 862                        DB.save_path(item_id, workspace_id, path.clone())
 863                            .await
 864                            .log_err()
 865                    })
 866                    .detach();
 867            }
 868        }
 869
 870        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 871            serialize(buffer.clone(), workspace_id, item_id, cx);
 872
 873            cx.subscribe(&buffer, |this, buffer, event, cx| {
 874                if let Some((_, workspace_id)) = this.workspace.as_ref() {
 875                    if let language::Event::FileHandleChanged = event {
 876                        serialize(
 877                            buffer,
 878                            *workspace_id,
 879                            cx.view().item_id().as_u64() as ItemId,
 880                            cx,
 881                        );
 882                    }
 883                }
 884            })
 885            .detach();
 886        }
 887    }
 888
 889    fn serialized_item_kind() -> Option<&'static str> {
 890        Some("Editor")
 891    }
 892
 893    fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
 894        match event {
 895            EditorEvent::Closed => f(ItemEvent::CloseItem),
 896
 897            EditorEvent::Saved | EditorEvent::TitleChanged => {
 898                f(ItemEvent::UpdateTab);
 899                f(ItemEvent::UpdateBreadcrumbs);
 900            }
 901
 902            EditorEvent::Reparsed => {
 903                f(ItemEvent::UpdateBreadcrumbs);
 904            }
 905
 906            EditorEvent::SelectionsChanged { local } if *local => {
 907                f(ItemEvent::UpdateBreadcrumbs);
 908            }
 909
 910            EditorEvent::DirtyChanged => {
 911                f(ItemEvent::UpdateTab);
 912            }
 913
 914            EditorEvent::BufferEdited => {
 915                f(ItemEvent::Edit);
 916                f(ItemEvent::UpdateBreadcrumbs);
 917            }
 918
 919            EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
 920                f(ItemEvent::Edit);
 921            }
 922
 923            _ => {}
 924        }
 925    }
 926
 927    fn deserialize(
 928        project: Model<Project>,
 929        _workspace: WeakView<Workspace>,
 930        workspace_id: workspace::WorkspaceId,
 931        item_id: ItemId,
 932        cx: &mut ViewContext<Pane>,
 933    ) -> Task<Result<View<Self>>> {
 934        let project_item: Result<_> = project.update(cx, |project, cx| {
 935            // Look up the path with this key associated, create a self with that path
 936            let path = DB
 937                .get_path(item_id, workspace_id)?
 938                .context("No path stored for this editor")?;
 939
 940            let (worktree, path) = project
 941                .find_local_worktree(&path, cx)
 942                .with_context(|| format!("No worktree for path: {path:?}"))?;
 943            let project_path = ProjectPath {
 944                worktree_id: worktree.read(cx).id(),
 945                path: path.into(),
 946            };
 947
 948            Ok(project.open_path(project_path, cx))
 949        });
 950
 951        project_item
 952            .map(|project_item| {
 953                cx.spawn(|pane, mut cx| async move {
 954                    let (_, project_item) = project_item.await?;
 955                    let buffer = project_item
 956                        .downcast::<Buffer>()
 957                        .map_err(|_| anyhow!("Project item at stored path was not a buffer"))?;
 958                    pane.update(&mut cx, |_, cx| {
 959                        cx.new_view(|cx| {
 960                            let mut editor = Editor::for_buffer(buffer, Some(project), cx);
 961
 962                            editor.read_scroll_position_from_db(item_id, workspace_id, cx);
 963                            editor
 964                        })
 965                    })
 966                })
 967            })
 968            .unwrap_or_else(|error| Task::ready(Err(error)))
 969    }
 970}
 971
 972impl ProjectItem for Editor {
 973    type Item = Buffer;
 974
 975    fn for_project_item(
 976        project: Model<Project>,
 977        buffer: Model<Buffer>,
 978        cx: &mut ViewContext<Self>,
 979    ) -> Self {
 980        Self::for_buffer(buffer, Some(project), cx)
 981    }
 982}
 983
 984impl EventEmitter<SearchEvent> for Editor {}
 985
 986pub(crate) enum BufferSearchHighlights {}
 987impl SearchableItem for Editor {
 988    type Match = Range<Anchor>;
 989
 990    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
 991        self.clear_background_highlights::<BufferSearchHighlights>(cx);
 992    }
 993
 994    fn update_matches(&mut self, matches: Vec<Range<Anchor>>, cx: &mut ViewContext<Self>) {
 995        self.highlight_background::<BufferSearchHighlights>(
 996            matches,
 997            |theme| theme.search_match_background,
 998            cx,
 999        );
1000    }
1001
1002    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
1003        let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1004        let snapshot = &self.snapshot(cx).buffer_snapshot;
1005        let selection = self.selections.newest::<usize>(cx);
1006
1007        match setting {
1008            SeedQuerySetting::Never => String::new(),
1009            SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1010                snapshot
1011                    .text_for_range(selection.start..selection.end)
1012                    .collect()
1013            }
1014            SeedQuerySetting::Selection => String::new(),
1015            SeedQuerySetting::Always => {
1016                let (range, kind) = snapshot.surrounding_word(selection.start);
1017                if kind == Some(CharKind::Word) {
1018                    let text: String = snapshot.text_for_range(range).collect();
1019                    if !text.trim().is_empty() {
1020                        return text;
1021                    }
1022                }
1023                String::new()
1024            }
1025        }
1026    }
1027
1028    fn activate_match(
1029        &mut self,
1030        index: usize,
1031        matches: Vec<Range<Anchor>>,
1032        cx: &mut ViewContext<Self>,
1033    ) {
1034        self.unfold_ranges([matches[index].clone()], false, true, cx);
1035        let range = self.range_for_match(&matches[index]);
1036        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
1037            s.select_ranges([range]);
1038        })
1039    }
1040
1041    fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
1042        self.unfold_ranges(matches.clone(), false, false, cx);
1043        let mut ranges = Vec::new();
1044        for m in &matches {
1045            ranges.push(self.range_for_match(&m))
1046        }
1047        self.change_selections(None, cx, |s| s.select_ranges(ranges));
1048    }
1049    fn replace(
1050        &mut self,
1051        identifier: &Self::Match,
1052        query: &SearchQuery,
1053        cx: &mut ViewContext<Self>,
1054    ) {
1055        let text = self.buffer.read(cx);
1056        let text = text.snapshot(cx);
1057        let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1058        let text: Cow<_> = if text.len() == 1 {
1059            text.first().cloned().unwrap().into()
1060        } else {
1061            let joined_chunks = text.join("");
1062            joined_chunks.into()
1063        };
1064
1065        if let Some(replacement) = query.replacement_for(&text) {
1066            self.transact(cx, |this, cx| {
1067                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1068            });
1069        }
1070    }
1071    fn match_index_for_direction(
1072        &mut self,
1073        matches: &Vec<Range<Anchor>>,
1074        current_index: usize,
1075        direction: Direction,
1076        count: usize,
1077        cx: &mut ViewContext<Self>,
1078    ) -> usize {
1079        let buffer = self.buffer().read(cx).snapshot(cx);
1080        let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1081            self.selections.newest_anchor().head()
1082        } else {
1083            matches[current_index].start
1084        };
1085
1086        let mut count = count % matches.len();
1087        if count == 0 {
1088            return current_index;
1089        }
1090        match direction {
1091            Direction::Next => {
1092                if matches[current_index]
1093                    .start
1094                    .cmp(&current_index_position, &buffer)
1095                    .is_gt()
1096                {
1097                    count = count - 1
1098                }
1099
1100                (current_index + count) % matches.len()
1101            }
1102            Direction::Prev => {
1103                if matches[current_index]
1104                    .end
1105                    .cmp(&current_index_position, &buffer)
1106                    .is_lt()
1107                {
1108                    count = count - 1;
1109                }
1110
1111                if current_index >= count {
1112                    current_index - count
1113                } else {
1114                    matches.len() - (count - current_index)
1115                }
1116            }
1117        }
1118    }
1119
1120    fn find_matches(
1121        &mut self,
1122        query: Arc<project::search::SearchQuery>,
1123        cx: &mut ViewContext<Self>,
1124    ) -> Task<Vec<Range<Anchor>>> {
1125        let buffer = self.buffer().read(cx).snapshot(cx);
1126        cx.background_executor().spawn(async move {
1127            let mut ranges = Vec::new();
1128            if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
1129                ranges.extend(
1130                    query
1131                        .search(excerpt_buffer, None)
1132                        .await
1133                        .into_iter()
1134                        .map(|range| {
1135                            buffer.anchor_after(range.start)..buffer.anchor_before(range.end)
1136                        }),
1137                );
1138            } else {
1139                for excerpt in buffer.excerpt_boundaries_in_range(0..buffer.len()) {
1140                    let excerpt_range = excerpt.range.context.to_offset(&excerpt.buffer);
1141                    ranges.extend(
1142                        query
1143                            .search(&excerpt.buffer, Some(excerpt_range.clone()))
1144                            .await
1145                            .into_iter()
1146                            .map(|range| {
1147                                let start = excerpt
1148                                    .buffer
1149                                    .anchor_after(excerpt_range.start + range.start);
1150                                let end = excerpt
1151                                    .buffer
1152                                    .anchor_before(excerpt_range.start + range.end);
1153                                buffer.anchor_in_excerpt(excerpt.id, start).unwrap()
1154                                    ..buffer.anchor_in_excerpt(excerpt.id, end).unwrap()
1155                            }),
1156                    );
1157                }
1158            }
1159            ranges
1160        })
1161    }
1162
1163    fn active_match_index(
1164        &mut self,
1165        matches: Vec<Range<Anchor>>,
1166        cx: &mut ViewContext<Self>,
1167    ) -> Option<usize> {
1168        active_match_index(
1169            &matches,
1170            &self.selections.newest_anchor().head(),
1171            &self.buffer().read(cx).snapshot(cx),
1172        )
1173    }
1174}
1175
1176pub fn active_match_index(
1177    ranges: &[Range<Anchor>],
1178    cursor: &Anchor,
1179    buffer: &MultiBufferSnapshot,
1180) -> Option<usize> {
1181    if ranges.is_empty() {
1182        None
1183    } else {
1184        match ranges.binary_search_by(|probe| {
1185            if probe.end.cmp(cursor, buffer).is_lt() {
1186                Ordering::Less
1187            } else if probe.start.cmp(cursor, buffer).is_gt() {
1188                Ordering::Greater
1189            } else {
1190                Ordering::Equal
1191            }
1192        }) {
1193            Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1194        }
1195    }
1196}
1197
1198fn path_for_buffer<'a>(
1199    buffer: &Model<MultiBuffer>,
1200    height: usize,
1201    include_filename: bool,
1202    cx: &'a AppContext,
1203) -> Option<Cow<'a, Path>> {
1204    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1205    path_for_file(file.as_ref(), height, include_filename, cx)
1206}
1207
1208fn path_for_file<'a>(
1209    file: &'a dyn language::File,
1210    mut height: usize,
1211    include_filename: bool,
1212    cx: &'a AppContext,
1213) -> Option<Cow<'a, Path>> {
1214    // Ensure we always render at least the filename.
1215    height += 1;
1216
1217    let mut prefix = file.path().as_ref();
1218    while height > 0 {
1219        if let Some(parent) = prefix.parent() {
1220            prefix = parent;
1221            height -= 1;
1222        } else {
1223            break;
1224        }
1225    }
1226
1227    // Here we could have just always used `full_path`, but that is very
1228    // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1229    // traversed all the way up to the worktree's root.
1230    if height > 0 {
1231        let full_path = file.full_path(cx);
1232        if include_filename {
1233            Some(full_path.into())
1234        } else {
1235            Some(full_path.parent()?.to_path_buf().into())
1236        }
1237    } else {
1238        let mut path = file.path().strip_prefix(prefix).ok()?;
1239        if !include_filename {
1240            path = path.parent()?;
1241        }
1242        Some(path.into())
1243    }
1244}
1245
1246#[cfg(test)]
1247mod tests {
1248    use super::*;
1249    use gpui::AppContext;
1250    use std::{
1251        path::{Path, PathBuf},
1252        sync::Arc,
1253        time::SystemTime,
1254    };
1255
1256    #[gpui::test]
1257    fn test_path_for_file(cx: &mut AppContext) {
1258        let file = TestFile {
1259            path: Path::new("").into(),
1260            full_path: PathBuf::from(""),
1261        };
1262        assert_eq!(path_for_file(&file, 0, false, cx), None);
1263    }
1264
1265    struct TestFile {
1266        path: Arc<Path>,
1267        full_path: PathBuf,
1268    }
1269
1270    impl language::File for TestFile {
1271        fn path(&self) -> &Arc<Path> {
1272            &self.path
1273        }
1274
1275        fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
1276            self.full_path.clone()
1277        }
1278
1279        fn as_local(&self) -> Option<&dyn language::LocalFile> {
1280            unimplemented!()
1281        }
1282
1283        fn mtime(&self) -> Option<SystemTime> {
1284            unimplemented!()
1285        }
1286
1287        fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
1288            unimplemented!()
1289        }
1290
1291        fn worktree_id(&self) -> usize {
1292            0
1293        }
1294
1295        fn is_deleted(&self) -> bool {
1296            unimplemented!()
1297        }
1298
1299        fn as_any(&self) -> &dyn std::any::Any {
1300            unimplemented!()
1301        }
1302
1303        fn to_proto(&self) -> rpc::proto::File {
1304            unimplemented!()
1305        }
1306
1307        fn is_private(&self) -> bool {
1308            false
1309        }
1310    }
1311}