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