items.rs

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