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