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            if !lang_server
1729                .capabilities()
1730                .borrow()
1731                .as_ref()
1732                .map_or(false, |capabilities| {
1733                    capabilities.code_action_provider.is_some()
1734                })
1735            {
1736                return Task::ready(Ok(Default::default()));
1737            }
1738
1739            let lsp_range = lsp::Range::new(
1740                range.start.to_point_utf16(buffer).to_lsp_position(),
1741                range.end.to_point_utf16(buffer).to_lsp_position(),
1742            );
1743            cx.foreground().spawn(async move {
1744                Ok(lang_server
1745                    .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
1746                        text_document: lsp::TextDocumentIdentifier::new(
1747                            lsp::Url::from_file_path(buffer_abs_path).unwrap(),
1748                        ),
1749                        range: lsp_range,
1750                        work_done_progress_params: Default::default(),
1751                        partial_result_params: Default::default(),
1752                        context: lsp::CodeActionContext {
1753                            diagnostics: Default::default(),
1754                            only: Some(vec![
1755                                lsp::CodeActionKind::QUICKFIX,
1756                                lsp::CodeActionKind::REFACTOR,
1757                                lsp::CodeActionKind::REFACTOR_EXTRACT,
1758                            ]),
1759                        },
1760                    })
1761                    .await?
1762                    .unwrap_or_default()
1763                    .into_iter()
1764                    .filter_map(|entry| {
1765                        if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
1766                            Some(CodeAction {
1767                                range: range.clone(),
1768                                lsp_action,
1769                            })
1770                        } else {
1771                            None
1772                        }
1773                    })
1774                    .collect())
1775            })
1776        } else if let Some(project_id) = self.remote_id() {
1777            let rpc = self.client.clone();
1778            cx.spawn_weak(|_, mut cx| async move {
1779                let response = rpc
1780                    .request(proto::GetCodeActions {
1781                        project_id,
1782                        buffer_id,
1783                        start: Some(language::proto::serialize_anchor(&range.start)),
1784                        end: Some(language::proto::serialize_anchor(&range.end)),
1785                    })
1786                    .await?;
1787
1788                buffer_handle
1789                    .update(&mut cx, |buffer, _| {
1790                        buffer.wait_for_version(response.version.into())
1791                    })
1792                    .await;
1793
1794                response
1795                    .actions
1796                    .into_iter()
1797                    .map(language::proto::deserialize_code_action)
1798                    .collect()
1799            })
1800        } else {
1801            Task::ready(Ok(Default::default()))
1802        }
1803    }
1804
1805    pub fn apply_code_action(
1806        &self,
1807        buffer_handle: ModelHandle<Buffer>,
1808        mut action: CodeAction,
1809        push_to_history: bool,
1810        cx: &mut ModelContext<Self>,
1811    ) -> Task<Result<ProjectTransaction>> {
1812        if self.is_local() {
1813            let buffer = buffer_handle.read(cx);
1814            let lang_name = if let Some(lang) = buffer.language() {
1815                lang.name().to_string()
1816            } else {
1817                return Task::ready(Ok(Default::default()));
1818            };
1819            let lang_server = if let Some(language_server) = buffer.language_server() {
1820                language_server.clone()
1821            } else {
1822                return Task::ready(Err(anyhow!("buffer does not have a language server")));
1823            };
1824            let range = action.range.to_point_utf16(buffer);
1825
1826            cx.spawn(|this, mut cx| async move {
1827                if let Some(lsp_range) = action
1828                    .lsp_action
1829                    .data
1830                    .as_mut()
1831                    .and_then(|d| d.get_mut("codeActionParams"))
1832                    .and_then(|d| d.get_mut("range"))
1833                {
1834                    *lsp_range = serde_json::to_value(&lsp::Range::new(
1835                        range.start.to_lsp_position(),
1836                        range.end.to_lsp_position(),
1837                    ))
1838                    .unwrap();
1839                    action.lsp_action = lang_server
1840                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
1841                        .await?;
1842                } else {
1843                    let actions = this
1844                        .update(&mut cx, |this, cx| {
1845                            this.code_actions(&buffer_handle, action.range, cx)
1846                        })
1847                        .await?;
1848                    action.lsp_action = actions
1849                        .into_iter()
1850                        .find(|a| a.lsp_action.title == action.lsp_action.title)
1851                        .ok_or_else(|| anyhow!("code action is outdated"))?
1852                        .lsp_action;
1853                }
1854
1855                if let Some(edit) = action.lsp_action.edit {
1856                    Self::deserialize_workspace_edit(
1857                        this,
1858                        edit,
1859                        push_to_history,
1860                        lang_name,
1861                        lang_server,
1862                        &mut cx,
1863                    )
1864                    .await
1865                } else {
1866                    Ok(ProjectTransaction::default())
1867                }
1868            })
1869        } else if let Some(project_id) = self.remote_id() {
1870            let client = self.client.clone();
1871            let request = proto::ApplyCodeAction {
1872                project_id,
1873                buffer_id: buffer_handle.read(cx).remote_id(),
1874                action: Some(language::proto::serialize_code_action(&action)),
1875            };
1876            cx.spawn(|this, mut cx| async move {
1877                let response = client
1878                    .request(request)
1879                    .await?
1880                    .transaction
1881                    .ok_or_else(|| anyhow!("missing transaction"))?;
1882                this.update(&mut cx, |this, cx| {
1883                    this.deserialize_project_transaction(response, push_to_history, cx)
1884                })
1885                .await
1886            })
1887        } else {
1888            Task::ready(Err(anyhow!("project does not have a remote id")))
1889        }
1890    }
1891
1892    async fn deserialize_workspace_edit(
1893        this: ModelHandle<Self>,
1894        edit: lsp::WorkspaceEdit,
1895        push_to_history: bool,
1896        language_name: String,
1897        language_server: Arc<LanguageServer>,
1898        cx: &mut AsyncAppContext,
1899    ) -> Result<ProjectTransaction> {
1900        let fs = this.read_with(cx, |this, _| this.fs.clone());
1901        let mut operations = Vec::new();
1902        if let Some(document_changes) = edit.document_changes {
1903            match document_changes {
1904                lsp::DocumentChanges::Edits(edits) => {
1905                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
1906                }
1907                lsp::DocumentChanges::Operations(ops) => operations = ops,
1908            }
1909        } else if let Some(changes) = edit.changes {
1910            operations.extend(changes.into_iter().map(|(uri, edits)| {
1911                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
1912                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
1913                        uri,
1914                        version: None,
1915                    },
1916                    edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
1917                })
1918            }));
1919        }
1920
1921        let mut project_transaction = ProjectTransaction::default();
1922        for operation in operations {
1923            match operation {
1924                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
1925                    let abs_path = op
1926                        .uri
1927                        .to_file_path()
1928                        .map_err(|_| anyhow!("can't convert URI to path"))?;
1929
1930                    if let Some(parent_path) = abs_path.parent() {
1931                        fs.create_dir(parent_path).await?;
1932                    }
1933                    if abs_path.ends_with("/") {
1934                        fs.create_dir(&abs_path).await?;
1935                    } else {
1936                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
1937                            .await?;
1938                    }
1939                }
1940                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
1941                    let source_abs_path = op
1942                        .old_uri
1943                        .to_file_path()
1944                        .map_err(|_| anyhow!("can't convert URI to path"))?;
1945                    let target_abs_path = op
1946                        .new_uri
1947                        .to_file_path()
1948                        .map_err(|_| anyhow!("can't convert URI to path"))?;
1949                    fs.rename(
1950                        &source_abs_path,
1951                        &target_abs_path,
1952                        op.options.map(Into::into).unwrap_or_default(),
1953                    )
1954                    .await?;
1955                }
1956                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
1957                    let abs_path = op
1958                        .uri
1959                        .to_file_path()
1960                        .map_err(|_| anyhow!("can't convert URI to path"))?;
1961                    let options = op.options.map(Into::into).unwrap_or_default();
1962                    if abs_path.ends_with("/") {
1963                        fs.remove_dir(&abs_path, options).await?;
1964                    } else {
1965                        fs.remove_file(&abs_path, options).await?;
1966                    }
1967                }
1968                lsp::DocumentChangeOperation::Edit(op) => {
1969                    let buffer_to_edit = this
1970                        .update(cx, |this, cx| {
1971                            this.open_local_buffer_via_lsp(
1972                                op.text_document.uri,
1973                                language_name.clone(),
1974                                language_server.clone(),
1975                                cx,
1976                            )
1977                        })
1978                        .await?;
1979
1980                    let edits = buffer_to_edit
1981                        .update(cx, |buffer, cx| {
1982                            let edits = op.edits.into_iter().map(|edit| match edit {
1983                                lsp::OneOf::Left(edit) => edit,
1984                                lsp::OneOf::Right(edit) => edit.text_edit,
1985                            });
1986                            buffer.edits_from_lsp(edits, op.text_document.version, cx)
1987                        })
1988                        .await?;
1989
1990                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
1991                        buffer.finalize_last_transaction();
1992                        buffer.start_transaction();
1993                        for (range, text) in edits {
1994                            buffer.edit([range], text, cx);
1995                        }
1996                        let transaction = if buffer.end_transaction(cx).is_some() {
1997                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
1998                            if !push_to_history {
1999                                buffer.forget_transaction(transaction.id);
2000                            }
2001                            Some(transaction)
2002                        } else {
2003                            None
2004                        };
2005
2006                        transaction
2007                    });
2008                    if let Some(transaction) = transaction {
2009                        project_transaction.0.insert(buffer_to_edit, transaction);
2010                    }
2011                }
2012            }
2013        }
2014
2015        Ok(project_transaction)
2016    }
2017
2018    pub fn prepare_rename<T: ToPointUtf16>(
2019        &self,
2020        buffer: ModelHandle<Buffer>,
2021        position: T,
2022        cx: &mut ModelContext<Self>,
2023    ) -> Task<Result<Option<Range<Anchor>>>> {
2024        let position = position.to_point_utf16(buffer.read(cx));
2025        self.request_lsp(buffer, PrepareRename { position }, cx)
2026    }
2027
2028    pub fn perform_rename<T: ToPointUtf16>(
2029        &self,
2030        buffer: ModelHandle<Buffer>,
2031        position: T,
2032        new_name: String,
2033        push_to_history: bool,
2034        cx: &mut ModelContext<Self>,
2035    ) -> Task<Result<ProjectTransaction>> {
2036        let position = position.to_point_utf16(buffer.read(cx));
2037        self.request_lsp(
2038            buffer,
2039            PerformRename {
2040                position,
2041                new_name,
2042                push_to_history,
2043            },
2044            cx,
2045        )
2046    }
2047
2048    pub fn search(
2049        &self,
2050        query: SearchQuery,
2051        cx: &mut ModelContext<Self>,
2052    ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
2053        if self.is_local() {
2054            let snapshots = self
2055                .strong_worktrees(cx)
2056                .filter_map(|tree| {
2057                    let tree = tree.read(cx).as_local()?;
2058                    Some(tree.snapshot())
2059                })
2060                .collect::<Vec<_>>();
2061
2062            let background = cx.background().clone();
2063            let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
2064            if path_count == 0 {
2065                return Task::ready(Ok(Default::default()));
2066            }
2067            let workers = background.num_cpus().min(path_count);
2068            let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
2069            cx.background()
2070                .spawn({
2071                    let fs = self.fs.clone();
2072                    let background = cx.background().clone();
2073                    let query = query.clone();
2074                    async move {
2075                        let fs = &fs;
2076                        let query = &query;
2077                        let matching_paths_tx = &matching_paths_tx;
2078                        let paths_per_worker = (path_count + workers - 1) / workers;
2079                        let snapshots = &snapshots;
2080                        background
2081                            .scoped(|scope| {
2082                                for worker_ix in 0..workers {
2083                                    let worker_start_ix = worker_ix * paths_per_worker;
2084                                    let worker_end_ix = worker_start_ix + paths_per_worker;
2085                                    scope.spawn(async move {
2086                                        let mut snapshot_start_ix = 0;
2087                                        let mut abs_path = PathBuf::new();
2088                                        for snapshot in snapshots {
2089                                            let snapshot_end_ix =
2090                                                snapshot_start_ix + snapshot.visible_file_count();
2091                                            if worker_end_ix <= snapshot_start_ix {
2092                                                break;
2093                                            } else if worker_start_ix > snapshot_end_ix {
2094                                                snapshot_start_ix = snapshot_end_ix;
2095                                                continue;
2096                                            } else {
2097                                                let start_in_snapshot = worker_start_ix
2098                                                    .saturating_sub(snapshot_start_ix);
2099                                                let end_in_snapshot =
2100                                                    cmp::min(worker_end_ix, snapshot_end_ix)
2101                                                        - snapshot_start_ix;
2102
2103                                                for entry in snapshot
2104                                                    .files(false, start_in_snapshot)
2105                                                    .take(end_in_snapshot - start_in_snapshot)
2106                                                {
2107                                                    if matching_paths_tx.is_closed() {
2108                                                        break;
2109                                                    }
2110
2111                                                    abs_path.clear();
2112                                                    abs_path.push(&snapshot.abs_path());
2113                                                    abs_path.push(&entry.path);
2114                                                    let matches = if let Some(file) =
2115                                                        fs.open_sync(&abs_path).await.log_err()
2116                                                    {
2117                                                        query.detect(file).unwrap_or(false)
2118                                                    } else {
2119                                                        false
2120                                                    };
2121
2122                                                    if matches {
2123                                                        let project_path =
2124                                                            (snapshot.id(), entry.path.clone());
2125                                                        if matching_paths_tx
2126                                                            .send(project_path)
2127                                                            .await
2128                                                            .is_err()
2129                                                        {
2130                                                            break;
2131                                                        }
2132                                                    }
2133                                                }
2134
2135                                                snapshot_start_ix = snapshot_end_ix;
2136                                            }
2137                                        }
2138                                    });
2139                                }
2140                            })
2141                            .await;
2142                    }
2143                })
2144                .detach();
2145
2146            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
2147            let open_buffers = self
2148                .opened_buffers
2149                .values()
2150                .filter_map(|b| b.upgrade(cx))
2151                .collect::<HashSet<_>>();
2152            cx.spawn(|this, cx| async move {
2153                for buffer in &open_buffers {
2154                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
2155                    buffers_tx.send((buffer.clone(), snapshot)).await?;
2156                }
2157
2158                let open_buffers = Rc::new(RefCell::new(open_buffers));
2159                while let Some(project_path) = matching_paths_rx.next().await {
2160                    if buffers_tx.is_closed() {
2161                        break;
2162                    }
2163
2164                    let this = this.clone();
2165                    let open_buffers = open_buffers.clone();
2166                    let buffers_tx = buffers_tx.clone();
2167                    cx.spawn(|mut cx| async move {
2168                        if let Some(buffer) = this
2169                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
2170                            .await
2171                            .log_err()
2172                        {
2173                            if open_buffers.borrow_mut().insert(buffer.clone()) {
2174                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
2175                                buffers_tx.send((buffer, snapshot)).await?;
2176                            }
2177                        }
2178
2179                        Ok::<_, anyhow::Error>(())
2180                    })
2181                    .detach();
2182                }
2183
2184                Ok::<_, anyhow::Error>(())
2185            })
2186            .detach_and_log_err(cx);
2187
2188            let background = cx.background().clone();
2189            cx.background().spawn(async move {
2190                let query = &query;
2191                let mut matched_buffers = Vec::new();
2192                for _ in 0..workers {
2193                    matched_buffers.push(HashMap::default());
2194                }
2195                background
2196                    .scoped(|scope| {
2197                        for worker_matched_buffers in matched_buffers.iter_mut() {
2198                            let mut buffers_rx = buffers_rx.clone();
2199                            scope.spawn(async move {
2200                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
2201                                    let buffer_matches = query
2202                                        .search(snapshot.as_rope())
2203                                        .await
2204                                        .iter()
2205                                        .map(|range| {
2206                                            snapshot.anchor_before(range.start)
2207                                                ..snapshot.anchor_after(range.end)
2208                                        })
2209                                        .collect::<Vec<_>>();
2210                                    if !buffer_matches.is_empty() {
2211                                        worker_matched_buffers
2212                                            .insert(buffer.clone(), buffer_matches);
2213                                    }
2214                                }
2215                            });
2216                        }
2217                    })
2218                    .await;
2219                Ok(matched_buffers.into_iter().flatten().collect())
2220            })
2221        } else if let Some(project_id) = self.remote_id() {
2222            let request = self.client.request(query.to_proto(project_id));
2223            cx.spawn(|this, mut cx| async move {
2224                let response = request.await?;
2225                let mut result = HashMap::default();
2226                for location in response.locations {
2227                    let buffer = location.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
2228                    let target_buffer = this
2229                        .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
2230                        .await?;
2231                    let start = location
2232                        .start
2233                        .and_then(deserialize_anchor)
2234                        .ok_or_else(|| anyhow!("missing target start"))?;
2235                    let end = location
2236                        .end
2237                        .and_then(deserialize_anchor)
2238                        .ok_or_else(|| anyhow!("missing target end"))?;
2239                    result
2240                        .entry(target_buffer)
2241                        .or_insert(Vec::new())
2242                        .push(start..end)
2243                }
2244                Ok(result)
2245            })
2246        } else {
2247            Task::ready(Ok(Default::default()))
2248        }
2249    }
2250
2251    fn request_lsp<R: LspCommand>(
2252        &self,
2253        buffer_handle: ModelHandle<Buffer>,
2254        request: R,
2255        cx: &mut ModelContext<Self>,
2256    ) -> Task<Result<R::Response>>
2257    where
2258        <R::LspRequest as lsp::request::Request>::Result: Send,
2259    {
2260        let buffer = buffer_handle.read(cx);
2261        if self.is_local() {
2262            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
2263            if let Some((file, language_server)) = file.zip(buffer.language_server().cloned()) {
2264                let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
2265                return cx.spawn(|this, cx| async move {
2266                    if !language_server
2267                        .capabilities()
2268                        .borrow()
2269                        .as_ref()
2270                        .map_or(false, |capabilities| {
2271                            request.check_capabilities(capabilities)
2272                        })
2273                    {
2274                        return Ok(Default::default());
2275                    }
2276
2277                    let response = language_server
2278                        .request::<R::LspRequest>(lsp_params)
2279                        .await
2280                        .context("lsp request failed")?;
2281                    request
2282                        .response_from_lsp(response, this, buffer_handle, cx)
2283                        .await
2284                });
2285            }
2286        } else if let Some(project_id) = self.remote_id() {
2287            let rpc = self.client.clone();
2288            let message = request.to_proto(project_id, buffer);
2289            return cx.spawn(|this, cx| async move {
2290                let response = rpc.request(message).await?;
2291                request
2292                    .response_from_proto(response, this, buffer_handle, cx)
2293                    .await
2294            });
2295        }
2296        Task::ready(Ok(Default::default()))
2297    }
2298
2299    pub fn find_or_create_local_worktree(
2300        &self,
2301        abs_path: impl AsRef<Path>,
2302        weak: bool,
2303        cx: &mut ModelContext<Self>,
2304    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
2305        let abs_path = abs_path.as_ref();
2306        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
2307            Task::ready(Ok((tree.clone(), relative_path.into())))
2308        } else {
2309            let worktree = self.create_local_worktree(abs_path, weak, cx);
2310            cx.foreground()
2311                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
2312        }
2313    }
2314
2315    pub fn find_local_worktree(
2316        &self,
2317        abs_path: &Path,
2318        cx: &AppContext,
2319    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
2320        for tree in self.worktrees(cx) {
2321            if let Some(relative_path) = tree
2322                .read(cx)
2323                .as_local()
2324                .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
2325            {
2326                return Some((tree.clone(), relative_path.into()));
2327            }
2328        }
2329        None
2330    }
2331
2332    pub fn is_shared(&self) -> bool {
2333        match &self.client_state {
2334            ProjectClientState::Local { is_shared, .. } => *is_shared,
2335            ProjectClientState::Remote { .. } => false,
2336        }
2337    }
2338
2339    fn create_local_worktree(
2340        &self,
2341        abs_path: impl AsRef<Path>,
2342        weak: bool,
2343        cx: &mut ModelContext<Self>,
2344    ) -> Task<Result<ModelHandle<Worktree>>> {
2345        let fs = self.fs.clone();
2346        let client = self.client.clone();
2347        let path = Arc::from(abs_path.as_ref());
2348        cx.spawn(|project, mut cx| async move {
2349            let worktree = Worktree::local(client.clone(), path, weak, fs, &mut cx).await?;
2350
2351            let (remote_project_id, is_shared) = project.update(&mut cx, |project, cx| {
2352                project.add_worktree(&worktree, cx);
2353                (project.remote_id(), project.is_shared())
2354            });
2355
2356            if let Some(project_id) = remote_project_id {
2357                worktree
2358                    .update(&mut cx, |worktree, cx| {
2359                        worktree.as_local_mut().unwrap().register(project_id, cx)
2360                    })
2361                    .await?;
2362                if is_shared {
2363                    worktree
2364                        .update(&mut cx, |worktree, cx| {
2365                            worktree.as_local_mut().unwrap().share(project_id, cx)
2366                        })
2367                        .await?;
2368                }
2369            }
2370
2371            Ok(worktree)
2372        })
2373    }
2374
2375    pub fn remove_worktree(&mut self, id: WorktreeId, cx: &mut ModelContext<Self>) {
2376        self.worktrees.retain(|worktree| {
2377            worktree
2378                .upgrade(cx)
2379                .map_or(false, |w| w.read(cx).id() != id)
2380        });
2381        cx.notify();
2382    }
2383
2384    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
2385        cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
2386        if worktree.read(cx).is_local() {
2387            cx.subscribe(&worktree, |this, worktree, _, cx| {
2388                this.update_local_worktree_buffers(worktree, cx);
2389            })
2390            .detach();
2391        }
2392
2393        let push_weak_handle = {
2394            let worktree = worktree.read(cx);
2395            worktree.is_local() && worktree.is_weak()
2396        };
2397        if push_weak_handle {
2398            cx.observe_release(&worktree, |this, cx| {
2399                this.worktrees
2400                    .retain(|worktree| worktree.upgrade(cx).is_some());
2401                cx.notify();
2402            })
2403            .detach();
2404            self.worktrees
2405                .push(WorktreeHandle::Weak(worktree.downgrade()));
2406        } else {
2407            self.worktrees
2408                .push(WorktreeHandle::Strong(worktree.clone()));
2409        }
2410        cx.notify();
2411    }
2412
2413    fn update_local_worktree_buffers(
2414        &mut self,
2415        worktree_handle: ModelHandle<Worktree>,
2416        cx: &mut ModelContext<Self>,
2417    ) {
2418        let snapshot = worktree_handle.read(cx).snapshot();
2419        let mut buffers_to_delete = Vec::new();
2420        for (buffer_id, buffer) in &self.opened_buffers {
2421            if let Some(buffer) = buffer.upgrade(cx) {
2422                buffer.update(cx, |buffer, cx| {
2423                    if let Some(old_file) = File::from_dyn(buffer.file()) {
2424                        if old_file.worktree != worktree_handle {
2425                            return;
2426                        }
2427
2428                        let new_file = if let Some(entry) = old_file
2429                            .entry_id
2430                            .and_then(|entry_id| snapshot.entry_for_id(entry_id))
2431                        {
2432                            File {
2433                                is_local: true,
2434                                entry_id: Some(entry.id),
2435                                mtime: entry.mtime,
2436                                path: entry.path.clone(),
2437                                worktree: worktree_handle.clone(),
2438                            }
2439                        } else if let Some(entry) =
2440                            snapshot.entry_for_path(old_file.path().as_ref())
2441                        {
2442                            File {
2443                                is_local: true,
2444                                entry_id: Some(entry.id),
2445                                mtime: entry.mtime,
2446                                path: entry.path.clone(),
2447                                worktree: worktree_handle.clone(),
2448                            }
2449                        } else {
2450                            File {
2451                                is_local: true,
2452                                entry_id: None,
2453                                path: old_file.path().clone(),
2454                                mtime: old_file.mtime(),
2455                                worktree: worktree_handle.clone(),
2456                            }
2457                        };
2458
2459                        if let Some(project_id) = self.remote_id() {
2460                            self.client
2461                                .send(proto::UpdateBufferFile {
2462                                    project_id,
2463                                    buffer_id: *buffer_id as u64,
2464                                    file: Some(new_file.to_proto()),
2465                                })
2466                                .log_err();
2467                        }
2468                        buffer.file_updated(Box::new(new_file), cx).detach();
2469                    }
2470                });
2471            } else {
2472                buffers_to_delete.push(*buffer_id);
2473            }
2474        }
2475
2476        for buffer_id in buffers_to_delete {
2477            self.opened_buffers.remove(&buffer_id);
2478        }
2479    }
2480
2481    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
2482        let new_active_entry = entry.and_then(|project_path| {
2483            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
2484            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
2485            Some(ProjectEntry {
2486                worktree_id: project_path.worktree_id,
2487                entry_id: entry.id,
2488            })
2489        });
2490        if new_active_entry != self.active_entry {
2491            self.active_entry = new_active_entry;
2492            cx.emit(Event::ActiveEntryChanged(new_active_entry));
2493        }
2494    }
2495
2496    pub fn is_running_disk_based_diagnostics(&self) -> bool {
2497        self.language_servers_with_diagnostics_running > 0
2498    }
2499
2500    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
2501        let mut summary = DiagnosticSummary::default();
2502        for (_, path_summary) in self.diagnostic_summaries(cx) {
2503            summary.error_count += path_summary.error_count;
2504            summary.warning_count += path_summary.warning_count;
2505            summary.info_count += path_summary.info_count;
2506            summary.hint_count += path_summary.hint_count;
2507        }
2508        summary
2509    }
2510
2511    pub fn diagnostic_summaries<'a>(
2512        &'a self,
2513        cx: &'a AppContext,
2514    ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
2515        self.worktrees(cx).flat_map(move |worktree| {
2516            let worktree = worktree.read(cx);
2517            let worktree_id = worktree.id();
2518            worktree
2519                .diagnostic_summaries()
2520                .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
2521        })
2522    }
2523
2524    pub fn disk_based_diagnostics_started(&mut self, cx: &mut ModelContext<Self>) {
2525        self.language_servers_with_diagnostics_running += 1;
2526        if self.language_servers_with_diagnostics_running == 1 {
2527            cx.emit(Event::DiskBasedDiagnosticsStarted);
2528        }
2529    }
2530
2531    pub fn disk_based_diagnostics_finished(&mut self, cx: &mut ModelContext<Self>) {
2532        cx.emit(Event::DiskBasedDiagnosticsUpdated);
2533        self.language_servers_with_diagnostics_running -= 1;
2534        if self.language_servers_with_diagnostics_running == 0 {
2535            cx.emit(Event::DiskBasedDiagnosticsFinished);
2536        }
2537    }
2538
2539    pub fn active_entry(&self) -> Option<ProjectEntry> {
2540        self.active_entry
2541    }
2542
2543    // RPC message handlers
2544
2545    async fn handle_unshare_project(
2546        this: ModelHandle<Self>,
2547        _: TypedEnvelope<proto::UnshareProject>,
2548        _: Arc<Client>,
2549        mut cx: AsyncAppContext,
2550    ) -> Result<()> {
2551        this.update(&mut cx, |this, cx| {
2552            if let ProjectClientState::Remote {
2553                sharing_has_stopped,
2554                ..
2555            } = &mut this.client_state
2556            {
2557                *sharing_has_stopped = true;
2558                this.collaborators.clear();
2559                cx.notify();
2560            } else {
2561                unreachable!()
2562            }
2563        });
2564
2565        Ok(())
2566    }
2567
2568    async fn handle_add_collaborator(
2569        this: ModelHandle<Self>,
2570        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
2571        _: Arc<Client>,
2572        mut cx: AsyncAppContext,
2573    ) -> Result<()> {
2574        let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
2575        let collaborator = envelope
2576            .payload
2577            .collaborator
2578            .take()
2579            .ok_or_else(|| anyhow!("empty collaborator"))?;
2580
2581        let collaborator = Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
2582        this.update(&mut cx, |this, cx| {
2583            this.collaborators
2584                .insert(collaborator.peer_id, collaborator);
2585            cx.notify();
2586        });
2587
2588        Ok(())
2589    }
2590
2591    async fn handle_remove_collaborator(
2592        this: ModelHandle<Self>,
2593        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
2594        _: Arc<Client>,
2595        mut cx: AsyncAppContext,
2596    ) -> Result<()> {
2597        this.update(&mut cx, |this, cx| {
2598            let peer_id = PeerId(envelope.payload.peer_id);
2599            let replica_id = this
2600                .collaborators
2601                .remove(&peer_id)
2602                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
2603                .replica_id;
2604            for (_, buffer) in &this.opened_buffers {
2605                if let Some(buffer) = buffer.upgrade(cx) {
2606                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
2607                }
2608            }
2609            cx.notify();
2610            Ok(())
2611        })
2612    }
2613
2614    async fn handle_register_worktree(
2615        this: ModelHandle<Self>,
2616        envelope: TypedEnvelope<proto::RegisterWorktree>,
2617        client: Arc<Client>,
2618        mut cx: AsyncAppContext,
2619    ) -> Result<()> {
2620        this.update(&mut cx, |this, cx| {
2621            let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
2622            let replica_id = this.replica_id();
2623            let worktree = proto::Worktree {
2624                id: envelope.payload.worktree_id,
2625                root_name: envelope.payload.root_name,
2626                entries: Default::default(),
2627                diagnostic_summaries: Default::default(),
2628                weak: envelope.payload.weak,
2629            };
2630            let (worktree, load_task) =
2631                Worktree::remote(remote_id, replica_id, worktree, client, cx);
2632            this.add_worktree(&worktree, cx);
2633            load_task.detach();
2634            Ok(())
2635        })
2636    }
2637
2638    async fn handle_unregister_worktree(
2639        this: ModelHandle<Self>,
2640        envelope: TypedEnvelope<proto::UnregisterWorktree>,
2641        _: Arc<Client>,
2642        mut cx: AsyncAppContext,
2643    ) -> Result<()> {
2644        this.update(&mut cx, |this, cx| {
2645            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2646            this.remove_worktree(worktree_id, cx);
2647            Ok(())
2648        })
2649    }
2650
2651    async fn handle_update_worktree(
2652        this: ModelHandle<Self>,
2653        envelope: TypedEnvelope<proto::UpdateWorktree>,
2654        _: Arc<Client>,
2655        mut cx: AsyncAppContext,
2656    ) -> Result<()> {
2657        this.update(&mut cx, |this, cx| {
2658            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2659            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
2660                worktree.update(cx, |worktree, _| {
2661                    let worktree = worktree.as_remote_mut().unwrap();
2662                    worktree.update_from_remote(envelope)
2663                })?;
2664            }
2665            Ok(())
2666        })
2667    }
2668
2669    async fn handle_update_diagnostic_summary(
2670        this: ModelHandle<Self>,
2671        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
2672        _: Arc<Client>,
2673        mut cx: AsyncAppContext,
2674    ) -> Result<()> {
2675        this.update(&mut cx, |this, cx| {
2676            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2677            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
2678                if let Some(summary) = envelope.payload.summary {
2679                    let project_path = ProjectPath {
2680                        worktree_id,
2681                        path: Path::new(&summary.path).into(),
2682                    };
2683                    worktree.update(cx, |worktree, _| {
2684                        worktree
2685                            .as_remote_mut()
2686                            .unwrap()
2687                            .update_diagnostic_summary(project_path.path.clone(), &summary);
2688                    });
2689                    cx.emit(Event::DiagnosticsUpdated(project_path));
2690                }
2691            }
2692            Ok(())
2693        })
2694    }
2695
2696    async fn handle_disk_based_diagnostics_updating(
2697        this: ModelHandle<Self>,
2698        _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdating>,
2699        _: Arc<Client>,
2700        mut cx: AsyncAppContext,
2701    ) -> Result<()> {
2702        this.update(&mut cx, |this, cx| this.disk_based_diagnostics_started(cx));
2703        Ok(())
2704    }
2705
2706    async fn handle_disk_based_diagnostics_updated(
2707        this: ModelHandle<Self>,
2708        _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdated>,
2709        _: Arc<Client>,
2710        mut cx: AsyncAppContext,
2711    ) -> Result<()> {
2712        this.update(&mut cx, |this, cx| this.disk_based_diagnostics_finished(cx));
2713        Ok(())
2714    }
2715
2716    async fn handle_update_buffer(
2717        this: ModelHandle<Self>,
2718        envelope: TypedEnvelope<proto::UpdateBuffer>,
2719        _: Arc<Client>,
2720        mut cx: AsyncAppContext,
2721    ) -> Result<()> {
2722        this.update(&mut cx, |this, cx| {
2723            let payload = envelope.payload.clone();
2724            let buffer_id = payload.buffer_id;
2725            let ops = payload
2726                .operations
2727                .into_iter()
2728                .map(|op| language::proto::deserialize_operation(op))
2729                .collect::<Result<Vec<_>, _>>()?;
2730            match this.opened_buffers.entry(buffer_id) {
2731                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
2732                    OpenBuffer::Strong(buffer) => {
2733                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
2734                    }
2735                    OpenBuffer::Loading(operations) => operations.extend_from_slice(&ops),
2736                    _ => unreachable!(),
2737                },
2738                hash_map::Entry::Vacant(e) => {
2739                    e.insert(OpenBuffer::Loading(ops));
2740                }
2741            }
2742            Ok(())
2743        })
2744    }
2745
2746    async fn handle_update_buffer_file(
2747        this: ModelHandle<Self>,
2748        envelope: TypedEnvelope<proto::UpdateBufferFile>,
2749        _: Arc<Client>,
2750        mut cx: AsyncAppContext,
2751    ) -> Result<()> {
2752        this.update(&mut cx, |this, cx| {
2753            let payload = envelope.payload.clone();
2754            let buffer_id = payload.buffer_id;
2755            let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
2756            let worktree = this
2757                .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
2758                .ok_or_else(|| anyhow!("no such worktree"))?;
2759            let file = File::from_proto(file, worktree.clone(), cx)?;
2760            let buffer = this
2761                .opened_buffers
2762                .get_mut(&buffer_id)
2763                .and_then(|b| b.upgrade(cx))
2764                .ok_or_else(|| anyhow!("no such buffer"))?;
2765            buffer.update(cx, |buffer, cx| {
2766                buffer.file_updated(Box::new(file), cx).detach();
2767            });
2768            Ok(())
2769        })
2770    }
2771
2772    async fn handle_save_buffer(
2773        this: ModelHandle<Self>,
2774        envelope: TypedEnvelope<proto::SaveBuffer>,
2775        _: Arc<Client>,
2776        mut cx: AsyncAppContext,
2777    ) -> Result<proto::BufferSaved> {
2778        let buffer_id = envelope.payload.buffer_id;
2779        let requested_version = envelope.payload.version.try_into()?;
2780
2781        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
2782            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
2783            let buffer = this
2784                .opened_buffers
2785                .get(&buffer_id)
2786                .map(|buffer| buffer.upgrade(cx).unwrap())
2787                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
2788            Ok::<_, anyhow::Error>((project_id, buffer))
2789        })?;
2790
2791        if !buffer
2792            .read_with(&cx, |buffer, _| buffer.version())
2793            .observed_all(&requested_version)
2794        {
2795            Err(anyhow!("save request depends on unreceived edits"))?;
2796        }
2797
2798        let (saved_version, mtime) = buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
2799        Ok(proto::BufferSaved {
2800            project_id,
2801            buffer_id,
2802            version: (&saved_version).into(),
2803            mtime: Some(mtime.into()),
2804        })
2805    }
2806
2807    async fn handle_format_buffers(
2808        this: ModelHandle<Self>,
2809        envelope: TypedEnvelope<proto::FormatBuffers>,
2810        _: Arc<Client>,
2811        mut cx: AsyncAppContext,
2812    ) -> Result<proto::FormatBuffersResponse> {
2813        let sender_id = envelope.original_sender_id()?;
2814        let format = this.update(&mut cx, |this, cx| {
2815            let mut buffers = HashSet::default();
2816            for buffer_id in &envelope.payload.buffer_ids {
2817                buffers.insert(
2818                    this.opened_buffers
2819                        .get(buffer_id)
2820                        .map(|buffer| buffer.upgrade(cx).unwrap())
2821                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
2822                );
2823            }
2824            Ok::<_, anyhow::Error>(this.format(buffers, false, cx))
2825        })?;
2826
2827        let project_transaction = format.await?;
2828        let project_transaction = this.update(&mut cx, |this, cx| {
2829            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
2830        });
2831        Ok(proto::FormatBuffersResponse {
2832            transaction: Some(project_transaction),
2833        })
2834    }
2835
2836    async fn handle_get_completions(
2837        this: ModelHandle<Self>,
2838        envelope: TypedEnvelope<proto::GetCompletions>,
2839        _: Arc<Client>,
2840        mut cx: AsyncAppContext,
2841    ) -> Result<proto::GetCompletionsResponse> {
2842        let position = envelope
2843            .payload
2844            .position
2845            .and_then(language::proto::deserialize_anchor)
2846            .ok_or_else(|| anyhow!("invalid position"))?;
2847        let version = clock::Global::from(envelope.payload.version);
2848        let buffer = this.read_with(&cx, |this, cx| {
2849            this.opened_buffers
2850                .get(&envelope.payload.buffer_id)
2851                .map(|buffer| buffer.upgrade(cx).unwrap())
2852                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
2853        })?;
2854        if !buffer
2855            .read_with(&cx, |buffer, _| buffer.version())
2856            .observed_all(&version)
2857        {
2858            Err(anyhow!("completion request depends on unreceived edits"))?;
2859        }
2860        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
2861        let completions = this
2862            .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
2863            .await?;
2864
2865        Ok(proto::GetCompletionsResponse {
2866            completions: completions
2867                .iter()
2868                .map(language::proto::serialize_completion)
2869                .collect(),
2870            version: (&version).into(),
2871        })
2872    }
2873
2874    async fn handle_apply_additional_edits_for_completion(
2875        this: ModelHandle<Self>,
2876        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
2877        _: Arc<Client>,
2878        mut cx: AsyncAppContext,
2879    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
2880        let apply_additional_edits = this.update(&mut cx, |this, cx| {
2881            let buffer = this
2882                .opened_buffers
2883                .get(&envelope.payload.buffer_id)
2884                .map(|buffer| buffer.upgrade(cx).unwrap())
2885                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2886            let language = buffer.read(cx).language();
2887            let completion = language::proto::deserialize_completion(
2888                envelope
2889                    .payload
2890                    .completion
2891                    .ok_or_else(|| anyhow!("invalid completion"))?,
2892                language,
2893            )?;
2894            Ok::<_, anyhow::Error>(
2895                this.apply_additional_edits_for_completion(buffer, completion, false, cx),
2896            )
2897        })?;
2898
2899        Ok(proto::ApplyCompletionAdditionalEditsResponse {
2900            transaction: apply_additional_edits
2901                .await?
2902                .as_ref()
2903                .map(language::proto::serialize_transaction),
2904        })
2905    }
2906
2907    async fn handle_get_code_actions(
2908        this: ModelHandle<Self>,
2909        envelope: TypedEnvelope<proto::GetCodeActions>,
2910        _: Arc<Client>,
2911        mut cx: AsyncAppContext,
2912    ) -> Result<proto::GetCodeActionsResponse> {
2913        let start = envelope
2914            .payload
2915            .start
2916            .and_then(language::proto::deserialize_anchor)
2917            .ok_or_else(|| anyhow!("invalid start"))?;
2918        let end = envelope
2919            .payload
2920            .end
2921            .and_then(language::proto::deserialize_anchor)
2922            .ok_or_else(|| anyhow!("invalid end"))?;
2923        let buffer = this.update(&mut cx, |this, cx| {
2924            this.opened_buffers
2925                .get(&envelope.payload.buffer_id)
2926                .map(|buffer| buffer.upgrade(cx).unwrap())
2927                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
2928        })?;
2929        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
2930        if !version.observed(start.timestamp) || !version.observed(end.timestamp) {
2931            Err(anyhow!("code action request references unreceived edits"))?;
2932        }
2933        let code_actions = this.update(&mut cx, |this, cx| {
2934            Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
2935        })?;
2936
2937        Ok(proto::GetCodeActionsResponse {
2938            actions: code_actions
2939                .await?
2940                .iter()
2941                .map(language::proto::serialize_code_action)
2942                .collect(),
2943            version: (&version).into(),
2944        })
2945    }
2946
2947    async fn handle_apply_code_action(
2948        this: ModelHandle<Self>,
2949        envelope: TypedEnvelope<proto::ApplyCodeAction>,
2950        _: Arc<Client>,
2951        mut cx: AsyncAppContext,
2952    ) -> Result<proto::ApplyCodeActionResponse> {
2953        let sender_id = envelope.original_sender_id()?;
2954        let action = language::proto::deserialize_code_action(
2955            envelope
2956                .payload
2957                .action
2958                .ok_or_else(|| anyhow!("invalid action"))?,
2959        )?;
2960        let apply_code_action = this.update(&mut cx, |this, cx| {
2961            let buffer = this
2962                .opened_buffers
2963                .get(&envelope.payload.buffer_id)
2964                .map(|buffer| buffer.upgrade(cx).unwrap())
2965                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2966            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
2967        })?;
2968
2969        let project_transaction = apply_code_action.await?;
2970        let project_transaction = this.update(&mut cx, |this, cx| {
2971            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
2972        });
2973        Ok(proto::ApplyCodeActionResponse {
2974            transaction: Some(project_transaction),
2975        })
2976    }
2977
2978    async fn handle_lsp_command<T: LspCommand>(
2979        this: ModelHandle<Self>,
2980        envelope: TypedEnvelope<T::ProtoRequest>,
2981        _: Arc<Client>,
2982        mut cx: AsyncAppContext,
2983    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
2984    where
2985        <T::LspRequest as lsp::request::Request>::Result: Send,
2986    {
2987        let sender_id = envelope.original_sender_id()?;
2988        let (request, buffer_version) = this.update(&mut cx, |this, cx| {
2989            let buffer_id = T::buffer_id_from_proto(&envelope.payload);
2990            let buffer_handle = this
2991                .opened_buffers
2992                .get(&buffer_id)
2993                .map(|buffer| buffer.upgrade(cx).unwrap())
2994                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
2995            let buffer = buffer_handle.read(cx);
2996            let buffer_version = buffer.version();
2997            let request = T::from_proto(envelope.payload, this, buffer)?;
2998            Ok::<_, anyhow::Error>((this.request_lsp(buffer_handle, request, cx), buffer_version))
2999        })?;
3000        let response = request.await?;
3001        this.update(&mut cx, |this, cx| {
3002            Ok(T::response_to_proto(
3003                response,
3004                this,
3005                sender_id,
3006                &buffer_version,
3007                cx,
3008            ))
3009        })
3010    }
3011
3012    async fn handle_get_project_symbols(
3013        this: ModelHandle<Self>,
3014        envelope: TypedEnvelope<proto::GetProjectSymbols>,
3015        _: Arc<Client>,
3016        mut cx: AsyncAppContext,
3017    ) -> Result<proto::GetProjectSymbolsResponse> {
3018        let symbols = this
3019            .update(&mut cx, |this, cx| {
3020                this.symbols(&envelope.payload.query, cx)
3021            })
3022            .await?;
3023
3024        Ok(proto::GetProjectSymbolsResponse {
3025            symbols: symbols.iter().map(serialize_symbol).collect(),
3026        })
3027    }
3028
3029    async fn handle_search_project(
3030        this: ModelHandle<Self>,
3031        envelope: TypedEnvelope<proto::SearchProject>,
3032        _: Arc<Client>,
3033        mut cx: AsyncAppContext,
3034    ) -> Result<proto::SearchProjectResponse> {
3035        let peer_id = envelope.original_sender_id()?;
3036        let query = SearchQuery::from_proto(envelope.payload)?;
3037        let result = this
3038            .update(&mut cx, |this, cx| this.search(query, cx))
3039            .await?;
3040
3041        this.update(&mut cx, |this, cx| {
3042            let mut locations = Vec::new();
3043            for (buffer, ranges) in result {
3044                for range in ranges {
3045                    let start = serialize_anchor(&range.start);
3046                    let end = serialize_anchor(&range.end);
3047                    let buffer = this.serialize_buffer_for_peer(&buffer, peer_id, cx);
3048                    locations.push(proto::Location {
3049                        buffer: Some(buffer),
3050                        start: Some(start),
3051                        end: Some(end),
3052                    });
3053                }
3054            }
3055            Ok(proto::SearchProjectResponse { locations })
3056        })
3057    }
3058
3059    async fn handle_open_buffer_for_symbol(
3060        this: ModelHandle<Self>,
3061        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
3062        _: Arc<Client>,
3063        mut cx: AsyncAppContext,
3064    ) -> Result<proto::OpenBufferForSymbolResponse> {
3065        let peer_id = envelope.original_sender_id()?;
3066        let symbol = envelope
3067            .payload
3068            .symbol
3069            .ok_or_else(|| anyhow!("invalid symbol"))?;
3070        let symbol = this.read_with(&cx, |this, _| {
3071            let symbol = this.deserialize_symbol(symbol)?;
3072            let signature = this.symbol_signature(symbol.worktree_id, &symbol.path);
3073            if signature == symbol.signature {
3074                Ok(symbol)
3075            } else {
3076                Err(anyhow!("invalid symbol signature"))
3077            }
3078        })?;
3079        let buffer = this
3080            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
3081            .await?;
3082
3083        Ok(proto::OpenBufferForSymbolResponse {
3084            buffer: Some(this.update(&mut cx, |this, cx| {
3085                this.serialize_buffer_for_peer(&buffer, peer_id, cx)
3086            })),
3087        })
3088    }
3089
3090    fn symbol_signature(&self, worktree_id: WorktreeId, path: &Path) -> [u8; 32] {
3091        let mut hasher = Sha256::new();
3092        hasher.update(worktree_id.to_proto().to_be_bytes());
3093        hasher.update(path.to_string_lossy().as_bytes());
3094        hasher.update(self.nonce.to_be_bytes());
3095        hasher.finalize().as_slice().try_into().unwrap()
3096    }
3097
3098    async fn handle_open_buffer(
3099        this: ModelHandle<Self>,
3100        envelope: TypedEnvelope<proto::OpenBuffer>,
3101        _: Arc<Client>,
3102        mut cx: AsyncAppContext,
3103    ) -> Result<proto::OpenBufferResponse> {
3104        let peer_id = envelope.original_sender_id()?;
3105        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3106        let open_buffer = this.update(&mut cx, |this, cx| {
3107            this.open_buffer(
3108                ProjectPath {
3109                    worktree_id,
3110                    path: PathBuf::from(envelope.payload.path).into(),
3111                },
3112                cx,
3113            )
3114        });
3115
3116        let buffer = open_buffer.await?;
3117        this.update(&mut cx, |this, cx| {
3118            Ok(proto::OpenBufferResponse {
3119                buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
3120            })
3121        })
3122    }
3123
3124    fn serialize_project_transaction_for_peer(
3125        &mut self,
3126        project_transaction: ProjectTransaction,
3127        peer_id: PeerId,
3128        cx: &AppContext,
3129    ) -> proto::ProjectTransaction {
3130        let mut serialized_transaction = proto::ProjectTransaction {
3131            buffers: Default::default(),
3132            transactions: Default::default(),
3133        };
3134        for (buffer, transaction) in project_transaction.0 {
3135            serialized_transaction
3136                .buffers
3137                .push(self.serialize_buffer_for_peer(&buffer, peer_id, cx));
3138            serialized_transaction
3139                .transactions
3140                .push(language::proto::serialize_transaction(&transaction));
3141        }
3142        serialized_transaction
3143    }
3144
3145    fn deserialize_project_transaction(
3146        &mut self,
3147        message: proto::ProjectTransaction,
3148        push_to_history: bool,
3149        cx: &mut ModelContext<Self>,
3150    ) -> Task<Result<ProjectTransaction>> {
3151        cx.spawn(|this, mut cx| async move {
3152            let mut project_transaction = ProjectTransaction::default();
3153            for (buffer, transaction) in message.buffers.into_iter().zip(message.transactions) {
3154                let buffer = this
3155                    .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
3156                    .await?;
3157                let transaction = language::proto::deserialize_transaction(transaction)?;
3158                project_transaction.0.insert(buffer, transaction);
3159            }
3160
3161            for (buffer, transaction) in &project_transaction.0 {
3162                buffer
3163                    .update(&mut cx, |buffer, _| {
3164                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3165                    })
3166                    .await;
3167
3168                if push_to_history {
3169                    buffer.update(&mut cx, |buffer, _| {
3170                        buffer.push_transaction(transaction.clone(), Instant::now());
3171                    });
3172                }
3173            }
3174
3175            Ok(project_transaction)
3176        })
3177    }
3178
3179    fn serialize_buffer_for_peer(
3180        &mut self,
3181        buffer: &ModelHandle<Buffer>,
3182        peer_id: PeerId,
3183        cx: &AppContext,
3184    ) -> proto::Buffer {
3185        let buffer_id = buffer.read(cx).remote_id();
3186        let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
3187        if shared_buffers.insert(buffer_id) {
3188            proto::Buffer {
3189                variant: Some(proto::buffer::Variant::State(buffer.read(cx).to_proto())),
3190            }
3191        } else {
3192            proto::Buffer {
3193                variant: Some(proto::buffer::Variant::Id(buffer_id)),
3194            }
3195        }
3196    }
3197
3198    fn deserialize_buffer(
3199        &mut self,
3200        buffer: proto::Buffer,
3201        cx: &mut ModelContext<Self>,
3202    ) -> Task<Result<ModelHandle<Buffer>>> {
3203        let replica_id = self.replica_id();
3204
3205        let opened_buffer_tx = self.opened_buffer.0.clone();
3206        let mut opened_buffer_rx = self.opened_buffer.1.clone();
3207        cx.spawn(|this, mut cx| async move {
3208            match buffer.variant.ok_or_else(|| anyhow!("missing buffer"))? {
3209                proto::buffer::Variant::Id(id) => {
3210                    let buffer = loop {
3211                        let buffer = this.read_with(&cx, |this, cx| {
3212                            this.opened_buffers
3213                                .get(&id)
3214                                .and_then(|buffer| buffer.upgrade(cx))
3215                        });
3216                        if let Some(buffer) = buffer {
3217                            break buffer;
3218                        }
3219                        opened_buffer_rx
3220                            .next()
3221                            .await
3222                            .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
3223                    };
3224                    Ok(buffer)
3225                }
3226                proto::buffer::Variant::State(mut buffer) => {
3227                    let mut buffer_worktree = None;
3228                    let mut buffer_file = None;
3229                    if let Some(file) = buffer.file.take() {
3230                        this.read_with(&cx, |this, cx| {
3231                            let worktree_id = WorktreeId::from_proto(file.worktree_id);
3232                            let worktree =
3233                                this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
3234                                    anyhow!("no worktree found for id {}", file.worktree_id)
3235                                })?;
3236                            buffer_file =
3237                                Some(Box::new(File::from_proto(file, worktree.clone(), cx)?)
3238                                    as Box<dyn language::File>);
3239                            buffer_worktree = Some(worktree);
3240                            Ok::<_, anyhow::Error>(())
3241                        })?;
3242                    }
3243
3244                    let buffer = cx.add_model(|cx| {
3245                        Buffer::from_proto(replica_id, buffer, buffer_file, cx).unwrap()
3246                    });
3247
3248                    this.update(&mut cx, |this, cx| {
3249                        this.register_buffer(&buffer, buffer_worktree.as_ref(), cx)
3250                    })?;
3251
3252                    *opened_buffer_tx.borrow_mut().borrow_mut() = ();
3253                    Ok(buffer)
3254                }
3255            }
3256        })
3257    }
3258
3259    fn deserialize_symbol(&self, serialized_symbol: proto::Symbol) -> Result<Symbol> {
3260        let language = self
3261            .languages
3262            .get_language(&serialized_symbol.language_name);
3263        let start = serialized_symbol
3264            .start
3265            .ok_or_else(|| anyhow!("invalid start"))?;
3266        let end = serialized_symbol
3267            .end
3268            .ok_or_else(|| anyhow!("invalid end"))?;
3269        let kind = unsafe { mem::transmute(serialized_symbol.kind) };
3270        Ok(Symbol {
3271            source_worktree_id: WorktreeId::from_proto(serialized_symbol.source_worktree_id),
3272            worktree_id: WorktreeId::from_proto(serialized_symbol.worktree_id),
3273            language_name: serialized_symbol.language_name.clone(),
3274            label: language
3275                .and_then(|language| language.label_for_symbol(&serialized_symbol.name, kind))
3276                .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None)),
3277            name: serialized_symbol.name,
3278            path: PathBuf::from(serialized_symbol.path),
3279            range: PointUtf16::new(start.row, start.column)..PointUtf16::new(end.row, end.column),
3280            kind,
3281            signature: serialized_symbol
3282                .signature
3283                .try_into()
3284                .map_err(|_| anyhow!("invalid signature"))?,
3285        })
3286    }
3287
3288    async fn handle_close_buffer(
3289        _: ModelHandle<Self>,
3290        _: TypedEnvelope<proto::CloseBuffer>,
3291        _: Arc<Client>,
3292        _: AsyncAppContext,
3293    ) -> Result<()> {
3294        // TODO: use this for following
3295        Ok(())
3296    }
3297
3298    async fn handle_buffer_saved(
3299        this: ModelHandle<Self>,
3300        envelope: TypedEnvelope<proto::BufferSaved>,
3301        _: Arc<Client>,
3302        mut cx: AsyncAppContext,
3303    ) -> Result<()> {
3304        let version = envelope.payload.version.try_into()?;
3305        let mtime = envelope
3306            .payload
3307            .mtime
3308            .ok_or_else(|| anyhow!("missing mtime"))?
3309            .into();
3310
3311        this.update(&mut cx, |this, cx| {
3312            let buffer = this
3313                .opened_buffers
3314                .get(&envelope.payload.buffer_id)
3315                .and_then(|buffer| buffer.upgrade(cx));
3316            if let Some(buffer) = buffer {
3317                buffer.update(cx, |buffer, cx| {
3318                    buffer.did_save(version, mtime, None, cx);
3319                });
3320            }
3321            Ok(())
3322        })
3323    }
3324
3325    async fn handle_buffer_reloaded(
3326        this: ModelHandle<Self>,
3327        envelope: TypedEnvelope<proto::BufferReloaded>,
3328        _: Arc<Client>,
3329        mut cx: AsyncAppContext,
3330    ) -> Result<()> {
3331        let payload = envelope.payload.clone();
3332        let version = payload.version.try_into()?;
3333        let mtime = payload
3334            .mtime
3335            .ok_or_else(|| anyhow!("missing mtime"))?
3336            .into();
3337        this.update(&mut cx, |this, cx| {
3338            let buffer = this
3339                .opened_buffers
3340                .get(&payload.buffer_id)
3341                .and_then(|buffer| buffer.upgrade(cx));
3342            if let Some(buffer) = buffer {
3343                buffer.update(cx, |buffer, cx| {
3344                    buffer.did_reload(version, mtime, cx);
3345                });
3346            }
3347            Ok(())
3348        })
3349    }
3350
3351    pub fn match_paths<'a>(
3352        &self,
3353        query: &'a str,
3354        include_ignored: bool,
3355        smart_case: bool,
3356        max_results: usize,
3357        cancel_flag: &'a AtomicBool,
3358        cx: &AppContext,
3359    ) -> impl 'a + Future<Output = Vec<PathMatch>> {
3360        let worktrees = self
3361            .worktrees(cx)
3362            .filter(|worktree| !worktree.read(cx).is_weak())
3363            .collect::<Vec<_>>();
3364        let include_root_name = worktrees.len() > 1;
3365        let candidate_sets = worktrees
3366            .into_iter()
3367            .map(|worktree| CandidateSet {
3368                snapshot: worktree.read(cx).snapshot(),
3369                include_ignored,
3370                include_root_name,
3371            })
3372            .collect::<Vec<_>>();
3373
3374        let background = cx.background().clone();
3375        async move {
3376            fuzzy::match_paths(
3377                candidate_sets.as_slice(),
3378                query,
3379                smart_case,
3380                max_results,
3381                cancel_flag,
3382                background,
3383            )
3384            .await
3385        }
3386    }
3387}
3388
3389impl WorktreeHandle {
3390    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
3391        match self {
3392            WorktreeHandle::Strong(handle) => Some(handle.clone()),
3393            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
3394        }
3395    }
3396}
3397
3398impl OpenBuffer {
3399    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
3400        match self {
3401            OpenBuffer::Strong(handle) => Some(handle.clone()),
3402            OpenBuffer::Weak(handle) => handle.upgrade(cx),
3403            OpenBuffer::Loading(_) => None,
3404        }
3405    }
3406}
3407
3408struct CandidateSet {
3409    snapshot: Snapshot,
3410    include_ignored: bool,
3411    include_root_name: bool,
3412}
3413
3414impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
3415    type Candidates = CandidateSetIter<'a>;
3416
3417    fn id(&self) -> usize {
3418        self.snapshot.id().to_usize()
3419    }
3420
3421    fn len(&self) -> usize {
3422        if self.include_ignored {
3423            self.snapshot.file_count()
3424        } else {
3425            self.snapshot.visible_file_count()
3426        }
3427    }
3428
3429    fn prefix(&self) -> Arc<str> {
3430        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
3431            self.snapshot.root_name().into()
3432        } else if self.include_root_name {
3433            format!("{}/", self.snapshot.root_name()).into()
3434        } else {
3435            "".into()
3436        }
3437    }
3438
3439    fn candidates(&'a self, start: usize) -> Self::Candidates {
3440        CandidateSetIter {
3441            traversal: self.snapshot.files(self.include_ignored, start),
3442        }
3443    }
3444}
3445
3446struct CandidateSetIter<'a> {
3447    traversal: Traversal<'a>,
3448}
3449
3450impl<'a> Iterator for CandidateSetIter<'a> {
3451    type Item = PathMatchCandidate<'a>;
3452
3453    fn next(&mut self) -> Option<Self::Item> {
3454        self.traversal.next().map(|entry| {
3455            if let EntryKind::File(char_bag) = entry.kind {
3456                PathMatchCandidate {
3457                    path: &entry.path,
3458                    char_bag,
3459                }
3460            } else {
3461                unreachable!()
3462            }
3463        })
3464    }
3465}
3466
3467impl Entity for Project {
3468    type Event = Event;
3469
3470    fn release(&mut self, _: &mut gpui::MutableAppContext) {
3471        match &self.client_state {
3472            ProjectClientState::Local { remote_id_rx, .. } => {
3473                if let Some(project_id) = *remote_id_rx.borrow() {
3474                    self.client
3475                        .send(proto::UnregisterProject { project_id })
3476                        .log_err();
3477                }
3478            }
3479            ProjectClientState::Remote { remote_id, .. } => {
3480                self.client
3481                    .send(proto::LeaveProject {
3482                        project_id: *remote_id,
3483                    })
3484                    .log_err();
3485            }
3486        }
3487    }
3488
3489    fn app_will_quit(
3490        &mut self,
3491        _: &mut MutableAppContext,
3492    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
3493        let shutdown_futures = self
3494            .language_servers
3495            .drain()
3496            .filter_map(|(_, server)| server.shutdown())
3497            .collect::<Vec<_>>();
3498        Some(
3499            async move {
3500                futures::future::join_all(shutdown_futures).await;
3501            }
3502            .boxed(),
3503        )
3504    }
3505}
3506
3507impl Collaborator {
3508    fn from_proto(
3509        message: proto::Collaborator,
3510        user_store: &ModelHandle<UserStore>,
3511        cx: &mut AsyncAppContext,
3512    ) -> impl Future<Output = Result<Self>> {
3513        let user = user_store.update(cx, |user_store, cx| {
3514            user_store.fetch_user(message.user_id, cx)
3515        });
3516
3517        async move {
3518            Ok(Self {
3519                peer_id: PeerId(message.peer_id),
3520                user: user.await?,
3521                replica_id: message.replica_id as ReplicaId,
3522            })
3523        }
3524    }
3525}
3526
3527impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
3528    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
3529        Self {
3530            worktree_id,
3531            path: path.as_ref().into(),
3532        }
3533    }
3534}
3535
3536impl From<lsp::CreateFileOptions> for fs::CreateOptions {
3537    fn from(options: lsp::CreateFileOptions) -> Self {
3538        Self {
3539            overwrite: options.overwrite.unwrap_or(false),
3540            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
3541        }
3542    }
3543}
3544
3545impl From<lsp::RenameFileOptions> for fs::RenameOptions {
3546    fn from(options: lsp::RenameFileOptions) -> Self {
3547        Self {
3548            overwrite: options.overwrite.unwrap_or(false),
3549            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
3550        }
3551    }
3552}
3553
3554impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
3555    fn from(options: lsp::DeleteFileOptions) -> Self {
3556        Self {
3557            recursive: options.recursive.unwrap_or(false),
3558            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
3559        }
3560    }
3561}
3562
3563fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
3564    proto::Symbol {
3565        source_worktree_id: symbol.source_worktree_id.to_proto(),
3566        worktree_id: symbol.worktree_id.to_proto(),
3567        language_name: symbol.language_name.clone(),
3568        name: symbol.name.clone(),
3569        kind: unsafe { mem::transmute(symbol.kind) },
3570        path: symbol.path.to_string_lossy().to_string(),
3571        start: Some(proto::Point {
3572            row: symbol.range.start.row,
3573            column: symbol.range.start.column,
3574        }),
3575        end: Some(proto::Point {
3576            row: symbol.range.end.row,
3577            column: symbol.range.end.column,
3578        }),
3579        signature: symbol.signature.to_vec(),
3580    }
3581}
3582
3583fn relativize_path(base: &Path, path: &Path) -> PathBuf {
3584    let mut path_components = path.components();
3585    let mut base_components = base.components();
3586    let mut components: Vec<Component> = Vec::new();
3587    loop {
3588        match (path_components.next(), base_components.next()) {
3589            (None, None) => break,
3590            (Some(a), None) => {
3591                components.push(a);
3592                components.extend(path_components.by_ref());
3593                break;
3594            }
3595            (None, _) => components.push(Component::ParentDir),
3596            (Some(a), Some(b)) if components.is_empty() && a == b => (),
3597            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
3598            (Some(a), Some(_)) => {
3599                components.push(Component::ParentDir);
3600                for _ in base_components {
3601                    components.push(Component::ParentDir);
3602                }
3603                components.push(a);
3604                components.extend(path_components.by_ref());
3605                break;
3606            }
3607        }
3608    }
3609    components.iter().map(|c| c.as_os_str()).collect()
3610}
3611
3612#[cfg(test)]
3613mod tests {
3614    use super::{Event, *};
3615    use fs::RealFs;
3616    use futures::StreamExt;
3617    use gpui::test::subscribe;
3618    use language::{
3619        tree_sitter_rust, AnchorRangeExt, Diagnostic, LanguageConfig, LanguageServerConfig, Point,
3620    };
3621    use lsp::Url;
3622    use serde_json::json;
3623    use std::{cell::RefCell, os::unix, path::PathBuf, rc::Rc};
3624    use unindent::Unindent as _;
3625    use util::test::temp_tree;
3626    use worktree::WorktreeHandle as _;
3627
3628    #[gpui::test]
3629    async fn test_populate_and_search(cx: &mut gpui::TestAppContext) {
3630        let dir = temp_tree(json!({
3631            "root": {
3632                "apple": "",
3633                "banana": {
3634                    "carrot": {
3635                        "date": "",
3636                        "endive": "",
3637                    }
3638                },
3639                "fennel": {
3640                    "grape": "",
3641                }
3642            }
3643        }));
3644
3645        let root_link_path = dir.path().join("root_link");
3646        unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
3647        unix::fs::symlink(
3648            &dir.path().join("root/fennel"),
3649            &dir.path().join("root/finnochio"),
3650        )
3651        .unwrap();
3652
3653        let project = Project::test(Arc::new(RealFs), cx);
3654
3655        let (tree, _) = project
3656            .update(cx, |project, cx| {
3657                project.find_or_create_local_worktree(&root_link_path, false, cx)
3658            })
3659            .await
3660            .unwrap();
3661
3662        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3663            .await;
3664        cx.read(|cx| {
3665            let tree = tree.read(cx);
3666            assert_eq!(tree.file_count(), 5);
3667            assert_eq!(
3668                tree.inode_for_path("fennel/grape"),
3669                tree.inode_for_path("finnochio/grape")
3670            );
3671        });
3672
3673        let cancel_flag = Default::default();
3674        let results = project
3675            .read_with(cx, |project, cx| {
3676                project.match_paths("bna", false, false, 10, &cancel_flag, cx)
3677            })
3678            .await;
3679        assert_eq!(
3680            results
3681                .into_iter()
3682                .map(|result| result.path)
3683                .collect::<Vec<Arc<Path>>>(),
3684            vec![
3685                PathBuf::from("banana/carrot/date").into(),
3686                PathBuf::from("banana/carrot/endive").into(),
3687            ]
3688        );
3689    }
3690
3691    #[gpui::test]
3692    async fn test_language_server_diagnostics(cx: &mut gpui::TestAppContext) {
3693        let (language_server_config, mut fake_servers) = LanguageServerConfig::fake();
3694        let progress_token = language_server_config
3695            .disk_based_diagnostics_progress_token
3696            .clone()
3697            .unwrap();
3698
3699        let language = Arc::new(Language::new(
3700            LanguageConfig {
3701                name: "Rust".into(),
3702                path_suffixes: vec!["rs".to_string()],
3703                language_server: Some(language_server_config),
3704                ..Default::default()
3705            },
3706            Some(tree_sitter_rust::language()),
3707        ));
3708
3709        let fs = FakeFs::new(cx.background());
3710        fs.insert_tree(
3711            "/dir",
3712            json!({
3713                "a.rs": "fn a() { A }",
3714                "b.rs": "const y: i32 = 1",
3715            }),
3716        )
3717        .await;
3718
3719        let project = Project::test(fs, cx);
3720        project.update(cx, |project, _| {
3721            Arc::get_mut(&mut project.languages).unwrap().add(language);
3722        });
3723
3724        let (tree, _) = project
3725            .update(cx, |project, cx| {
3726                project.find_or_create_local_worktree("/dir", false, cx)
3727            })
3728            .await
3729            .unwrap();
3730        let worktree_id = tree.read_with(cx, |tree, _| tree.id());
3731
3732        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3733            .await;
3734
3735        // Cause worktree to start the fake language server
3736        let _buffer = project
3737            .update(cx, |project, cx| {
3738                project.open_buffer((worktree_id, Path::new("b.rs")), cx)
3739            })
3740            .await
3741            .unwrap();
3742
3743        let mut events = subscribe(&project, cx);
3744
3745        let mut fake_server = fake_servers.next().await.unwrap();
3746        fake_server.start_progress(&progress_token).await;
3747        assert_eq!(
3748            events.next().await.unwrap(),
3749            Event::DiskBasedDiagnosticsStarted
3750        );
3751
3752        fake_server.start_progress(&progress_token).await;
3753        fake_server.end_progress(&progress_token).await;
3754        fake_server.start_progress(&progress_token).await;
3755
3756        fake_server
3757            .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
3758                uri: Url::from_file_path("/dir/a.rs").unwrap(),
3759                version: None,
3760                diagnostics: vec![lsp::Diagnostic {
3761                    range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
3762                    severity: Some(lsp::DiagnosticSeverity::ERROR),
3763                    message: "undefined variable 'A'".to_string(),
3764                    ..Default::default()
3765                }],
3766            })
3767            .await;
3768        assert_eq!(
3769            events.next().await.unwrap(),
3770            Event::DiagnosticsUpdated((worktree_id, Path::new("a.rs")).into())
3771        );
3772
3773        fake_server.end_progress(&progress_token).await;
3774        fake_server.end_progress(&progress_token).await;
3775        assert_eq!(
3776            events.next().await.unwrap(),
3777            Event::DiskBasedDiagnosticsUpdated
3778        );
3779        assert_eq!(
3780            events.next().await.unwrap(),
3781            Event::DiskBasedDiagnosticsFinished
3782        );
3783
3784        let buffer = project
3785            .update(cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
3786            .await
3787            .unwrap();
3788
3789        buffer.read_with(cx, |buffer, _| {
3790            let snapshot = buffer.snapshot();
3791            let diagnostics = snapshot
3792                .diagnostics_in_range::<_, Point>(0..buffer.len())
3793                .collect::<Vec<_>>();
3794            assert_eq!(
3795                diagnostics,
3796                &[DiagnosticEntry {
3797                    range: Point::new(0, 9)..Point::new(0, 10),
3798                    diagnostic: Diagnostic {
3799                        severity: lsp::DiagnosticSeverity::ERROR,
3800                        message: "undefined variable 'A'".to_string(),
3801                        group_id: 0,
3802                        is_primary: true,
3803                        ..Default::default()
3804                    }
3805                }]
3806            )
3807        });
3808    }
3809
3810    #[gpui::test]
3811    async fn test_search_worktree_without_files(cx: &mut gpui::TestAppContext) {
3812        let dir = temp_tree(json!({
3813            "root": {
3814                "dir1": {},
3815                "dir2": {
3816                    "dir3": {}
3817                }
3818            }
3819        }));
3820
3821        let project = Project::test(Arc::new(RealFs), cx);
3822        let (tree, _) = project
3823            .update(cx, |project, cx| {
3824                project.find_or_create_local_worktree(&dir.path(), false, cx)
3825            })
3826            .await
3827            .unwrap();
3828
3829        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3830            .await;
3831
3832        let cancel_flag = Default::default();
3833        let results = project
3834            .read_with(cx, |project, cx| {
3835                project.match_paths("dir", false, false, 10, &cancel_flag, cx)
3836            })
3837            .await;
3838
3839        assert!(results.is_empty());
3840    }
3841
3842    #[gpui::test]
3843    async fn test_definition(cx: &mut gpui::TestAppContext) {
3844        let (language_server_config, mut fake_servers) = LanguageServerConfig::fake();
3845        let language = Arc::new(Language::new(
3846            LanguageConfig {
3847                name: "Rust".into(),
3848                path_suffixes: vec!["rs".to_string()],
3849                language_server: Some(language_server_config),
3850                ..Default::default()
3851            },
3852            Some(tree_sitter_rust::language()),
3853        ));
3854
3855        let fs = FakeFs::new(cx.background());
3856        fs.insert_tree(
3857            "/dir",
3858            json!({
3859                "a.rs": "const fn a() { A }",
3860                "b.rs": "const y: i32 = crate::a()",
3861            }),
3862        )
3863        .await;
3864
3865        let project = Project::test(fs, cx);
3866        project.update(cx, |project, _| {
3867            Arc::get_mut(&mut project.languages).unwrap().add(language);
3868        });
3869
3870        let (tree, _) = project
3871            .update(cx, |project, cx| {
3872                project.find_or_create_local_worktree("/dir/b.rs", false, cx)
3873            })
3874            .await
3875            .unwrap();
3876        let worktree_id = tree.read_with(cx, |tree, _| tree.id());
3877        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3878            .await;
3879
3880        let buffer = project
3881            .update(cx, |project, cx| {
3882                project.open_buffer(
3883                    ProjectPath {
3884                        worktree_id,
3885                        path: Path::new("").into(),
3886                    },
3887                    cx,
3888                )
3889            })
3890            .await
3891            .unwrap();
3892
3893        let mut fake_server = fake_servers.next().await.unwrap();
3894        fake_server.handle_request::<lsp::request::GotoDefinition, _>(move |params, _| {
3895            let params = params.text_document_position_params;
3896            assert_eq!(
3897                params.text_document.uri.to_file_path().unwrap(),
3898                Path::new("/dir/b.rs"),
3899            );
3900            assert_eq!(params.position, lsp::Position::new(0, 22));
3901
3902            Some(lsp::GotoDefinitionResponse::Scalar(lsp::Location::new(
3903                lsp::Url::from_file_path("/dir/a.rs").unwrap(),
3904                lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
3905            )))
3906        });
3907
3908        let mut definitions = project
3909            .update(cx, |project, cx| project.definition(&buffer, 22, cx))
3910            .await
3911            .unwrap();
3912
3913        assert_eq!(definitions.len(), 1);
3914        let definition = definitions.pop().unwrap();
3915        cx.update(|cx| {
3916            let target_buffer = definition.buffer.read(cx);
3917            assert_eq!(
3918                target_buffer
3919                    .file()
3920                    .unwrap()
3921                    .as_local()
3922                    .unwrap()
3923                    .abs_path(cx),
3924                Path::new("/dir/a.rs"),
3925            );
3926            assert_eq!(definition.range.to_offset(target_buffer), 9..10);
3927            assert_eq!(
3928                list_worktrees(&project, cx),
3929                [("/dir/b.rs".as_ref(), false), ("/dir/a.rs".as_ref(), true)]
3930            );
3931
3932            drop(definition);
3933        });
3934        cx.read(|cx| {
3935            assert_eq!(
3936                list_worktrees(&project, cx),
3937                [("/dir/b.rs".as_ref(), false)]
3938            );
3939        });
3940
3941        fn list_worktrees<'a>(
3942            project: &'a ModelHandle<Project>,
3943            cx: &'a AppContext,
3944        ) -> Vec<(&'a Path, bool)> {
3945            project
3946                .read(cx)
3947                .worktrees(cx)
3948                .map(|worktree| {
3949                    let worktree = worktree.read(cx);
3950                    (
3951                        worktree.as_local().unwrap().abs_path().as_ref(),
3952                        worktree.is_weak(),
3953                    )
3954                })
3955                .collect::<Vec<_>>()
3956        }
3957    }
3958
3959    #[gpui::test]
3960    async fn test_save_file(cx: &mut gpui::TestAppContext) {
3961        let fs = FakeFs::new(cx.background());
3962        fs.insert_tree(
3963            "/dir",
3964            json!({
3965                "file1": "the old contents",
3966            }),
3967        )
3968        .await;
3969
3970        let project = Project::test(fs.clone(), cx);
3971        let worktree_id = project
3972            .update(cx, |p, cx| {
3973                p.find_or_create_local_worktree("/dir", false, cx)
3974            })
3975            .await
3976            .unwrap()
3977            .0
3978            .read_with(cx, |tree, _| tree.id());
3979
3980        let buffer = project
3981            .update(cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
3982            .await
3983            .unwrap();
3984        buffer
3985            .update(cx, |buffer, cx| {
3986                assert_eq!(buffer.text(), "the old contents");
3987                buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
3988                buffer.save(cx)
3989            })
3990            .await
3991            .unwrap();
3992
3993        let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
3994        assert_eq!(new_text, buffer.read_with(cx, |buffer, _| buffer.text()));
3995    }
3996
3997    #[gpui::test]
3998    async fn test_save_in_single_file_worktree(cx: &mut gpui::TestAppContext) {
3999        let fs = FakeFs::new(cx.background());
4000        fs.insert_tree(
4001            "/dir",
4002            json!({
4003                "file1": "the old contents",
4004            }),
4005        )
4006        .await;
4007
4008        let project = Project::test(fs.clone(), cx);
4009        let worktree_id = project
4010            .update(cx, |p, cx| {
4011                p.find_or_create_local_worktree("/dir/file1", false, cx)
4012            })
4013            .await
4014            .unwrap()
4015            .0
4016            .read_with(cx, |tree, _| tree.id());
4017
4018        let buffer = project
4019            .update(cx, |p, cx| p.open_buffer((worktree_id, ""), cx))
4020            .await
4021            .unwrap();
4022        buffer
4023            .update(cx, |buffer, cx| {
4024                buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
4025                buffer.save(cx)
4026            })
4027            .await
4028            .unwrap();
4029
4030        let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
4031        assert_eq!(new_text, buffer.read_with(cx, |buffer, _| buffer.text()));
4032    }
4033
4034    #[gpui::test(retries = 5)]
4035    async fn test_rescan_and_remote_updates(cx: &mut gpui::TestAppContext) {
4036        let dir = temp_tree(json!({
4037            "a": {
4038                "file1": "",
4039                "file2": "",
4040                "file3": "",
4041            },
4042            "b": {
4043                "c": {
4044                    "file4": "",
4045                    "file5": "",
4046                }
4047            }
4048        }));
4049
4050        let project = Project::test(Arc::new(RealFs), cx);
4051        let rpc = project.read_with(cx, |p, _| p.client.clone());
4052
4053        let (tree, _) = project
4054            .update(cx, |p, cx| {
4055                p.find_or_create_local_worktree(dir.path(), false, cx)
4056            })
4057            .await
4058            .unwrap();
4059        let worktree_id = tree.read_with(cx, |tree, _| tree.id());
4060
4061        let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
4062            let buffer = project.update(cx, |p, cx| p.open_buffer((worktree_id, path), cx));
4063            async move { buffer.await.unwrap() }
4064        };
4065        let id_for_path = |path: &'static str, cx: &gpui::TestAppContext| {
4066            tree.read_with(cx, |tree, _| {
4067                tree.entry_for_path(path)
4068                    .expect(&format!("no entry for path {}", path))
4069                    .id
4070            })
4071        };
4072
4073        let buffer2 = buffer_for_path("a/file2", cx).await;
4074        let buffer3 = buffer_for_path("a/file3", cx).await;
4075        let buffer4 = buffer_for_path("b/c/file4", cx).await;
4076        let buffer5 = buffer_for_path("b/c/file5", cx).await;
4077
4078        let file2_id = id_for_path("a/file2", &cx);
4079        let file3_id = id_for_path("a/file3", &cx);
4080        let file4_id = id_for_path("b/c/file4", &cx);
4081
4082        // Wait for the initial scan.
4083        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4084            .await;
4085
4086        // Create a remote copy of this worktree.
4087        let initial_snapshot = tree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
4088        let (remote, load_task) = cx.update(|cx| {
4089            Worktree::remote(
4090                1,
4091                1,
4092                initial_snapshot.to_proto(&Default::default(), Default::default()),
4093                rpc.clone(),
4094                cx,
4095            )
4096        });
4097        load_task.await;
4098
4099        cx.read(|cx| {
4100            assert!(!buffer2.read(cx).is_dirty());
4101            assert!(!buffer3.read(cx).is_dirty());
4102            assert!(!buffer4.read(cx).is_dirty());
4103            assert!(!buffer5.read(cx).is_dirty());
4104        });
4105
4106        // Rename and delete files and directories.
4107        tree.flush_fs_events(&cx).await;
4108        std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
4109        std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
4110        std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
4111        std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
4112        tree.flush_fs_events(&cx).await;
4113
4114        let expected_paths = vec![
4115            "a",
4116            "a/file1",
4117            "a/file2.new",
4118            "b",
4119            "d",
4120            "d/file3",
4121            "d/file4",
4122        ];
4123
4124        cx.read(|app| {
4125            assert_eq!(
4126                tree.read(app)
4127                    .paths()
4128                    .map(|p| p.to_str().unwrap())
4129                    .collect::<Vec<_>>(),
4130                expected_paths
4131            );
4132
4133            assert_eq!(id_for_path("a/file2.new", &cx), file2_id);
4134            assert_eq!(id_for_path("d/file3", &cx), file3_id);
4135            assert_eq!(id_for_path("d/file4", &cx), file4_id);
4136
4137            assert_eq!(
4138                buffer2.read(app).file().unwrap().path().as_ref(),
4139                Path::new("a/file2.new")
4140            );
4141            assert_eq!(
4142                buffer3.read(app).file().unwrap().path().as_ref(),
4143                Path::new("d/file3")
4144            );
4145            assert_eq!(
4146                buffer4.read(app).file().unwrap().path().as_ref(),
4147                Path::new("d/file4")
4148            );
4149            assert_eq!(
4150                buffer5.read(app).file().unwrap().path().as_ref(),
4151                Path::new("b/c/file5")
4152            );
4153
4154            assert!(!buffer2.read(app).file().unwrap().is_deleted());
4155            assert!(!buffer3.read(app).file().unwrap().is_deleted());
4156            assert!(!buffer4.read(app).file().unwrap().is_deleted());
4157            assert!(buffer5.read(app).file().unwrap().is_deleted());
4158        });
4159
4160        // Update the remote worktree. Check that it becomes consistent with the
4161        // local worktree.
4162        remote.update(cx, |remote, cx| {
4163            let update_message = tree.read(cx).as_local().unwrap().snapshot().build_update(
4164                &initial_snapshot,
4165                1,
4166                1,
4167                true,
4168            );
4169            remote
4170                .as_remote_mut()
4171                .unwrap()
4172                .snapshot
4173                .apply_remote_update(update_message)
4174                .unwrap();
4175
4176            assert_eq!(
4177                remote
4178                    .paths()
4179                    .map(|p| p.to_str().unwrap())
4180                    .collect::<Vec<_>>(),
4181                expected_paths
4182            );
4183        });
4184    }
4185
4186    #[gpui::test]
4187    async fn test_buffer_deduping(cx: &mut gpui::TestAppContext) {
4188        let fs = FakeFs::new(cx.background());
4189        fs.insert_tree(
4190            "/the-dir",
4191            json!({
4192                "a.txt": "a-contents",
4193                "b.txt": "b-contents",
4194            }),
4195        )
4196        .await;
4197
4198        let project = Project::test(fs.clone(), cx);
4199        let worktree_id = project
4200            .update(cx, |p, cx| {
4201                p.find_or_create_local_worktree("/the-dir", false, cx)
4202            })
4203            .await
4204            .unwrap()
4205            .0
4206            .read_with(cx, |tree, _| tree.id());
4207
4208        // Spawn multiple tasks to open paths, repeating some paths.
4209        let (buffer_a_1, buffer_b, buffer_a_2) = project.update(cx, |p, cx| {
4210            (
4211                p.open_buffer((worktree_id, "a.txt"), cx),
4212                p.open_buffer((worktree_id, "b.txt"), cx),
4213                p.open_buffer((worktree_id, "a.txt"), cx),
4214            )
4215        });
4216
4217        let buffer_a_1 = buffer_a_1.await.unwrap();
4218        let buffer_a_2 = buffer_a_2.await.unwrap();
4219        let buffer_b = buffer_b.await.unwrap();
4220        assert_eq!(buffer_a_1.read_with(cx, |b, _| b.text()), "a-contents");
4221        assert_eq!(buffer_b.read_with(cx, |b, _| b.text()), "b-contents");
4222
4223        // There is only one buffer per path.
4224        let buffer_a_id = buffer_a_1.id();
4225        assert_eq!(buffer_a_2.id(), buffer_a_id);
4226
4227        // Open the same path again while it is still open.
4228        drop(buffer_a_1);
4229        let buffer_a_3 = project
4230            .update(cx, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
4231            .await
4232            .unwrap();
4233
4234        // There's still only one buffer per path.
4235        assert_eq!(buffer_a_3.id(), buffer_a_id);
4236    }
4237
4238    #[gpui::test]
4239    async fn test_buffer_is_dirty(cx: &mut gpui::TestAppContext) {
4240        use std::fs;
4241
4242        let dir = temp_tree(json!({
4243            "file1": "abc",
4244            "file2": "def",
4245            "file3": "ghi",
4246        }));
4247
4248        let project = Project::test(Arc::new(RealFs), cx);
4249        let (worktree, _) = project
4250            .update(cx, |p, cx| {
4251                p.find_or_create_local_worktree(dir.path(), false, cx)
4252            })
4253            .await
4254            .unwrap();
4255        let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
4256
4257        worktree.flush_fs_events(&cx).await;
4258        worktree
4259            .read_with(cx, |t, _| t.as_local().unwrap().scan_complete())
4260            .await;
4261
4262        let buffer1 = project
4263            .update(cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
4264            .await
4265            .unwrap();
4266        let events = Rc::new(RefCell::new(Vec::new()));
4267
4268        // initially, the buffer isn't dirty.
4269        buffer1.update(cx, |buffer, cx| {
4270            cx.subscribe(&buffer1, {
4271                let events = events.clone();
4272                move |_, _, event, _| events.borrow_mut().push(event.clone())
4273            })
4274            .detach();
4275
4276            assert!(!buffer.is_dirty());
4277            assert!(events.borrow().is_empty());
4278
4279            buffer.edit(vec![1..2], "", cx);
4280        });
4281
4282        // after the first edit, the buffer is dirty, and emits a dirtied event.
4283        buffer1.update(cx, |buffer, cx| {
4284            assert!(buffer.text() == "ac");
4285            assert!(buffer.is_dirty());
4286            assert_eq!(
4287                *events.borrow(),
4288                &[language::Event::Edited, language::Event::Dirtied]
4289            );
4290            events.borrow_mut().clear();
4291            buffer.did_save(buffer.version(), buffer.file().unwrap().mtime(), None, cx);
4292        });
4293
4294        // after saving, the buffer is not dirty, and emits a saved event.
4295        buffer1.update(cx, |buffer, cx| {
4296            assert!(!buffer.is_dirty());
4297            assert_eq!(*events.borrow(), &[language::Event::Saved]);
4298            events.borrow_mut().clear();
4299
4300            buffer.edit(vec![1..1], "B", cx);
4301            buffer.edit(vec![2..2], "D", cx);
4302        });
4303
4304        // after editing again, the buffer is dirty, and emits another dirty event.
4305        buffer1.update(cx, |buffer, cx| {
4306            assert!(buffer.text() == "aBDc");
4307            assert!(buffer.is_dirty());
4308            assert_eq!(
4309                *events.borrow(),
4310                &[
4311                    language::Event::Edited,
4312                    language::Event::Dirtied,
4313                    language::Event::Edited,
4314                ],
4315            );
4316            events.borrow_mut().clear();
4317
4318            // TODO - currently, after restoring the buffer to its
4319            // previously-saved state, the is still considered dirty.
4320            buffer.edit([1..3], "", cx);
4321            assert!(buffer.text() == "ac");
4322            assert!(buffer.is_dirty());
4323        });
4324
4325        assert_eq!(*events.borrow(), &[language::Event::Edited]);
4326
4327        // When a file is deleted, the buffer is considered dirty.
4328        let events = Rc::new(RefCell::new(Vec::new()));
4329        let buffer2 = project
4330            .update(cx, |p, cx| p.open_buffer((worktree_id, "file2"), cx))
4331            .await
4332            .unwrap();
4333        buffer2.update(cx, |_, cx| {
4334            cx.subscribe(&buffer2, {
4335                let events = events.clone();
4336                move |_, _, event, _| events.borrow_mut().push(event.clone())
4337            })
4338            .detach();
4339        });
4340
4341        fs::remove_file(dir.path().join("file2")).unwrap();
4342        buffer2.condition(&cx, |b, _| b.is_dirty()).await;
4343        assert_eq!(
4344            *events.borrow(),
4345            &[language::Event::Dirtied, language::Event::FileHandleChanged]
4346        );
4347
4348        // When a file is already dirty when deleted, we don't emit a Dirtied event.
4349        let events = Rc::new(RefCell::new(Vec::new()));
4350        let buffer3 = project
4351            .update(cx, |p, cx| p.open_buffer((worktree_id, "file3"), cx))
4352            .await
4353            .unwrap();
4354        buffer3.update(cx, |_, cx| {
4355            cx.subscribe(&buffer3, {
4356                let events = events.clone();
4357                move |_, _, event, _| events.borrow_mut().push(event.clone())
4358            })
4359            .detach();
4360        });
4361
4362        worktree.flush_fs_events(&cx).await;
4363        buffer3.update(cx, |buffer, cx| {
4364            buffer.edit(Some(0..0), "x", cx);
4365        });
4366        events.borrow_mut().clear();
4367        fs::remove_file(dir.path().join("file3")).unwrap();
4368        buffer3
4369            .condition(&cx, |_, _| !events.borrow().is_empty())
4370            .await;
4371        assert_eq!(*events.borrow(), &[language::Event::FileHandleChanged]);
4372        cx.read(|cx| assert!(buffer3.read(cx).is_dirty()));
4373    }
4374
4375    #[gpui::test]
4376    async fn test_buffer_file_changes_on_disk(cx: &mut gpui::TestAppContext) {
4377        use std::fs;
4378
4379        let initial_contents = "aaa\nbbbbb\nc\n";
4380        let dir = temp_tree(json!({ "the-file": initial_contents }));
4381
4382        let project = Project::test(Arc::new(RealFs), cx);
4383        let (worktree, _) = project
4384            .update(cx, |p, cx| {
4385                p.find_or_create_local_worktree(dir.path(), false, cx)
4386            })
4387            .await
4388            .unwrap();
4389        let worktree_id = worktree.read_with(cx, |tree, _| tree.id());
4390
4391        worktree
4392            .read_with(cx, |t, _| t.as_local().unwrap().scan_complete())
4393            .await;
4394
4395        let abs_path = dir.path().join("the-file");
4396        let buffer = project
4397            .update(cx, |p, cx| p.open_buffer((worktree_id, "the-file"), cx))
4398            .await
4399            .unwrap();
4400
4401        // TODO
4402        // Add a cursor on each row.
4403        // let selection_set_id = buffer.update(&mut cx, |buffer, cx| {
4404        //     assert!(!buffer.is_dirty());
4405        //     buffer.add_selection_set(
4406        //         &(0..3)
4407        //             .map(|row| Selection {
4408        //                 id: row as usize,
4409        //                 start: Point::new(row, 1),
4410        //                 end: Point::new(row, 1),
4411        //                 reversed: false,
4412        //                 goal: SelectionGoal::None,
4413        //             })
4414        //             .collect::<Vec<_>>(),
4415        //         cx,
4416        //     )
4417        // });
4418
4419        // Change the file on disk, adding two new lines of text, and removing
4420        // one line.
4421        buffer.read_with(cx, |buffer, _| {
4422            assert!(!buffer.is_dirty());
4423            assert!(!buffer.has_conflict());
4424        });
4425        let new_contents = "AAAA\naaa\nBB\nbbbbb\n";
4426        fs::write(&abs_path, new_contents).unwrap();
4427
4428        // Because the buffer was not modified, it is reloaded from disk. Its
4429        // contents are edited according to the diff between the old and new
4430        // file contents.
4431        buffer
4432            .condition(&cx, |buffer, _| buffer.text() == new_contents)
4433            .await;
4434
4435        buffer.update(cx, |buffer, _| {
4436            assert_eq!(buffer.text(), new_contents);
4437            assert!(!buffer.is_dirty());
4438            assert!(!buffer.has_conflict());
4439
4440            // TODO
4441            // let cursor_positions = buffer
4442            //     .selection_set(selection_set_id)
4443            //     .unwrap()
4444            //     .selections::<Point>(&*buffer)
4445            //     .map(|selection| {
4446            //         assert_eq!(selection.start, selection.end);
4447            //         selection.start
4448            //     })
4449            //     .collect::<Vec<_>>();
4450            // assert_eq!(
4451            //     cursor_positions,
4452            //     [Point::new(1, 1), Point::new(3, 1), Point::new(4, 0)]
4453            // );
4454        });
4455
4456        // Modify the buffer
4457        buffer.update(cx, |buffer, cx| {
4458            buffer.edit(vec![0..0], " ", cx);
4459            assert!(buffer.is_dirty());
4460            assert!(!buffer.has_conflict());
4461        });
4462
4463        // Change the file on disk again, adding blank lines to the beginning.
4464        fs::write(&abs_path, "\n\n\nAAAA\naaa\nBB\nbbbbb\n").unwrap();
4465
4466        // Because the buffer is modified, it doesn't reload from disk, but is
4467        // marked as having a conflict.
4468        buffer
4469            .condition(&cx, |buffer, _| buffer.has_conflict())
4470            .await;
4471    }
4472
4473    #[gpui::test]
4474    async fn test_grouped_diagnostics(cx: &mut gpui::TestAppContext) {
4475        let fs = FakeFs::new(cx.background());
4476        fs.insert_tree(
4477            "/the-dir",
4478            json!({
4479                "a.rs": "
4480                    fn foo(mut v: Vec<usize>) {
4481                        for x in &v {
4482                            v.push(1);
4483                        }
4484                    }
4485                "
4486                .unindent(),
4487            }),
4488        )
4489        .await;
4490
4491        let project = Project::test(fs.clone(), cx);
4492        let (worktree, _) = project
4493            .update(cx, |p, cx| {
4494                p.find_or_create_local_worktree("/the-dir", false, cx)
4495            })
4496            .await
4497            .unwrap();
4498        let worktree_id = worktree.read_with(cx, |tree, _| tree.id());
4499
4500        let buffer = project
4501            .update(cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
4502            .await
4503            .unwrap();
4504
4505        let buffer_uri = Url::from_file_path("/the-dir/a.rs").unwrap();
4506        let message = lsp::PublishDiagnosticsParams {
4507            uri: buffer_uri.clone(),
4508            diagnostics: vec![
4509                lsp::Diagnostic {
4510                    range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
4511                    severity: Some(DiagnosticSeverity::WARNING),
4512                    message: "error 1".to_string(),
4513                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
4514                        location: lsp::Location {
4515                            uri: buffer_uri.clone(),
4516                            range: lsp::Range::new(
4517                                lsp::Position::new(1, 8),
4518                                lsp::Position::new(1, 9),
4519                            ),
4520                        },
4521                        message: "error 1 hint 1".to_string(),
4522                    }]),
4523                    ..Default::default()
4524                },
4525                lsp::Diagnostic {
4526                    range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
4527                    severity: Some(DiagnosticSeverity::HINT),
4528                    message: "error 1 hint 1".to_string(),
4529                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
4530                        location: lsp::Location {
4531                            uri: buffer_uri.clone(),
4532                            range: lsp::Range::new(
4533                                lsp::Position::new(1, 8),
4534                                lsp::Position::new(1, 9),
4535                            ),
4536                        },
4537                        message: "original diagnostic".to_string(),
4538                    }]),
4539                    ..Default::default()
4540                },
4541                lsp::Diagnostic {
4542                    range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
4543                    severity: Some(DiagnosticSeverity::ERROR),
4544                    message: "error 2".to_string(),
4545                    related_information: Some(vec![
4546                        lsp::DiagnosticRelatedInformation {
4547                            location: lsp::Location {
4548                                uri: buffer_uri.clone(),
4549                                range: lsp::Range::new(
4550                                    lsp::Position::new(1, 13),
4551                                    lsp::Position::new(1, 15),
4552                                ),
4553                            },
4554                            message: "error 2 hint 1".to_string(),
4555                        },
4556                        lsp::DiagnosticRelatedInformation {
4557                            location: lsp::Location {
4558                                uri: buffer_uri.clone(),
4559                                range: lsp::Range::new(
4560                                    lsp::Position::new(1, 13),
4561                                    lsp::Position::new(1, 15),
4562                                ),
4563                            },
4564                            message: "error 2 hint 2".to_string(),
4565                        },
4566                    ]),
4567                    ..Default::default()
4568                },
4569                lsp::Diagnostic {
4570                    range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
4571                    severity: Some(DiagnosticSeverity::HINT),
4572                    message: "error 2 hint 1".to_string(),
4573                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
4574                        location: lsp::Location {
4575                            uri: buffer_uri.clone(),
4576                            range: lsp::Range::new(
4577                                lsp::Position::new(2, 8),
4578                                lsp::Position::new(2, 17),
4579                            ),
4580                        },
4581                        message: "original diagnostic".to_string(),
4582                    }]),
4583                    ..Default::default()
4584                },
4585                lsp::Diagnostic {
4586                    range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
4587                    severity: Some(DiagnosticSeverity::HINT),
4588                    message: "error 2 hint 2".to_string(),
4589                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
4590                        location: lsp::Location {
4591                            uri: buffer_uri.clone(),
4592                            range: lsp::Range::new(
4593                                lsp::Position::new(2, 8),
4594                                lsp::Position::new(2, 17),
4595                            ),
4596                        },
4597                        message: "original diagnostic".to_string(),
4598                    }]),
4599                    ..Default::default()
4600                },
4601            ],
4602            version: None,
4603        };
4604
4605        project
4606            .update(cx, |p, cx| {
4607                p.update_diagnostics(message, &Default::default(), cx)
4608            })
4609            .unwrap();
4610        let buffer = buffer.read_with(cx, |buffer, _| buffer.snapshot());
4611
4612        assert_eq!(
4613            buffer
4614                .diagnostics_in_range::<_, Point>(0..buffer.len())
4615                .collect::<Vec<_>>(),
4616            &[
4617                DiagnosticEntry {
4618                    range: Point::new(1, 8)..Point::new(1, 9),
4619                    diagnostic: Diagnostic {
4620                        severity: DiagnosticSeverity::WARNING,
4621                        message: "error 1".to_string(),
4622                        group_id: 0,
4623                        is_primary: true,
4624                        ..Default::default()
4625                    }
4626                },
4627                DiagnosticEntry {
4628                    range: Point::new(1, 8)..Point::new(1, 9),
4629                    diagnostic: Diagnostic {
4630                        severity: DiagnosticSeverity::HINT,
4631                        message: "error 1 hint 1".to_string(),
4632                        group_id: 0,
4633                        is_primary: false,
4634                        ..Default::default()
4635                    }
4636                },
4637                DiagnosticEntry {
4638                    range: Point::new(1, 13)..Point::new(1, 15),
4639                    diagnostic: Diagnostic {
4640                        severity: DiagnosticSeverity::HINT,
4641                        message: "error 2 hint 1".to_string(),
4642                        group_id: 1,
4643                        is_primary: false,
4644                        ..Default::default()
4645                    }
4646                },
4647                DiagnosticEntry {
4648                    range: Point::new(1, 13)..Point::new(1, 15),
4649                    diagnostic: Diagnostic {
4650                        severity: DiagnosticSeverity::HINT,
4651                        message: "error 2 hint 2".to_string(),
4652                        group_id: 1,
4653                        is_primary: false,
4654                        ..Default::default()
4655                    }
4656                },
4657                DiagnosticEntry {
4658                    range: Point::new(2, 8)..Point::new(2, 17),
4659                    diagnostic: Diagnostic {
4660                        severity: DiagnosticSeverity::ERROR,
4661                        message: "error 2".to_string(),
4662                        group_id: 1,
4663                        is_primary: true,
4664                        ..Default::default()
4665                    }
4666                }
4667            ]
4668        );
4669
4670        assert_eq!(
4671            buffer.diagnostic_group::<Point>(0).collect::<Vec<_>>(),
4672            &[
4673                DiagnosticEntry {
4674                    range: Point::new(1, 8)..Point::new(1, 9),
4675                    diagnostic: Diagnostic {
4676                        severity: DiagnosticSeverity::WARNING,
4677                        message: "error 1".to_string(),
4678                        group_id: 0,
4679                        is_primary: true,
4680                        ..Default::default()
4681                    }
4682                },
4683                DiagnosticEntry {
4684                    range: Point::new(1, 8)..Point::new(1, 9),
4685                    diagnostic: Diagnostic {
4686                        severity: DiagnosticSeverity::HINT,
4687                        message: "error 1 hint 1".to_string(),
4688                        group_id: 0,
4689                        is_primary: false,
4690                        ..Default::default()
4691                    }
4692                },
4693            ]
4694        );
4695        assert_eq!(
4696            buffer.diagnostic_group::<Point>(1).collect::<Vec<_>>(),
4697            &[
4698                DiagnosticEntry {
4699                    range: Point::new(1, 13)..Point::new(1, 15),
4700                    diagnostic: Diagnostic {
4701                        severity: DiagnosticSeverity::HINT,
4702                        message: "error 2 hint 1".to_string(),
4703                        group_id: 1,
4704                        is_primary: false,
4705                        ..Default::default()
4706                    }
4707                },
4708                DiagnosticEntry {
4709                    range: Point::new(1, 13)..Point::new(1, 15),
4710                    diagnostic: Diagnostic {
4711                        severity: DiagnosticSeverity::HINT,
4712                        message: "error 2 hint 2".to_string(),
4713                        group_id: 1,
4714                        is_primary: false,
4715                        ..Default::default()
4716                    }
4717                },
4718                DiagnosticEntry {
4719                    range: Point::new(2, 8)..Point::new(2, 17),
4720                    diagnostic: Diagnostic {
4721                        severity: DiagnosticSeverity::ERROR,
4722                        message: "error 2".to_string(),
4723                        group_id: 1,
4724                        is_primary: true,
4725                        ..Default::default()
4726                    }
4727                }
4728            ]
4729        );
4730    }
4731
4732    #[gpui::test]
4733    async fn test_rename(cx: &mut gpui::TestAppContext) {
4734        let (language_server_config, mut fake_servers) = LanguageServerConfig::fake();
4735        let language = Arc::new(Language::new(
4736            LanguageConfig {
4737                name: "Rust".into(),
4738                path_suffixes: vec!["rs".to_string()],
4739                language_server: Some(language_server_config),
4740                ..Default::default()
4741            },
4742            Some(tree_sitter_rust::language()),
4743        ));
4744
4745        let fs = FakeFs::new(cx.background());
4746        fs.insert_tree(
4747            "/dir",
4748            json!({
4749                "one.rs": "const ONE: usize = 1;",
4750                "two.rs": "const TWO: usize = one::ONE + one::ONE;"
4751            }),
4752        )
4753        .await;
4754
4755        let project = Project::test(fs.clone(), cx);
4756        project.update(cx, |project, _| {
4757            Arc::get_mut(&mut project.languages).unwrap().add(language);
4758        });
4759
4760        let (tree, _) = project
4761            .update(cx, |project, cx| {
4762                project.find_or_create_local_worktree("/dir", false, cx)
4763            })
4764            .await
4765            .unwrap();
4766        let worktree_id = tree.read_with(cx, |tree, _| tree.id());
4767        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4768            .await;
4769
4770        let buffer = project
4771            .update(cx, |project, cx| {
4772                project.open_buffer((worktree_id, Path::new("one.rs")), cx)
4773            })
4774            .await
4775            .unwrap();
4776
4777        let mut fake_server = fake_servers.next().await.unwrap();
4778
4779        let response = project.update(cx, |project, cx| {
4780            project.prepare_rename(buffer.clone(), 7, cx)
4781        });
4782        fake_server
4783            .handle_request::<lsp::request::PrepareRenameRequest, _>(|params, _| {
4784                assert_eq!(params.text_document.uri.as_str(), "file:///dir/one.rs");
4785                assert_eq!(params.position, lsp::Position::new(0, 7));
4786                Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
4787                    lsp::Position::new(0, 6),
4788                    lsp::Position::new(0, 9),
4789                )))
4790            })
4791            .next()
4792            .await
4793            .unwrap();
4794        let range = response.await.unwrap().unwrap();
4795        let range = buffer.read_with(cx, |buffer, _| range.to_offset(buffer));
4796        assert_eq!(range, 6..9);
4797
4798        let response = project.update(cx, |project, cx| {
4799            project.perform_rename(buffer.clone(), 7, "THREE".to_string(), true, cx)
4800        });
4801        fake_server
4802            .handle_request::<lsp::request::Rename, _>(|params, _| {
4803                assert_eq!(
4804                    params.text_document_position.text_document.uri.as_str(),
4805                    "file:///dir/one.rs"
4806                );
4807                assert_eq!(
4808                    params.text_document_position.position,
4809                    lsp::Position::new(0, 7)
4810                );
4811                assert_eq!(params.new_name, "THREE");
4812                Some(lsp::WorkspaceEdit {
4813                    changes: Some(
4814                        [
4815                            (
4816                                lsp::Url::from_file_path("/dir/one.rs").unwrap(),
4817                                vec![lsp::TextEdit::new(
4818                                    lsp::Range::new(
4819                                        lsp::Position::new(0, 6),
4820                                        lsp::Position::new(0, 9),
4821                                    ),
4822                                    "THREE".to_string(),
4823                                )],
4824                            ),
4825                            (
4826                                lsp::Url::from_file_path("/dir/two.rs").unwrap(),
4827                                vec![
4828                                    lsp::TextEdit::new(
4829                                        lsp::Range::new(
4830                                            lsp::Position::new(0, 24),
4831                                            lsp::Position::new(0, 27),
4832                                        ),
4833                                        "THREE".to_string(),
4834                                    ),
4835                                    lsp::TextEdit::new(
4836                                        lsp::Range::new(
4837                                            lsp::Position::new(0, 35),
4838                                            lsp::Position::new(0, 38),
4839                                        ),
4840                                        "THREE".to_string(),
4841                                    ),
4842                                ],
4843                            ),
4844                        ]
4845                        .into_iter()
4846                        .collect(),
4847                    ),
4848                    ..Default::default()
4849                })
4850            })
4851            .next()
4852            .await
4853            .unwrap();
4854        let mut transaction = response.await.unwrap().0;
4855        assert_eq!(transaction.len(), 2);
4856        assert_eq!(
4857            transaction
4858                .remove_entry(&buffer)
4859                .unwrap()
4860                .0
4861                .read_with(cx, |buffer, _| buffer.text()),
4862            "const THREE: usize = 1;"
4863        );
4864        assert_eq!(
4865            transaction
4866                .into_keys()
4867                .next()
4868                .unwrap()
4869                .read_with(cx, |buffer, _| buffer.text()),
4870            "const TWO: usize = one::THREE + one::THREE;"
4871        );
4872    }
4873
4874    #[gpui::test]
4875    async fn test_search(cx: &mut gpui::TestAppContext) {
4876        let fs = FakeFs::new(cx.background());
4877        fs.insert_tree(
4878            "/dir",
4879            json!({
4880                "one.rs": "const ONE: usize = 1;",
4881                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
4882                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
4883                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
4884            }),
4885        )
4886        .await;
4887        let project = Project::test(fs.clone(), cx);
4888        let (tree, _) = project
4889            .update(cx, |project, cx| {
4890                project.find_or_create_local_worktree("/dir", false, cx)
4891            })
4892            .await
4893            .unwrap();
4894        let worktree_id = tree.read_with(cx, |tree, _| tree.id());
4895        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4896            .await;
4897
4898        assert_eq!(
4899            search(&project, SearchQuery::text("TWO", false, true), cx)
4900                .await
4901                .unwrap(),
4902            HashMap::from_iter([
4903                ("two.rs".to_string(), vec![6..9]),
4904                ("three.rs".to_string(), vec![37..40])
4905            ])
4906        );
4907
4908        let buffer_4 = project
4909            .update(cx, |project, cx| {
4910                project.open_buffer((worktree_id, "four.rs"), cx)
4911            })
4912            .await
4913            .unwrap();
4914        buffer_4.update(cx, |buffer, cx| {
4915            buffer.edit([20..28, 31..43], "two::TWO", cx);
4916        });
4917
4918        assert_eq!(
4919            search(&project, SearchQuery::text("TWO", false, true), cx)
4920                .await
4921                .unwrap(),
4922            HashMap::from_iter([
4923                ("two.rs".to_string(), vec![6..9]),
4924                ("three.rs".to_string(), vec![37..40]),
4925                ("four.rs".to_string(), vec![25..28, 36..39])
4926            ])
4927        );
4928
4929        async fn search(
4930            project: &ModelHandle<Project>,
4931            query: SearchQuery,
4932            cx: &mut gpui::TestAppContext,
4933        ) -> Result<HashMap<String, Vec<Range<usize>>>> {
4934            let results = project
4935                .update(cx, |project, cx| project.search(query, cx))
4936                .await?;
4937
4938            Ok(results
4939                .into_iter()
4940                .map(|(buffer, ranges)| {
4941                    buffer.read_with(cx, |buffer, _| {
4942                        let path = buffer.file().unwrap().path().to_string_lossy().to_string();
4943                        let ranges = ranges
4944                            .into_iter()
4945                            .map(|range| range.to_offset(buffer))
4946                            .collect::<Vec<_>>();
4947                        (path, ranges)
4948                    })
4949                })
4950                .collect())
4951        }
4952    }
4953}