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