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