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