project.rs

   1pub mod fs;
   2mod ignore;
   3mod lsp_command;
   4pub mod search;
   5pub mod worktree;
   6
   7use anyhow::{anyhow, Context, Result};
   8use client::{proto, Client, PeerId, TypedEnvelope, User, UserStore};
   9use clock::ReplicaId;
  10use collections::{hash_map, HashMap, HashSet};
  11use futures::{future::Shared, Future, FutureExt, StreamExt, TryFutureExt};
  12use fuzzy::{PathMatch, PathMatchCandidate, PathMatchCandidateSet};
  13use gpui::{
  14    AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext, Task,
  15    UpgradeModelHandle, WeakModelHandle,
  16};
  17use language::{
  18    proto::{deserialize_anchor, serialize_anchor},
  19    range_from_lsp, Anchor, AnchorRangeExt, Bias, Buffer, CodeAction, CodeLabel, Completion,
  20    Diagnostic, DiagnosticEntry, File as _, Language, LanguageRegistry, Operation, PointUtf16,
  21    ToLspPosition, ToOffset, ToPointUtf16, Transaction,
  22};
  23use lsp::{DiagnosticSeverity, DocumentHighlightKind, LanguageServer};
  24use lsp_command::*;
  25use postage::watch;
  26use rand::prelude::*;
  27use search::SearchQuery;
  28use sha2::{Digest, Sha256};
  29use smol::block_on;
  30use std::{
  31    cell::RefCell,
  32    cmp,
  33    convert::TryInto,
  34    hash::Hash,
  35    mem,
  36    ops::Range,
  37    path::{Component, Path, PathBuf},
  38    rc::Rc,
  39    sync::{atomic::AtomicBool, Arc},
  40    time::Instant,
  41};
  42use util::{post_inc, ResultExt, TryFutureExt as _};
  43
  44pub use fs::*;
  45pub use worktree::*;
  46
  47pub struct Project {
  48    worktrees: Vec<WorktreeHandle>,
  49    active_entry: Option<ProjectEntry>,
  50    languages: Arc<LanguageRegistry>,
  51    language_servers: HashMap<(WorktreeId, String), Arc<LanguageServer>>,
  52    started_language_servers:
  53        HashMap<(WorktreeId, String), Shared<Task<Option<Arc<LanguageServer>>>>>,
  54    client: Arc<client::Client>,
  55    user_store: ModelHandle<UserStore>,
  56    fs: Arc<dyn Fs>,
  57    client_state: ProjectClientState,
  58    collaborators: HashMap<PeerId, Collaborator>,
  59    subscriptions: Vec<client::Subscription>,
  60    language_servers_with_diagnostics_running: isize,
  61    opened_buffer: (Rc<RefCell<watch::Sender<()>>>, watch::Receiver<()>),
  62    shared_buffers: HashMap<PeerId, HashSet<u64>>,
  63    loading_buffers: HashMap<
  64        ProjectPath,
  65        postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
  66    >,
  67    loading_local_worktrees:
  68        HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
  69    opened_buffers: HashMap<u64, OpenBuffer>,
  70    nonce: u128,
  71}
  72
  73enum OpenBuffer {
  74    Strong(ModelHandle<Buffer>),
  75    Weak(WeakModelHandle<Buffer>),
  76    Loading(Vec<Operation>),
  77}
  78
  79enum WorktreeHandle {
  80    Strong(ModelHandle<Worktree>),
  81    Weak(WeakModelHandle<Worktree>),
  82}
  83
  84enum ProjectClientState {
  85    Local {
  86        is_shared: bool,
  87        remote_id_tx: watch::Sender<Option<u64>>,
  88        remote_id_rx: watch::Receiver<Option<u64>>,
  89        _maintain_remote_id_task: Task<Option<()>>,
  90    },
  91    Remote {
  92        sharing_has_stopped: bool,
  93        remote_id: u64,
  94        replica_id: ReplicaId,
  95    },
  96}
  97
  98#[derive(Clone, Debug)]
  99pub struct Collaborator {
 100    pub user: Arc<User>,
 101    pub peer_id: PeerId,
 102    pub replica_id: ReplicaId,
 103}
 104
 105#[derive(Clone, Debug, PartialEq)]
 106pub enum Event {
 107    ActiveEntryChanged(Option<ProjectEntry>),
 108    WorktreeRemoved(WorktreeId),
 109    DiskBasedDiagnosticsStarted,
 110    DiskBasedDiagnosticsUpdated,
 111    DiskBasedDiagnosticsFinished,
 112    DiagnosticsUpdated(ProjectPath),
 113}
 114
 115#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 116pub struct ProjectPath {
 117    pub worktree_id: WorktreeId,
 118    pub path: Arc<Path>,
 119}
 120
 121#[derive(Clone, Debug, Default, PartialEq)]
 122pub struct DiagnosticSummary {
 123    pub error_count: usize,
 124    pub warning_count: usize,
 125    pub info_count: usize,
 126    pub hint_count: usize,
 127}
 128
 129#[derive(Debug)]
 130pub struct Location {
 131    pub buffer: ModelHandle<Buffer>,
 132    pub range: Range<language::Anchor>,
 133}
 134
 135#[derive(Debug)]
 136pub struct DocumentHighlight {
 137    pub range: Range<language::Anchor>,
 138    pub kind: DocumentHighlightKind,
 139}
 140
 141#[derive(Clone, Debug)]
 142pub struct Symbol {
 143    pub source_worktree_id: WorktreeId,
 144    pub worktree_id: WorktreeId,
 145    pub language_name: String,
 146    pub path: PathBuf,
 147    pub label: CodeLabel,
 148    pub name: String,
 149    pub kind: lsp::SymbolKind,
 150    pub range: Range<PointUtf16>,
 151    pub signature: [u8; 32],
 152}
 153
 154#[derive(Default)]
 155pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
 156
 157impl DiagnosticSummary {
 158    fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
 159        let mut this = Self {
 160            error_count: 0,
 161            warning_count: 0,
 162            info_count: 0,
 163            hint_count: 0,
 164        };
 165
 166        for entry in diagnostics {
 167            if entry.diagnostic.is_primary {
 168                match entry.diagnostic.severity {
 169                    DiagnosticSeverity::ERROR => this.error_count += 1,
 170                    DiagnosticSeverity::WARNING => this.warning_count += 1,
 171                    DiagnosticSeverity::INFORMATION => this.info_count += 1,
 172                    DiagnosticSeverity::HINT => this.hint_count += 1,
 173                    _ => {}
 174                }
 175            }
 176        }
 177
 178        this
 179    }
 180
 181    pub fn to_proto(&self, path: &Path) -> proto::DiagnosticSummary {
 182        proto::DiagnosticSummary {
 183            path: path.to_string_lossy().to_string(),
 184            error_count: self.error_count as u32,
 185            warning_count: self.warning_count as u32,
 186            info_count: self.info_count as u32,
 187            hint_count: self.hint_count as u32,
 188        }
 189    }
 190}
 191
 192#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 193pub struct ProjectEntry {
 194    pub worktree_id: WorktreeId,
 195    pub entry_id: usize,
 196}
 197
 198impl Project {
 199    pub fn init(client: &Arc<Client>) {
 200        client.add_entity_message_handler(Self::handle_add_collaborator);
 201        client.add_entity_message_handler(Self::handle_buffer_reloaded);
 202        client.add_entity_message_handler(Self::handle_buffer_saved);
 203        client.add_entity_message_handler(Self::handle_close_buffer);
 204        client.add_entity_message_handler(Self::handle_disk_based_diagnostics_updated);
 205        client.add_entity_message_handler(Self::handle_disk_based_diagnostics_updating);
 206        client.add_entity_message_handler(Self::handle_remove_collaborator);
 207        client.add_entity_message_handler(Self::handle_register_worktree);
 208        client.add_entity_message_handler(Self::handle_unregister_worktree);
 209        client.add_entity_message_handler(Self::handle_unshare_project);
 210        client.add_entity_message_handler(Self::handle_update_buffer_file);
 211        client.add_entity_message_handler(Self::handle_update_buffer);
 212        client.add_entity_message_handler(Self::handle_update_diagnostic_summary);
 213        client.add_entity_message_handler(Self::handle_update_worktree);
 214        client.add_entity_request_handler(Self::handle_apply_additional_edits_for_completion);
 215        client.add_entity_request_handler(Self::handle_apply_code_action);
 216        client.add_entity_request_handler(Self::handle_format_buffers);
 217        client.add_entity_request_handler(Self::handle_get_code_actions);
 218        client.add_entity_request_handler(Self::handle_get_completions);
 219        client.add_entity_request_handler(Self::handle_lsp_command::<GetDefinition>);
 220        client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
 221        client.add_entity_request_handler(Self::handle_lsp_command::<GetReferences>);
 222        client.add_entity_request_handler(Self::handle_lsp_command::<PrepareRename>);
 223        client.add_entity_request_handler(Self::handle_lsp_command::<PerformRename>);
 224        client.add_entity_request_handler(Self::handle_search_project);
 225        client.add_entity_request_handler(Self::handle_get_project_symbols);
 226        client.add_entity_request_handler(Self::handle_open_buffer_for_symbol);
 227        client.add_entity_request_handler(Self::handle_open_buffer);
 228        client.add_entity_request_handler(Self::handle_save_buffer);
 229    }
 230
 231    pub fn local(
 232        client: Arc<Client>,
 233        user_store: ModelHandle<UserStore>,
 234        languages: Arc<LanguageRegistry>,
 235        fs: Arc<dyn Fs>,
 236        cx: &mut MutableAppContext,
 237    ) -> ModelHandle<Self> {
 238        cx.add_model(|cx: &mut ModelContext<Self>| {
 239            let (remote_id_tx, remote_id_rx) = watch::channel();
 240            let _maintain_remote_id_task = cx.spawn_weak({
 241                let rpc = client.clone();
 242                move |this, mut cx| {
 243                    async move {
 244                        let mut status = rpc.status();
 245                        while let Some(status) = status.next().await {
 246                            if let Some(this) = this.upgrade(&cx) {
 247                                let remote_id = if let client::Status::Connected { .. } = status {
 248                                    let response = rpc.request(proto::RegisterProject {}).await?;
 249                                    Some(response.project_id)
 250                                } else {
 251                                    None
 252                                };
 253
 254                                if let Some(project_id) = remote_id {
 255                                    let mut registrations = Vec::new();
 256                                    this.update(&mut cx, |this, cx| {
 257                                        for worktree in this.worktrees(cx).collect::<Vec<_>>() {
 258                                            registrations.push(worktree.update(
 259                                                cx,
 260                                                |worktree, cx| {
 261                                                    let worktree = worktree.as_local_mut().unwrap();
 262                                                    worktree.register(project_id, cx)
 263                                                },
 264                                            ));
 265                                        }
 266                                    });
 267                                    for registration in registrations {
 268                                        registration.await?;
 269                                    }
 270                                }
 271                                this.update(&mut cx, |this, cx| this.set_remote_id(remote_id, cx));
 272                            }
 273                        }
 274                        Ok(())
 275                    }
 276                    .log_err()
 277                }
 278            });
 279
 280            let (opened_buffer_tx, opened_buffer_rx) = watch::channel();
 281            Self {
 282                worktrees: Default::default(),
 283                collaborators: Default::default(),
 284                opened_buffers: Default::default(),
 285                shared_buffers: Default::default(),
 286                loading_buffers: Default::default(),
 287                loading_local_worktrees: Default::default(),
 288                client_state: ProjectClientState::Local {
 289                    is_shared: false,
 290                    remote_id_tx,
 291                    remote_id_rx,
 292                    _maintain_remote_id_task,
 293                },
 294                opened_buffer: (Rc::new(RefCell::new(opened_buffer_tx)), opened_buffer_rx),
 295                subscriptions: Vec::new(),
 296                active_entry: None,
 297                languages,
 298                client,
 299                user_store,
 300                fs,
 301                language_servers_with_diagnostics_running: 0,
 302                language_servers: Default::default(),
 303                started_language_servers: Default::default(),
 304                nonce: StdRng::from_entropy().gen(),
 305            }
 306        })
 307    }
 308
 309    pub async fn remote(
 310        remote_id: u64,
 311        client: Arc<Client>,
 312        user_store: ModelHandle<UserStore>,
 313        languages: Arc<LanguageRegistry>,
 314        fs: Arc<dyn Fs>,
 315        cx: &mut AsyncAppContext,
 316    ) -> Result<ModelHandle<Self>> {
 317        client.authenticate_and_connect(&cx).await?;
 318
 319        let response = client
 320            .request(proto::JoinProject {
 321                project_id: remote_id,
 322            })
 323            .await?;
 324
 325        let replica_id = response.replica_id as ReplicaId;
 326
 327        let mut worktrees = Vec::new();
 328        for worktree in response.worktrees {
 329            let (worktree, load_task) = cx
 330                .update(|cx| Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx));
 331            worktrees.push(worktree);
 332            load_task.detach();
 333        }
 334
 335        let (opened_buffer_tx, opened_buffer_rx) = watch::channel();
 336        let this = cx.add_model(|cx| {
 337            let mut this = Self {
 338                worktrees: Vec::new(),
 339                loading_buffers: Default::default(),
 340                opened_buffer: (Rc::new(RefCell::new(opened_buffer_tx)), opened_buffer_rx),
 341                shared_buffers: Default::default(),
 342                loading_local_worktrees: Default::default(),
 343                active_entry: None,
 344                collaborators: Default::default(),
 345                languages,
 346                user_store: user_store.clone(),
 347                fs,
 348                subscriptions: vec![client.add_model_for_remote_entity(remote_id, cx)],
 349                client,
 350                client_state: ProjectClientState::Remote {
 351                    sharing_has_stopped: false,
 352                    remote_id,
 353                    replica_id,
 354                },
 355                language_servers_with_diagnostics_running: 0,
 356                language_servers: Default::default(),
 357                started_language_servers: Default::default(),
 358                opened_buffers: Default::default(),
 359                nonce: StdRng::from_entropy().gen(),
 360            };
 361            for worktree in worktrees {
 362                this.add_worktree(&worktree, cx);
 363            }
 364            this
 365        });
 366
 367        let user_ids = response
 368            .collaborators
 369            .iter()
 370            .map(|peer| peer.user_id)
 371            .collect();
 372        user_store
 373            .update(cx, |user_store, cx| user_store.load_users(user_ids, cx))
 374            .await?;
 375        let mut collaborators = HashMap::default();
 376        for message in response.collaborators {
 377            let collaborator = Collaborator::from_proto(message, &user_store, cx).await?;
 378            collaborators.insert(collaborator.peer_id, collaborator);
 379        }
 380
 381        this.update(cx, |this, _| {
 382            this.collaborators = collaborators;
 383        });
 384
 385        Ok(this)
 386    }
 387
 388    #[cfg(any(test, feature = "test-support"))]
 389    pub fn test(fs: Arc<dyn Fs>, cx: &mut gpui::TestAppContext) -> ModelHandle<Project> {
 390        let languages = Arc::new(LanguageRegistry::new());
 391        let http_client = client::test::FakeHttpClient::with_404_response();
 392        let client = client::Client::new(http_client.clone());
 393        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 394        cx.update(|cx| Project::local(client, user_store, languages, fs, cx))
 395    }
 396
 397    #[cfg(any(test, feature = "test-support"))]
 398    pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
 399        self.opened_buffers
 400            .get(&remote_id)
 401            .and_then(|buffer| buffer.upgrade(cx))
 402    }
 403
 404    #[cfg(any(test, feature = "test-support"))]
 405    pub fn languages(&self) -> &Arc<LanguageRegistry> {
 406        &self.languages
 407    }
 408
 409    #[cfg(any(test, feature = "test-support"))]
 410    pub fn check_invariants(&self, cx: &AppContext) {
 411        if self.is_local() {
 412            let mut worktree_root_paths = HashMap::default();
 413            for worktree in self.worktrees(cx) {
 414                let worktree = worktree.read(cx);
 415                let abs_path = worktree.as_local().unwrap().abs_path().clone();
 416                let prev_worktree_id = worktree_root_paths.insert(abs_path.clone(), worktree.id());
 417                assert_eq!(
 418                    prev_worktree_id,
 419                    None,
 420                    "abs path {:?} for worktree {:?} is not unique ({:?} was already registered with the same path)",
 421                    abs_path,
 422                    worktree.id(),
 423                    prev_worktree_id
 424                )
 425            }
 426        } else {
 427            let replica_id = self.replica_id();
 428            for buffer in self.opened_buffers.values() {
 429                if let Some(buffer) = buffer.upgrade(cx) {
 430                    let buffer = buffer.read(cx);
 431                    assert_eq!(
 432                        buffer.deferred_ops_len(),
 433                        0,
 434                        "replica {}, buffer {} has deferred operations",
 435                        replica_id,
 436                        buffer.remote_id()
 437                    );
 438                }
 439            }
 440        }
 441    }
 442
 443    #[cfg(any(test, feature = "test-support"))]
 444    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
 445        let path = path.into();
 446        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
 447            self.opened_buffers.iter().any(|(_, buffer)| {
 448                if let Some(buffer) = buffer.upgrade(cx) {
 449                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 450                        if file.worktree == worktree && file.path() == &path.path {
 451                            return true;
 452                        }
 453                    }
 454                }
 455                false
 456            })
 457        } else {
 458            false
 459        }
 460    }
 461
 462    pub fn fs(&self) -> &Arc<dyn Fs> {
 463        &self.fs
 464    }
 465
 466    fn set_remote_id(&mut self, remote_id: Option<u64>, cx: &mut ModelContext<Self>) {
 467        if let ProjectClientState::Local { remote_id_tx, .. } = &mut self.client_state {
 468            *remote_id_tx.borrow_mut() = remote_id;
 469        }
 470
 471        self.subscriptions.clear();
 472        if let Some(remote_id) = remote_id {
 473            self.subscriptions
 474                .push(self.client.add_model_for_remote_entity(remote_id, cx));
 475        }
 476    }
 477
 478    pub fn remote_id(&self) -> Option<u64> {
 479        match &self.client_state {
 480            ProjectClientState::Local { remote_id_rx, .. } => *remote_id_rx.borrow(),
 481            ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
 482        }
 483    }
 484
 485    pub fn next_remote_id(&self) -> impl Future<Output = u64> {
 486        let mut id = None;
 487        let mut watch = None;
 488        match &self.client_state {
 489            ProjectClientState::Local { remote_id_rx, .. } => watch = Some(remote_id_rx.clone()),
 490            ProjectClientState::Remote { remote_id, .. } => id = Some(*remote_id),
 491        }
 492
 493        async move {
 494            if let Some(id) = id {
 495                return id;
 496            }
 497            let mut watch = watch.unwrap();
 498            loop {
 499                let id = *watch.borrow();
 500                if let Some(id) = id {
 501                    return id;
 502                }
 503                watch.next().await;
 504            }
 505        }
 506    }
 507
 508    pub fn replica_id(&self) -> ReplicaId {
 509        match &self.client_state {
 510            ProjectClientState::Local { .. } => 0,
 511            ProjectClientState::Remote { replica_id, .. } => *replica_id,
 512        }
 513    }
 514
 515    pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
 516        &self.collaborators
 517    }
 518
 519    pub fn worktrees<'a>(
 520        &'a self,
 521        cx: &'a AppContext,
 522    ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
 523        self.worktrees
 524            .iter()
 525            .filter_map(move |worktree| worktree.upgrade(cx))
 526    }
 527
 528    pub fn visible_worktrees<'a>(
 529        &'a self,
 530        cx: &'a AppContext,
 531    ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
 532        self.worktrees.iter().filter_map(|worktree| {
 533            worktree.upgrade(cx).and_then(|worktree| {
 534                if worktree.read(cx).is_visible() {
 535                    Some(worktree)
 536                } else {
 537                    None
 538                }
 539            })
 540        })
 541    }
 542
 543    pub fn worktree_for_id(
 544        &self,
 545        id: WorktreeId,
 546        cx: &AppContext,
 547    ) -> Option<ModelHandle<Worktree>> {
 548        self.worktrees(cx)
 549            .find(|worktree| worktree.read(cx).id() == id)
 550    }
 551
 552    pub fn share(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 553        let rpc = self.client.clone();
 554        cx.spawn(|this, mut cx| async move {
 555            let project_id = this.update(&mut cx, |this, cx| {
 556                if let ProjectClientState::Local {
 557                    is_shared,
 558                    remote_id_rx,
 559                    ..
 560                } = &mut this.client_state
 561                {
 562                    *is_shared = true;
 563
 564                    for open_buffer in this.opened_buffers.values_mut() {
 565                        match open_buffer {
 566                            OpenBuffer::Strong(_) => {}
 567                            OpenBuffer::Weak(buffer) => {
 568                                if let Some(buffer) = buffer.upgrade(cx) {
 569                                    *open_buffer = OpenBuffer::Strong(buffer);
 570                                }
 571                            }
 572                            OpenBuffer::Loading(_) => unreachable!(),
 573                        }
 574                    }
 575
 576                    for worktree_handle in this.worktrees.iter_mut() {
 577                        match worktree_handle {
 578                            WorktreeHandle::Strong(_) => {}
 579                            WorktreeHandle::Weak(worktree) => {
 580                                if let Some(worktree) = worktree.upgrade(cx) {
 581                                    *worktree_handle = WorktreeHandle::Strong(worktree);
 582                                }
 583                            }
 584                        }
 585                    }
 586
 587                    remote_id_rx
 588                        .borrow()
 589                        .ok_or_else(|| anyhow!("no project id"))
 590                } else {
 591                    Err(anyhow!("can't share a remote project"))
 592                }
 593            })?;
 594
 595            rpc.request(proto::ShareProject { project_id }).await?;
 596
 597            let mut tasks = Vec::new();
 598            this.update(&mut cx, |this, cx| {
 599                for worktree in this.worktrees(cx).collect::<Vec<_>>() {
 600                    worktree.update(cx, |worktree, cx| {
 601                        let worktree = worktree.as_local_mut().unwrap();
 602                        tasks.push(worktree.share(project_id, cx));
 603                    });
 604                }
 605            });
 606            for task in tasks {
 607                task.await?;
 608            }
 609            this.update(&mut cx, |_, cx| cx.notify());
 610            Ok(())
 611        })
 612    }
 613
 614    pub fn unshare(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 615        let rpc = self.client.clone();
 616        cx.spawn(|this, mut cx| async move {
 617            let project_id = this.update(&mut cx, |this, cx| {
 618                if let ProjectClientState::Local {
 619                    is_shared,
 620                    remote_id_rx,
 621                    ..
 622                } = &mut this.client_state
 623                {
 624                    *is_shared = false;
 625
 626                    for open_buffer in this.opened_buffers.values_mut() {
 627                        match open_buffer {
 628                            OpenBuffer::Strong(buffer) => {
 629                                *open_buffer = OpenBuffer::Weak(buffer.downgrade());
 630                            }
 631                            _ => {}
 632                        }
 633                    }
 634
 635                    for worktree_handle in this.worktrees.iter_mut() {
 636                        match worktree_handle {
 637                            WorktreeHandle::Strong(worktree) => {
 638                                if !worktree.read(cx).is_visible() {
 639                                    *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
 640                                }
 641                            }
 642                            _ => {}
 643                        }
 644                    }
 645
 646                    remote_id_rx
 647                        .borrow()
 648                        .ok_or_else(|| anyhow!("no project id"))
 649                } else {
 650                    Err(anyhow!("can't share a remote project"))
 651                }
 652            })?;
 653
 654            rpc.send(proto::UnshareProject { project_id })?;
 655            this.update(&mut cx, |this, cx| {
 656                this.collaborators.clear();
 657                this.shared_buffers.clear();
 658                for worktree in this.worktrees(cx).collect::<Vec<_>>() {
 659                    worktree.update(cx, |worktree, _| {
 660                        worktree.as_local_mut().unwrap().unshare();
 661                    });
 662                }
 663                cx.notify()
 664            });
 665            Ok(())
 666        })
 667    }
 668
 669    pub fn is_read_only(&self) -> bool {
 670        match &self.client_state {
 671            ProjectClientState::Local { .. } => false,
 672            ProjectClientState::Remote {
 673                sharing_has_stopped,
 674                ..
 675            } => *sharing_has_stopped,
 676        }
 677    }
 678
 679    pub fn is_local(&self) -> bool {
 680        match &self.client_state {
 681            ProjectClientState::Local { .. } => true,
 682            ProjectClientState::Remote { .. } => false,
 683        }
 684    }
 685
 686    pub fn is_remote(&self) -> bool {
 687        !self.is_local()
 688    }
 689
 690    pub fn open_buffer(
 691        &mut self,
 692        path: impl Into<ProjectPath>,
 693        cx: &mut ModelContext<Self>,
 694    ) -> Task<Result<ModelHandle<Buffer>>> {
 695        let project_path = path.into();
 696        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
 697            worktree
 698        } else {
 699            return Task::ready(Err(anyhow!("no such worktree")));
 700        };
 701
 702        // If there is already a buffer for the given path, then return it.
 703        let existing_buffer = self.get_open_buffer(&project_path, cx);
 704        if let Some(existing_buffer) = existing_buffer {
 705            return Task::ready(Ok(existing_buffer));
 706        }
 707
 708        let mut loading_watch = match self.loading_buffers.entry(project_path.clone()) {
 709            // If the given path is already being loaded, then wait for that existing
 710            // task to complete and return the same buffer.
 711            hash_map::Entry::Occupied(e) => e.get().clone(),
 712
 713            // Otherwise, record the fact that this path is now being loaded.
 714            hash_map::Entry::Vacant(entry) => {
 715                let (mut tx, rx) = postage::watch::channel();
 716                entry.insert(rx.clone());
 717
 718                let load_buffer = if worktree.read(cx).is_local() {
 719                    self.open_local_buffer(&project_path.path, &worktree, cx)
 720                } else {
 721                    self.open_remote_buffer(&project_path.path, &worktree, cx)
 722                };
 723
 724                cx.spawn(move |this, mut cx| async move {
 725                    let load_result = load_buffer.await;
 726                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
 727                        // Record the fact that the buffer is no longer loading.
 728                        this.loading_buffers.remove(&project_path);
 729                        let buffer = load_result.map_err(Arc::new)?;
 730                        Ok(buffer)
 731                    }));
 732                })
 733                .detach();
 734                rx
 735            }
 736        };
 737
 738        cx.foreground().spawn(async move {
 739            loop {
 740                if let Some(result) = loading_watch.borrow().as_ref() {
 741                    match result {
 742                        Ok(buffer) => return Ok(buffer.clone()),
 743                        Err(error) => return Err(anyhow!("{}", error)),
 744                    }
 745                }
 746                loading_watch.next().await;
 747            }
 748        })
 749    }
 750
 751    fn open_local_buffer(
 752        &mut self,
 753        path: &Arc<Path>,
 754        worktree: &ModelHandle<Worktree>,
 755        cx: &mut ModelContext<Self>,
 756    ) -> Task<Result<ModelHandle<Buffer>>> {
 757        let load_buffer = worktree.update(cx, |worktree, cx| {
 758            let worktree = worktree.as_local_mut().unwrap();
 759            worktree.load_buffer(path, cx)
 760        });
 761        let worktree = worktree.downgrade();
 762        cx.spawn(|this, mut cx| async move {
 763            let buffer = load_buffer.await?;
 764            let worktree = worktree
 765                .upgrade(&cx)
 766                .ok_or_else(|| anyhow!("worktree was removed"))?;
 767            this.update(&mut cx, |this, cx| {
 768                this.register_buffer(&buffer, Some(&worktree), cx)
 769            })?;
 770            Ok(buffer)
 771        })
 772    }
 773
 774    fn open_remote_buffer(
 775        &mut self,
 776        path: &Arc<Path>,
 777        worktree: &ModelHandle<Worktree>,
 778        cx: &mut ModelContext<Self>,
 779    ) -> Task<Result<ModelHandle<Buffer>>> {
 780        let rpc = self.client.clone();
 781        let project_id = self.remote_id().unwrap();
 782        let remote_worktree_id = worktree.read(cx).id();
 783        let path = path.clone();
 784        let path_string = path.to_string_lossy().to_string();
 785        cx.spawn(|this, mut cx| async move {
 786            let response = rpc
 787                .request(proto::OpenBuffer {
 788                    project_id,
 789                    worktree_id: remote_worktree_id.to_proto(),
 790                    path: path_string,
 791                })
 792                .await?;
 793            let buffer = response.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
 794            this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
 795                .await
 796        })
 797    }
 798
 799    fn open_local_buffer_via_lsp(
 800        &mut self,
 801        abs_path: lsp::Url,
 802        lang_name: String,
 803        lang_server: Arc<LanguageServer>,
 804        cx: &mut ModelContext<Self>,
 805    ) -> Task<Result<ModelHandle<Buffer>>> {
 806        cx.spawn(|this, mut cx| async move {
 807            let abs_path = abs_path
 808                .to_file_path()
 809                .map_err(|_| anyhow!("can't convert URI to path"))?;
 810            let (worktree, relative_path) = if let Some(result) =
 811                this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
 812            {
 813                result
 814            } else {
 815                let worktree = this
 816                    .update(&mut cx, |this, cx| {
 817                        this.create_local_worktree(&abs_path, false, cx)
 818                    })
 819                    .await?;
 820                this.update(&mut cx, |this, cx| {
 821                    this.language_servers
 822                        .insert((worktree.read(cx).id(), lang_name), lang_server);
 823                });
 824                (worktree, PathBuf::new())
 825            };
 826
 827            let project_path = ProjectPath {
 828                worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
 829                path: relative_path.into(),
 830            };
 831            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
 832                .await
 833        })
 834    }
 835
 836    pub fn save_buffer_as(
 837        &mut self,
 838        buffer: ModelHandle<Buffer>,
 839        abs_path: PathBuf,
 840        cx: &mut ModelContext<Project>,
 841    ) -> Task<Result<()>> {
 842        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
 843        cx.spawn(|this, mut cx| async move {
 844            let (worktree, path) = worktree_task.await?;
 845            worktree
 846                .update(&mut cx, |worktree, cx| {
 847                    worktree
 848                        .as_local_mut()
 849                        .unwrap()
 850                        .save_buffer_as(buffer.clone(), path, cx)
 851                })
 852                .await?;
 853            this.update(&mut cx, |this, cx| {
 854                this.assign_language_to_buffer(&buffer, Some(&worktree), cx);
 855            });
 856            Ok(())
 857        })
 858    }
 859
 860    pub fn get_open_buffer(
 861        &mut self,
 862        path: &ProjectPath,
 863        cx: &mut ModelContext<Self>,
 864    ) -> Option<ModelHandle<Buffer>> {
 865        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
 866        self.opened_buffers.values().find_map(|buffer| {
 867            let buffer = buffer.upgrade(cx)?;
 868            let file = File::from_dyn(buffer.read(cx).file())?;
 869            if file.worktree == worktree && file.path() == &path.path {
 870                Some(buffer)
 871            } else {
 872                None
 873            }
 874        })
 875    }
 876
 877    fn register_buffer(
 878        &mut self,
 879        buffer: &ModelHandle<Buffer>,
 880        worktree: Option<&ModelHandle<Worktree>>,
 881        cx: &mut ModelContext<Self>,
 882    ) -> Result<()> {
 883        let remote_id = buffer.read(cx).remote_id();
 884        let open_buffer = if self.is_remote() || self.is_shared() {
 885            OpenBuffer::Strong(buffer.clone())
 886        } else {
 887            OpenBuffer::Weak(buffer.downgrade())
 888        };
 889
 890        match self.opened_buffers.insert(remote_id, open_buffer) {
 891            None => {}
 892            Some(OpenBuffer::Loading(operations)) => {
 893                buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?
 894            }
 895            Some(OpenBuffer::Weak(existing_handle)) => {
 896                if existing_handle.upgrade(cx).is_some() {
 897                    Err(anyhow!(
 898                        "already registered buffer with remote id {}",
 899                        remote_id
 900                    ))?
 901                }
 902            }
 903            Some(OpenBuffer::Strong(_)) => Err(anyhow!(
 904                "already registered buffer with remote id {}",
 905                remote_id
 906            ))?,
 907        }
 908        self.assign_language_to_buffer(&buffer, worktree, cx);
 909        Ok(())
 910    }
 911
 912    fn assign_language_to_buffer(
 913        &mut self,
 914        buffer: &ModelHandle<Buffer>,
 915        worktree: Option<&ModelHandle<Worktree>>,
 916        cx: &mut ModelContext<Self>,
 917    ) -> Option<()> {
 918        let (path, full_path) = {
 919            let file = buffer.read(cx).file()?;
 920            (file.path().clone(), file.full_path(cx))
 921        };
 922
 923        // If the buffer has a language, set it and start/assign the language server
 924        if let Some(language) = self.languages.select_language(&full_path) {
 925            buffer.update(cx, |buffer, cx| {
 926                buffer.set_language(Some(language.clone()), cx);
 927            });
 928
 929            // For local worktrees, start a language server if needed.
 930            // Also assign the language server and any previously stored diagnostics to the buffer.
 931            if let Some(local_worktree) = worktree.and_then(|w| w.read(cx).as_local()) {
 932                let worktree_id = local_worktree.id();
 933                let worktree_abs_path = local_worktree.abs_path().clone();
 934                let buffer = buffer.downgrade();
 935                let language_server =
 936                    self.start_language_server(worktree_id, worktree_abs_path, language, cx);
 937
 938                cx.spawn_weak(|_, mut cx| async move {
 939                    if let Some(language_server) = language_server.await {
 940                        if let Some(buffer) = buffer.upgrade(&cx) {
 941                            buffer.update(&mut cx, |buffer, cx| {
 942                                buffer.set_language_server(Some(language_server), cx);
 943                            });
 944                        }
 945                    }
 946                })
 947                .detach();
 948            }
 949        }
 950
 951        if let Some(local_worktree) = worktree.and_then(|w| w.read(cx).as_local()) {
 952            if let Some(diagnostics) = local_worktree.diagnostics_for_path(&path) {
 953                buffer.update(cx, |buffer, cx| {
 954                    buffer.update_diagnostics(diagnostics, None, cx).log_err();
 955                });
 956            }
 957        }
 958
 959        None
 960    }
 961
 962    fn start_language_server(
 963        &mut self,
 964        worktree_id: WorktreeId,
 965        worktree_path: Arc<Path>,
 966        language: Arc<Language>,
 967        cx: &mut ModelContext<Self>,
 968    ) -> Shared<Task<Option<Arc<LanguageServer>>>> {
 969        enum LspEvent {
 970            DiagnosticsStart,
 971            DiagnosticsUpdate(lsp::PublishDiagnosticsParams),
 972            DiagnosticsFinish,
 973        }
 974
 975        let key = (worktree_id, language.name().to_string());
 976        self.started_language_servers
 977            .entry(key.clone())
 978            .or_insert_with(|| {
 979                let language_server = self.languages.start_language_server(
 980                    &language,
 981                    worktree_path,
 982                    self.client.http_client(),
 983                    cx,
 984                );
 985                let rpc = self.client.clone();
 986                cx.spawn_weak(|this, mut cx| async move {
 987                    let language_server = language_server?.await.log_err()?;
 988                    if let Some(this) = this.upgrade(&cx) {
 989                        this.update(&mut cx, |this, _| {
 990                            this.language_servers.insert(key, language_server.clone());
 991                        });
 992                    }
 993
 994                    let disk_based_sources = language
 995                        .disk_based_diagnostic_sources()
 996                        .cloned()
 997                        .unwrap_or_default();
 998                    let disk_based_diagnostics_progress_token =
 999                        language.disk_based_diagnostics_progress_token().cloned();
1000                    let has_disk_based_diagnostic_progress_token =
1001                        disk_based_diagnostics_progress_token.is_some();
1002                    let (diagnostics_tx, diagnostics_rx) = smol::channel::unbounded();
1003
1004                    // Listen for `PublishDiagnostics` notifications.
1005                    language_server
1006                        .on_notification::<lsp::notification::PublishDiagnostics, _>({
1007                            let diagnostics_tx = diagnostics_tx.clone();
1008                            move |params| {
1009                                if !has_disk_based_diagnostic_progress_token {
1010                                    block_on(diagnostics_tx.send(LspEvent::DiagnosticsStart)).ok();
1011                                }
1012                                block_on(diagnostics_tx.send(LspEvent::DiagnosticsUpdate(params)))
1013                                    .ok();
1014                                if !has_disk_based_diagnostic_progress_token {
1015                                    block_on(diagnostics_tx.send(LspEvent::DiagnosticsFinish)).ok();
1016                                }
1017                            }
1018                        })
1019                        .detach();
1020
1021                    // Listen for `Progress` notifications. Send an event when the language server
1022                    // transitions between running jobs and not running any jobs.
1023                    let mut running_jobs_for_this_server: i32 = 0;
1024                    language_server
1025                        .on_notification::<lsp::notification::Progress, _>(move |params| {
1026                            let token = match params.token {
1027                                lsp::NumberOrString::Number(_) => None,
1028                                lsp::NumberOrString::String(token) => Some(token),
1029                            };
1030
1031                            if token == disk_based_diagnostics_progress_token {
1032                                match params.value {
1033                                    lsp::ProgressParamsValue::WorkDone(progress) => {
1034                                        match progress {
1035                                            lsp::WorkDoneProgress::Begin(_) => {
1036                                                running_jobs_for_this_server += 1;
1037                                                if running_jobs_for_this_server == 1 {
1038                                                    block_on(
1039                                                        diagnostics_tx
1040                                                            .send(LspEvent::DiagnosticsStart),
1041                                                    )
1042                                                    .ok();
1043                                                }
1044                                            }
1045                                            lsp::WorkDoneProgress::End(_) => {
1046                                                running_jobs_for_this_server -= 1;
1047                                                if running_jobs_for_this_server == 0 {
1048                                                    block_on(
1049                                                        diagnostics_tx
1050                                                            .send(LspEvent::DiagnosticsFinish),
1051                                                    )
1052                                                    .ok();
1053                                                }
1054                                            }
1055                                            _ => {}
1056                                        }
1057                                    }
1058                                }
1059                            }
1060                        })
1061                        .detach();
1062
1063                    // Process all the LSP events.
1064                    cx.spawn(|mut cx| async move {
1065                        while let Ok(message) = diagnostics_rx.recv().await {
1066                            let this = this.upgrade(&cx)?;
1067                            match message {
1068                                LspEvent::DiagnosticsStart => {
1069                                    this.update(&mut cx, |this, cx| {
1070                                        this.disk_based_diagnostics_started(cx);
1071                                        if let Some(project_id) = this.remote_id() {
1072                                            rpc.send(proto::DiskBasedDiagnosticsUpdating {
1073                                                project_id,
1074                                            })
1075                                            .log_err();
1076                                        }
1077                                    });
1078                                }
1079                                LspEvent::DiagnosticsUpdate(mut params) => {
1080                                    language.process_diagnostics(&mut params);
1081                                    this.update(&mut cx, |this, cx| {
1082                                        this.update_diagnostics(params, &disk_based_sources, cx)
1083                                            .log_err();
1084                                    });
1085                                }
1086                                LspEvent::DiagnosticsFinish => {
1087                                    this.update(&mut cx, |this, cx| {
1088                                        this.disk_based_diagnostics_finished(cx);
1089                                        if let Some(project_id) = this.remote_id() {
1090                                            rpc.send(proto::DiskBasedDiagnosticsUpdated {
1091                                                project_id,
1092                                            })
1093                                            .log_err();
1094                                        }
1095                                    });
1096                                }
1097                            }
1098                        }
1099                        Some(())
1100                    })
1101                    .detach();
1102
1103                    Some(language_server)
1104                })
1105                .shared()
1106            })
1107            .clone()
1108    }
1109
1110    pub fn update_diagnostics(
1111        &mut self,
1112        params: lsp::PublishDiagnosticsParams,
1113        disk_based_sources: &HashSet<String>,
1114        cx: &mut ModelContext<Self>,
1115    ) -> Result<()> {
1116        let abs_path = params
1117            .uri
1118            .to_file_path()
1119            .map_err(|_| anyhow!("URI is not a file"))?;
1120        let mut next_group_id = 0;
1121        let mut diagnostics = Vec::default();
1122        let mut primary_diagnostic_group_ids = HashMap::default();
1123        let mut sources_by_group_id = HashMap::default();
1124        let mut supporting_diagnostic_severities = HashMap::default();
1125        for diagnostic in &params.diagnostics {
1126            let source = diagnostic.source.as_ref();
1127            let code = diagnostic.code.as_ref().map(|code| match code {
1128                lsp::NumberOrString::Number(code) => code.to_string(),
1129                lsp::NumberOrString::String(code) => code.clone(),
1130            });
1131            let range = range_from_lsp(diagnostic.range);
1132            let is_supporting = diagnostic
1133                .related_information
1134                .as_ref()
1135                .map_or(false, |infos| {
1136                    infos.iter().any(|info| {
1137                        primary_diagnostic_group_ids.contains_key(&(
1138                            source,
1139                            code.clone(),
1140                            range_from_lsp(info.location.range),
1141                        ))
1142                    })
1143                });
1144
1145            if is_supporting {
1146                if let Some(severity) = diagnostic.severity {
1147                    supporting_diagnostic_severities
1148                        .insert((source, code.clone(), range), severity);
1149                }
1150            } else {
1151                let group_id = post_inc(&mut next_group_id);
1152                let is_disk_based =
1153                    source.map_or(false, |source| disk_based_sources.contains(source));
1154
1155                sources_by_group_id.insert(group_id, source);
1156                primary_diagnostic_group_ids
1157                    .insert((source, code.clone(), range.clone()), group_id);
1158
1159                diagnostics.push(DiagnosticEntry {
1160                    range,
1161                    diagnostic: Diagnostic {
1162                        code: code.clone(),
1163                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
1164                        message: diagnostic.message.clone(),
1165                        group_id,
1166                        is_primary: true,
1167                        is_valid: true,
1168                        is_disk_based,
1169                    },
1170                });
1171                if let Some(infos) = &diagnostic.related_information {
1172                    for info in infos {
1173                        if info.location.uri == params.uri && !info.message.is_empty() {
1174                            let range = range_from_lsp(info.location.range);
1175                            diagnostics.push(DiagnosticEntry {
1176                                range,
1177                                diagnostic: Diagnostic {
1178                                    code: code.clone(),
1179                                    severity: DiagnosticSeverity::INFORMATION,
1180                                    message: info.message.clone(),
1181                                    group_id,
1182                                    is_primary: false,
1183                                    is_valid: true,
1184                                    is_disk_based,
1185                                },
1186                            });
1187                        }
1188                    }
1189                }
1190            }
1191        }
1192
1193        for entry in &mut diagnostics {
1194            let diagnostic = &mut entry.diagnostic;
1195            if !diagnostic.is_primary {
1196                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
1197                if let Some(&severity) = supporting_diagnostic_severities.get(&(
1198                    source,
1199                    diagnostic.code.clone(),
1200                    entry.range.clone(),
1201                )) {
1202                    diagnostic.severity = severity;
1203                }
1204            }
1205        }
1206
1207        self.update_diagnostic_entries(abs_path, params.version, diagnostics, cx)?;
1208        Ok(())
1209    }
1210
1211    pub fn update_diagnostic_entries(
1212        &mut self,
1213        abs_path: PathBuf,
1214        version: Option<i32>,
1215        diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
1216        cx: &mut ModelContext<Project>,
1217    ) -> Result<(), anyhow::Error> {
1218        let (worktree, relative_path) = self
1219            .find_local_worktree(&abs_path, cx)
1220            .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
1221        if !worktree.read(cx).is_visible() {
1222            return Ok(());
1223        }
1224
1225        let project_path = ProjectPath {
1226            worktree_id: worktree.read(cx).id(),
1227            path: relative_path.into(),
1228        };
1229
1230        for buffer in self.opened_buffers.values() {
1231            if let Some(buffer) = buffer.upgrade(cx) {
1232                if buffer
1233                    .read(cx)
1234                    .file()
1235                    .map_or(false, |file| *file.path() == project_path.path)
1236                {
1237                    buffer.update(cx, |buffer, cx| {
1238                        buffer.update_diagnostics(diagnostics.clone(), version, cx)
1239                    })?;
1240                    break;
1241                }
1242            }
1243        }
1244        worktree.update(cx, |worktree, cx| {
1245            worktree
1246                .as_local_mut()
1247                .ok_or_else(|| anyhow!("not a local worktree"))?
1248                .update_diagnostics(project_path.path.clone(), diagnostics, cx)
1249        })?;
1250        cx.emit(Event::DiagnosticsUpdated(project_path));
1251        Ok(())
1252    }
1253
1254    pub fn format(
1255        &self,
1256        buffers: HashSet<ModelHandle<Buffer>>,
1257        push_to_history: bool,
1258        cx: &mut ModelContext<Project>,
1259    ) -> Task<Result<ProjectTransaction>> {
1260        let mut local_buffers = Vec::new();
1261        let mut remote_buffers = None;
1262        for buffer_handle in buffers {
1263            let buffer = buffer_handle.read(cx);
1264            let worktree;
1265            if let Some(file) = File::from_dyn(buffer.file()) {
1266                worktree = file.worktree.clone();
1267                if let Some(buffer_abs_path) = file.as_local().map(|f| f.abs_path(cx)) {
1268                    let lang_server;
1269                    if let Some(lang) = buffer.language() {
1270                        if let Some(server) = self
1271                            .language_servers
1272                            .get(&(worktree.read(cx).id(), lang.name().to_string()))
1273                        {
1274                            lang_server = server.clone();
1275                        } else {
1276                            return Task::ready(Ok(Default::default()));
1277                        };
1278                    } else {
1279                        return Task::ready(Ok(Default::default()));
1280                    }
1281
1282                    local_buffers.push((buffer_handle, buffer_abs_path, lang_server));
1283                } else {
1284                    remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
1285                }
1286            } else {
1287                return Task::ready(Ok(Default::default()));
1288            }
1289        }
1290
1291        let remote_buffers = self.remote_id().zip(remote_buffers);
1292        let client = self.client.clone();
1293
1294        cx.spawn(|this, mut cx| async move {
1295            let mut project_transaction = ProjectTransaction::default();
1296
1297            if let Some((project_id, remote_buffers)) = remote_buffers {
1298                let response = client
1299                    .request(proto::FormatBuffers {
1300                        project_id,
1301                        buffer_ids: remote_buffers
1302                            .iter()
1303                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
1304                            .collect(),
1305                    })
1306                    .await?
1307                    .transaction
1308                    .ok_or_else(|| anyhow!("missing transaction"))?;
1309                project_transaction = this
1310                    .update(&mut cx, |this, cx| {
1311                        this.deserialize_project_transaction(response, push_to_history, cx)
1312                    })
1313                    .await?;
1314            }
1315
1316            for (buffer, buffer_abs_path, lang_server) in local_buffers {
1317                let capabilities = if let Some(capabilities) = lang_server.capabilities().await {
1318                    capabilities
1319                } else {
1320                    continue;
1321                };
1322
1323                let text_document = lsp::TextDocumentIdentifier::new(
1324                    lsp::Url::from_file_path(&buffer_abs_path).unwrap(),
1325                );
1326                let lsp_edits = if capabilities.document_formatting_provider.is_some() {
1327                    lang_server
1328                        .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
1329                            text_document,
1330                            options: Default::default(),
1331                            work_done_progress_params: Default::default(),
1332                        })
1333                        .await?
1334                } else if capabilities.document_range_formatting_provider.is_some() {
1335                    let buffer_start = lsp::Position::new(0, 0);
1336                    let buffer_end = buffer
1337                        .read_with(&cx, |buffer, _| buffer.max_point_utf16())
1338                        .to_lsp_position();
1339                    lang_server
1340                        .request::<lsp::request::RangeFormatting>(
1341                            lsp::DocumentRangeFormattingParams {
1342                                text_document,
1343                                range: lsp::Range::new(buffer_start, buffer_end),
1344                                options: Default::default(),
1345                                work_done_progress_params: Default::default(),
1346                            },
1347                        )
1348                        .await?
1349                } else {
1350                    continue;
1351                };
1352
1353                if let Some(lsp_edits) = lsp_edits {
1354                    let edits = buffer
1355                        .update(&mut cx, |buffer, cx| {
1356                            buffer.edits_from_lsp(lsp_edits, None, cx)
1357                        })
1358                        .await?;
1359                    buffer.update(&mut cx, |buffer, cx| {
1360                        buffer.finalize_last_transaction();
1361                        buffer.start_transaction();
1362                        for (range, text) in edits {
1363                            buffer.edit([range], text, cx);
1364                        }
1365                        if buffer.end_transaction(cx).is_some() {
1366                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
1367                            if !push_to_history {
1368                                buffer.forget_transaction(transaction.id);
1369                            }
1370                            project_transaction.0.insert(cx.handle(), transaction);
1371                        }
1372                    });
1373                }
1374            }
1375
1376            Ok(project_transaction)
1377        })
1378    }
1379
1380    pub fn definition<T: ToPointUtf16>(
1381        &self,
1382        buffer: &ModelHandle<Buffer>,
1383        position: T,
1384        cx: &mut ModelContext<Self>,
1385    ) -> Task<Result<Vec<Location>>> {
1386        let position = position.to_point_utf16(buffer.read(cx));
1387        self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
1388    }
1389
1390    pub fn references<T: ToPointUtf16>(
1391        &self,
1392        buffer: &ModelHandle<Buffer>,
1393        position: T,
1394        cx: &mut ModelContext<Self>,
1395    ) -> Task<Result<Vec<Location>>> {
1396        let position = position.to_point_utf16(buffer.read(cx));
1397        self.request_lsp(buffer.clone(), GetReferences { position }, cx)
1398    }
1399
1400    pub fn document_highlights<T: ToPointUtf16>(
1401        &self,
1402        buffer: &ModelHandle<Buffer>,
1403        position: T,
1404        cx: &mut ModelContext<Self>,
1405    ) -> Task<Result<Vec<DocumentHighlight>>> {
1406        let position = position.to_point_utf16(buffer.read(cx));
1407
1408        self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
1409    }
1410
1411    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
1412        if self.is_local() {
1413            let mut language_servers = HashMap::default();
1414            for ((worktree_id, language_name), language_server) in self.language_servers.iter() {
1415                if let Some((worktree, language)) = self
1416                    .worktree_for_id(*worktree_id, cx)
1417                    .and_then(|worktree| worktree.read(cx).as_local())
1418                    .zip(self.languages.get_language(language_name))
1419                {
1420                    language_servers
1421                        .entry(Arc::as_ptr(language_server))
1422                        .or_insert((
1423                            language_server.clone(),
1424                            *worktree_id,
1425                            worktree.abs_path().clone(),
1426                            language.clone(),
1427                        ));
1428                }
1429            }
1430
1431            let mut requests = Vec::new();
1432            for (language_server, _, _, _) in language_servers.values() {
1433                requests.push(language_server.request::<lsp::request::WorkspaceSymbol>(
1434                    lsp::WorkspaceSymbolParams {
1435                        query: query.to_string(),
1436                        ..Default::default()
1437                    },
1438                ));
1439            }
1440
1441            cx.spawn_weak(|this, cx| async move {
1442                let responses = futures::future::try_join_all(requests).await?;
1443
1444                let mut symbols = Vec::new();
1445                if let Some(this) = this.upgrade(&cx) {
1446                    this.read_with(&cx, |this, cx| {
1447                        for ((_, source_worktree_id, worktree_abs_path, language), lsp_symbols) in
1448                            language_servers.into_values().zip(responses)
1449                        {
1450                            symbols.extend(lsp_symbols.into_iter().flatten().filter_map(
1451                                |lsp_symbol| {
1452                                    let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
1453                                    let mut worktree_id = source_worktree_id;
1454                                    let path;
1455                                    if let Some((worktree, rel_path)) =
1456                                        this.find_local_worktree(&abs_path, cx)
1457                                    {
1458                                        worktree_id = worktree.read(cx).id();
1459                                        path = rel_path;
1460                                    } else {
1461                                        path = relativize_path(&worktree_abs_path, &abs_path);
1462                                    }
1463
1464                                    let label = language
1465                                        .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
1466                                        .unwrap_or_else(|| {
1467                                            CodeLabel::plain(lsp_symbol.name.clone(), None)
1468                                        });
1469                                    let signature = this.symbol_signature(worktree_id, &path);
1470
1471                                    Some(Symbol {
1472                                        source_worktree_id,
1473                                        worktree_id,
1474                                        language_name: language.name().to_string(),
1475                                        name: lsp_symbol.name,
1476                                        kind: lsp_symbol.kind,
1477                                        label,
1478                                        path,
1479                                        range: range_from_lsp(lsp_symbol.location.range),
1480                                        signature,
1481                                    })
1482                                },
1483                            ));
1484                        }
1485                    })
1486                }
1487
1488                Ok(symbols)
1489            })
1490        } else if let Some(project_id) = self.remote_id() {
1491            let request = self.client.request(proto::GetProjectSymbols {
1492                project_id,
1493                query: query.to_string(),
1494            });
1495            cx.spawn_weak(|this, cx| async move {
1496                let response = request.await?;
1497                let mut symbols = Vec::new();
1498                if let Some(this) = this.upgrade(&cx) {
1499                    this.read_with(&cx, |this, _| {
1500                        symbols.extend(
1501                            response
1502                                .symbols
1503                                .into_iter()
1504                                .filter_map(|symbol| this.deserialize_symbol(symbol).log_err()),
1505                        );
1506                    })
1507                }
1508                Ok(symbols)
1509            })
1510        } else {
1511            Task::ready(Ok(Default::default()))
1512        }
1513    }
1514
1515    pub fn open_buffer_for_symbol(
1516        &mut self,
1517        symbol: &Symbol,
1518        cx: &mut ModelContext<Self>,
1519    ) -> Task<Result<ModelHandle<Buffer>>> {
1520        if self.is_local() {
1521            let language_server = if let Some(server) = self
1522                .language_servers
1523                .get(&(symbol.source_worktree_id, symbol.language_name.clone()))
1524            {
1525                server.clone()
1526            } else {
1527                return Task::ready(Err(anyhow!(
1528                    "language server for worktree and language not found"
1529                )));
1530            };
1531
1532            let worktree_abs_path = if let Some(worktree_abs_path) = self
1533                .worktree_for_id(symbol.worktree_id, cx)
1534                .and_then(|worktree| worktree.read(cx).as_local())
1535                .map(|local_worktree| local_worktree.abs_path())
1536            {
1537                worktree_abs_path
1538            } else {
1539                return Task::ready(Err(anyhow!("worktree not found for symbol")));
1540            };
1541            let symbol_abs_path = worktree_abs_path.join(&symbol.path);
1542            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
1543                uri
1544            } else {
1545                return Task::ready(Err(anyhow!("invalid symbol path")));
1546            };
1547
1548            self.open_local_buffer_via_lsp(
1549                symbol_uri,
1550                symbol.language_name.clone(),
1551                language_server,
1552                cx,
1553            )
1554        } else if let Some(project_id) = self.remote_id() {
1555            let request = self.client.request(proto::OpenBufferForSymbol {
1556                project_id,
1557                symbol: Some(serialize_symbol(symbol)),
1558            });
1559            cx.spawn(|this, mut cx| async move {
1560                let response = request.await?;
1561                let buffer = response.buffer.ok_or_else(|| anyhow!("invalid buffer"))?;
1562                this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
1563                    .await
1564            })
1565        } else {
1566            Task::ready(Err(anyhow!("project does not have a remote id")))
1567        }
1568    }
1569
1570    pub fn completions<T: ToPointUtf16>(
1571        &self,
1572        source_buffer_handle: &ModelHandle<Buffer>,
1573        position: T,
1574        cx: &mut ModelContext<Self>,
1575    ) -> Task<Result<Vec<Completion>>> {
1576        let source_buffer_handle = source_buffer_handle.clone();
1577        let source_buffer = source_buffer_handle.read(cx);
1578        let buffer_id = source_buffer.remote_id();
1579        let language = source_buffer.language().cloned();
1580        let worktree;
1581        let buffer_abs_path;
1582        if let Some(file) = File::from_dyn(source_buffer.file()) {
1583            worktree = file.worktree.clone();
1584            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
1585        } else {
1586            return Task::ready(Ok(Default::default()));
1587        };
1588
1589        let position = position.to_point_utf16(source_buffer);
1590        let anchor = source_buffer.anchor_after(position);
1591
1592        if worktree.read(cx).as_local().is_some() {
1593            let buffer_abs_path = buffer_abs_path.unwrap();
1594            let lang_server = if let Some(server) = source_buffer.language_server().cloned() {
1595                server
1596            } else {
1597                return Task::ready(Ok(Default::default()));
1598            };
1599
1600            cx.spawn(|_, cx| async move {
1601                let completions = lang_server
1602                    .request::<lsp::request::Completion>(lsp::CompletionParams {
1603                        text_document_position: lsp::TextDocumentPositionParams::new(
1604                            lsp::TextDocumentIdentifier::new(
1605                                lsp::Url::from_file_path(buffer_abs_path).unwrap(),
1606                            ),
1607                            position.to_lsp_position(),
1608                        ),
1609                        context: Default::default(),
1610                        work_done_progress_params: Default::default(),
1611                        partial_result_params: Default::default(),
1612                    })
1613                    .await
1614                    .context("lsp completion request failed")?;
1615
1616                let completions = if let Some(completions) = completions {
1617                    match completions {
1618                        lsp::CompletionResponse::Array(completions) => completions,
1619                        lsp::CompletionResponse::List(list) => list.items,
1620                    }
1621                } else {
1622                    Default::default()
1623                };
1624
1625                source_buffer_handle.read_with(&cx, |this, _| {
1626                    Ok(completions
1627                        .into_iter()
1628                        .filter_map(|lsp_completion| {
1629                            let (old_range, new_text) = match lsp_completion.text_edit.as_ref()? {
1630                                lsp::CompletionTextEdit::Edit(edit) => {
1631                                    (range_from_lsp(edit.range), edit.new_text.clone())
1632                                }
1633                                lsp::CompletionTextEdit::InsertAndReplace(_) => {
1634                                    log::info!("unsupported insert/replace completion");
1635                                    return None;
1636                                }
1637                            };
1638
1639                            let clipped_start = this.clip_point_utf16(old_range.start, Bias::Left);
1640                            let clipped_end = this.clip_point_utf16(old_range.end, Bias::Left);
1641                            if clipped_start == old_range.start && clipped_end == old_range.end {
1642                                Some(Completion {
1643                                    old_range: this.anchor_before(old_range.start)
1644                                        ..this.anchor_after(old_range.end),
1645                                    new_text,
1646                                    label: language
1647                                        .as_ref()
1648                                        .and_then(|l| l.label_for_completion(&lsp_completion))
1649                                        .unwrap_or_else(|| {
1650                                            CodeLabel::plain(
1651                                                lsp_completion.label.clone(),
1652                                                lsp_completion.filter_text.as_deref(),
1653                                            )
1654                                        }),
1655                                    lsp_completion,
1656                                })
1657                            } else {
1658                                None
1659                            }
1660                        })
1661                        .collect())
1662                })
1663            })
1664        } else if let Some(project_id) = self.remote_id() {
1665            let rpc = self.client.clone();
1666            let message = proto::GetCompletions {
1667                project_id,
1668                buffer_id,
1669                position: Some(language::proto::serialize_anchor(&anchor)),
1670                version: (&source_buffer.version()).into(),
1671            };
1672            cx.spawn_weak(|_, mut cx| async move {
1673                let response = rpc.request(message).await?;
1674
1675                source_buffer_handle
1676                    .update(&mut cx, |buffer, _| {
1677                        buffer.wait_for_version(response.version.into())
1678                    })
1679                    .await;
1680
1681                response
1682                    .completions
1683                    .into_iter()
1684                    .map(|completion| {
1685                        language::proto::deserialize_completion(completion, language.as_ref())
1686                    })
1687                    .collect()
1688            })
1689        } else {
1690            Task::ready(Ok(Default::default()))
1691        }
1692    }
1693
1694    pub fn apply_additional_edits_for_completion(
1695        &self,
1696        buffer_handle: ModelHandle<Buffer>,
1697        completion: Completion,
1698        push_to_history: bool,
1699        cx: &mut ModelContext<Self>,
1700    ) -> Task<Result<Option<Transaction>>> {
1701        let buffer = buffer_handle.read(cx);
1702        let buffer_id = buffer.remote_id();
1703
1704        if self.is_local() {
1705            let lang_server = if let Some(language_server) = buffer.language_server() {
1706                language_server.clone()
1707            } else {
1708                return Task::ready(Err(anyhow!("buffer does not have a language server")));
1709            };
1710
1711            cx.spawn(|_, mut cx| async move {
1712                let resolved_completion = lang_server
1713                    .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
1714                    .await?;
1715                if let Some(edits) = resolved_completion.additional_text_edits {
1716                    let edits = buffer_handle
1717                        .update(&mut cx, |buffer, cx| buffer.edits_from_lsp(edits, None, cx))
1718                        .await?;
1719                    buffer_handle.update(&mut cx, |buffer, cx| {
1720                        buffer.finalize_last_transaction();
1721                        buffer.start_transaction();
1722                        for (range, text) in edits {
1723                            buffer.edit([range], text, cx);
1724                        }
1725                        let transaction = if buffer.end_transaction(cx).is_some() {
1726                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
1727                            if !push_to_history {
1728                                buffer.forget_transaction(transaction.id);
1729                            }
1730                            Some(transaction)
1731                        } else {
1732                            None
1733                        };
1734                        Ok(transaction)
1735                    })
1736                } else {
1737                    Ok(None)
1738                }
1739            })
1740        } else if let Some(project_id) = self.remote_id() {
1741            let client = self.client.clone();
1742            cx.spawn(|_, mut cx| async move {
1743                let response = client
1744                    .request(proto::ApplyCompletionAdditionalEdits {
1745                        project_id,
1746                        buffer_id,
1747                        completion: Some(language::proto::serialize_completion(&completion)),
1748                    })
1749                    .await?;
1750
1751                if let Some(transaction) = response.transaction {
1752                    let transaction = language::proto::deserialize_transaction(transaction)?;
1753                    buffer_handle
1754                        .update(&mut cx, |buffer, _| {
1755                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
1756                        })
1757                        .await;
1758                    if push_to_history {
1759                        buffer_handle.update(&mut cx, |buffer, _| {
1760                            buffer.push_transaction(transaction.clone(), Instant::now());
1761                        });
1762                    }
1763                    Ok(Some(transaction))
1764                } else {
1765                    Ok(None)
1766                }
1767            })
1768        } else {
1769            Task::ready(Err(anyhow!("project does not have a remote id")))
1770        }
1771    }
1772
1773    pub fn code_actions<T: ToOffset>(
1774        &self,
1775        buffer_handle: &ModelHandle<Buffer>,
1776        range: Range<T>,
1777        cx: &mut ModelContext<Self>,
1778    ) -> Task<Result<Vec<CodeAction>>> {
1779        let buffer_handle = buffer_handle.clone();
1780        let buffer = buffer_handle.read(cx);
1781        let buffer_id = buffer.remote_id();
1782        let worktree;
1783        let buffer_abs_path;
1784        if let Some(file) = File::from_dyn(buffer.file()) {
1785            worktree = file.worktree.clone();
1786            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
1787        } else {
1788            return Task::ready(Ok(Default::default()));
1789        };
1790        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
1791
1792        if worktree.read(cx).as_local().is_some() {
1793            let buffer_abs_path = buffer_abs_path.unwrap();
1794            let lang_name;
1795            let lang_server;
1796            if let Some(lang) = buffer.language() {
1797                lang_name = lang.name().to_string();
1798                if let Some(server) = self
1799                    .language_servers
1800                    .get(&(worktree.read(cx).id(), lang_name.clone()))
1801                {
1802                    lang_server = server.clone();
1803                } else {
1804                    return Task::ready(Ok(Default::default()));
1805                };
1806            } else {
1807                return Task::ready(Ok(Default::default()));
1808            }
1809
1810            let lsp_range = lsp::Range::new(
1811                range.start.to_point_utf16(buffer).to_lsp_position(),
1812                range.end.to_point_utf16(buffer).to_lsp_position(),
1813            );
1814            cx.foreground().spawn(async move {
1815                if !lang_server
1816                    .capabilities()
1817                    .await
1818                    .map_or(false, |capabilities| {
1819                        capabilities.code_action_provider.is_some()
1820                    })
1821                {
1822                    return Ok(Default::default());
1823                }
1824
1825                Ok(lang_server
1826                    .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
1827                        text_document: lsp::TextDocumentIdentifier::new(
1828                            lsp::Url::from_file_path(buffer_abs_path).unwrap(),
1829                        ),
1830                        range: lsp_range,
1831                        work_done_progress_params: Default::default(),
1832                        partial_result_params: Default::default(),
1833                        context: lsp::CodeActionContext {
1834                            diagnostics: Default::default(),
1835                            only: Some(vec![
1836                                lsp::CodeActionKind::QUICKFIX,
1837                                lsp::CodeActionKind::REFACTOR,
1838                                lsp::CodeActionKind::REFACTOR_EXTRACT,
1839                            ]),
1840                        },
1841                    })
1842                    .await?
1843                    .unwrap_or_default()
1844                    .into_iter()
1845                    .filter_map(|entry| {
1846                        if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
1847                            Some(CodeAction {
1848                                range: range.clone(),
1849                                lsp_action,
1850                            })
1851                        } else {
1852                            None
1853                        }
1854                    })
1855                    .collect())
1856            })
1857        } else if let Some(project_id) = self.remote_id() {
1858            let rpc = self.client.clone();
1859            let version = buffer.version();
1860            cx.spawn_weak(|_, mut cx| async move {
1861                let response = rpc
1862                    .request(proto::GetCodeActions {
1863                        project_id,
1864                        buffer_id,
1865                        start: Some(language::proto::serialize_anchor(&range.start)),
1866                        end: Some(language::proto::serialize_anchor(&range.end)),
1867                        version: (&version).into(),
1868                    })
1869                    .await?;
1870
1871                buffer_handle
1872                    .update(&mut cx, |buffer, _| {
1873                        buffer.wait_for_version(response.version.into())
1874                    })
1875                    .await;
1876
1877                response
1878                    .actions
1879                    .into_iter()
1880                    .map(language::proto::deserialize_code_action)
1881                    .collect()
1882            })
1883        } else {
1884            Task::ready(Ok(Default::default()))
1885        }
1886    }
1887
1888    pub fn apply_code_action(
1889        &self,
1890        buffer_handle: ModelHandle<Buffer>,
1891        mut action: CodeAction,
1892        push_to_history: bool,
1893        cx: &mut ModelContext<Self>,
1894    ) -> Task<Result<ProjectTransaction>> {
1895        if self.is_local() {
1896            let buffer = buffer_handle.read(cx);
1897            let lang_name = if let Some(lang) = buffer.language() {
1898                lang.name().to_string()
1899            } else {
1900                return Task::ready(Ok(Default::default()));
1901            };
1902            let lang_server = if let Some(language_server) = buffer.language_server() {
1903                language_server.clone()
1904            } else {
1905                return Task::ready(Err(anyhow!("buffer does not have a language server")));
1906            };
1907            let range = action.range.to_point_utf16(buffer);
1908
1909            cx.spawn(|this, mut cx| async move {
1910                if let Some(lsp_range) = action
1911                    .lsp_action
1912                    .data
1913                    .as_mut()
1914                    .and_then(|d| d.get_mut("codeActionParams"))
1915                    .and_then(|d| d.get_mut("range"))
1916                {
1917                    *lsp_range = serde_json::to_value(&lsp::Range::new(
1918                        range.start.to_lsp_position(),
1919                        range.end.to_lsp_position(),
1920                    ))
1921                    .unwrap();
1922                    action.lsp_action = lang_server
1923                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
1924                        .await?;
1925                } else {
1926                    let actions = this
1927                        .update(&mut cx, |this, cx| {
1928                            this.code_actions(&buffer_handle, action.range, cx)
1929                        })
1930                        .await?;
1931                    action.lsp_action = actions
1932                        .into_iter()
1933                        .find(|a| a.lsp_action.title == action.lsp_action.title)
1934                        .ok_or_else(|| anyhow!("code action is outdated"))?
1935                        .lsp_action;
1936                }
1937
1938                if let Some(edit) = action.lsp_action.edit {
1939                    Self::deserialize_workspace_edit(
1940                        this,
1941                        edit,
1942                        push_to_history,
1943                        lang_name,
1944                        lang_server,
1945                        &mut cx,
1946                    )
1947                    .await
1948                } else {
1949                    Ok(ProjectTransaction::default())
1950                }
1951            })
1952        } else if let Some(project_id) = self.remote_id() {
1953            let client = self.client.clone();
1954            let request = proto::ApplyCodeAction {
1955                project_id,
1956                buffer_id: buffer_handle.read(cx).remote_id(),
1957                action: Some(language::proto::serialize_code_action(&action)),
1958            };
1959            cx.spawn(|this, mut cx| async move {
1960                let response = client
1961                    .request(request)
1962                    .await?
1963                    .transaction
1964                    .ok_or_else(|| anyhow!("missing transaction"))?;
1965                this.update(&mut cx, |this, cx| {
1966                    this.deserialize_project_transaction(response, push_to_history, cx)
1967                })
1968                .await
1969            })
1970        } else {
1971            Task::ready(Err(anyhow!("project does not have a remote id")))
1972        }
1973    }
1974
1975    async fn deserialize_workspace_edit(
1976        this: ModelHandle<Self>,
1977        edit: lsp::WorkspaceEdit,
1978        push_to_history: bool,
1979        language_name: String,
1980        language_server: Arc<LanguageServer>,
1981        cx: &mut AsyncAppContext,
1982    ) -> Result<ProjectTransaction> {
1983        let fs = this.read_with(cx, |this, _| this.fs.clone());
1984        let mut operations = Vec::new();
1985        if let Some(document_changes) = edit.document_changes {
1986            match document_changes {
1987                lsp::DocumentChanges::Edits(edits) => {
1988                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
1989                }
1990                lsp::DocumentChanges::Operations(ops) => operations = ops,
1991            }
1992        } else if let Some(changes) = edit.changes {
1993            operations.extend(changes.into_iter().map(|(uri, edits)| {
1994                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
1995                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
1996                        uri,
1997                        version: None,
1998                    },
1999                    edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
2000                })
2001            }));
2002        }
2003
2004        let mut project_transaction = ProjectTransaction::default();
2005        for operation in operations {
2006            match operation {
2007                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
2008                    let abs_path = op
2009                        .uri
2010                        .to_file_path()
2011                        .map_err(|_| anyhow!("can't convert URI to path"))?;
2012
2013                    if let Some(parent_path) = abs_path.parent() {
2014                        fs.create_dir(parent_path).await?;
2015                    }
2016                    if abs_path.ends_with("/") {
2017                        fs.create_dir(&abs_path).await?;
2018                    } else {
2019                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
2020                            .await?;
2021                    }
2022                }
2023                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
2024                    let source_abs_path = op
2025                        .old_uri
2026                        .to_file_path()
2027                        .map_err(|_| anyhow!("can't convert URI to path"))?;
2028                    let target_abs_path = op
2029                        .new_uri
2030                        .to_file_path()
2031                        .map_err(|_| anyhow!("can't convert URI to path"))?;
2032                    fs.rename(
2033                        &source_abs_path,
2034                        &target_abs_path,
2035                        op.options.map(Into::into).unwrap_or_default(),
2036                    )
2037                    .await?;
2038                }
2039                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
2040                    let abs_path = op
2041                        .uri
2042                        .to_file_path()
2043                        .map_err(|_| anyhow!("can't convert URI to path"))?;
2044                    let options = op.options.map(Into::into).unwrap_or_default();
2045                    if abs_path.ends_with("/") {
2046                        fs.remove_dir(&abs_path, options).await?;
2047                    } else {
2048                        fs.remove_file(&abs_path, options).await?;
2049                    }
2050                }
2051                lsp::DocumentChangeOperation::Edit(op) => {
2052                    let buffer_to_edit = this
2053                        .update(cx, |this, cx| {
2054                            this.open_local_buffer_via_lsp(
2055                                op.text_document.uri,
2056                                language_name.clone(),
2057                                language_server.clone(),
2058                                cx,
2059                            )
2060                        })
2061                        .await?;
2062
2063                    let edits = buffer_to_edit
2064                        .update(cx, |buffer, cx| {
2065                            let edits = op.edits.into_iter().map(|edit| match edit {
2066                                lsp::OneOf::Left(edit) => edit,
2067                                lsp::OneOf::Right(edit) => edit.text_edit,
2068                            });
2069                            buffer.edits_from_lsp(edits, op.text_document.version, cx)
2070                        })
2071                        .await?;
2072
2073                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
2074                        buffer.finalize_last_transaction();
2075                        buffer.start_transaction();
2076                        for (range, text) in edits {
2077                            buffer.edit([range], text, cx);
2078                        }
2079                        let transaction = if buffer.end_transaction(cx).is_some() {
2080                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
2081                            if !push_to_history {
2082                                buffer.forget_transaction(transaction.id);
2083                            }
2084                            Some(transaction)
2085                        } else {
2086                            None
2087                        };
2088
2089                        transaction
2090                    });
2091                    if let Some(transaction) = transaction {
2092                        project_transaction.0.insert(buffer_to_edit, transaction);
2093                    }
2094                }
2095            }
2096        }
2097
2098        Ok(project_transaction)
2099    }
2100
2101    pub fn prepare_rename<T: ToPointUtf16>(
2102        &self,
2103        buffer: ModelHandle<Buffer>,
2104        position: T,
2105        cx: &mut ModelContext<Self>,
2106    ) -> Task<Result<Option<Range<Anchor>>>> {
2107        let position = position.to_point_utf16(buffer.read(cx));
2108        self.request_lsp(buffer, PrepareRename { position }, cx)
2109    }
2110
2111    pub fn perform_rename<T: ToPointUtf16>(
2112        &self,
2113        buffer: ModelHandle<Buffer>,
2114        position: T,
2115        new_name: String,
2116        push_to_history: bool,
2117        cx: &mut ModelContext<Self>,
2118    ) -> Task<Result<ProjectTransaction>> {
2119        let position = position.to_point_utf16(buffer.read(cx));
2120        self.request_lsp(
2121            buffer,
2122            PerformRename {
2123                position,
2124                new_name,
2125                push_to_history,
2126            },
2127            cx,
2128        )
2129    }
2130
2131    pub fn search(
2132        &self,
2133        query: SearchQuery,
2134        cx: &mut ModelContext<Self>,
2135    ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
2136        if self.is_local() {
2137            let snapshots = self
2138                .visible_worktrees(cx)
2139                .filter_map(|tree| {
2140                    let tree = tree.read(cx).as_local()?;
2141                    Some(tree.snapshot())
2142                })
2143                .collect::<Vec<_>>();
2144
2145            let background = cx.background().clone();
2146            let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
2147            if path_count == 0 {
2148                return Task::ready(Ok(Default::default()));
2149            }
2150            let workers = background.num_cpus().min(path_count);
2151            let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
2152            cx.background()
2153                .spawn({
2154                    let fs = self.fs.clone();
2155                    let background = cx.background().clone();
2156                    let query = query.clone();
2157                    async move {
2158                        let fs = &fs;
2159                        let query = &query;
2160                        let matching_paths_tx = &matching_paths_tx;
2161                        let paths_per_worker = (path_count + workers - 1) / workers;
2162                        let snapshots = &snapshots;
2163                        background
2164                            .scoped(|scope| {
2165                                for worker_ix in 0..workers {
2166                                    let worker_start_ix = worker_ix * paths_per_worker;
2167                                    let worker_end_ix = worker_start_ix + paths_per_worker;
2168                                    scope.spawn(async move {
2169                                        let mut snapshot_start_ix = 0;
2170                                        let mut abs_path = PathBuf::new();
2171                                        for snapshot in snapshots {
2172                                            let snapshot_end_ix =
2173                                                snapshot_start_ix + snapshot.visible_file_count();
2174                                            if worker_end_ix <= snapshot_start_ix {
2175                                                break;
2176                                            } else if worker_start_ix > snapshot_end_ix {
2177                                                snapshot_start_ix = snapshot_end_ix;
2178                                                continue;
2179                                            } else {
2180                                                let start_in_snapshot = worker_start_ix
2181                                                    .saturating_sub(snapshot_start_ix);
2182                                                let end_in_snapshot =
2183                                                    cmp::min(worker_end_ix, snapshot_end_ix)
2184                                                        - snapshot_start_ix;
2185
2186                                                for entry in snapshot
2187                                                    .files(false, start_in_snapshot)
2188                                                    .take(end_in_snapshot - start_in_snapshot)
2189                                                {
2190                                                    if matching_paths_tx.is_closed() {
2191                                                        break;
2192                                                    }
2193
2194                                                    abs_path.clear();
2195                                                    abs_path.push(&snapshot.abs_path());
2196                                                    abs_path.push(&entry.path);
2197                                                    let matches = if let Some(file) =
2198                                                        fs.open_sync(&abs_path).await.log_err()
2199                                                    {
2200                                                        query.detect(file).unwrap_or(false)
2201                                                    } else {
2202                                                        false
2203                                                    };
2204
2205                                                    if matches {
2206                                                        let project_path =
2207                                                            (snapshot.id(), entry.path.clone());
2208                                                        if matching_paths_tx
2209                                                            .send(project_path)
2210                                                            .await
2211                                                            .is_err()
2212                                                        {
2213                                                            break;
2214                                                        }
2215                                                    }
2216                                                }
2217
2218                                                snapshot_start_ix = snapshot_end_ix;
2219                                            }
2220                                        }
2221                                    });
2222                                }
2223                            })
2224                            .await;
2225                    }
2226                })
2227                .detach();
2228
2229            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
2230            let open_buffers = self
2231                .opened_buffers
2232                .values()
2233                .filter_map(|b| b.upgrade(cx))
2234                .collect::<HashSet<_>>();
2235            cx.spawn(|this, cx| async move {
2236                for buffer in &open_buffers {
2237                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
2238                    buffers_tx.send((buffer.clone(), snapshot)).await?;
2239                }
2240
2241                let open_buffers = Rc::new(RefCell::new(open_buffers));
2242                while let Some(project_path) = matching_paths_rx.next().await {
2243                    if buffers_tx.is_closed() {
2244                        break;
2245                    }
2246
2247                    let this = this.clone();
2248                    let open_buffers = open_buffers.clone();
2249                    let buffers_tx = buffers_tx.clone();
2250                    cx.spawn(|mut cx| async move {
2251                        if let Some(buffer) = this
2252                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
2253                            .await
2254                            .log_err()
2255                        {
2256                            if open_buffers.borrow_mut().insert(buffer.clone()) {
2257                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
2258                                buffers_tx.send((buffer, snapshot)).await?;
2259                            }
2260                        }
2261
2262                        Ok::<_, anyhow::Error>(())
2263                    })
2264                    .detach();
2265                }
2266
2267                Ok::<_, anyhow::Error>(())
2268            })
2269            .detach_and_log_err(cx);
2270
2271            let background = cx.background().clone();
2272            cx.background().spawn(async move {
2273                let query = &query;
2274                let mut matched_buffers = Vec::new();
2275                for _ in 0..workers {
2276                    matched_buffers.push(HashMap::default());
2277                }
2278                background
2279                    .scoped(|scope| {
2280                        for worker_matched_buffers in matched_buffers.iter_mut() {
2281                            let mut buffers_rx = buffers_rx.clone();
2282                            scope.spawn(async move {
2283                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
2284                                    let buffer_matches = query
2285                                        .search(snapshot.as_rope())
2286                                        .await
2287                                        .iter()
2288                                        .map(|range| {
2289                                            snapshot.anchor_before(range.start)
2290                                                ..snapshot.anchor_after(range.end)
2291                                        })
2292                                        .collect::<Vec<_>>();
2293                                    if !buffer_matches.is_empty() {
2294                                        worker_matched_buffers
2295                                            .insert(buffer.clone(), buffer_matches);
2296                                    }
2297                                }
2298                            });
2299                        }
2300                    })
2301                    .await;
2302                Ok(matched_buffers.into_iter().flatten().collect())
2303            })
2304        } else if let Some(project_id) = self.remote_id() {
2305            let request = self.client.request(query.to_proto(project_id));
2306            cx.spawn(|this, mut cx| async move {
2307                let response = request.await?;
2308                let mut result = HashMap::default();
2309                for location in response.locations {
2310                    let buffer = location.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
2311                    let target_buffer = this
2312                        .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
2313                        .await?;
2314                    let start = location
2315                        .start
2316                        .and_then(deserialize_anchor)
2317                        .ok_or_else(|| anyhow!("missing target start"))?;
2318                    let end = location
2319                        .end
2320                        .and_then(deserialize_anchor)
2321                        .ok_or_else(|| anyhow!("missing target end"))?;
2322                    result
2323                        .entry(target_buffer)
2324                        .or_insert(Vec::new())
2325                        .push(start..end)
2326                }
2327                Ok(result)
2328            })
2329        } else {
2330            Task::ready(Ok(Default::default()))
2331        }
2332    }
2333
2334    fn request_lsp<R: LspCommand>(
2335        &self,
2336        buffer_handle: ModelHandle<Buffer>,
2337        request: R,
2338        cx: &mut ModelContext<Self>,
2339    ) -> Task<Result<R::Response>>
2340    where
2341        <R::LspRequest as lsp::request::Request>::Result: Send,
2342    {
2343        let buffer = buffer_handle.read(cx);
2344        if self.is_local() {
2345            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
2346            if let Some((file, language_server)) = file.zip(buffer.language_server().cloned()) {
2347                let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
2348                return cx.spawn(|this, cx| async move {
2349                    if !language_server
2350                        .capabilities()
2351                        .await
2352                        .map_or(false, |capabilities| {
2353                            request.check_capabilities(&capabilities)
2354                        })
2355                    {
2356                        return Ok(Default::default());
2357                    }
2358
2359                    let response = language_server
2360                        .request::<R::LspRequest>(lsp_params)
2361                        .await
2362                        .context("lsp request failed")?;
2363                    request
2364                        .response_from_lsp(response, this, buffer_handle, cx)
2365                        .await
2366                });
2367            }
2368        } else if let Some(project_id) = self.remote_id() {
2369            let rpc = self.client.clone();
2370            let message = request.to_proto(project_id, buffer);
2371            return cx.spawn(|this, cx| async move {
2372                let response = rpc.request(message).await?;
2373                request
2374                    .response_from_proto(response, this, buffer_handle, cx)
2375                    .await
2376            });
2377        }
2378        Task::ready(Ok(Default::default()))
2379    }
2380
2381    pub fn find_or_create_local_worktree(
2382        &mut self,
2383        abs_path: impl AsRef<Path>,
2384        visible: bool,
2385        cx: &mut ModelContext<Self>,
2386    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
2387        let abs_path = abs_path.as_ref();
2388        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
2389            Task::ready(Ok((tree.clone(), relative_path.into())))
2390        } else {
2391            let worktree = self.create_local_worktree(abs_path, visible, cx);
2392            cx.foreground()
2393                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
2394        }
2395    }
2396
2397    pub fn find_local_worktree(
2398        &self,
2399        abs_path: &Path,
2400        cx: &AppContext,
2401    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
2402        for tree in self.worktrees(cx) {
2403            if let Some(relative_path) = tree
2404                .read(cx)
2405                .as_local()
2406                .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
2407            {
2408                return Some((tree.clone(), relative_path.into()));
2409            }
2410        }
2411        None
2412    }
2413
2414    pub fn is_shared(&self) -> bool {
2415        match &self.client_state {
2416            ProjectClientState::Local { is_shared, .. } => *is_shared,
2417            ProjectClientState::Remote { .. } => false,
2418        }
2419    }
2420
2421    fn create_local_worktree(
2422        &mut self,
2423        abs_path: impl AsRef<Path>,
2424        visible: bool,
2425        cx: &mut ModelContext<Self>,
2426    ) -> Task<Result<ModelHandle<Worktree>>> {
2427        let fs = self.fs.clone();
2428        let client = self.client.clone();
2429        let path: Arc<Path> = abs_path.as_ref().into();
2430        let task = self
2431            .loading_local_worktrees
2432            .entry(path.clone())
2433            .or_insert_with(|| {
2434                cx.spawn(|project, mut cx| {
2435                    async move {
2436                        let worktree =
2437                            Worktree::local(client.clone(), path.clone(), visible, fs, &mut cx)
2438                                .await;
2439                        project.update(&mut cx, |project, _| {
2440                            project.loading_local_worktrees.remove(&path);
2441                        });
2442                        let worktree = worktree?;
2443
2444                        let (remote_project_id, is_shared) =
2445                            project.update(&mut cx, |project, cx| {
2446                                project.add_worktree(&worktree, cx);
2447                                (project.remote_id(), project.is_shared())
2448                            });
2449
2450                        if let Some(project_id) = remote_project_id {
2451                            if is_shared {
2452                                worktree
2453                                    .update(&mut cx, |worktree, cx| {
2454                                        worktree.as_local_mut().unwrap().share(project_id, cx)
2455                                    })
2456                                    .await?;
2457                            } else {
2458                                worktree
2459                                    .update(&mut cx, |worktree, cx| {
2460                                        worktree.as_local_mut().unwrap().register(project_id, cx)
2461                                    })
2462                                    .await?;
2463                            }
2464                        }
2465
2466                        Ok(worktree)
2467                    }
2468                    .map_err(|err| Arc::new(err))
2469                })
2470                .shared()
2471            })
2472            .clone();
2473        cx.foreground().spawn(async move {
2474            match task.await {
2475                Ok(worktree) => Ok(worktree),
2476                Err(err) => Err(anyhow!("{}", err)),
2477            }
2478        })
2479    }
2480
2481    pub fn remove_worktree(&mut self, id: WorktreeId, cx: &mut ModelContext<Self>) {
2482        self.worktrees.retain(|worktree| {
2483            worktree
2484                .upgrade(cx)
2485                .map_or(false, |w| w.read(cx).id() != id)
2486        });
2487        cx.notify();
2488    }
2489
2490    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
2491        cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
2492        if worktree.read(cx).is_local() {
2493            cx.subscribe(&worktree, |this, worktree, _, cx| {
2494                this.update_local_worktree_buffers(worktree, cx);
2495            })
2496            .detach();
2497        }
2498
2499        let push_strong_handle = {
2500            let worktree = worktree.read(cx);
2501            self.is_shared() || worktree.is_visible() || worktree.is_remote()
2502        };
2503        if push_strong_handle {
2504            self.worktrees
2505                .push(WorktreeHandle::Strong(worktree.clone()));
2506        } else {
2507            cx.observe_release(&worktree, |this, cx| {
2508                this.worktrees
2509                    .retain(|worktree| worktree.upgrade(cx).is_some());
2510                cx.notify();
2511            })
2512            .detach();
2513            self.worktrees
2514                .push(WorktreeHandle::Weak(worktree.downgrade()));
2515        }
2516        cx.notify();
2517    }
2518
2519    fn update_local_worktree_buffers(
2520        &mut self,
2521        worktree_handle: ModelHandle<Worktree>,
2522        cx: &mut ModelContext<Self>,
2523    ) {
2524        let snapshot = worktree_handle.read(cx).snapshot();
2525        let mut buffers_to_delete = Vec::new();
2526        for (buffer_id, buffer) in &self.opened_buffers {
2527            if let Some(buffer) = buffer.upgrade(cx) {
2528                buffer.update(cx, |buffer, cx| {
2529                    if let Some(old_file) = File::from_dyn(buffer.file()) {
2530                        if old_file.worktree != worktree_handle {
2531                            return;
2532                        }
2533
2534                        let new_file = if let Some(entry) = old_file
2535                            .entry_id
2536                            .and_then(|entry_id| snapshot.entry_for_id(entry_id))
2537                        {
2538                            File {
2539                                is_local: true,
2540                                entry_id: Some(entry.id),
2541                                mtime: entry.mtime,
2542                                path: entry.path.clone(),
2543                                worktree: worktree_handle.clone(),
2544                            }
2545                        } else if let Some(entry) =
2546                            snapshot.entry_for_path(old_file.path().as_ref())
2547                        {
2548                            File {
2549                                is_local: true,
2550                                entry_id: Some(entry.id),
2551                                mtime: entry.mtime,
2552                                path: entry.path.clone(),
2553                                worktree: worktree_handle.clone(),
2554                            }
2555                        } else {
2556                            File {
2557                                is_local: true,
2558                                entry_id: None,
2559                                path: old_file.path().clone(),
2560                                mtime: old_file.mtime(),
2561                                worktree: worktree_handle.clone(),
2562                            }
2563                        };
2564
2565                        if let Some(project_id) = self.remote_id() {
2566                            self.client
2567                                .send(proto::UpdateBufferFile {
2568                                    project_id,
2569                                    buffer_id: *buffer_id as u64,
2570                                    file: Some(new_file.to_proto()),
2571                                })
2572                                .log_err();
2573                        }
2574                        buffer.file_updated(Box::new(new_file), cx).detach();
2575                    }
2576                });
2577            } else {
2578                buffers_to_delete.push(*buffer_id);
2579            }
2580        }
2581
2582        for buffer_id in buffers_to_delete {
2583            self.opened_buffers.remove(&buffer_id);
2584        }
2585    }
2586
2587    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
2588        let new_active_entry = entry.and_then(|project_path| {
2589            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
2590            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
2591            Some(ProjectEntry {
2592                worktree_id: project_path.worktree_id,
2593                entry_id: entry.id,
2594            })
2595        });
2596        if new_active_entry != self.active_entry {
2597            self.active_entry = new_active_entry;
2598            cx.emit(Event::ActiveEntryChanged(new_active_entry));
2599        }
2600    }
2601
2602    pub fn is_running_disk_based_diagnostics(&self) -> bool {
2603        self.language_servers_with_diagnostics_running > 0
2604    }
2605
2606    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
2607        let mut summary = DiagnosticSummary::default();
2608        for (_, path_summary) in self.diagnostic_summaries(cx) {
2609            summary.error_count += path_summary.error_count;
2610            summary.warning_count += path_summary.warning_count;
2611            summary.info_count += path_summary.info_count;
2612            summary.hint_count += path_summary.hint_count;
2613        }
2614        summary
2615    }
2616
2617    pub fn diagnostic_summaries<'a>(
2618        &'a self,
2619        cx: &'a AppContext,
2620    ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
2621        self.worktrees(cx).flat_map(move |worktree| {
2622            let worktree = worktree.read(cx);
2623            let worktree_id = worktree.id();
2624            worktree
2625                .diagnostic_summaries()
2626                .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
2627        })
2628    }
2629
2630    pub fn disk_based_diagnostics_started(&mut self, cx: &mut ModelContext<Self>) {
2631        self.language_servers_with_diagnostics_running += 1;
2632        if self.language_servers_with_diagnostics_running == 1 {
2633            cx.emit(Event::DiskBasedDiagnosticsStarted);
2634        }
2635    }
2636
2637    pub fn disk_based_diagnostics_finished(&mut self, cx: &mut ModelContext<Self>) {
2638        cx.emit(Event::DiskBasedDiagnosticsUpdated);
2639        self.language_servers_with_diagnostics_running -= 1;
2640        if self.language_servers_with_diagnostics_running == 0 {
2641            cx.emit(Event::DiskBasedDiagnosticsFinished);
2642        }
2643    }
2644
2645    pub fn active_entry(&self) -> Option<ProjectEntry> {
2646        self.active_entry
2647    }
2648
2649    // RPC message handlers
2650
2651    async fn handle_unshare_project(
2652        this: ModelHandle<Self>,
2653        _: TypedEnvelope<proto::UnshareProject>,
2654        _: Arc<Client>,
2655        mut cx: AsyncAppContext,
2656    ) -> Result<()> {
2657        this.update(&mut cx, |this, cx| {
2658            if let ProjectClientState::Remote {
2659                sharing_has_stopped,
2660                ..
2661            } = &mut this.client_state
2662            {
2663                *sharing_has_stopped = true;
2664                this.collaborators.clear();
2665                cx.notify();
2666            } else {
2667                unreachable!()
2668            }
2669        });
2670
2671        Ok(())
2672    }
2673
2674    async fn handle_add_collaborator(
2675        this: ModelHandle<Self>,
2676        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
2677        _: Arc<Client>,
2678        mut cx: AsyncAppContext,
2679    ) -> Result<()> {
2680        let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
2681        let collaborator = envelope
2682            .payload
2683            .collaborator
2684            .take()
2685            .ok_or_else(|| anyhow!("empty collaborator"))?;
2686
2687        let collaborator = Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
2688        this.update(&mut cx, |this, cx| {
2689            this.collaborators
2690                .insert(collaborator.peer_id, collaborator);
2691            cx.notify();
2692        });
2693
2694        Ok(())
2695    }
2696
2697    async fn handle_remove_collaborator(
2698        this: ModelHandle<Self>,
2699        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
2700        _: Arc<Client>,
2701        mut cx: AsyncAppContext,
2702    ) -> Result<()> {
2703        this.update(&mut cx, |this, cx| {
2704            let peer_id = PeerId(envelope.payload.peer_id);
2705            let replica_id = this
2706                .collaborators
2707                .remove(&peer_id)
2708                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
2709                .replica_id;
2710            for (_, buffer) in &this.opened_buffers {
2711                if let Some(buffer) = buffer.upgrade(cx) {
2712                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
2713                }
2714            }
2715            cx.notify();
2716            Ok(())
2717        })
2718    }
2719
2720    async fn handle_register_worktree(
2721        this: ModelHandle<Self>,
2722        envelope: TypedEnvelope<proto::RegisterWorktree>,
2723        client: Arc<Client>,
2724        mut cx: AsyncAppContext,
2725    ) -> Result<()> {
2726        this.update(&mut cx, |this, cx| {
2727            let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
2728            let replica_id = this.replica_id();
2729            let worktree = proto::Worktree {
2730                id: envelope.payload.worktree_id,
2731                root_name: envelope.payload.root_name,
2732                entries: Default::default(),
2733                diagnostic_summaries: Default::default(),
2734                visible: envelope.payload.visible,
2735            };
2736            let (worktree, load_task) =
2737                Worktree::remote(remote_id, replica_id, worktree, client, cx);
2738            this.add_worktree(&worktree, cx);
2739            load_task.detach();
2740            Ok(())
2741        })
2742    }
2743
2744    async fn handle_unregister_worktree(
2745        this: ModelHandle<Self>,
2746        envelope: TypedEnvelope<proto::UnregisterWorktree>,
2747        _: Arc<Client>,
2748        mut cx: AsyncAppContext,
2749    ) -> Result<()> {
2750        this.update(&mut cx, |this, cx| {
2751            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2752            this.remove_worktree(worktree_id, cx);
2753            Ok(())
2754        })
2755    }
2756
2757    async fn handle_update_worktree(
2758        this: ModelHandle<Self>,
2759        envelope: TypedEnvelope<proto::UpdateWorktree>,
2760        _: Arc<Client>,
2761        mut cx: AsyncAppContext,
2762    ) -> Result<()> {
2763        this.update(&mut cx, |this, cx| {
2764            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2765            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
2766                worktree.update(cx, |worktree, _| {
2767                    let worktree = worktree.as_remote_mut().unwrap();
2768                    worktree.update_from_remote(envelope)
2769                })?;
2770            }
2771            Ok(())
2772        })
2773    }
2774
2775    async fn handle_update_diagnostic_summary(
2776        this: ModelHandle<Self>,
2777        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
2778        _: Arc<Client>,
2779        mut cx: AsyncAppContext,
2780    ) -> Result<()> {
2781        this.update(&mut cx, |this, cx| {
2782            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2783            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
2784                if let Some(summary) = envelope.payload.summary {
2785                    let project_path = ProjectPath {
2786                        worktree_id,
2787                        path: Path::new(&summary.path).into(),
2788                    };
2789                    worktree.update(cx, |worktree, _| {
2790                        worktree
2791                            .as_remote_mut()
2792                            .unwrap()
2793                            .update_diagnostic_summary(project_path.path.clone(), &summary);
2794                    });
2795                    cx.emit(Event::DiagnosticsUpdated(project_path));
2796                }
2797            }
2798            Ok(())
2799        })
2800    }
2801
2802    async fn handle_disk_based_diagnostics_updating(
2803        this: ModelHandle<Self>,
2804        _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdating>,
2805        _: Arc<Client>,
2806        mut cx: AsyncAppContext,
2807    ) -> Result<()> {
2808        this.update(&mut cx, |this, cx| this.disk_based_diagnostics_started(cx));
2809        Ok(())
2810    }
2811
2812    async fn handle_disk_based_diagnostics_updated(
2813        this: ModelHandle<Self>,
2814        _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdated>,
2815        _: Arc<Client>,
2816        mut cx: AsyncAppContext,
2817    ) -> Result<()> {
2818        this.update(&mut cx, |this, cx| this.disk_based_diagnostics_finished(cx));
2819        Ok(())
2820    }
2821
2822    async fn handle_update_buffer(
2823        this: ModelHandle<Self>,
2824        envelope: TypedEnvelope<proto::UpdateBuffer>,
2825        _: Arc<Client>,
2826        mut cx: AsyncAppContext,
2827    ) -> Result<()> {
2828        this.update(&mut cx, |this, cx| {
2829            let payload = envelope.payload.clone();
2830            let buffer_id = payload.buffer_id;
2831            let ops = payload
2832                .operations
2833                .into_iter()
2834                .map(|op| language::proto::deserialize_operation(op))
2835                .collect::<Result<Vec<_>, _>>()?;
2836            match this.opened_buffers.entry(buffer_id) {
2837                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
2838                    OpenBuffer::Strong(buffer) => {
2839                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
2840                    }
2841                    OpenBuffer::Loading(operations) => operations.extend_from_slice(&ops),
2842                    OpenBuffer::Weak(_) => {}
2843                },
2844                hash_map::Entry::Vacant(e) => {
2845                    e.insert(OpenBuffer::Loading(ops));
2846                }
2847            }
2848            Ok(())
2849        })
2850    }
2851
2852    async fn handle_update_buffer_file(
2853        this: ModelHandle<Self>,
2854        envelope: TypedEnvelope<proto::UpdateBufferFile>,
2855        _: Arc<Client>,
2856        mut cx: AsyncAppContext,
2857    ) -> Result<()> {
2858        this.update(&mut cx, |this, cx| {
2859            let payload = envelope.payload.clone();
2860            let buffer_id = payload.buffer_id;
2861            let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
2862            let worktree = this
2863                .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
2864                .ok_or_else(|| anyhow!("no such worktree"))?;
2865            let file = File::from_proto(file, worktree.clone(), cx)?;
2866            let buffer = this
2867                .opened_buffers
2868                .get_mut(&buffer_id)
2869                .and_then(|b| b.upgrade(cx))
2870                .ok_or_else(|| anyhow!("no such buffer"))?;
2871            buffer.update(cx, |buffer, cx| {
2872                buffer.file_updated(Box::new(file), cx).detach();
2873            });
2874            Ok(())
2875        })
2876    }
2877
2878    async fn handle_save_buffer(
2879        this: ModelHandle<Self>,
2880        envelope: TypedEnvelope<proto::SaveBuffer>,
2881        _: Arc<Client>,
2882        mut cx: AsyncAppContext,
2883    ) -> Result<proto::BufferSaved> {
2884        let buffer_id = envelope.payload.buffer_id;
2885        let requested_version = envelope.payload.version.try_into()?;
2886
2887        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
2888            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
2889            let buffer = this
2890                .opened_buffers
2891                .get(&buffer_id)
2892                .map(|buffer| buffer.upgrade(cx).unwrap())
2893                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
2894            Ok::<_, anyhow::Error>((project_id, buffer))
2895        })?;
2896        buffer
2897            .update(&mut cx, |buffer, _| {
2898                buffer.wait_for_version(requested_version)
2899            })
2900            .await;
2901
2902        let (saved_version, mtime) = buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
2903        Ok(proto::BufferSaved {
2904            project_id,
2905            buffer_id,
2906            version: (&saved_version).into(),
2907            mtime: Some(mtime.into()),
2908        })
2909    }
2910
2911    async fn handle_format_buffers(
2912        this: ModelHandle<Self>,
2913        envelope: TypedEnvelope<proto::FormatBuffers>,
2914        _: Arc<Client>,
2915        mut cx: AsyncAppContext,
2916    ) -> Result<proto::FormatBuffersResponse> {
2917        let sender_id = envelope.original_sender_id()?;
2918        let format = this.update(&mut cx, |this, cx| {
2919            let mut buffers = HashSet::default();
2920            for buffer_id in &envelope.payload.buffer_ids {
2921                buffers.insert(
2922                    this.opened_buffers
2923                        .get(buffer_id)
2924                        .map(|buffer| buffer.upgrade(cx).unwrap())
2925                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
2926                );
2927            }
2928            Ok::<_, anyhow::Error>(this.format(buffers, false, cx))
2929        })?;
2930
2931        let project_transaction = format.await?;
2932        let project_transaction = this.update(&mut cx, |this, cx| {
2933            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
2934        });
2935        Ok(proto::FormatBuffersResponse {
2936            transaction: Some(project_transaction),
2937        })
2938    }
2939
2940    async fn handle_get_completions(
2941        this: ModelHandle<Self>,
2942        envelope: TypedEnvelope<proto::GetCompletions>,
2943        _: Arc<Client>,
2944        mut cx: AsyncAppContext,
2945    ) -> Result<proto::GetCompletionsResponse> {
2946        let position = envelope
2947            .payload
2948            .position
2949            .and_then(language::proto::deserialize_anchor)
2950            .ok_or_else(|| anyhow!("invalid position"))?;
2951        let version = clock::Global::from(envelope.payload.version);
2952        let buffer = this.read_with(&cx, |this, cx| {
2953            this.opened_buffers
2954                .get(&envelope.payload.buffer_id)
2955                .map(|buffer| buffer.upgrade(cx).unwrap())
2956                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
2957        })?;
2958        buffer
2959            .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
2960            .await;
2961        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
2962        let completions = this
2963            .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
2964            .await?;
2965
2966        Ok(proto::GetCompletionsResponse {
2967            completions: completions
2968                .iter()
2969                .map(language::proto::serialize_completion)
2970                .collect(),
2971            version: (&version).into(),
2972        })
2973    }
2974
2975    async fn handle_apply_additional_edits_for_completion(
2976        this: ModelHandle<Self>,
2977        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
2978        _: Arc<Client>,
2979        mut cx: AsyncAppContext,
2980    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
2981        let apply_additional_edits = this.update(&mut cx, |this, cx| {
2982            let buffer = this
2983                .opened_buffers
2984                .get(&envelope.payload.buffer_id)
2985                .map(|buffer| buffer.upgrade(cx).unwrap())
2986                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2987            let language = buffer.read(cx).language();
2988            let completion = language::proto::deserialize_completion(
2989                envelope
2990                    .payload
2991                    .completion
2992                    .ok_or_else(|| anyhow!("invalid completion"))?,
2993                language,
2994            )?;
2995            Ok::<_, anyhow::Error>(
2996                this.apply_additional_edits_for_completion(buffer, completion, false, cx),
2997            )
2998        })?;
2999
3000        Ok(proto::ApplyCompletionAdditionalEditsResponse {
3001            transaction: apply_additional_edits
3002                .await?
3003                .as_ref()
3004                .map(language::proto::serialize_transaction),
3005        })
3006    }
3007
3008    async fn handle_get_code_actions(
3009        this: ModelHandle<Self>,
3010        envelope: TypedEnvelope<proto::GetCodeActions>,
3011        _: Arc<Client>,
3012        mut cx: AsyncAppContext,
3013    ) -> Result<proto::GetCodeActionsResponse> {
3014        let start = envelope
3015            .payload
3016            .start
3017            .and_then(language::proto::deserialize_anchor)
3018            .ok_or_else(|| anyhow!("invalid start"))?;
3019        let end = envelope
3020            .payload
3021            .end
3022            .and_then(language::proto::deserialize_anchor)
3023            .ok_or_else(|| anyhow!("invalid end"))?;
3024        let buffer = this.update(&mut cx, |this, cx| {
3025            this.opened_buffers
3026                .get(&envelope.payload.buffer_id)
3027                .map(|buffer| buffer.upgrade(cx).unwrap())
3028                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
3029        })?;
3030        buffer
3031            .update(&mut cx, |buffer, _| {
3032                buffer.wait_for_version(envelope.payload.version.into())
3033            })
3034            .await;
3035
3036        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
3037        let code_actions = this.update(&mut cx, |this, cx| {
3038            Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
3039        })?;
3040
3041        Ok(proto::GetCodeActionsResponse {
3042            actions: code_actions
3043                .await?
3044                .iter()
3045                .map(language::proto::serialize_code_action)
3046                .collect(),
3047            version: (&version).into(),
3048        })
3049    }
3050
3051    async fn handle_apply_code_action(
3052        this: ModelHandle<Self>,
3053        envelope: TypedEnvelope<proto::ApplyCodeAction>,
3054        _: Arc<Client>,
3055        mut cx: AsyncAppContext,
3056    ) -> Result<proto::ApplyCodeActionResponse> {
3057        let sender_id = envelope.original_sender_id()?;
3058        let action = language::proto::deserialize_code_action(
3059            envelope
3060                .payload
3061                .action
3062                .ok_or_else(|| anyhow!("invalid action"))?,
3063        )?;
3064        let apply_code_action = this.update(&mut cx, |this, cx| {
3065            let buffer = this
3066                .opened_buffers
3067                .get(&envelope.payload.buffer_id)
3068                .map(|buffer| buffer.upgrade(cx).unwrap())
3069                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
3070            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
3071        })?;
3072
3073        let project_transaction = apply_code_action.await?;
3074        let project_transaction = this.update(&mut cx, |this, cx| {
3075            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
3076        });
3077        Ok(proto::ApplyCodeActionResponse {
3078            transaction: Some(project_transaction),
3079        })
3080    }
3081
3082    async fn handle_lsp_command<T: LspCommand>(
3083        this: ModelHandle<Self>,
3084        envelope: TypedEnvelope<T::ProtoRequest>,
3085        _: Arc<Client>,
3086        mut cx: AsyncAppContext,
3087    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
3088    where
3089        <T::LspRequest as lsp::request::Request>::Result: Send,
3090    {
3091        let sender_id = envelope.original_sender_id()?;
3092        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
3093        let buffer_handle = this.read_with(&cx, |this, _| {
3094            this.opened_buffers
3095                .get(&buffer_id)
3096                .map(|buffer| buffer.upgrade(&cx).unwrap())
3097                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
3098        })?;
3099        let request = T::from_proto(
3100            envelope.payload,
3101            this.clone(),
3102            buffer_handle.clone(),
3103            cx.clone(),
3104        )
3105        .await?;
3106        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
3107        let response = this
3108            .update(&mut cx, |this, cx| {
3109                this.request_lsp(buffer_handle, request, cx)
3110            })
3111            .await?;
3112        this.update(&mut cx, |this, cx| {
3113            Ok(T::response_to_proto(
3114                response,
3115                this,
3116                sender_id,
3117                &buffer_version,
3118                cx,
3119            ))
3120        })
3121    }
3122
3123    async fn handle_get_project_symbols(
3124        this: ModelHandle<Self>,
3125        envelope: TypedEnvelope<proto::GetProjectSymbols>,
3126        _: Arc<Client>,
3127        mut cx: AsyncAppContext,
3128    ) -> Result<proto::GetProjectSymbolsResponse> {
3129        let symbols = this
3130            .update(&mut cx, |this, cx| {
3131                this.symbols(&envelope.payload.query, cx)
3132            })
3133            .await?;
3134
3135        Ok(proto::GetProjectSymbolsResponse {
3136            symbols: symbols.iter().map(serialize_symbol).collect(),
3137        })
3138    }
3139
3140    async fn handle_search_project(
3141        this: ModelHandle<Self>,
3142        envelope: TypedEnvelope<proto::SearchProject>,
3143        _: Arc<Client>,
3144        mut cx: AsyncAppContext,
3145    ) -> Result<proto::SearchProjectResponse> {
3146        let peer_id = envelope.original_sender_id()?;
3147        let query = SearchQuery::from_proto(envelope.payload)?;
3148        let result = this
3149            .update(&mut cx, |this, cx| this.search(query, cx))
3150            .await?;
3151
3152        this.update(&mut cx, |this, cx| {
3153            let mut locations = Vec::new();
3154            for (buffer, ranges) in result {
3155                for range in ranges {
3156                    let start = serialize_anchor(&range.start);
3157                    let end = serialize_anchor(&range.end);
3158                    let buffer = this.serialize_buffer_for_peer(&buffer, peer_id, cx);
3159                    locations.push(proto::Location {
3160                        buffer: Some(buffer),
3161                        start: Some(start),
3162                        end: Some(end),
3163                    });
3164                }
3165            }
3166            Ok(proto::SearchProjectResponse { locations })
3167        })
3168    }
3169
3170    async fn handle_open_buffer_for_symbol(
3171        this: ModelHandle<Self>,
3172        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
3173        _: Arc<Client>,
3174        mut cx: AsyncAppContext,
3175    ) -> Result<proto::OpenBufferForSymbolResponse> {
3176        let peer_id = envelope.original_sender_id()?;
3177        let symbol = envelope
3178            .payload
3179            .symbol
3180            .ok_or_else(|| anyhow!("invalid symbol"))?;
3181        let symbol = this.read_with(&cx, |this, _| {
3182            let symbol = this.deserialize_symbol(symbol)?;
3183            let signature = this.symbol_signature(symbol.worktree_id, &symbol.path);
3184            if signature == symbol.signature {
3185                Ok(symbol)
3186            } else {
3187                Err(anyhow!("invalid symbol signature"))
3188            }
3189        })?;
3190        let buffer = this
3191            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
3192            .await?;
3193
3194        Ok(proto::OpenBufferForSymbolResponse {
3195            buffer: Some(this.update(&mut cx, |this, cx| {
3196                this.serialize_buffer_for_peer(&buffer, peer_id, cx)
3197            })),
3198        })
3199    }
3200
3201    fn symbol_signature(&self, worktree_id: WorktreeId, path: &Path) -> [u8; 32] {
3202        let mut hasher = Sha256::new();
3203        hasher.update(worktree_id.to_proto().to_be_bytes());
3204        hasher.update(path.to_string_lossy().as_bytes());
3205        hasher.update(self.nonce.to_be_bytes());
3206        hasher.finalize().as_slice().try_into().unwrap()
3207    }
3208
3209    async fn handle_open_buffer(
3210        this: ModelHandle<Self>,
3211        envelope: TypedEnvelope<proto::OpenBuffer>,
3212        _: Arc<Client>,
3213        mut cx: AsyncAppContext,
3214    ) -> Result<proto::OpenBufferResponse> {
3215        let peer_id = envelope.original_sender_id()?;
3216        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3217        let open_buffer = this.update(&mut cx, |this, cx| {
3218            this.open_buffer(
3219                ProjectPath {
3220                    worktree_id,
3221                    path: PathBuf::from(envelope.payload.path).into(),
3222                },
3223                cx,
3224            )
3225        });
3226
3227        let buffer = open_buffer.await?;
3228        this.update(&mut cx, |this, cx| {
3229            Ok(proto::OpenBufferResponse {
3230                buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
3231            })
3232        })
3233    }
3234
3235    fn serialize_project_transaction_for_peer(
3236        &mut self,
3237        project_transaction: ProjectTransaction,
3238        peer_id: PeerId,
3239        cx: &AppContext,
3240    ) -> proto::ProjectTransaction {
3241        let mut serialized_transaction = proto::ProjectTransaction {
3242            buffers: Default::default(),
3243            transactions: Default::default(),
3244        };
3245        for (buffer, transaction) in project_transaction.0 {
3246            serialized_transaction
3247                .buffers
3248                .push(self.serialize_buffer_for_peer(&buffer, peer_id, cx));
3249            serialized_transaction
3250                .transactions
3251                .push(language::proto::serialize_transaction(&transaction));
3252        }
3253        serialized_transaction
3254    }
3255
3256    fn deserialize_project_transaction(
3257        &mut self,
3258        message: proto::ProjectTransaction,
3259        push_to_history: bool,
3260        cx: &mut ModelContext<Self>,
3261    ) -> Task<Result<ProjectTransaction>> {
3262        cx.spawn(|this, mut cx| async move {
3263            let mut project_transaction = ProjectTransaction::default();
3264            for (buffer, transaction) in message.buffers.into_iter().zip(message.transactions) {
3265                let buffer = this
3266                    .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
3267                    .await?;
3268                let transaction = language::proto::deserialize_transaction(transaction)?;
3269                project_transaction.0.insert(buffer, transaction);
3270            }
3271
3272            for (buffer, transaction) in &project_transaction.0 {
3273                buffer
3274                    .update(&mut cx, |buffer, _| {
3275                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3276                    })
3277                    .await;
3278
3279                if push_to_history {
3280                    buffer.update(&mut cx, |buffer, _| {
3281                        buffer.push_transaction(transaction.clone(), Instant::now());
3282                    });
3283                }
3284            }
3285
3286            Ok(project_transaction)
3287        })
3288    }
3289
3290    fn serialize_buffer_for_peer(
3291        &mut self,
3292        buffer: &ModelHandle<Buffer>,
3293        peer_id: PeerId,
3294        cx: &AppContext,
3295    ) -> proto::Buffer {
3296        let buffer_id = buffer.read(cx).remote_id();
3297        let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
3298        if shared_buffers.insert(buffer_id) {
3299            proto::Buffer {
3300                variant: Some(proto::buffer::Variant::State(buffer.read(cx).to_proto())),
3301            }
3302        } else {
3303            proto::Buffer {
3304                variant: Some(proto::buffer::Variant::Id(buffer_id)),
3305            }
3306        }
3307    }
3308
3309    fn deserialize_buffer(
3310        &mut self,
3311        buffer: proto::Buffer,
3312        cx: &mut ModelContext<Self>,
3313    ) -> Task<Result<ModelHandle<Buffer>>> {
3314        let replica_id = self.replica_id();
3315
3316        let opened_buffer_tx = self.opened_buffer.0.clone();
3317        let mut opened_buffer_rx = self.opened_buffer.1.clone();
3318        cx.spawn(|this, mut cx| async move {
3319            match buffer.variant.ok_or_else(|| anyhow!("missing buffer"))? {
3320                proto::buffer::Variant::Id(id) => {
3321                    let buffer = loop {
3322                        let buffer = this.read_with(&cx, |this, cx| {
3323                            this.opened_buffers
3324                                .get(&id)
3325                                .and_then(|buffer| buffer.upgrade(cx))
3326                        });
3327                        if let Some(buffer) = buffer {
3328                            break buffer;
3329                        }
3330                        opened_buffer_rx
3331                            .next()
3332                            .await
3333                            .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
3334                    };
3335                    Ok(buffer)
3336                }
3337                proto::buffer::Variant::State(mut buffer) => {
3338                    let mut buffer_worktree = None;
3339                    let mut buffer_file = None;
3340                    if let Some(file) = buffer.file.take() {
3341                        this.read_with(&cx, |this, cx| {
3342                            let worktree_id = WorktreeId::from_proto(file.worktree_id);
3343                            let worktree =
3344                                this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
3345                                    anyhow!("no worktree found for id {}", file.worktree_id)
3346                                })?;
3347                            buffer_file =
3348                                Some(Box::new(File::from_proto(file, worktree.clone(), cx)?)
3349                                    as Box<dyn language::File>);
3350                            buffer_worktree = Some(worktree);
3351                            Ok::<_, anyhow::Error>(())
3352                        })?;
3353                    }
3354
3355                    let buffer = cx.add_model(|cx| {
3356                        Buffer::from_proto(replica_id, buffer, buffer_file, cx).unwrap()
3357                    });
3358
3359                    this.update(&mut cx, |this, cx| {
3360                        this.register_buffer(&buffer, buffer_worktree.as_ref(), cx)
3361                    })?;
3362
3363                    *opened_buffer_tx.borrow_mut().borrow_mut() = ();
3364                    Ok(buffer)
3365                }
3366            }
3367        })
3368    }
3369
3370    fn deserialize_symbol(&self, serialized_symbol: proto::Symbol) -> Result<Symbol> {
3371        let language = self
3372            .languages
3373            .get_language(&serialized_symbol.language_name);
3374        let start = serialized_symbol
3375            .start
3376            .ok_or_else(|| anyhow!("invalid start"))?;
3377        let end = serialized_symbol
3378            .end
3379            .ok_or_else(|| anyhow!("invalid end"))?;
3380        let kind = unsafe { mem::transmute(serialized_symbol.kind) };
3381        Ok(Symbol {
3382            source_worktree_id: WorktreeId::from_proto(serialized_symbol.source_worktree_id),
3383            worktree_id: WorktreeId::from_proto(serialized_symbol.worktree_id),
3384            language_name: serialized_symbol.language_name.clone(),
3385            label: language
3386                .and_then(|language| language.label_for_symbol(&serialized_symbol.name, kind))
3387                .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None)),
3388            name: serialized_symbol.name,
3389            path: PathBuf::from(serialized_symbol.path),
3390            range: PointUtf16::new(start.row, start.column)..PointUtf16::new(end.row, end.column),
3391            kind,
3392            signature: serialized_symbol
3393                .signature
3394                .try_into()
3395                .map_err(|_| anyhow!("invalid signature"))?,
3396        })
3397    }
3398
3399    async fn handle_close_buffer(
3400        _: ModelHandle<Self>,
3401        _: TypedEnvelope<proto::CloseBuffer>,
3402        _: Arc<Client>,
3403        _: AsyncAppContext,
3404    ) -> Result<()> {
3405        // TODO: use this for following
3406        Ok(())
3407    }
3408
3409    async fn handle_buffer_saved(
3410        this: ModelHandle<Self>,
3411        envelope: TypedEnvelope<proto::BufferSaved>,
3412        _: Arc<Client>,
3413        mut cx: AsyncAppContext,
3414    ) -> Result<()> {
3415        let version = envelope.payload.version.try_into()?;
3416        let mtime = envelope
3417            .payload
3418            .mtime
3419            .ok_or_else(|| anyhow!("missing mtime"))?
3420            .into();
3421
3422        this.update(&mut cx, |this, cx| {
3423            let buffer = this
3424                .opened_buffers
3425                .get(&envelope.payload.buffer_id)
3426                .and_then(|buffer| buffer.upgrade(cx));
3427            if let Some(buffer) = buffer {
3428                buffer.update(cx, |buffer, cx| {
3429                    buffer.did_save(version, mtime, None, cx);
3430                });
3431            }
3432            Ok(())
3433        })
3434    }
3435
3436    async fn handle_buffer_reloaded(
3437        this: ModelHandle<Self>,
3438        envelope: TypedEnvelope<proto::BufferReloaded>,
3439        _: Arc<Client>,
3440        mut cx: AsyncAppContext,
3441    ) -> Result<()> {
3442        let payload = envelope.payload.clone();
3443        let version = payload.version.try_into()?;
3444        let mtime = payload
3445            .mtime
3446            .ok_or_else(|| anyhow!("missing mtime"))?
3447            .into();
3448        this.update(&mut cx, |this, cx| {
3449            let buffer = this
3450                .opened_buffers
3451                .get(&payload.buffer_id)
3452                .and_then(|buffer| buffer.upgrade(cx));
3453            if let Some(buffer) = buffer {
3454                buffer.update(cx, |buffer, cx| {
3455                    buffer.did_reload(version, mtime, cx);
3456                });
3457            }
3458            Ok(())
3459        })
3460    }
3461
3462    pub fn match_paths<'a>(
3463        &self,
3464        query: &'a str,
3465        include_ignored: bool,
3466        smart_case: bool,
3467        max_results: usize,
3468        cancel_flag: &'a AtomicBool,
3469        cx: &AppContext,
3470    ) -> impl 'a + Future<Output = Vec<PathMatch>> {
3471        let worktrees = self
3472            .worktrees(cx)
3473            .filter(|worktree| worktree.read(cx).is_visible())
3474            .collect::<Vec<_>>();
3475        let include_root_name = worktrees.len() > 1;
3476        let candidate_sets = worktrees
3477            .into_iter()
3478            .map(|worktree| CandidateSet {
3479                snapshot: worktree.read(cx).snapshot(),
3480                include_ignored,
3481                include_root_name,
3482            })
3483            .collect::<Vec<_>>();
3484
3485        let background = cx.background().clone();
3486        async move {
3487            fuzzy::match_paths(
3488                candidate_sets.as_slice(),
3489                query,
3490                smart_case,
3491                max_results,
3492                cancel_flag,
3493                background,
3494            )
3495            .await
3496        }
3497    }
3498}
3499
3500impl WorktreeHandle {
3501    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
3502        match self {
3503            WorktreeHandle::Strong(handle) => Some(handle.clone()),
3504            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
3505        }
3506    }
3507}
3508
3509impl OpenBuffer {
3510    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
3511        match self {
3512            OpenBuffer::Strong(handle) => Some(handle.clone()),
3513            OpenBuffer::Weak(handle) => handle.upgrade(cx),
3514            OpenBuffer::Loading(_) => None,
3515        }
3516    }
3517}
3518
3519struct CandidateSet {
3520    snapshot: Snapshot,
3521    include_ignored: bool,
3522    include_root_name: bool,
3523}
3524
3525impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
3526    type Candidates = CandidateSetIter<'a>;
3527
3528    fn id(&self) -> usize {
3529        self.snapshot.id().to_usize()
3530    }
3531
3532    fn len(&self) -> usize {
3533        if self.include_ignored {
3534            self.snapshot.file_count()
3535        } else {
3536            self.snapshot.visible_file_count()
3537        }
3538    }
3539
3540    fn prefix(&self) -> Arc<str> {
3541        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
3542            self.snapshot.root_name().into()
3543        } else if self.include_root_name {
3544            format!("{}/", self.snapshot.root_name()).into()
3545        } else {
3546            "".into()
3547        }
3548    }
3549
3550    fn candidates(&'a self, start: usize) -> Self::Candidates {
3551        CandidateSetIter {
3552            traversal: self.snapshot.files(self.include_ignored, start),
3553        }
3554    }
3555}
3556
3557struct CandidateSetIter<'a> {
3558    traversal: Traversal<'a>,
3559}
3560
3561impl<'a> Iterator for CandidateSetIter<'a> {
3562    type Item = PathMatchCandidate<'a>;
3563
3564    fn next(&mut self) -> Option<Self::Item> {
3565        self.traversal.next().map(|entry| {
3566            if let EntryKind::File(char_bag) = entry.kind {
3567                PathMatchCandidate {
3568                    path: &entry.path,
3569                    char_bag,
3570                }
3571            } else {
3572                unreachable!()
3573            }
3574        })
3575    }
3576}
3577
3578impl Entity for Project {
3579    type Event = Event;
3580
3581    fn release(&mut self, _: &mut gpui::MutableAppContext) {
3582        match &self.client_state {
3583            ProjectClientState::Local { remote_id_rx, .. } => {
3584                if let Some(project_id) = *remote_id_rx.borrow() {
3585                    self.client
3586                        .send(proto::UnregisterProject { project_id })
3587                        .log_err();
3588                }
3589            }
3590            ProjectClientState::Remote { remote_id, .. } => {
3591                self.client
3592                    .send(proto::LeaveProject {
3593                        project_id: *remote_id,
3594                    })
3595                    .log_err();
3596            }
3597        }
3598    }
3599
3600    fn app_will_quit(
3601        &mut self,
3602        _: &mut MutableAppContext,
3603    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
3604        let shutdown_futures = self
3605            .language_servers
3606            .drain()
3607            .filter_map(|(_, server)| server.shutdown())
3608            .collect::<Vec<_>>();
3609        Some(
3610            async move {
3611                futures::future::join_all(shutdown_futures).await;
3612            }
3613            .boxed(),
3614        )
3615    }
3616}
3617
3618impl Collaborator {
3619    fn from_proto(
3620        message: proto::Collaborator,
3621        user_store: &ModelHandle<UserStore>,
3622        cx: &mut AsyncAppContext,
3623    ) -> impl Future<Output = Result<Self>> {
3624        let user = user_store.update(cx, |user_store, cx| {
3625            user_store.fetch_user(message.user_id, cx)
3626        });
3627
3628        async move {
3629            Ok(Self {
3630                peer_id: PeerId(message.peer_id),
3631                user: user.await?,
3632                replica_id: message.replica_id as ReplicaId,
3633            })
3634        }
3635    }
3636}
3637
3638impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
3639    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
3640        Self {
3641            worktree_id,
3642            path: path.as_ref().into(),
3643        }
3644    }
3645}
3646
3647impl From<lsp::CreateFileOptions> for fs::CreateOptions {
3648    fn from(options: lsp::CreateFileOptions) -> Self {
3649        Self {
3650            overwrite: options.overwrite.unwrap_or(false),
3651            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
3652        }
3653    }
3654}
3655
3656impl From<lsp::RenameFileOptions> for fs::RenameOptions {
3657    fn from(options: lsp::RenameFileOptions) -> Self {
3658        Self {
3659            overwrite: options.overwrite.unwrap_or(false),
3660            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
3661        }
3662    }
3663}
3664
3665impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
3666    fn from(options: lsp::DeleteFileOptions) -> Self {
3667        Self {
3668            recursive: options.recursive.unwrap_or(false),
3669            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
3670        }
3671    }
3672}
3673
3674fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
3675    proto::Symbol {
3676        source_worktree_id: symbol.source_worktree_id.to_proto(),
3677        worktree_id: symbol.worktree_id.to_proto(),
3678        language_name: symbol.language_name.clone(),
3679        name: symbol.name.clone(),
3680        kind: unsafe { mem::transmute(symbol.kind) },
3681        path: symbol.path.to_string_lossy().to_string(),
3682        start: Some(proto::Point {
3683            row: symbol.range.start.row,
3684            column: symbol.range.start.column,
3685        }),
3686        end: Some(proto::Point {
3687            row: symbol.range.end.row,
3688            column: symbol.range.end.column,
3689        }),
3690        signature: symbol.signature.to_vec(),
3691    }
3692}
3693
3694fn relativize_path(base: &Path, path: &Path) -> PathBuf {
3695    let mut path_components = path.components();
3696    let mut base_components = base.components();
3697    let mut components: Vec<Component> = Vec::new();
3698    loop {
3699        match (path_components.next(), base_components.next()) {
3700            (None, None) => break,
3701            (Some(a), None) => {
3702                components.push(a);
3703                components.extend(path_components.by_ref());
3704                break;
3705            }
3706            (None, _) => components.push(Component::ParentDir),
3707            (Some(a), Some(b)) if components.is_empty() && a == b => (),
3708            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
3709            (Some(a), Some(_)) => {
3710                components.push(Component::ParentDir);
3711                for _ in base_components {
3712                    components.push(Component::ParentDir);
3713                }
3714                components.push(a);
3715                components.extend(path_components.by_ref());
3716                break;
3717            }
3718        }
3719    }
3720    components.iter().map(|c| c.as_os_str()).collect()
3721}
3722
3723#[cfg(test)]
3724mod tests {
3725    use super::{Event, *};
3726    use fs::RealFs;
3727    use futures::StreamExt;
3728    use gpui::test::subscribe;
3729    use language::{
3730        tree_sitter_rust, AnchorRangeExt, Diagnostic, LanguageConfig, LanguageServerConfig, Point,
3731    };
3732    use lsp::Url;
3733    use serde_json::json;
3734    use std::{cell::RefCell, os::unix, path::PathBuf, rc::Rc};
3735    use unindent::Unindent as _;
3736    use util::test::temp_tree;
3737    use worktree::WorktreeHandle as _;
3738
3739    #[gpui::test]
3740    async fn test_populate_and_search(cx: &mut gpui::TestAppContext) {
3741        let dir = temp_tree(json!({
3742            "root": {
3743                "apple": "",
3744                "banana": {
3745                    "carrot": {
3746                        "date": "",
3747                        "endive": "",
3748                    }
3749                },
3750                "fennel": {
3751                    "grape": "",
3752                }
3753            }
3754        }));
3755
3756        let root_link_path = dir.path().join("root_link");
3757        unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
3758        unix::fs::symlink(
3759            &dir.path().join("root/fennel"),
3760            &dir.path().join("root/finnochio"),
3761        )
3762        .unwrap();
3763
3764        let project = Project::test(Arc::new(RealFs), cx);
3765
3766        let (tree, _) = project
3767            .update(cx, |project, cx| {
3768                project.find_or_create_local_worktree(&root_link_path, true, cx)
3769            })
3770            .await
3771            .unwrap();
3772
3773        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3774            .await;
3775        cx.read(|cx| {
3776            let tree = tree.read(cx);
3777            assert_eq!(tree.file_count(), 5);
3778            assert_eq!(
3779                tree.inode_for_path("fennel/grape"),
3780                tree.inode_for_path("finnochio/grape")
3781            );
3782        });
3783
3784        let cancel_flag = Default::default();
3785        let results = project
3786            .read_with(cx, |project, cx| {
3787                project.match_paths("bna", false, false, 10, &cancel_flag, cx)
3788            })
3789            .await;
3790        assert_eq!(
3791            results
3792                .into_iter()
3793                .map(|result| result.path)
3794                .collect::<Vec<Arc<Path>>>(),
3795            vec![
3796                PathBuf::from("banana/carrot/date").into(),
3797                PathBuf::from("banana/carrot/endive").into(),
3798            ]
3799        );
3800    }
3801
3802    #[gpui::test]
3803    async fn test_language_server_diagnostics(cx: &mut gpui::TestAppContext) {
3804        let (language_server_config, mut fake_servers) = LanguageServerConfig::fake();
3805        let progress_token = language_server_config
3806            .disk_based_diagnostics_progress_token
3807            .clone()
3808            .unwrap();
3809
3810        let language = Arc::new(Language::new(
3811            LanguageConfig {
3812                name: "Rust".into(),
3813                path_suffixes: vec!["rs".to_string()],
3814                language_server: Some(language_server_config),
3815                ..Default::default()
3816            },
3817            Some(tree_sitter_rust::language()),
3818        ));
3819
3820        let fs = FakeFs::new(cx.background());
3821        fs.insert_tree(
3822            "/dir",
3823            json!({
3824                "a.rs": "fn a() { A }",
3825                "b.rs": "const y: i32 = 1",
3826            }),
3827        )
3828        .await;
3829
3830        let project = Project::test(fs, cx);
3831        project.update(cx, |project, _| {
3832            Arc::get_mut(&mut project.languages).unwrap().add(language);
3833        });
3834
3835        let (tree, _) = project
3836            .update(cx, |project, cx| {
3837                project.find_or_create_local_worktree("/dir", true, cx)
3838            })
3839            .await
3840            .unwrap();
3841        let worktree_id = tree.read_with(cx, |tree, _| tree.id());
3842
3843        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3844            .await;
3845
3846        // Cause worktree to start the fake language server
3847        let _buffer = project
3848            .update(cx, |project, cx| {
3849                project.open_buffer((worktree_id, Path::new("b.rs")), cx)
3850            })
3851            .await
3852            .unwrap();
3853
3854        let mut events = subscribe(&project, cx);
3855
3856        let mut fake_server = fake_servers.next().await.unwrap();
3857        fake_server.start_progress(&progress_token).await;
3858        assert_eq!(
3859            events.next().await.unwrap(),
3860            Event::DiskBasedDiagnosticsStarted
3861        );
3862
3863        fake_server.start_progress(&progress_token).await;
3864        fake_server.end_progress(&progress_token).await;
3865        fake_server.start_progress(&progress_token).await;
3866
3867        fake_server
3868            .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
3869                uri: Url::from_file_path("/dir/a.rs").unwrap(),
3870                version: None,
3871                diagnostics: vec![lsp::Diagnostic {
3872                    range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
3873                    severity: Some(lsp::DiagnosticSeverity::ERROR),
3874                    message: "undefined variable 'A'".to_string(),
3875                    ..Default::default()
3876                }],
3877            })
3878            .await;
3879        assert_eq!(
3880            events.next().await.unwrap(),
3881            Event::DiagnosticsUpdated((worktree_id, Path::new("a.rs")).into())
3882        );
3883
3884        fake_server.end_progress(&progress_token).await;
3885        fake_server.end_progress(&progress_token).await;
3886        assert_eq!(
3887            events.next().await.unwrap(),
3888            Event::DiskBasedDiagnosticsUpdated
3889        );
3890        assert_eq!(
3891            events.next().await.unwrap(),
3892            Event::DiskBasedDiagnosticsFinished
3893        );
3894
3895        let buffer = project
3896            .update(cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
3897            .await
3898            .unwrap();
3899
3900        buffer.read_with(cx, |buffer, _| {
3901            let snapshot = buffer.snapshot();
3902            let diagnostics = snapshot
3903                .diagnostics_in_range::<_, Point>(0..buffer.len())
3904                .collect::<Vec<_>>();
3905            assert_eq!(
3906                diagnostics,
3907                &[DiagnosticEntry {
3908                    range: Point::new(0, 9)..Point::new(0, 10),
3909                    diagnostic: Diagnostic {
3910                        severity: lsp::DiagnosticSeverity::ERROR,
3911                        message: "undefined variable 'A'".to_string(),
3912                        group_id: 0,
3913                        is_primary: true,
3914                        ..Default::default()
3915                    }
3916                }]
3917            )
3918        });
3919    }
3920
3921    #[gpui::test]
3922    async fn test_search_worktree_without_files(cx: &mut gpui::TestAppContext) {
3923        let dir = temp_tree(json!({
3924            "root": {
3925                "dir1": {},
3926                "dir2": {
3927                    "dir3": {}
3928                }
3929            }
3930        }));
3931
3932        let project = Project::test(Arc::new(RealFs), cx);
3933        let (tree, _) = project
3934            .update(cx, |project, cx| {
3935                project.find_or_create_local_worktree(&dir.path(), true, cx)
3936            })
3937            .await
3938            .unwrap();
3939
3940        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3941            .await;
3942
3943        let cancel_flag = Default::default();
3944        let results = project
3945            .read_with(cx, |project, cx| {
3946                project.match_paths("dir", false, false, 10, &cancel_flag, cx)
3947            })
3948            .await;
3949
3950        assert!(results.is_empty());
3951    }
3952
3953    #[gpui::test]
3954    async fn test_definition(cx: &mut gpui::TestAppContext) {
3955        let (language_server_config, mut fake_servers) = LanguageServerConfig::fake();
3956        let language = Arc::new(Language::new(
3957            LanguageConfig {
3958                name: "Rust".into(),
3959                path_suffixes: vec!["rs".to_string()],
3960                language_server: Some(language_server_config),
3961                ..Default::default()
3962            },
3963            Some(tree_sitter_rust::language()),
3964        ));
3965
3966        let fs = FakeFs::new(cx.background());
3967        fs.insert_tree(
3968            "/dir",
3969            json!({
3970                "a.rs": "const fn a() { A }",
3971                "b.rs": "const y: i32 = crate::a()",
3972            }),
3973        )
3974        .await;
3975
3976        let project = Project::test(fs, cx);
3977        project.update(cx, |project, _| {
3978            Arc::get_mut(&mut project.languages).unwrap().add(language);
3979        });
3980
3981        let (tree, _) = project
3982            .update(cx, |project, cx| {
3983                project.find_or_create_local_worktree("/dir/b.rs", true, cx)
3984            })
3985            .await
3986            .unwrap();
3987        let worktree_id = tree.read_with(cx, |tree, _| tree.id());
3988        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3989            .await;
3990
3991        let buffer = project
3992            .update(cx, |project, cx| {
3993                project.open_buffer(
3994                    ProjectPath {
3995                        worktree_id,
3996                        path: Path::new("").into(),
3997                    },
3998                    cx,
3999                )
4000            })
4001            .await
4002            .unwrap();
4003
4004        let mut fake_server = fake_servers.next().await.unwrap();
4005        fake_server.handle_request::<lsp::request::GotoDefinition, _>(move |params, _| {
4006            let params = params.text_document_position_params;
4007            assert_eq!(
4008                params.text_document.uri.to_file_path().unwrap(),
4009                Path::new("/dir/b.rs"),
4010            );
4011            assert_eq!(params.position, lsp::Position::new(0, 22));
4012
4013            Some(lsp::GotoDefinitionResponse::Scalar(lsp::Location::new(
4014                lsp::Url::from_file_path("/dir/a.rs").unwrap(),
4015                lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
4016            )))
4017        });
4018
4019        let mut definitions = project
4020            .update(cx, |project, cx| project.definition(&buffer, 22, cx))
4021            .await
4022            .unwrap();
4023
4024        assert_eq!(definitions.len(), 1);
4025        let definition = definitions.pop().unwrap();
4026        cx.update(|cx| {
4027            let target_buffer = definition.buffer.read(cx);
4028            assert_eq!(
4029                target_buffer
4030                    .file()
4031                    .unwrap()
4032                    .as_local()
4033                    .unwrap()
4034                    .abs_path(cx),
4035                Path::new("/dir/a.rs"),
4036            );
4037            assert_eq!(definition.range.to_offset(target_buffer), 9..10);
4038            assert_eq!(
4039                list_worktrees(&project, cx),
4040                [("/dir/b.rs".as_ref(), true), ("/dir/a.rs".as_ref(), false)]
4041            );
4042
4043            drop(definition);
4044        });
4045        cx.read(|cx| {
4046            assert_eq!(list_worktrees(&project, cx), [("/dir/b.rs".as_ref(), true)]);
4047        });
4048
4049        fn list_worktrees<'a>(
4050            project: &'a ModelHandle<Project>,
4051            cx: &'a AppContext,
4052        ) -> Vec<(&'a Path, bool)> {
4053            project
4054                .read(cx)
4055                .worktrees(cx)
4056                .map(|worktree| {
4057                    let worktree = worktree.read(cx);
4058                    (
4059                        worktree.as_local().unwrap().abs_path().as_ref(),
4060                        worktree.is_visible(),
4061                    )
4062                })
4063                .collect::<Vec<_>>()
4064        }
4065    }
4066
4067    #[gpui::test]
4068    async fn test_save_file(cx: &mut gpui::TestAppContext) {
4069        let fs = FakeFs::new(cx.background());
4070        fs.insert_tree(
4071            "/dir",
4072            json!({
4073                "file1": "the old contents",
4074            }),
4075        )
4076        .await;
4077
4078        let project = Project::test(fs.clone(), cx);
4079        let worktree_id = project
4080            .update(cx, |p, cx| {
4081                p.find_or_create_local_worktree("/dir", true, cx)
4082            })
4083            .await
4084            .unwrap()
4085            .0
4086            .read_with(cx, |tree, _| tree.id());
4087
4088        let buffer = project
4089            .update(cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
4090            .await
4091            .unwrap();
4092        buffer
4093            .update(cx, |buffer, cx| {
4094                assert_eq!(buffer.text(), "the old contents");
4095                buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
4096                buffer.save(cx)
4097            })
4098            .await
4099            .unwrap();
4100
4101        let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
4102        assert_eq!(new_text, buffer.read_with(cx, |buffer, _| buffer.text()));
4103    }
4104
4105    #[gpui::test]
4106    async fn test_save_in_single_file_worktree(cx: &mut gpui::TestAppContext) {
4107        let fs = FakeFs::new(cx.background());
4108        fs.insert_tree(
4109            "/dir",
4110            json!({
4111                "file1": "the old contents",
4112            }),
4113        )
4114        .await;
4115
4116        let project = Project::test(fs.clone(), cx);
4117        let worktree_id = project
4118            .update(cx, |p, cx| {
4119                p.find_or_create_local_worktree("/dir/file1", true, cx)
4120            })
4121            .await
4122            .unwrap()
4123            .0
4124            .read_with(cx, |tree, _| tree.id());
4125
4126        let buffer = project
4127            .update(cx, |p, cx| p.open_buffer((worktree_id, ""), cx))
4128            .await
4129            .unwrap();
4130        buffer
4131            .update(cx, |buffer, cx| {
4132                buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
4133                buffer.save(cx)
4134            })
4135            .await
4136            .unwrap();
4137
4138        let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
4139        assert_eq!(new_text, buffer.read_with(cx, |buffer, _| buffer.text()));
4140    }
4141
4142    #[gpui::test(retries = 5)]
4143    async fn test_rescan_and_remote_updates(cx: &mut gpui::TestAppContext) {
4144        let dir = temp_tree(json!({
4145            "a": {
4146                "file1": "",
4147                "file2": "",
4148                "file3": "",
4149            },
4150            "b": {
4151                "c": {
4152                    "file4": "",
4153                    "file5": "",
4154                }
4155            }
4156        }));
4157
4158        let project = Project::test(Arc::new(RealFs), cx);
4159        let rpc = project.read_with(cx, |p, _| p.client.clone());
4160
4161        let (tree, _) = project
4162            .update(cx, |p, cx| {
4163                p.find_or_create_local_worktree(dir.path(), true, cx)
4164            })
4165            .await
4166            .unwrap();
4167        let worktree_id = tree.read_with(cx, |tree, _| tree.id());
4168
4169        let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
4170            let buffer = project.update(cx, |p, cx| p.open_buffer((worktree_id, path), cx));
4171            async move { buffer.await.unwrap() }
4172        };
4173        let id_for_path = |path: &'static str, cx: &gpui::TestAppContext| {
4174            tree.read_with(cx, |tree, _| {
4175                tree.entry_for_path(path)
4176                    .expect(&format!("no entry for path {}", path))
4177                    .id
4178            })
4179        };
4180
4181        let buffer2 = buffer_for_path("a/file2", cx).await;
4182        let buffer3 = buffer_for_path("a/file3", cx).await;
4183        let buffer4 = buffer_for_path("b/c/file4", cx).await;
4184        let buffer5 = buffer_for_path("b/c/file5", cx).await;
4185
4186        let file2_id = id_for_path("a/file2", &cx);
4187        let file3_id = id_for_path("a/file3", &cx);
4188        let file4_id = id_for_path("b/c/file4", &cx);
4189
4190        // Wait for the initial scan.
4191        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4192            .await;
4193
4194        // Create a remote copy of this worktree.
4195        let initial_snapshot = tree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
4196        let (remote, load_task) = cx.update(|cx| {
4197            Worktree::remote(
4198                1,
4199                1,
4200                initial_snapshot.to_proto(&Default::default(), true),
4201                rpc.clone(),
4202                cx,
4203            )
4204        });
4205        load_task.await;
4206
4207        cx.read(|cx| {
4208            assert!(!buffer2.read(cx).is_dirty());
4209            assert!(!buffer3.read(cx).is_dirty());
4210            assert!(!buffer4.read(cx).is_dirty());
4211            assert!(!buffer5.read(cx).is_dirty());
4212        });
4213
4214        // Rename and delete files and directories.
4215        tree.flush_fs_events(&cx).await;
4216        std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
4217        std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
4218        std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
4219        std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
4220        tree.flush_fs_events(&cx).await;
4221
4222        let expected_paths = vec![
4223            "a",
4224            "a/file1",
4225            "a/file2.new",
4226            "b",
4227            "d",
4228            "d/file3",
4229            "d/file4",
4230        ];
4231
4232        cx.read(|app| {
4233            assert_eq!(
4234                tree.read(app)
4235                    .paths()
4236                    .map(|p| p.to_str().unwrap())
4237                    .collect::<Vec<_>>(),
4238                expected_paths
4239            );
4240
4241            assert_eq!(id_for_path("a/file2.new", &cx), file2_id);
4242            assert_eq!(id_for_path("d/file3", &cx), file3_id);
4243            assert_eq!(id_for_path("d/file4", &cx), file4_id);
4244
4245            assert_eq!(
4246                buffer2.read(app).file().unwrap().path().as_ref(),
4247                Path::new("a/file2.new")
4248            );
4249            assert_eq!(
4250                buffer3.read(app).file().unwrap().path().as_ref(),
4251                Path::new("d/file3")
4252            );
4253            assert_eq!(
4254                buffer4.read(app).file().unwrap().path().as_ref(),
4255                Path::new("d/file4")
4256            );
4257            assert_eq!(
4258                buffer5.read(app).file().unwrap().path().as_ref(),
4259                Path::new("b/c/file5")
4260            );
4261
4262            assert!(!buffer2.read(app).file().unwrap().is_deleted());
4263            assert!(!buffer3.read(app).file().unwrap().is_deleted());
4264            assert!(!buffer4.read(app).file().unwrap().is_deleted());
4265            assert!(buffer5.read(app).file().unwrap().is_deleted());
4266        });
4267
4268        // Update the remote worktree. Check that it becomes consistent with the
4269        // local worktree.
4270        remote.update(cx, |remote, cx| {
4271            let update_message = tree.read(cx).as_local().unwrap().snapshot().build_update(
4272                &initial_snapshot,
4273                1,
4274                1,
4275                true,
4276            );
4277            remote
4278                .as_remote_mut()
4279                .unwrap()
4280                .snapshot
4281                .apply_remote_update(update_message)
4282                .unwrap();
4283
4284            assert_eq!(
4285                remote
4286                    .paths()
4287                    .map(|p| p.to_str().unwrap())
4288                    .collect::<Vec<_>>(),
4289                expected_paths
4290            );
4291        });
4292    }
4293
4294    #[gpui::test]
4295    async fn test_buffer_deduping(cx: &mut gpui::TestAppContext) {
4296        let fs = FakeFs::new(cx.background());
4297        fs.insert_tree(
4298            "/the-dir",
4299            json!({
4300                "a.txt": "a-contents",
4301                "b.txt": "b-contents",
4302            }),
4303        )
4304        .await;
4305
4306        let project = Project::test(fs.clone(), cx);
4307        let worktree_id = project
4308            .update(cx, |p, cx| {
4309                p.find_or_create_local_worktree("/the-dir", true, cx)
4310            })
4311            .await
4312            .unwrap()
4313            .0
4314            .read_with(cx, |tree, _| tree.id());
4315
4316        // Spawn multiple tasks to open paths, repeating some paths.
4317        let (buffer_a_1, buffer_b, buffer_a_2) = project.update(cx, |p, cx| {
4318            (
4319                p.open_buffer((worktree_id, "a.txt"), cx),
4320                p.open_buffer((worktree_id, "b.txt"), cx),
4321                p.open_buffer((worktree_id, "a.txt"), cx),
4322            )
4323        });
4324
4325        let buffer_a_1 = buffer_a_1.await.unwrap();
4326        let buffer_a_2 = buffer_a_2.await.unwrap();
4327        let buffer_b = buffer_b.await.unwrap();
4328        assert_eq!(buffer_a_1.read_with(cx, |b, _| b.text()), "a-contents");
4329        assert_eq!(buffer_b.read_with(cx, |b, _| b.text()), "b-contents");
4330
4331        // There is only one buffer per path.
4332        let buffer_a_id = buffer_a_1.id();
4333        assert_eq!(buffer_a_2.id(), buffer_a_id);
4334
4335        // Open the same path again while it is still open.
4336        drop(buffer_a_1);
4337        let buffer_a_3 = project
4338            .update(cx, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
4339            .await
4340            .unwrap();
4341
4342        // There's still only one buffer per path.
4343        assert_eq!(buffer_a_3.id(), buffer_a_id);
4344    }
4345
4346    #[gpui::test]
4347    async fn test_buffer_is_dirty(cx: &mut gpui::TestAppContext) {
4348        use std::fs;
4349
4350        let dir = temp_tree(json!({
4351            "file1": "abc",
4352            "file2": "def",
4353            "file3": "ghi",
4354        }));
4355
4356        let project = Project::test(Arc::new(RealFs), cx);
4357        let (worktree, _) = project
4358            .update(cx, |p, cx| {
4359                p.find_or_create_local_worktree(dir.path(), true, cx)
4360            })
4361            .await
4362            .unwrap();
4363        let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
4364
4365        worktree.flush_fs_events(&cx).await;
4366        worktree
4367            .read_with(cx, |t, _| t.as_local().unwrap().scan_complete())
4368            .await;
4369
4370        let buffer1 = project
4371            .update(cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
4372            .await
4373            .unwrap();
4374        let events = Rc::new(RefCell::new(Vec::new()));
4375
4376        // initially, the buffer isn't dirty.
4377        buffer1.update(cx, |buffer, cx| {
4378            cx.subscribe(&buffer1, {
4379                let events = events.clone();
4380                move |_, _, event, _| events.borrow_mut().push(event.clone())
4381            })
4382            .detach();
4383
4384            assert!(!buffer.is_dirty());
4385            assert!(events.borrow().is_empty());
4386
4387            buffer.edit(vec![1..2], "", cx);
4388        });
4389
4390        // after the first edit, the buffer is dirty, and emits a dirtied event.
4391        buffer1.update(cx, |buffer, cx| {
4392            assert!(buffer.text() == "ac");
4393            assert!(buffer.is_dirty());
4394            assert_eq!(
4395                *events.borrow(),
4396                &[language::Event::Edited, language::Event::Dirtied]
4397            );
4398            events.borrow_mut().clear();
4399            buffer.did_save(buffer.version(), buffer.file().unwrap().mtime(), None, cx);
4400        });
4401
4402        // after saving, the buffer is not dirty, and emits a saved event.
4403        buffer1.update(cx, |buffer, cx| {
4404            assert!(!buffer.is_dirty());
4405            assert_eq!(*events.borrow(), &[language::Event::Saved]);
4406            events.borrow_mut().clear();
4407
4408            buffer.edit(vec![1..1], "B", cx);
4409            buffer.edit(vec![2..2], "D", cx);
4410        });
4411
4412        // after editing again, the buffer is dirty, and emits another dirty event.
4413        buffer1.update(cx, |buffer, cx| {
4414            assert!(buffer.text() == "aBDc");
4415            assert!(buffer.is_dirty());
4416            assert_eq!(
4417                *events.borrow(),
4418                &[
4419                    language::Event::Edited,
4420                    language::Event::Dirtied,
4421                    language::Event::Edited,
4422                ],
4423            );
4424            events.borrow_mut().clear();
4425
4426            // TODO - currently, after restoring the buffer to its
4427            // previously-saved state, the is still considered dirty.
4428            buffer.edit([1..3], "", cx);
4429            assert!(buffer.text() == "ac");
4430            assert!(buffer.is_dirty());
4431        });
4432
4433        assert_eq!(*events.borrow(), &[language::Event::Edited]);
4434
4435        // When a file is deleted, the buffer is considered dirty.
4436        let events = Rc::new(RefCell::new(Vec::new()));
4437        let buffer2 = project
4438            .update(cx, |p, cx| p.open_buffer((worktree_id, "file2"), cx))
4439            .await
4440            .unwrap();
4441        buffer2.update(cx, |_, cx| {
4442            cx.subscribe(&buffer2, {
4443                let events = events.clone();
4444                move |_, _, event, _| events.borrow_mut().push(event.clone())
4445            })
4446            .detach();
4447        });
4448
4449        fs::remove_file(dir.path().join("file2")).unwrap();
4450        buffer2.condition(&cx, |b, _| b.is_dirty()).await;
4451        assert_eq!(
4452            *events.borrow(),
4453            &[language::Event::Dirtied, language::Event::FileHandleChanged]
4454        );
4455
4456        // When a file is already dirty when deleted, we don't emit a Dirtied event.
4457        let events = Rc::new(RefCell::new(Vec::new()));
4458        let buffer3 = project
4459            .update(cx, |p, cx| p.open_buffer((worktree_id, "file3"), cx))
4460            .await
4461            .unwrap();
4462        buffer3.update(cx, |_, cx| {
4463            cx.subscribe(&buffer3, {
4464                let events = events.clone();
4465                move |_, _, event, _| events.borrow_mut().push(event.clone())
4466            })
4467            .detach();
4468        });
4469
4470        worktree.flush_fs_events(&cx).await;
4471        buffer3.update(cx, |buffer, cx| {
4472            buffer.edit(Some(0..0), "x", cx);
4473        });
4474        events.borrow_mut().clear();
4475        fs::remove_file(dir.path().join("file3")).unwrap();
4476        buffer3
4477            .condition(&cx, |_, _| !events.borrow().is_empty())
4478            .await;
4479        assert_eq!(*events.borrow(), &[language::Event::FileHandleChanged]);
4480        cx.read(|cx| assert!(buffer3.read(cx).is_dirty()));
4481    }
4482
4483    #[gpui::test]
4484    async fn test_buffer_file_changes_on_disk(cx: &mut gpui::TestAppContext) {
4485        use std::fs;
4486
4487        let initial_contents = "aaa\nbbbbb\nc\n";
4488        let dir = temp_tree(json!({ "the-file": initial_contents }));
4489
4490        let project = Project::test(Arc::new(RealFs), cx);
4491        let (worktree, _) = project
4492            .update(cx, |p, cx| {
4493                p.find_or_create_local_worktree(dir.path(), true, cx)
4494            })
4495            .await
4496            .unwrap();
4497        let worktree_id = worktree.read_with(cx, |tree, _| tree.id());
4498
4499        worktree
4500            .read_with(cx, |t, _| t.as_local().unwrap().scan_complete())
4501            .await;
4502
4503        let abs_path = dir.path().join("the-file");
4504        let buffer = project
4505            .update(cx, |p, cx| p.open_buffer((worktree_id, "the-file"), cx))
4506            .await
4507            .unwrap();
4508
4509        // TODO
4510        // Add a cursor on each row.
4511        // let selection_set_id = buffer.update(&mut cx, |buffer, cx| {
4512        //     assert!(!buffer.is_dirty());
4513        //     buffer.add_selection_set(
4514        //         &(0..3)
4515        //             .map(|row| Selection {
4516        //                 id: row as usize,
4517        //                 start: Point::new(row, 1),
4518        //                 end: Point::new(row, 1),
4519        //                 reversed: false,
4520        //                 goal: SelectionGoal::None,
4521        //             })
4522        //             .collect::<Vec<_>>(),
4523        //         cx,
4524        //     )
4525        // });
4526
4527        // Change the file on disk, adding two new lines of text, and removing
4528        // one line.
4529        buffer.read_with(cx, |buffer, _| {
4530            assert!(!buffer.is_dirty());
4531            assert!(!buffer.has_conflict());
4532        });
4533        let new_contents = "AAAA\naaa\nBB\nbbbbb\n";
4534        fs::write(&abs_path, new_contents).unwrap();
4535
4536        // Because the buffer was not modified, it is reloaded from disk. Its
4537        // contents are edited according to the diff between the old and new
4538        // file contents.
4539        buffer
4540            .condition(&cx, |buffer, _| buffer.text() == new_contents)
4541            .await;
4542
4543        buffer.update(cx, |buffer, _| {
4544            assert_eq!(buffer.text(), new_contents);
4545            assert!(!buffer.is_dirty());
4546            assert!(!buffer.has_conflict());
4547
4548            // TODO
4549            // let cursor_positions = buffer
4550            //     .selection_set(selection_set_id)
4551            //     .unwrap()
4552            //     .selections::<Point>(&*buffer)
4553            //     .map(|selection| {
4554            //         assert_eq!(selection.start, selection.end);
4555            //         selection.start
4556            //     })
4557            //     .collect::<Vec<_>>();
4558            // assert_eq!(
4559            //     cursor_positions,
4560            //     [Point::new(1, 1), Point::new(3, 1), Point::new(4, 0)]
4561            // );
4562        });
4563
4564        // Modify the buffer
4565        buffer.update(cx, |buffer, cx| {
4566            buffer.edit(vec![0..0], " ", cx);
4567            assert!(buffer.is_dirty());
4568            assert!(!buffer.has_conflict());
4569        });
4570
4571        // Change the file on disk again, adding blank lines to the beginning.
4572        fs::write(&abs_path, "\n\n\nAAAA\naaa\nBB\nbbbbb\n").unwrap();
4573
4574        // Because the buffer is modified, it doesn't reload from disk, but is
4575        // marked as having a conflict.
4576        buffer
4577            .condition(&cx, |buffer, _| buffer.has_conflict())
4578            .await;
4579    }
4580
4581    #[gpui::test]
4582    async fn test_grouped_diagnostics(cx: &mut gpui::TestAppContext) {
4583        let fs = FakeFs::new(cx.background());
4584        fs.insert_tree(
4585            "/the-dir",
4586            json!({
4587                "a.rs": "
4588                    fn foo(mut v: Vec<usize>) {
4589                        for x in &v {
4590                            v.push(1);
4591                        }
4592                    }
4593                "
4594                .unindent(),
4595            }),
4596        )
4597        .await;
4598
4599        let project = Project::test(fs.clone(), cx);
4600        let (worktree, _) = project
4601            .update(cx, |p, cx| {
4602                p.find_or_create_local_worktree("/the-dir", true, cx)
4603            })
4604            .await
4605            .unwrap();
4606        let worktree_id = worktree.read_with(cx, |tree, _| tree.id());
4607
4608        let buffer = project
4609            .update(cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
4610            .await
4611            .unwrap();
4612
4613        let buffer_uri = Url::from_file_path("/the-dir/a.rs").unwrap();
4614        let message = lsp::PublishDiagnosticsParams {
4615            uri: buffer_uri.clone(),
4616            diagnostics: vec![
4617                lsp::Diagnostic {
4618                    range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
4619                    severity: Some(DiagnosticSeverity::WARNING),
4620                    message: "error 1".to_string(),
4621                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
4622                        location: lsp::Location {
4623                            uri: buffer_uri.clone(),
4624                            range: lsp::Range::new(
4625                                lsp::Position::new(1, 8),
4626                                lsp::Position::new(1, 9),
4627                            ),
4628                        },
4629                        message: "error 1 hint 1".to_string(),
4630                    }]),
4631                    ..Default::default()
4632                },
4633                lsp::Diagnostic {
4634                    range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
4635                    severity: Some(DiagnosticSeverity::HINT),
4636                    message: "error 1 hint 1".to_string(),
4637                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
4638                        location: lsp::Location {
4639                            uri: buffer_uri.clone(),
4640                            range: lsp::Range::new(
4641                                lsp::Position::new(1, 8),
4642                                lsp::Position::new(1, 9),
4643                            ),
4644                        },
4645                        message: "original diagnostic".to_string(),
4646                    }]),
4647                    ..Default::default()
4648                },
4649                lsp::Diagnostic {
4650                    range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
4651                    severity: Some(DiagnosticSeverity::ERROR),
4652                    message: "error 2".to_string(),
4653                    related_information: Some(vec![
4654                        lsp::DiagnosticRelatedInformation {
4655                            location: lsp::Location {
4656                                uri: buffer_uri.clone(),
4657                                range: lsp::Range::new(
4658                                    lsp::Position::new(1, 13),
4659                                    lsp::Position::new(1, 15),
4660                                ),
4661                            },
4662                            message: "error 2 hint 1".to_string(),
4663                        },
4664                        lsp::DiagnosticRelatedInformation {
4665                            location: lsp::Location {
4666                                uri: buffer_uri.clone(),
4667                                range: lsp::Range::new(
4668                                    lsp::Position::new(1, 13),
4669                                    lsp::Position::new(1, 15),
4670                                ),
4671                            },
4672                            message: "error 2 hint 2".to_string(),
4673                        },
4674                    ]),
4675                    ..Default::default()
4676                },
4677                lsp::Diagnostic {
4678                    range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
4679                    severity: Some(DiagnosticSeverity::HINT),
4680                    message: "error 2 hint 1".to_string(),
4681                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
4682                        location: lsp::Location {
4683                            uri: buffer_uri.clone(),
4684                            range: lsp::Range::new(
4685                                lsp::Position::new(2, 8),
4686                                lsp::Position::new(2, 17),
4687                            ),
4688                        },
4689                        message: "original diagnostic".to_string(),
4690                    }]),
4691                    ..Default::default()
4692                },
4693                lsp::Diagnostic {
4694                    range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
4695                    severity: Some(DiagnosticSeverity::HINT),
4696                    message: "error 2 hint 2".to_string(),
4697                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
4698                        location: lsp::Location {
4699                            uri: buffer_uri.clone(),
4700                            range: lsp::Range::new(
4701                                lsp::Position::new(2, 8),
4702                                lsp::Position::new(2, 17),
4703                            ),
4704                        },
4705                        message: "original diagnostic".to_string(),
4706                    }]),
4707                    ..Default::default()
4708                },
4709            ],
4710            version: None,
4711        };
4712
4713        project
4714            .update(cx, |p, cx| {
4715                p.update_diagnostics(message, &Default::default(), cx)
4716            })
4717            .unwrap();
4718        let buffer = buffer.read_with(cx, |buffer, _| buffer.snapshot());
4719
4720        assert_eq!(
4721            buffer
4722                .diagnostics_in_range::<_, Point>(0..buffer.len())
4723                .collect::<Vec<_>>(),
4724            &[
4725                DiagnosticEntry {
4726                    range: Point::new(1, 8)..Point::new(1, 9),
4727                    diagnostic: Diagnostic {
4728                        severity: DiagnosticSeverity::WARNING,
4729                        message: "error 1".to_string(),
4730                        group_id: 0,
4731                        is_primary: true,
4732                        ..Default::default()
4733                    }
4734                },
4735                DiagnosticEntry {
4736                    range: Point::new(1, 8)..Point::new(1, 9),
4737                    diagnostic: Diagnostic {
4738                        severity: DiagnosticSeverity::HINT,
4739                        message: "error 1 hint 1".to_string(),
4740                        group_id: 0,
4741                        is_primary: false,
4742                        ..Default::default()
4743                    }
4744                },
4745                DiagnosticEntry {
4746                    range: Point::new(1, 13)..Point::new(1, 15),
4747                    diagnostic: Diagnostic {
4748                        severity: DiagnosticSeverity::HINT,
4749                        message: "error 2 hint 1".to_string(),
4750                        group_id: 1,
4751                        is_primary: false,
4752                        ..Default::default()
4753                    }
4754                },
4755                DiagnosticEntry {
4756                    range: Point::new(1, 13)..Point::new(1, 15),
4757                    diagnostic: Diagnostic {
4758                        severity: DiagnosticSeverity::HINT,
4759                        message: "error 2 hint 2".to_string(),
4760                        group_id: 1,
4761                        is_primary: false,
4762                        ..Default::default()
4763                    }
4764                },
4765                DiagnosticEntry {
4766                    range: Point::new(2, 8)..Point::new(2, 17),
4767                    diagnostic: Diagnostic {
4768                        severity: DiagnosticSeverity::ERROR,
4769                        message: "error 2".to_string(),
4770                        group_id: 1,
4771                        is_primary: true,
4772                        ..Default::default()
4773                    }
4774                }
4775            ]
4776        );
4777
4778        assert_eq!(
4779            buffer.diagnostic_group::<Point>(0).collect::<Vec<_>>(),
4780            &[
4781                DiagnosticEntry {
4782                    range: Point::new(1, 8)..Point::new(1, 9),
4783                    diagnostic: Diagnostic {
4784                        severity: DiagnosticSeverity::WARNING,
4785                        message: "error 1".to_string(),
4786                        group_id: 0,
4787                        is_primary: true,
4788                        ..Default::default()
4789                    }
4790                },
4791                DiagnosticEntry {
4792                    range: Point::new(1, 8)..Point::new(1, 9),
4793                    diagnostic: Diagnostic {
4794                        severity: DiagnosticSeverity::HINT,
4795                        message: "error 1 hint 1".to_string(),
4796                        group_id: 0,
4797                        is_primary: false,
4798                        ..Default::default()
4799                    }
4800                },
4801            ]
4802        );
4803        assert_eq!(
4804            buffer.diagnostic_group::<Point>(1).collect::<Vec<_>>(),
4805            &[
4806                DiagnosticEntry {
4807                    range: Point::new(1, 13)..Point::new(1, 15),
4808                    diagnostic: Diagnostic {
4809                        severity: DiagnosticSeverity::HINT,
4810                        message: "error 2 hint 1".to_string(),
4811                        group_id: 1,
4812                        is_primary: false,
4813                        ..Default::default()
4814                    }
4815                },
4816                DiagnosticEntry {
4817                    range: Point::new(1, 13)..Point::new(1, 15),
4818                    diagnostic: Diagnostic {
4819                        severity: DiagnosticSeverity::HINT,
4820                        message: "error 2 hint 2".to_string(),
4821                        group_id: 1,
4822                        is_primary: false,
4823                        ..Default::default()
4824                    }
4825                },
4826                DiagnosticEntry {
4827                    range: Point::new(2, 8)..Point::new(2, 17),
4828                    diagnostic: Diagnostic {
4829                        severity: DiagnosticSeverity::ERROR,
4830                        message: "error 2".to_string(),
4831                        group_id: 1,
4832                        is_primary: true,
4833                        ..Default::default()
4834                    }
4835                }
4836            ]
4837        );
4838    }
4839
4840    #[gpui::test]
4841    async fn test_rename(cx: &mut gpui::TestAppContext) {
4842        let (language_server_config, mut fake_servers) = LanguageServerConfig::fake();
4843        let language = Arc::new(Language::new(
4844            LanguageConfig {
4845                name: "Rust".into(),
4846                path_suffixes: vec!["rs".to_string()],
4847                language_server: Some(language_server_config),
4848                ..Default::default()
4849            },
4850            Some(tree_sitter_rust::language()),
4851        ));
4852
4853        let fs = FakeFs::new(cx.background());
4854        fs.insert_tree(
4855            "/dir",
4856            json!({
4857                "one.rs": "const ONE: usize = 1;",
4858                "two.rs": "const TWO: usize = one::ONE + one::ONE;"
4859            }),
4860        )
4861        .await;
4862
4863        let project = Project::test(fs.clone(), cx);
4864        project.update(cx, |project, _| {
4865            Arc::get_mut(&mut project.languages).unwrap().add(language);
4866        });
4867
4868        let (tree, _) = project
4869            .update(cx, |project, cx| {
4870                project.find_or_create_local_worktree("/dir", true, cx)
4871            })
4872            .await
4873            .unwrap();
4874        let worktree_id = tree.read_with(cx, |tree, _| tree.id());
4875        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4876            .await;
4877
4878        let buffer = project
4879            .update(cx, |project, cx| {
4880                project.open_buffer((worktree_id, Path::new("one.rs")), cx)
4881            })
4882            .await
4883            .unwrap();
4884
4885        let mut fake_server = fake_servers.next().await.unwrap();
4886
4887        let response = project.update(cx, |project, cx| {
4888            project.prepare_rename(buffer.clone(), 7, cx)
4889        });
4890        fake_server
4891            .handle_request::<lsp::request::PrepareRenameRequest, _>(|params, _| {
4892                assert_eq!(params.text_document.uri.as_str(), "file:///dir/one.rs");
4893                assert_eq!(params.position, lsp::Position::new(0, 7));
4894                Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
4895                    lsp::Position::new(0, 6),
4896                    lsp::Position::new(0, 9),
4897                )))
4898            })
4899            .next()
4900            .await
4901            .unwrap();
4902        let range = response.await.unwrap().unwrap();
4903        let range = buffer.read_with(cx, |buffer, _| range.to_offset(buffer));
4904        assert_eq!(range, 6..9);
4905
4906        let response = project.update(cx, |project, cx| {
4907            project.perform_rename(buffer.clone(), 7, "THREE".to_string(), true, cx)
4908        });
4909        fake_server
4910            .handle_request::<lsp::request::Rename, _>(|params, _| {
4911                assert_eq!(
4912                    params.text_document_position.text_document.uri.as_str(),
4913                    "file:///dir/one.rs"
4914                );
4915                assert_eq!(
4916                    params.text_document_position.position,
4917                    lsp::Position::new(0, 7)
4918                );
4919                assert_eq!(params.new_name, "THREE");
4920                Some(lsp::WorkspaceEdit {
4921                    changes: Some(
4922                        [
4923                            (
4924                                lsp::Url::from_file_path("/dir/one.rs").unwrap(),
4925                                vec![lsp::TextEdit::new(
4926                                    lsp::Range::new(
4927                                        lsp::Position::new(0, 6),
4928                                        lsp::Position::new(0, 9),
4929                                    ),
4930                                    "THREE".to_string(),
4931                                )],
4932                            ),
4933                            (
4934                                lsp::Url::from_file_path("/dir/two.rs").unwrap(),
4935                                vec![
4936                                    lsp::TextEdit::new(
4937                                        lsp::Range::new(
4938                                            lsp::Position::new(0, 24),
4939                                            lsp::Position::new(0, 27),
4940                                        ),
4941                                        "THREE".to_string(),
4942                                    ),
4943                                    lsp::TextEdit::new(
4944                                        lsp::Range::new(
4945                                            lsp::Position::new(0, 35),
4946                                            lsp::Position::new(0, 38),
4947                                        ),
4948                                        "THREE".to_string(),
4949                                    ),
4950                                ],
4951                            ),
4952                        ]
4953                        .into_iter()
4954                        .collect(),
4955                    ),
4956                    ..Default::default()
4957                })
4958            })
4959            .next()
4960            .await
4961            .unwrap();
4962        let mut transaction = response.await.unwrap().0;
4963        assert_eq!(transaction.len(), 2);
4964        assert_eq!(
4965            transaction
4966                .remove_entry(&buffer)
4967                .unwrap()
4968                .0
4969                .read_with(cx, |buffer, _| buffer.text()),
4970            "const THREE: usize = 1;"
4971        );
4972        assert_eq!(
4973            transaction
4974                .into_keys()
4975                .next()
4976                .unwrap()
4977                .read_with(cx, |buffer, _| buffer.text()),
4978            "const TWO: usize = one::THREE + one::THREE;"
4979        );
4980    }
4981
4982    #[gpui::test]
4983    async fn test_search(cx: &mut gpui::TestAppContext) {
4984        let fs = FakeFs::new(cx.background());
4985        fs.insert_tree(
4986            "/dir",
4987            json!({
4988                "one.rs": "const ONE: usize = 1;",
4989                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
4990                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
4991                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
4992            }),
4993        )
4994        .await;
4995        let project = Project::test(fs.clone(), cx);
4996        let (tree, _) = project
4997            .update(cx, |project, cx| {
4998                project.find_or_create_local_worktree("/dir", true, cx)
4999            })
5000            .await
5001            .unwrap();
5002        let worktree_id = tree.read_with(cx, |tree, _| tree.id());
5003        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5004            .await;
5005
5006        assert_eq!(
5007            search(&project, SearchQuery::text("TWO", false, true), cx)
5008                .await
5009                .unwrap(),
5010            HashMap::from_iter([
5011                ("two.rs".to_string(), vec![6..9]),
5012                ("three.rs".to_string(), vec![37..40])
5013            ])
5014        );
5015
5016        let buffer_4 = project
5017            .update(cx, |project, cx| {
5018                project.open_buffer((worktree_id, "four.rs"), cx)
5019            })
5020            .await
5021            .unwrap();
5022        buffer_4.update(cx, |buffer, cx| {
5023            buffer.edit([20..28, 31..43], "two::TWO", cx);
5024        });
5025
5026        assert_eq!(
5027            search(&project, SearchQuery::text("TWO", false, true), cx)
5028                .await
5029                .unwrap(),
5030            HashMap::from_iter([
5031                ("two.rs".to_string(), vec![6..9]),
5032                ("three.rs".to_string(), vec![37..40]),
5033                ("four.rs".to_string(), vec![25..28, 36..39])
5034            ])
5035        );
5036
5037        async fn search(
5038            project: &ModelHandle<Project>,
5039            query: SearchQuery,
5040            cx: &mut gpui::TestAppContext,
5041        ) -> Result<HashMap<String, Vec<Range<usize>>>> {
5042            let results = project
5043                .update(cx, |project, cx| project.search(query, cx))
5044                .await?;
5045
5046            Ok(results
5047                .into_iter()
5048                .map(|(buffer, ranges)| {
5049                    buffer.read_with(cx, |buffer, _| {
5050                        let path = buffer.file().unwrap().path().to_string_lossy().to_string();
5051                        let ranges = ranges
5052                            .into_iter()
5053                            .map(|range| range.to_offset(buffer))
5054                            .collect::<Vec<_>>();
5055                        (path, ranges)
5056                    })
5057                })
5058                .collect())
5059        }
5060    }
5061}