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