items.rs

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